Index: sm/trunk/AUTHORS
===================================================================
--- /issm/trunk/AUTHORS	(revision 19104)
+++ 	(revision )
@@ -1,27 +1,0 @@
-Ice Sheet System Model is a JPL/UCI collaboration to develop a massively-parallelized
-multi-purpose finite element framework dedicated to ice sheet modeling
-
-Project Scientist: 
-   Eric Rignot <eric.rignot@jpl.nasa.gov>
-
-Project Manager: 
-   Eric Larour <eric.larour@jpl.nasa.gov>
-
-Current core developers:
-   * Eric Larour <eric.larour@jpl.nasa.gov>
-   * Helene Seroussi <helene.seroussi@jpl.nasa.gov>
-   * Mathieu Morlighem <mathieu.morlighem@uci.edu>
-
-Contributors:
-	We thank the following contributors for their help in making ISSM better!
-
-	Robert Crippen, Jet Propulsion Laboratory.  robbert.crippen@jpl.nasa.gov
-	HoleFiller routines to plug incomplete datasets. See HoleFiller module in src/m/matlab/utils
-
-	Point Inclusion in Polygon Test (pnpoly.c used in Utils/Arguscontourtomesh/IsInPoly.c)
-	W. Randolph Franklin (WRF)
-	http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
-
-	DACE: A Matlab Kriging toolbox, Søren N.Lophaen, Hans Bruun Nielsen and Jacob
-	Søndergaard (Technical University of Denmark)
-	http://www2.imm.dtu.dk/~hbn/dace/
Index: /issm/trunk/README
===================================================================
--- /issm/trunk/README	(revision 19104)
+++ /issm/trunk/README	(revision 19105)
@@ -6,22 +6,6 @@
 systems using Finite Elemenent Analysis, and parallel technologies.
 
-------------------------------------------------------------------------------
-
-Jet Propulsion Laboratory
-
-Eric    Larour (Project Manager)
-Mathieu Morlighem (Core Developer, Anisotropic Meshing, Control Methods)
-Helene  Seroussi (Core Develper Coupling 2D-3D, Multi-model, full-Stokes)
-Nicole  Schlegel (Developer, Atmospheric Forcing)
-Chris   Borstad (Developer, Rifting/Faulting/Crack Propagation)
-Feras   Habbal (Developer, Solver Technologies)
-Daria   Halkides (Analyst, Atmospheric Forcing)
-Ala     Khazendar (Analyst, Ice Sheet Processes)
-
-Email: issm@jpl.nasa.gov
-
-------------------------------------------------------------------------------
-
-Website: http://issm.jpl.nasa.gov/ for additional information.
+Email:   issm@jpl.nasa.gov
+Website: http://issm.jpl.nasa.gov/
 
 ------------------------------------------------------------------------------
@@ -32,5 +16,5 @@
 
 
-Copyright (c) 2002-2011, California Institute of Technology.
+Copyright (c) 2002-2014, California Institute of Technology.
 All rights reserved.  Based on Government Sponsored Research under contracts
 NAS7-1407 and/or NAS7-03001.
Index: /issm/trunk/configs/config-discover.sh
===================================================================
--- /issm/trunk/configs/config-discover.sh	(revision 19104)
+++ /issm/trunk/configs/config-discover.sh	(revision 19105)
@@ -14,8 +14,6 @@
  --with-mpi-include="/usr/local/intel/mpi/4.0.3.008/include64/" \
  --with-mpi-libflags="-L/usr/local/intel/mpi/4.0.3.008/lib64/ -lmpi -lmpiif" \
- --with-petsc-arch=$ISSM_ARCH \
  --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
  --with-scalapack-dir="/usr/local/intel/mkl/10.1.2.024/lib/64/" \
- --with-blacs-dir="/usr/local/intel/mkl/10.1.2.024/lib/64/" \
  --with-blas-lapack-dir="/usr/local/intel/mkl/10.1.2.024/lib/64/" \
  --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
Index: /issm/trunk/configs/config-greenplanet.sh
===================================================================
--- /issm/trunk/configs/config-greenplanet.sh	(revision 19104)
+++ /issm/trunk/configs/config-greenplanet.sh	(revision 19105)
@@ -13,5 +13,4 @@
  --with-mpi-include="/sopt/mpi/openmpi-1.5.4_psm/intel/include/" \
  --with-mpi-libflags="-L/sopt/mpi/openmpi-1.5.4_psm/intel/lib/ -lmpi -lmpi_f77" \
- --with-petsc-arch=$ISSM_ARCH \
  --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
  --with-mkl-dir=/opt/intel/mkl/10.2.4.032/ \
@@ -20,5 +19,4 @@
  --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-graphics-lib=/usr/lib64/libX11.so \
  --with-cxxoptflags="-O3" \
Index: /issm/trunk/configs/config-hoffman2.sh
===================================================================
--- /issm/trunk/configs/config-hoffman2.sh	(revision 19104)
+++ /issm/trunk/configs/config-hoffman2.sh	(revision 19105)
@@ -1,3 +1,3 @@
-#!/bin/csh
+.//config-greenplanet.sh:21: #!/bin/csh
 
 ./configure \
@@ -8,5 +8,4 @@
  --with-mpi-include=/u/local/intel/11.1/openmpi/1.4.5/include \
  --with-mpi-libflags="-L/u/local/intel/11.1/openmpi/1.4.5/include -lmpi" \
- --with-petsc-arch=$ISSM_ARCH \
  --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
  --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
@@ -14,5 +13,4 @@
  --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-graphics-lib=/usr/lib64/libX11.so \
  --with-cxxoptflags="-O3 -L/u/local/intel/11.1/openmpi/1.4.5/lib -lmpi -lmpi_f77 -lmpi_cxx"
Index: /issm/trunk/configs/config-linux64-cloud.sh
===================================================================
--- /issm/trunk/configs/config-linux64-cloud.sh	(revision 19104)
+++ /issm/trunk/configs/config-linux64-cloud.sh	(revision 19105)
@@ -14,6 +14,4 @@
  --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
  --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
- --with-petsc-arch=$ISSM_ARCH \
- --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
Index: /issm/trunk/configs/config-linux64-larsen-gia.sh
===================================================================
--- /issm/trunk/configs/config-linux64-larsen-gia.sh	(revision 19104)
+++ /issm/trunk/configs/config-linux64-larsen-gia.sh	(revision 19105)
@@ -17,5 +17,4 @@
  --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
  --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
- --with-petsc-arch=$ISSM_ARCH \
  --with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
  --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
Index: /issm/trunk/configs/config-linux64-larsen.sh
===================================================================
--- /issm/trunk/configs/config-linux64-larsen.sh	(revision 19104)
+++ /issm/trunk/configs/config-linux64-larsen.sh	(revision 19105)
@@ -17,5 +17,4 @@
  --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
  --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
- --with-petsc-arch=$ISSM_ARCH \
  --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
Index: /issm/trunk/configs/config-linux64-murdo.sh
===================================================================
--- /issm/trunk/configs/config-linux64-murdo.sh	(revision 19104)
+++ /issm/trunk/configs/config-linux64-murdo.sh	(revision 19105)
@@ -15,5 +15,4 @@
 	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy\
 	--with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
-	--with-petsc-arch=$ISSM_ARCH \
 	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
 	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
@@ -24,3 +23,2 @@
 	--with-numthreads=18 \
 	--enable-debugging 
-	#--with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
Index: /issm/trunk/configs/config-linux64-pleiades-gcc-4.4.4.sh
===================================================================
--- /issm/trunk/configs/config-linux64-pleiades-gcc-4.4.4.sh	(revision 19104)
+++ /issm/trunk/configs/config-linux64-pleiades-gcc-4.4.4.sh	(revision 19105)
@@ -4,5 +4,4 @@
 	--without-kriging \
 	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
-	--with-petsc-arch=$ISSM_ARCH \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
Index: /issm/trunk/configs/config-linux64-pleiades-gcc-4.7.0.sh
===================================================================
--- /issm/trunk/configs/config-linux64-pleiades-gcc-4.7.0.sh	(revision 19104)
+++ /issm/trunk/configs/config-linux64-pleiades-gcc-4.7.0.sh	(revision 19105)
@@ -4,5 +4,4 @@
 	--without-kriging \
 	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
-	--with-petsc-arch=$ISSM_ARCH \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
Index: /issm/trunk/configs/config-linux64-pleiades-intel2012.0.032-mpt.2.06rp16.sh
===================================================================
--- /issm/trunk/configs/config-linux64-pleiades-intel2012.0.032-mpt.2.06rp16.sh	(revision 19104)
+++ /issm/trunk/configs/config-linux64-pleiades-intel2012.0.032-mpt.2.06rp16.sh	(revision 19105)
@@ -5,5 +5,4 @@
 	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
 	--with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-petsc-arch=$ISSM_ARCH \
 	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
 	--with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
Index: /issm/trunk/configs/config-linux64-pleiades-intel2015.0.090-mpt.2.11r13.sh
===================================================================
--- /issm/trunk/configs/config-linux64-pleiades-intel2015.0.090-mpt.2.11r13.sh	(revision 19105)
+++ /issm/trunk/configs/config-linux64-pleiades-intel2015.0.090-mpt.2.11r13.sh	(revision 19105)
@@ -0,0 +1,15 @@
+#!/bin/csh
+./configure \
+	--prefix=$ISSM_DIR \
+	--without-kriging \
+	--with-wrappers=no \
+	--with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-mpi-include="/nasa/sgi/mpt/2.11r13/include" \
+	--with-mpi-libflags="-L/nasa/sgi/mpt/2.11r13/ -lmpi" \
+	--with-mkl-dir="/nasa/intel/Compiler/2015.0.090/composer_xe_2015.0.090/mkl/" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-cxxoptflags="-O3 -axAVX" \
+	--with-vendor="intel-pleiades"
Index: /issm/trunk/configs/config-linux64-skylla.sh
===================================================================
--- /issm/trunk/configs/config-linux64-skylla.sh	(revision 19104)
+++ /issm/trunk/configs/config-linux64-skylla.sh	(revision 19105)
@@ -13,5 +13,4 @@
  --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
  --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
- --with-petsc-arch=$ISSM_ARCH \
  --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
  --with-tao-dir=$ISSM_DIR/externalpackages/tao/install/ \
Index: /issm/trunk/configs/config-linux64-ubuntu64.sh
===================================================================
--- /issm/trunk/configs/config-linux64-ubuntu64.sh	(revision 19104)
+++ /issm/trunk/configs/config-linux64-ubuntu64.sh	(revision 19105)
@@ -9,9 +9,7 @@
  --with-mpi-include="/usr/lib/mpich/include" \
  --with-mpi-libflags="-L/usr/lib/mpich/lib -lmpich -lmpl -ldl" \
- --with-petsc-arch=$ISSM_ARCH \
  --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
  --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
  --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/externalpackages/PLAPACKR32-hg/INCLUDE" \
- --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
Index: /issm/trunk/configs/config-macosx64-static.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-static.sh	(revision 19105)
+++ /issm/trunk/configs/config-macosx64-static.sh	(revision 19105)
@@ -0,0 +1,19 @@
+#!/bin/sh
+
+./configure \
+	--prefix=$ISSM_DIR \
+   --disable-static \
+   --enable-standalone-executables \
+   --enable-standalone-libraries \
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
+   --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+	--with-mpi-libflags=" -L$ISSM_DIR/externalpackages/mpich/install/lib -lmpich -lpmpich" \
+	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
+   --with-fortran-lib="/usr/local/lib/libgfortran.a" \
+   --enable-debugging \
+	--with-numthreads=4
Index: /issm/trunk/configs/config-pleiades-petscdev.sh
===================================================================
--- /issm/trunk/configs/config-pleiades-petscdev.sh	(revision 19104)
+++ /issm/trunk/configs/config-pleiades-petscdev.sh	(revision 19105)
@@ -10,10 +10,8 @@
  --with-mpi-include=/nasa/sgi/mpt/2.04/include \
  --with-mpi-libflags="-L/nasa/sgi/mpt/2.04/lib/ -lmpi -lpthread -lgfortran" \
- --with-petsc-arch=$ISSM_ARCH \
  --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
  --with-mkl-dir=/nasa/intel/mkl/10.0.011/lib/64/ \
  --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-spai-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-hypre-dir=$ISSM_DIR/externalpackages/petsc/install/ \
Index: /issm/trunk/configs/config-win7-32.sh
===================================================================
--- /issm/trunk/configs/config-win7-32.sh	(revision 19104)
+++ /issm/trunk/configs/config-win7-32.sh	(revision 19105)
@@ -10,5 +10,4 @@
    --with-metis-dir="$ISSM_DIR/externalpackages/metis/install" \
    --with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
-   --with-petsc-arch=$ISSM_ARCH  \
    --with-mpi-libdir="$ISSM_DIR/externalpackages/petsc/install/lib" \
    --with-mpi-libflags="-Wl,libpetsc.lib" \
Index: /issm/trunk/configs/config-win7-64-parallel.sh
===================================================================
--- /issm/trunk/configs/config-win7-64-parallel.sh	(revision 19104)
+++ /issm/trunk/configs/config-win7-64-parallel.sh	(revision 19105)
@@ -11,5 +11,4 @@
 	--with-metis-dir="$ISSM_DIR_WIN/externalpackages/metis/install" \
 	--with-petsc-dir="$ISSM_DIR_WIN/externalpackages/petsc/install" \
-	--with-petsc-arch=$ISSM_ARCH  \
 	--with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install/lib"  \
 	--with-mpi-include="C:/MPICH2/include" \
Index: /issm/trunk/configs/config-win7-64.sh
===================================================================
--- /issm/trunk/configs/config-win7-64.sh	(revision 19104)
+++ /issm/trunk/configs/config-win7-64.sh	(revision 19105)
@@ -9,5 +9,4 @@
 	--with-metis-dir="$ISSM_DIR/externalpackages/metis/install" \
 	--with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-petsc-arch=$ISSM_ARCH  \
 	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install/lib/  \
 	--with-mpi-libflags-dir="$ISSM_DIR/externalpackages/petsc/install/lib" \
Index: /issm/trunk/configure.ac
===================================================================
--- /issm/trunk/configure.ac	(revision 19104)
+++ /issm/trunk/configure.ac	(revision 19105)
@@ -2,9 +2,11 @@
 
 #AUTOCONF
-AC_INIT([Ice Sheet System Model (ISSM)],[4.8],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_INIT([Ice Sheet System Model (ISSM)],[4.9],[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
 m4_include([m4/issm_options.m4])
-AC_CANONICAL_TARGET                       #Determine the system type
+
+#Determine System type and OS
+AC_CANONICAL_TARGET
 
 #Compilers
@@ -14,8 +16,4 @@
 AC_PROG_F77([ifort g77 gfortran])
 
-#Libraries and linking
-AC_F77_LIBRARY_LDFLAGS
-AC_PATH_XTRA      #figure out X library and include paths
-
 #AUTOMAKE
 #Initialize automake and declare foreign so that we don't need a ChangeLog, INSTALL, etc
@@ -23,5 +21,4 @@
 AC_CONFIG_HEADERS([./config.h])   #Config file must be config.h
 AM_SILENT_RULES([yes])           #Do not show compilation command by default
-AM_PROG_CC_C_O
 AM_PROG_AR
 
Index: /issm/trunk/etc/environment.csh
===================================================================
--- /issm/trunk/etc/environment.csh	(revision 19104)
+++ /issm/trunk/etc/environment.csh	(revision 19105)
@@ -43,6 +43,13 @@
 set DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
 if (-d $DAKOTA_DIR) then
-	setenv PATH {$PATH}:{$DAKOTA_DIR}/bin
+	setenv PATH {$DAKOTA_DIR}/bin:{$PATH}
 	setenv MANPATH {$MANPATH}:{$MPI_DIR}/man:{$DAKOTA_DIR}/docs/man:{$DAKOTA_DIR}/docs/man-ref
+endif
+
+#Boost
+set BOOST_DIR="$ISSM_DIR/externalpackages/boost/install"
+set BOOSTROOT="$ISSM_DIR/externalpackages/boost/install"
+if (-d $BOOST_DIR) then
+   setenv PATH {$BOOST_DIR}/bin:{$PATH}
 endif
 
@@ -100,4 +107,4 @@
 set SHELL2JUNIT_DIR="$ISSM_DIR/externalpackages/shell2junit"
 if (-d $SHELL2JUNIT_DIR) then
-	setenv PATH {$PATH}:{$SHELL2JUNIT_DIR}/install
+	setenv PATH {$SHELL2JUNIT_DIR}/install:{$PATH}
 endif
Index: /issm/trunk/etc/environment.sh
===================================================================
--- /issm/trunk/etc/environment.sh	(revision 19104)
+++ /issm/trunk/etc/environment.sh	(revision 19105)
@@ -71,4 +71,10 @@
 pathprepend   "$MATLAB_DIR/bin" #take precedence over /usr/local/bin/matlab
 libpathappend "$MATLAB_DIR/lib"
+
+#GMT 
+GMT_DIR="$ISSM_DIR/externalpackages/gmt/install"
+export GMT_DIR
+pathprepend   "$GMT_DIR/bin" 
+libpathappend "$GMT_DIR/lib"
 
 #legacy mpich2 (To be removed)
@@ -306,2 +312,7 @@
 libpathprepend   "$ISSM_DIR/externalpackages/expat/install"
 dylibpathprepend   "$ISSM_DIR/externalpackages/expat/install"
+
+#CURL
+libpathprepend   "$ISSM_DIR/externalpackages/curl/install/lib"
+dylibpathprepend   "$ISSM_DIR/externalpackages/curl/install/lib"
+pathprepend "$ISSM_DIR/externalpackages/curl/install/bin"
Index: /issm/trunk/examples/ISMIP/CheatyRunme.m
===================================================================
--- /issm/trunk/examples/ISMIP/CheatyRunme.m	(revision 19104)
+++ /issm/trunk/examples/ISMIP/CheatyRunme.m	(revision 19105)
@@ -10,5 +10,5 @@
 %Run Steps
 
-% {{{ Mesh Generation #1
+%Mesh Generation #1
 if any(steps==1)
 
@@ -31,7 +31,6 @@
 	save ./Models/ISMIP.Mesh_generation md;
 end
-% }}}
-
-% {{{ Masks #2
+
+%Masks #2
 if any(steps==2)
 
@@ -51,7 +50,6 @@
 	save ./Models/ISMIP.SetMask md;
 end
-% }}}
-
-% {{{ Parameterization #3
+
+%Parameterization #3
 if any(steps==3)
 
@@ -69,7 +67,6 @@
 	save ./Models/ISMIP.Parameterization md;
 end
-% }}}
-
-% {{{ Extrusion #4
+
+%Extrusion #4
 if any(steps==4)
 	
@@ -89,7 +86,6 @@
 	save ./Models/ISMIP.Extrusion md;
 end
-% }}}
-
-% {{{ Set the flow computing method #5
+
+%Set the flow computing method #5
 if any(steps==5)
 
@@ -106,7 +102,6 @@
 	save ./Models/ISMIP.SetFlow md;
 end
-% }}}
-
-% {{{ Set Boundary Conditions #6
+
+%Set Boundary Conditions #6
 if any(steps==6)
 
@@ -161,7 +156,6 @@
 	save ./Models/ISMIP.BoundaryCondition md;
 end
-% }}}
-
-% {{{ Solving #7
+
+%Solving #7
 if any(steps==7)
 	% load the preceding step #help loadmodel
@@ -188,7 +182,6 @@
 	plotmodel(md,'data',md.results.StressbalanceSolution.Vel)
 end
-% }}}
-
-% {{{ Solving #8
+
+%Solving #8
 if any(steps==8)
 	% load the preceding step #help loadmodel
@@ -227,3 +220,2 @@
 	plotmodel(md,'data',md.results.TransientSolution(20).Vel)
 end
-% }}}
Index: /issm/trunk/examples/ISMIP/runme.m
===================================================================
--- /issm/trunk/examples/ISMIP/runme.m	(revision 19104)
+++ /issm/trunk/examples/ISMIP/runme.m	(revision 19105)
@@ -10,5 +10,5 @@
 %Run Steps
 
-% {{{ Mesh Generation #1
+%Mesh Generation #1
 if any(steps==1) 
 
@@ -27,7 +27,6 @@
 
 end
-% }}}
-
-% {{{ Masks #2
+
+%Masks #2
 if any(steps==2) 
 
@@ -47,7 +46,6 @@
 
 end
-% }}}
-
-% {{{ Parameterization #3
+
+%Parameterization #3
 if any(steps==3) 
 
@@ -65,7 +63,6 @@
 
 end
-% }}}
-
-% {{{ Extrusion #4
+
+%Extrusion #4
 if any(steps==4)
 	
@@ -85,8 +82,6 @@
 
 end
-% }}}
-
-% {{{ Set the flow computing method #5
-
+
+%Set the flow computing method #5
 if any(steps==5)
 
@@ -103,7 +98,6 @@
 
 end
-% }}}
-
-% {{{ Set Boundary Conditions #6
+
+%Set Boundary Conditions #6
 if any(steps==6)
 
@@ -157,7 +151,6 @@
 
 end
-% }}}
-
-% {{{ Solving #7
+
+%Solving #7
 if any(steps==7)
 	% load the preceding step #help loadmodel
@@ -183,7 +176,6 @@
 	%->
 end
-% }}}
-
-% {{{ Solving #8
+
+%Solving #8
 if any(steps==8)
 	% load the preceding step #help loadmodel
@@ -222,3 +214,2 @@
 
 end
-% }}}
Index: /issm/trunk/examples/Pig/Pig.par
===================================================================
--- /issm/trunk/examples/Pig/Pig.par	(revision 19104)
+++ /issm/trunk/examples/Pig/Pig.par	(revision 19105)
@@ -7,5 +7,5 @@
 md.mesh.hemisphere='s';
 
-% {{{ NetCdf Loading
+%NetCdf Loading
 disp('   Loading SeaRISE data from NetCDF');
 ncdata='../Data/Antarctica_5km_withshelves_v0.75.nc';
@@ -47,6 +47,6 @@
 y2=(ymax-ny*spacing)+(0:1:ny)'*spacing; 
 y2=double(y2);
-% }}}
-% {{{ Geometry
+
+%Geometry
 disp('   Interpolating surface and ice base');
 md.geometry.base    = InterpFromGridToMesh(x1,y1,topg,md.mesh.x,md.mesh.y,0);
@@ -73,6 +73,6 @@
 md.geometry.thickness(pos0)=1;
 md.geometry.surface=md.geometry.thickness+md.geometry.base;
-% }}} 
-% {{{ Initialization parameters
+
+%Initialization parameters
 disp('   Interpolating temperatures');
 md.initialization.temperature=InterpFromGridToMesh(x1,y1,temp,md.mesh.x,md.mesh.y,0)+273.15+Temp_change;
@@ -93,11 +93,9 @@
 md.initialization.pressure=md.materials.rho_ice*md.constants.g*md.geometry.thickness;
 
-% }}}
-
 disp('   Construct ice rheological properties');
 md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
 md.materials.rheology_B=paterson(md.initialization.temperature);
 
-% {{{ Forcings
+%Forcings
 disp('   Interpolating surface mass balance');
 md.surfaceforcings.mass_balance=InterpFromGridToMesh(x1,y1,smb,md.mesh.x,md.mesh.y,0);
@@ -108,7 +106,6 @@
 md.basalforcings.geothermalflux=InterpFromGridToMesh(x1,y1,gflux,md.mesh.x,md.mesh.y,0);
 clear gflux;
-% }}}
 
-% {{{ Friction and inversion set up
+%Friction and inversion set up
 disp('   Construct basal friction parameters');
 md.friction.coefficient=friction_coefficient*ones(md.mesh.numberofvertices,1);
@@ -124,6 +121,4 @@
 md.inversion.vy_obs=vy_obs;
 md.inversion.vel_obs=vel_obs;
-% }}}
-
 
 disp('   Set boundary conditions');
@@ -133,3 +128,2 @@
 md.thermal.spctemperature     = [md.initialization.temperature;1]; %impose observed temperature on surface
 md.masstransport.spcthickness    = NaN*ones(md.mesh.numberofvertices,1);
-
Index: /issm/trunk/examples/Pig/PigRegion.m
===================================================================
--- /issm/trunk/examples/Pig/PigRegion.m	(revision 19104)
+++ /issm/trunk/examples/Pig/PigRegion.m	(revision 19105)
@@ -1,3 +1,3 @@
-% {{{ Getting the velocity in PIG vicinity for the ExpDraw
+%Getting the velocity in PIG vicinity for the ExpDraw
 
 % Load Velocities
@@ -51,4 +51,2 @@
 vel_obs=sqrt(vx_obs.^2.+vy_obs.^2.);
 imagesc(xred,yred,vel_obs)
-
-%}}}
Index: /issm/trunk/examples/Pig/runme.m
===================================================================
--- /issm/trunk/examples/Pig/runme.m	(revision 19104)
+++ /issm/trunk/examples/Pig/runme.m	(revision 19105)
@@ -4,5 +4,5 @@
 %Run Steps
 
-% {{{ Mesh Generation #1
+%Mesh Generation #1
 if any(steps==1)
 
@@ -73,7 +73,6 @@
 	save ./Models/PIG.Mesh_generation md;
 end
-% }}}
-
-% {{{ Masks #2
+
+%Masks #2
 if any(steps==2) 
 
@@ -104,7 +103,6 @@
 	save ./Models/PIG.SetMask md;
 end
-% }}}
-
-% {{{ Parameterization #3
+
+%Parameterization #3
 if any(steps==3) 
 
@@ -118,7 +116,6 @@
 	save ./Models/PIG.Parameterization md;
 end
-% }}}
-
-% {{{ Control Method #4
+
+%Control Method #4
 if any(steps==4)
 
@@ -163,7 +160,6 @@
 	save ./Models/PIG.Control_drag md;
 end
-% }}}
-
-% {{{ Plot #5
+
+%Plot #5
 if any(steps==5)
 
@@ -182,7 +178,6 @@
 		'colorbartitle#3','[m]', 'log#1-2',10);
 end
-% }}}
-
-% {{{ HO #6
+
+%HO #6
 if any(steps==6)
 
@@ -200,7 +195,6 @@
 
 end
-% }}}
-
-% {{{ Plot #7
+
+%Plot #7
 if any(steps==7)
 
@@ -226,3 +220,2 @@
 						'layer#5',1, 'log#1', 10,'log#3', 10,'log#5', 10);
 end
-% }}}
Index: /issm/trunk/examples/README.txt
===================================================================
--- /issm/trunk/examples/README.txt	(revision 19105)
+++ /issm/trunk/examples/README.txt	(revision 19105)
@@ -0,0 +1,6 @@
+To run the following examples see the accompanying tutorials that can be found within the
+documentation tab on the ISSM webpage. The tutorials were created to be parallel to lectures given,
+but the tutorials are up to date on their version of ISSM. However within the workshop directory you
+can find the lecture tutorials which will give a more in depth technical overview. If more help is
+needed see the Usermanual also found under the documentation tab. If you don't want to complete the
+tutorials in chronological order make sure to see Jakobshavn to run the download script. 
Index: /issm/trunk/examples/SquareIceShelf/runme.m
===================================================================
--- /issm/trunk/examples/SquareIceShelf/runme.m	(revision 19104)
+++ /issm/trunk/examples/SquareIceShelf/runme.m	(revision 19105)
@@ -5,3 +5,3 @@
 md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname,'np',2);
-md=solve(md,StressbalanceSolutionEnum);
+md=solve(md,StressbalanceSolutionEnum());
Index: /issm/trunk/externalpackages/boost/configs/1.55/darwin.jam.patch
===================================================================
--- /issm/trunk/externalpackages/boost/configs/1.55/darwin.jam.patch	(revision 19105)
+++ /issm/trunk/externalpackages/boost/configs/1.55/darwin.jam.patch	(revision 19105)
@@ -0,0 +1,4 @@
+587c587
+<     "$(.LIBTOOL)" -static -o "$(<:T)"  $(ARFLAGS)  "$(>:T)"
+---
+>     /usr/bin/libtool -static -o "$(<:T)"  $(ARFLAGS)  "$(>:T)"
Index: /issm/trunk/externalpackages/boost/configs/1.55/darwin.py.patch
===================================================================
--- /issm/trunk/externalpackages/boost/configs/1.55/darwin.py.patch	(revision 19105)
+++ /issm/trunk/externalpackages/boost/configs/1.55/darwin.py.patch	(revision 19105)
@@ -0,0 +1,4 @@
+40c40
+< toolset.flags ('darwin.compile', 'OPTIONS', None, ['-Wno-long-double', '-no-cpp-precomp'])
+---
+> toolset.flags ('darwin.compile', 'OPTIONS', None, ['-Wno-long-double'])
Index: /issm/trunk/externalpackages/boost/configs/1.55/user-config.jam.patch
===================================================================
--- /issm/trunk/externalpackages/boost/configs/1.55/user-config.jam.patch	(revision 19105)
+++ /issm/trunk/externalpackages/boost/configs/1.55/user-config.jam.patch	(revision 19105)
@@ -0,0 +1,4 @@
+42c42
+< # using gcc ;
+---
+> using darwin : std0x : "/usr/local/gfortran/bin/x86_64-apple-darwin10-g++" : <cxxflags>-std=gnu++0x;  
Index: /issm/trunk/externalpackages/boost/install-1.55-macosx-mavericks.sh
===================================================================
--- /issm/trunk/externalpackages/boost/install-1.55-macosx-mavericks.sh	(revision 19104)
+++ /issm/trunk/externalpackages/boost/install-1.55-macosx-mavericks.sh	(revision 19105)
@@ -22,6 +22,9 @@
 rm -rf boost_1_55_0
 
-patch src/boost/atomic/detail/cas128strong.hpp ./configs/1.55/cas128strong.hpp.patch
-patch src/boost/atomic/detail/gcc-atomic.hpp ./configs/1.55/gcc-atomic.hpp.patch
+#patch src/boost/atomic/detail/cas128strong.hpp ./configs/1.55/cas128strong.hpp.patch
+#patch src/boost/atomic/detail/gcc-atomic.hpp ./configs/1.55/gcc-atomic.hpp.patch
+patch src/tools/build/v2/user-config.jam ./configs/1.55/user-config.jam.patch
+patch src/tools/build/v2/tools/darwin.jam ./configs/1.55/darwin.jam.patch
+patch src/tools/build/v2/tools/darwin.py ./configs/1.55/darwin.py.patch
 
 #Configure and compile
@@ -29,10 +32,12 @@
 ./bootstrap.sh \
 	--prefix="$ISSM_DIR/externalpackages/boost/install" \
-	--with-python=python3.2 \
+	--with-python=python2.7 \
 	--with-python-root="$ISSM_DIR/externalpackages/python/install" 
 
 #Compile boost
-./b2 toolset=clang cxxflags=-stdlib=libstdc++ linkflags=-stdlib=libstdc++ -j2 variant=release link=static threading=multi install
-#./bjam install
+# Need gcc with iconv installed in a location that has been added to your path
+./bjam toolset=darwin-std0x link=static install
+
+#./b2 toolset=clang cxxflags=-stdlib=libstdc++ linkflags=-stdlib=libstdc++ -j2 variant=release link=static threading=multi instal
 
 #put bjam into install also: 
Index: /issm/trunk/externalpackages/curl/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/curl/install-macosx64.sh	(revision 19105)
+++ /issm/trunk/externalpackages/curl/install-macosx64.sh	(revision 19105)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install curl-7.39.0
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/curl-7.39.0.tar.gz' 'curl-7.39.0.tar.gz'
+
+#Untar 
+tar -zxvf  curl-7.39.0.tar.gz
+
+#Move curl into src directory
+mv curl-7.39.0/* src
+rm -rf curl-7.39.0
+
+#Configure curl
+cd src
+
+export CFLAGS=" -arch x86_64"
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/curl/install" 
+
+#Compile curl
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/dakota/configs/5.3.1/BuildDakotaCustom.cmake.mac.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3.1/BuildDakotaCustom.cmake.mac.patch	(revision 19105)
+++ /issm/trunk/externalpackages/dakota/configs/5.3.1/BuildDakotaCustom.cmake.mac.patch	(revision 19105)
@@ -0,0 +1,14 @@
+64,65c64,65
+< #set( DAKOTA_HAVE MPI ON
+< #     CACHE BOOL "Build with MPI enabled" FORCE)
+---
+> set( DAKOTA_HAVE MPI OFF
+>      CACHE BOOL "Build with MPI disabled" FORCE)
+91,93c91,93
+< #set( CMAKE_INSTALL_PREFIX
+< #     "/path/to/Dakota/installation"
+< #     CACHE PATH "Path to Dakota installation" )
+---
+> set( CMAKE_INSTALL_PREFIX
+>      "$ENV{ISSM_DIR}/externalpackages/dakota/install"
+>      CACHE PATH "Path to Dakota installation" )
Index: /issm/trunk/externalpackages/dakota/configs/5.3.1/CMakeLists.txt.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3.1/CMakeLists.txt.patch	(revision 19105)
+++ /issm/trunk/externalpackages/dakota/configs/5.3.1/CMakeLists.txt.patch	(revision 19105)
@@ -0,0 +1,4 @@
+47a48,50
+> set(BUILD_STATIC_LIBS ON CACHE BOOL "Set to ON to build static libraries" FORCE)
+> set(BUILD_SHARED_LIBS OFF CACHE BOOL "Set to ON to build DSO libraries" FORCE)
+> 
Index: /issm/trunk/externalpackages/dakota/install-5.3.1-macosx64-snowleopard.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-5.3.1-macosx64-snowleopard.sh	(revision 19105)
+++ /issm/trunk/externalpackages/dakota/install-5.3.1-macosx64-snowleopard.sh	(revision 19105)
@@ -0,0 +1,62 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf build 
+rm -rf install 
+mkdir src build install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/dakota-5.3.1-public-src.tar.gz' 'dakota-5.3.1-public-src.tar.gz'
+
+#Untar 
+tar -zxvf dakota-5.3.1-public-src.tar.gz
+
+#Move Dakota to src directory
+mv dakota-5.3.1.src/* src
+rm -rf dakota-5.3.1.src
+
+#Set up Dakota cmake variables and config
+export DAK_SRC=$ISSM_DIR/externalpackages/dakota/src
+export DAK_BUILD=$ISSM_DIR/externalpackages/dakota/build
+cp $DAK_SRC/cmake/BuildDakotaTemplate.cmake $DAK_SRC/cmake/BuildDakotaCustom.cmake
+patch $DAK_SRC/cmake/BuildDakotaCustom.cmake configs/5.3.1/BuildDakotaCustom.cmake.mac.patch
+patch $DAK_SRC/cmake/DakotaDev.cmake configs/5.3.1/DakotaDev.cmake.patch
+
+#Apply patches
+patch src/src/ParallelLibrary.cpp configs/5.3.1/ParallelLibrary.cpp.patch
+patch src/src/ParallelLibrary.hpp configs/5.3.1/ParallelLibrary.hpp.patch
+patch src/src/NonDSampling.cpp configs/5.3.1/NonDSampling.cpp.patch
+patch src/src/NonDLocalReliability.cpp configs/5.3.1/NonDLocalReliability.cpp.patch
+patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.3.1/pecos_global_defs.hpp.patch
+
+export BOOST_ROOT=$ISSM_DIR/externalpackages/boost/install
+
+#Configure dakota
+# Set your local gcc compiler here
+cd $DAK_BUILD
+cmake -DBoost_NO_BOOST_CMAKE=TRUE \
+    -DBoost_NO_SYSTEM_PATHS=TRUE \
+    -DBOOST_ROOT:PATHNAME=$BOOST_ROOT \
+    -DBoost_LIBRARY_DIRS:FILEPATH=${BOOST_ROOT}/lib \
+	 -DCMAKE_CXX_COMPILER=/usr/bin/g++ -DCMAKE_CC_COMPILER=/usr/bin/gcc \
+	 -DCMAKE_Fortran_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-gfortran \
+    -C $DAK_SRC/cmake/BuildDakotaCustom.cmake -C $DAK_SRC/cmake/DakotaDev.cmake $DAK_SRC
+
+#-DCMAKE_CXX_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-g++ -DCMAKE_Fortran_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-gfortran
+
+cd ..
+
+#Compile and install dakota
+cd $DAK_BUILD
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
Index: /issm/trunk/externalpackages/dakota/install-5.3.1-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-5.3.1-macosx64.sh	(revision 19104)
+++ /issm/trunk/externalpackages/dakota/install-5.3.1-macosx64.sh	(revision 19105)
@@ -23,6 +23,7 @@
 export DAK_BUILD=$ISSM_DIR/externalpackages/dakota/build
 cp $DAK_SRC/cmake/BuildDakotaTemplate.cmake $DAK_SRC/cmake/BuildDakotaCustom.cmake
-patch $DAK_SRC/cmake/BuildDakotaCustom.cmake configs/5.3.1/BuildDakotaCustom.cmake.patch
+patch $DAK_SRC/cmake/BuildDakotaCustom.cmake configs/5.3.1/BuildDakotaCustom.cmake.mac.patch
 patch $DAK_SRC/cmake/DakotaDev.cmake configs/5.3.1/DakotaDev.cmake.patch
+patch $DAK_SRC/CMakeLists.txt configs/5.3.1/CMakeLists.txt.patch
 
 #Apply patches
@@ -33,7 +34,18 @@
 patch src/packages/pecos/src/pecos_global_defs.hpp configs/5.3.1/pecos_global_defs.hpp.patch
 
+export BOOST_ROOT=$ISSM_DIR/externalpackages/boost/install
+
 #Configure dakota
+# Set your local gcc compiler here
 cd $DAK_BUILD
-cmake -D CMAKE_C_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-gcc -D CMAKE_CXX_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-g++ -D CMAKE_Fortran_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-gfortran -C $DAK_SRC/cmake/BuildDakotaCustom.cmake -C $DAK_SRC/cmake/DakotaDev.cmake $DAK_SRC
+cmake -DBoost_NO_BOOST_CMAKE=TRUE \
+    -DBoost_NO_SYSTEM_PATHS=TRUE \
+    -DBOOST_ROOT:PATHNAME=$BOOST_ROOT \
+    -DBoost_LIBRARY_DIRS:FILEPATH=${BOOST_ROOT}/lib \
+	 -DCMAKE_CXX_COMPILER=g++ -DCMAKE_CC_COMPILER=gcc \
+    -C $DAK_SRC/cmake/BuildDakotaCustom.cmake -C $DAK_SRC/cmake/DakotaDev.cmake $DAK_SRC
+
+#-DCMAKE_CXX_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-g++ -DCMAKE_Fortran_COMPILER=/usr/local/gfortran/bin/x86_64-apple-darwin10-gfortran
+
 cd ..
 
Index: /issm/trunk/externalpackages/distribute/README
===================================================================
--- /issm/trunk/externalpackages/distribute/README	(revision 19105)
+++ /issm/trunk/externalpackages/distribute/README	(revision 19105)
@@ -0,0 +1,9 @@
+At: https://pypi.python.org/pypi/setuptools
+
+Installation Instructions
+
+The recommended way to bootstrap setuptools on any system is to download ez_setup.py and run it using the target Python environment. Different operating systems have different recommended techniques to accomplish this basic routine, so below are some examples to get you started.
+
+Setuptools requires Python 2.6 or later. To install setuptools on Python 2.4 or Python 2.5, use the bootstrap script for Setuptools 1.x.
+
+The link provided to ez_setup.py is a bookmark to bootstrap script for the latest known stable release.
Index: /issm/trunk/externalpackages/export_fig/LICENSE
===================================================================
--- /issm/trunk/externalpackages/export_fig/LICENSE	(revision 19105)
+++ /issm/trunk/externalpackages/export_fig/LICENSE	(revision 19105)
@@ -0,0 +1,27 @@
+Copyright (c) 2014, Oliver J. Woodford
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+  list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+  this list of conditions and the following disclaimer in the documentation
+  and/or other materials provided with the distribution.
+
+* Neither the name of the {organization} nor the names of its
+  contributors may be used to endorse or promote products derived from
+  this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Index: /issm/trunk/externalpackages/export_fig/README.md
===================================================================
--- /issm/trunk/externalpackages/export_fig/README.md	(revision 19105)
+++ /issm/trunk/externalpackages/export_fig/README.md	(revision 19105)
@@ -0,0 +1,259 @@
+export_fig
+==========
+
+A toolbox for exporting figures from MATLAB to standard image and document formats nicely.
+
+### Overview
+Exporting a figure from MATLAB the way you want it (hopefully the way it looks on screen), can be a real headache for the unitiated, thanks to all the settings that are required, and also due to some eccentricities (a.k.a. features and bugs) of functions such as `print`. The first goal of export_fig is to make transferring a plot from screen to document, just the way you expect (again, assuming that's as it appears on screen), a doddle.
+  
+The second goal is to make the output media suitable for publication, allowing you to publish your results in the full glory that you originally intended. This includes embedding fonts, setting image compression levels (including lossless), anti-aliasing, cropping, setting the colourspace, alpha-blending and getting the right resolution.
+
+Perhaps the best way to demonstrate what export_fig can do is with some examples.
+  
+### Examples
+**Visual accuracy** - MATLAB's exporting functions, namely `saveas` and `print`, change many visual properties of a figure, such as size, axes limits and ticks, and background colour, in unexpected and unintended ways. Export_fig aims to faithfully reproduce the figure as it appears on screen. For example:  
+```Matlab
+plot(cos(linspace(0, 7, 1000)));
+set(gcf, 'Position', [100 100 150 150]);
+saveas(gcf, 'test.png');
+export_fig test2.png
+```
+generates the following:
+
+| Figure: | test.png: | test2.png: |
+|:-------:|:---------:|:----------:|
+|![](https://farm6.staticflickr.com/5616/15589249291_16e485c29a_o_d.png)|![](https://farm4.staticflickr.com/3944/15406302850_4d2e1c7afa_o_d.png)|![](https://farm6.staticflickr.com/5607/15568225476_8ce9bd5f6b_o_d.png)|
+
+Note that the size and background colour of test2.png (the output of export_fig) are the same as those of the on screen figure, in contrast to test.png. Of course, if you want want the figure background to be white (or any other colour) in the exported file then you can set this prior to exporting using:
+```Matlab
+set(gcf, 'Color', 'w');
+```
+  
+Notice also that export_fig crops and anti-aliases (smooths, for bitmaps only) the output by default. However, these options can be disabled; see the Tips section below for details.
+  
+**Resolution** - by default, export_fig exports bitmaps at screen resolution. However, you may wish to save them at a different resolution. You can do this using either of two options: `-m<val>`, where <val> is a positive real number, magnifies the figure by the factor <val> for export, e.g. `-m2` produces an image double the size (in pixels) of the on screen figure; `-r<val>`, again where <val> is a positive real number, specifies the output bitmap to have <val> pixels per inch, the dimensions of the figure (in inches) being those of the on screen figure. For example, using:  
+```Matlab
+export_fig test.png -m2.5
+```
+on the figure from the example above generates:
+
+![](https://farm4.staticflickr.com/3937/15591910915_dc7040c477_o_d.png)
+
+Sometimes you might have a figure with an image in. For example:
+```Matlab
+imshow(imread('cameraman.tif'))
+hold on
+plot(0:255, sin(linspace(0, 10, 256))*127+128);
+set(gcf, 'Position', [100 100 150 150]);
+```
+generates this figure:
+
+![](https://farm4.staticflickr.com/3942/15589249581_ff87a56a3f_o_d.png)
+  
+Here the image is displayed in the figure at resolution lower than its native resolution. However, you might want to export the figure at a resolution such that the image is output at its native (i.e. original) size (in pixels). Ordinarily this would require some non-trivial computation to work out what that resolution should be, but export_fig has an option to do this for you. Using:
+```Matlab
+export_fig test.png -native
+```
+produces:
+
+![](https://farm6.staticflickr.com/5604/15589249591_da2b2652e4_o_d.png)
+
+with the image being the size (in pixels) of the original image. Note that if you want an image to be a particular size, in pixels, in the output (other than its original size) then you can resize it to this size and use the `-native` option to achieve this.
+
+All resolution options (`-m<val>`, `-q<val>` and `-native`) correctly set the resolution information in PNG and TIFF files, as if the image were the dimensions of the on screen figure.
+
+**Shrinking dots & dashes** - when exporting figures with dashed or dotted lines using either the ZBuffer or OpenGL (default for bitmaps) renderers, the dots and dashes can appear much shorter, even non-existent, in the output file, especially if the lines are thick and/or the resolution is high. For example:  
+```Matlab
+plot(sin(linspace(0, 10, 1000)), 'b:', 'LineWidth', 4);
+hold on
+plot(cos(linspace(0, 7, 1000)), 'r--', 'LineWidth', 3);
+grid on
+export_fig test.png
+```
+generates:
+
+![](https://farm4.staticflickr.com/3956/15592747732_f943d4aa0a_o_d.png)
+
+This problem can be overcome by using the painters renderer. For example:
+```Matlab
+export_fig test.png -painters
+```
+used on the same figure generates:
+
+![](https://farm4.staticflickr.com/3945/14971168504_77692f11f5_o_d.png)
+
+Note that not only are the plot lines correct, but the grid lines are too.
+
+**Transparency** - sometimes you might want a figure and axes' backgrounds to be transparent, so that you can see through them to a document (for example a presentation slide, with coloured or textured background) that the exported figure is placed in. To achieve this, first (optionally) set the axes' colour to 'none' prior to exporting, using:  
+```Matlab
+set(gca, 'Color', 'none'); % Sets axes background
+```
+    
+then use export_fig's `-transparent` option when exporting:
+```Matlab
+export_fig test.png -transparent
+```
+
+This will make the background transparent in PDF, EPS and PNG outputs. You can additionally save fully alpha-blended semi-transparent patch objects to the PNG format. For example:
+
+```Matlab
+logo;
+alpha(0.5);
+```
+
+generates a figure like this:
+
+![](https://farm4.staticflickr.com/3933/15405290339_b08de33528_o_d.png)
+
+If you then export this to PNG using the `-transparent` option you can then put the resulting image into, for example, a presentation slide with fancy, textured background, like so:
+
+![](https://farm6.staticflickr.com/5599/15406302920_59beaefff1_o_d.png)
+
+and the image blends seamlessly with the background.
+
+**Image quality** - when publishing images of your results, you want them to look as good as possible. By default, when outputting to lossy file formats (PDF, EPS and JPEG), export_fig uses a high quality setting, i.e. low compression, for images, so little information is lost. This is in contrast to MATLAB's print and saveas functions, whose default quality settings are poor. For example:
+```Matlab
+A = im2double(imread('peppers.png'));
+B = randn(ceil(size(A, 1)/6), ceil(size(A, 2)/6), 3) * 0.1;
+B = cat(3, kron(B(:,:,1), ones(6)), kron(B(:,:,2), ones(6)), kron(B(:,:,3), ones(6)));
+B = A + B(1:size(A, 1),1:size(A, 2),:);
+imshow(B);
+print -dpdf test.pdf
+```
+generates a PDF file, a sub-window of which looks (when zoomed in) like this:
+
+![](https://farm6.staticflickr.com/5613/15405290309_881b2774d6_o_d.png)
+
+while the command
+
+```Matlab
+export_fig test.pdf
+```
+on the same figure produces this:
+
+![](https://farm4.staticflickr.com/3947/14971168174_687473133f_o_d.png)
+
+While much better, the image still contains some compression artifacts (see the low level noise around the edge of the pepper). You may prefer to export with no artifacts at all, i.e. lossless compression. Alternatively, you might need a smaller file, and be willing to accept more compression. Either way, export_fig has an option that can suit your needs: `-q<val>`, where <val> is a number from 0-100, will set the level of lossy image compression (again in PDF, EPS and JPEG outputs only; other formats are lossless), from high compression (0) to low compression/high quality (100). If you want lossless compression in any of those formats then specify a <val> greater than 100. For example:
+```Matlab
+export_fig test.pdf -q101
+```
+again on the same figure, produces this:
+
+![](https://farm6.staticflickr.com/5608/15405803908_934512c1fe_o_d.png)
+
+Notice that all the noise has gone.
+
+### Tips
+**Anti-aliasing** - the anti-aliasing which export_fig applies to bitmap outputs by default makes the images look nice, but it can also blur images and increase exporting time and memory requirements, so you might not always want it. You can set the level of anti-aliasing by using the `-a<val>` option, where <val> is 1 (no anti-aliasing), 2, 3 (default) or 4 (maximum anti-aliasing).  
+  
+**Cropping** - by default, export_fig crops its output to minimize the amount of empty space around the figure. If you'd prefer the figure to be uncropped, and instead have the same appearance (in terms of border width) as the on screen figure, then use the `-nocrop` option.  
+  
+**Colourspace** - by default, export_fig generates files in the RGB [colourspace](http://en.wikipedia.org/wiki/Color_space). However, you can also export in greyscale or the CMYK colourspace, using the `-grey` (or `-gray`) and `-cmyk` options respectively. The CMYK option is useful for publishers who require documents in this colourspace, but the option is only supported for PDF, EPS and TIFF files.
+
+**Specifying a target directory** - you can get export_fig to save output files to any directory (for which you have write permission), simply by specifying the full or relative path in the filename. For example:
+```Matlab
+export_fig ../subdir/fig.png;
+export_fig('C:/Users/Me/Documents/figures/myfig', '-pdf', '-png');
+```
+
+**Variable file names** - often you might want to save a series of figures in a for loop, each with a different name. For this you can use the functional form of input arguments, i.e. `export_fig(arg1, arg2)`,  and construct the filename string in a variable. Here's an example of this:  
+```Matlab
+for a = 1:5
+    plot(rand(5, 2));
+    export_fig(sprintf('plot%d.png', a));
+end
+```
+When using the functional form like this, be sure to put string variables in quotes:
+```Matlab
+export_fig(sprintf('plot%d', a), '-a1', '-pdf', '-png');
+```
+
+**Specifying the figure/axes** - if you have mutiple figures open you can specify which figure to export using its handle:  
+```Matlab
+export_fig(figure_handle, 'filename.fmt');
+```
+Equally, if your figure contains several subplots then you can export just one of them by giving export_fig the handle to the relevant axes:
+```Matlab
+export_fig(axes_handle, 'filename.fmt');
+```
+
+**Multiple formats** - save time by exporting to multiple formats simultaneously. E.g.: 
+```Matlab
+export_fig filename -pdf -eps -png -jpg -tiff
+```
+
+**Other file formats** - if you'd like to save your figure to a bitmap format that is not supported by export_fig, e.g. animated GIF, PPM file or a frame in a movie, then you can use export_fig to output the image, and optionally an alpha-matte, to the workspace. E.g.:  
+```Matlab
+frame = export_fig;
+```
+or
+```Matlab
+[frame, alpha] = export_fig;
+```
+These variables can then be saved to other image formats using other functions, such as imwrite.
+
+**Appending to a file** - you can use the `-append` option to append the figure to the end of an image/document, if it already exists. This is supported for PDF and TIFF files only. Note that if you wish to append a lot of figures consecutively to a PDF, it can be more efficient to save all the figures to PDF separately then append them all in one go at the end (e.g. using [append_pdfs](http://www.mathworks.com/matlabcentral/fileexchange/31215-appendpdfs)).  
+  
+**Font size** - if you want to place an exported figure in a document with the font a particular size then you need to set the font to that size in the figure, and not resize the output of export_fig in the document. To avoid resizing, simply make sure that the on screen figure is the size you want the output to be in the document before exporting.  
+  
+**Renderers** - MATLAB has three renderers for displaying and exporting figures: painters, OpenGL and ZBuffer. The different renderers have different [features](http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/f3-84337.html#f3-102410), so if you aren't happy with the result from one renderer try another. By default, vector formats (i.e. PDF and EPS outputs) use the painters renderer, while other formats use the OpenGL renderer. Non-default renderers can be selected by using one of these three export_fig input options: `-painters`, `-opengl`, `-zbuffer`.  
+  
+**Artifacts** - sometimes the output that you get from export_fig is not what you expected. If an output file contains artifacts that aren't in the on screen figure then make sure that the renderer used for rendering the figure on screen is the same as that used for exporting. To set the renderer used to display the figure, use:  
+```Matlab
+set(figure_handle, 'Renderer', 'opengl');
+```
+After matching the two renderers, if the artifact appears in the on screen figure then you'll need to fix that before exporting. Alternatively you can try changing the renderer used by export_fig. Finally check that it isn't one of the known issues mentioned in the section below.
+
+**Smoothed/interpolated images in output PDF** - if you produce a PDF using export_fig and images in the PDF look overly smoothed or interpolated, this is because the software you are using to view the PDF is smoothing or interpolating the image data. The image is not smoothed in the PDF file itself. If the software has an option to disable this feature, you should select it. Alternatively, use another PDF viewer that doesn't exhibit this problem.  
+  
+**Locating Ghostscript/pdftops** - You may find a dialogue box appears when using export_fig, asking you to locate either [Ghostscript](http://www.ghostscript.com) or [pdftops](http://www.foolabs.com/xpdf). These are separate applications which export_fig requires to perform certain functions. If such a dialogue appears it is because export_fig can't find the application automatically. This is because you either haven't installed it, or it isn't in the normal place. Make sure you install the applications correctly first. They can be downloaded from the following places:  
+ 1. Ghostscript:     [www.ghostscript.com](http://www.ghostscript.com)
+ 2. pdftops (install the Xpdf package): [www.foolabs.com/xpdf](http://www.foolabs.com/xpdf)
+
+If you choose to install them in a non-default location then point export_fig
+to this location using the dialogue box.
+
+**Undefined function errors** - If you download and run export_fig and get an error similar to this:  
+```Matlab
+??? Undefined function or method 'print2array' for input arguments of type 'double'.
+```
+then you are missing one or more of the files that come in the export_fig package. Make sure that you click the "Get from GitHub" button at the top-right of the download [page](http://www.mathworks.co.uk/matlabcentral/fileexchange/23629-exportfig), then extract all the files in the zip file to the same directory. You should then have all the necessary files.
+  
+### Known issues
+There are lots of problems with MATLAB's exporting functions, and unfortunately export_fig, which is simply a glorified wrapper for MATLAB's print function, doesn't solve all of them (yet?). Some of the problems I know about are:
+  
+**Fonts** - when using the painters renderer, MATLAB can only export a small number of fonts, details of which can be found [here](http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/f3-103191.html#f3-96545). Export_fig attempts to correct font names in the resulting EPS file (for upto a maximum of 11 different fonts in one figure), but this is not always guaranteed to work. In particular, the text positions will be affected. It also does not work for text blocks where the 'Interpreter' property is set to 'latex'.
+
+Also, when using the painters renderer, ghostscript will sometimes throw an error such as `Error: /undefined in /findfont`. This suggests that ghostscript could not find a definition file for one of your fonts. One possible fix for this is to make sure the file `EXPORT_FIG_PATH/.ignore/gs_font_path.txt` exists and contains a list of paths to the folder(s) containing the necessary font definitions (make sure they're TrueType definitions), separated by a semicolon.
+
+**RGB color data not yet supported in Painter's mode** - you will see this as a warning if you try to export a figure which contains patch objects whose face or vertex colors are specified as a an RGB colour, rather than an index into the colormap, using the painters renderer (the default renderer for vector output). This problem can arise if you use `pcolor`, for example. This is a problem with MATLAB's painters renderer, which also affects `print`; there is currently no fix available in export_fig (other than to export to bitmap). The suggested workaround is to avoid colouring patches using RGB. First, try to use colours in the figure's colourmap (instructions [here](http://www.mathworks.co.uk/support/solutions/en/data/1-6OTPQE/)) - change the colourmap, if necessary. If you are using `pcolor`, try using [uimagesc](http://www.mathworks.com/matlabcentral/fileexchange/11368) (on the file exchange) instead.  
+
+**Dashed contour lines appear solid** - when using the painters renderer, MATLAB cannot generate dashed lines using the `contour` function (either on screen or in exported PDF and EPS files). Details can be found [here](http://www.mathworks.com/support/solutions/en/data/1-14PPHB/?solution=1-14PPHB).  
+  
+**Text size** - when using the OpenGL or ZBuffer renderers, large text can be resized relative to the figure when exporting at non-screen-resolution (including using anti-alising at screen resolution). This is a feature of MATLAB's `print `function. In this case, try using the `-painters` option.  
+  
+**Lighting and transparency** - when using the painters renderer, transparency and lighting effects are not supported. Sorry, but this is a feature of the renderer. To find out more about the capabilities of each rendering method, see [here](http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/f3-84337.html#f3-102410). You can still export transparent objects to vector format (SVG) using the excellent [plot2svg](http://www.mathworks.com/matlabcentral/fileexchange/7401) package, then convert this to PDF, for example using [Inkscape](http://inkscape.org/). However, it can't handle lighting.  
+  
+**Lines in patch objects** - when exporting patch objects to PDF using the painters renderer (default), sometimes the output can appear to have lines across the middle of rectangular patches; these lines are the colour of the background, as if there is a crack in the patch, allowing you to see through. This issue is a feature of the software used to display the PDF, rather than the PDF itself. Sometimes disabling anti-aliasing in this software can get rid of the lines.  
+  
+**Out of memory** - if you run into memory issues when using export_fig, some ways to get round this are:  
+ 1. Reduce the level of anti-aliasing.
+ 2. Reduce the size of the on screen figure.
+ 3. Reduce the resolution (dpi) the figure is exported at.  
+  
+**Errors** - the other common type of errors people get with export_fig are OpenGL errors. This isn't a fault of export_fig, but either a bug in MATLAB's `print`, or your graphics driver getting itself into a state. Always make sure your graphics driver is up-to-date. If it still doesn't work, try using the ZBuffer renderer.  
+  
+### Raising issues
+If you think you have found a genuine error or issue with export_fig **that is not listed above**, first ensure that the figure looks correct on screen when rendered using the renderer that export_fig is set to use (e.g. if exporting to PDF or EPS, does the figure look correct on screen using the painters renderer, or if exporting to bitmap, does the figure look correct on screen using the OpenGL renderer?). If it looks wrong then the problem is there, and I cannot help (other than to suggest you try exporting using a different renderer).
+
+Secondly, if exporting to bitmap, do try all the renderers (i.e. try the options `-opengl`, `-zbuffer` and `-painters` separately), to see if one of them does produce an acceptable output, and if so, use that.
+
+If the figure looks correct on screen, but an error exists in the exported output (which cannot be solved using a different renderer) then please feel free to raise an [issue](https://github.com/ojwoodford/export_fig/issues). Please be sure to include the .fig file, the export_fig command you use, the output you get, and a description of what you expected. I can't promise anything, but if it's easy to fix I probably will do it. Often I will find that the error is due to a bug in MATLAB's print function, in which case I will suggest you submit it as a bug to TheMathWorks, and inform me of any fix they suggest. Also, if there's a feature you'd like that isn't supported please tell me what it is and I'll consider implementing it.
+
+### And finally...
+
+![](https://farm4.staticflickr.com/3956/15591911455_b9008bd77e_o_d.jpg)
+
+If you've ever wondered what's going on in the icon on the export_fig download page (reproduced on the left), then this explanantion is for you. The icon is designed to demonstrate as many of export_fig's features as possible. Given a
+figure containing a translucent mesh (top right), export_fig can export to pdf (bottom centre), which allows the figure to be zoomed in without losing quality (because it's a vector graphic), but isn't able to reproduce the translucency, and also, depending on the viewer, creates small gaps between the patches, which are seen here as thin white lines. By contrast, when exporting to png (top left), translucency is preserved (see how the graphic below shows through), the figure is anti-aliased, but zooming in does not reveal more detail.
+
Index: /issm/trunk/externalpackages/export_fig/append_pdfs.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/append_pdfs.m	(revision 19105)
+++ /issm/trunk/externalpackages/export_fig/append_pdfs.m	(revision 19105)
@@ -0,0 +1,58 @@
+%APPEND_PDFS Appends/concatenates multiple PDF files
+%
+% Example:
+%   append_pdfs(output, input1, input2, ...)
+%   append_pdfs(output, input_list{:})
+%   append_pdfs test.pdf temp1.pdf temp2.pdf
+%
+% This function appends multiple PDF files to an existing PDF file, or
+% concatenates them into a PDF file if the output file doesn't yet exist.
+%
+% This function requires that you have ghostscript installed on your
+% system. Ghostscript can be downloaded from: http://www.ghostscript.com
+%
+% IN:
+%    output - string of output file name (including the extension, .pdf).
+%             If it exists it is appended to; if not, it is created.
+%    input1 - string of an input file name (including the extension, .pdf).
+%             All input files are appended in order.
+%    input_list - cell array list of input file name strings. All input
+%                 files are appended in order.
+
+% Copyright: Oliver Woodford, 2011
+
+% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in
+% one go is much faster than appending them one at a time.
+
+% Thanks to Michael Teo for reporting the issue of a too long command line.
+% Issue resolved on 5/5/2011, by passing gs a command file.
+
+% Thanks to Martin Wittmann for pointing out the quality issue when
+% appending multiple bitmaps.
+% Issue resolved (to best of my ability) 1/6/2011, using the prepress
+% setting
+
+function append_pdfs(varargin)
+% Are we appending or creating a new file
+append = exist(varargin{1}, 'file') == 2;
+if append
+    output = [tempname '.pdf'];
+else
+    output = varargin{1};
+    varargin = varargin(2:end);
+end
+% Create the command file
+cmdfile = [tempname '.txt'];
+fh = fopen(cmdfile, 'w');
+fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
+fprintf(fh, ' "%s"', varargin{:});
+fclose(fh);
+% Call ghostscript
+ghostscript(['@"' cmdfile '"']);
+% Delete the command file
+delete(cmdfile);
+% Rename the file if needed
+if append
+    movefile(output, varargin{1});
+end
+end
Index: /issm/trunk/externalpackages/export_fig/copyfig.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/copyfig.m	(revision 19104)
+++ /issm/trunk/externalpackages/export_fig/copyfig.m	(revision 19105)
@@ -21,5 +21,5 @@
 end
 % Is there a legend?
-if isempty(findobj(fh, 'Type', 'axes', 'Tag', 'legend'))
+if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'))
     % Safe to copy using copyobj
     fh = copyobj(fh, 0);
@@ -31,3 +31,3 @@
     delete(tmp_nam);
 end
-return
+end
Index: /issm/trunk/externalpackages/export_fig/crop_borders.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/crop_borders.m	(revision 19105)
+++ /issm/trunk/externalpackages/export_fig/crop_borders.m	(revision 19105)
@@ -0,0 +1,81 @@
+%CROP_BORDERS Crop the borders of an image or stack of images
+%
+%   [B, v] = crop_borders(A, bcol, [padding])
+%
+%IN:
+%   A - HxWxCxN stack of images.
+%   bcol - Cx1 background colour vector.
+%   padding - scalar indicating how many pixels padding to have. Default: 0.
+%
+%OUT:
+%   B - JxKxCxN cropped stack of images.
+%   v - 1x4 vector of start and end indices for first two dimensions, s.t.
+%       B = A(v(1):v(2),v(3):v(4),:,:).
+
+function [A, v] = crop_borders(A, bcol, padding)
+if nargin < 3
+    padding = 0;
+end
+[h, w, c, n] = size(A);
+if isscalar(bcol)
+    bcol = bcol(ones(c, 1));
+end
+bail = false;
+for l = 1:w
+    for a = 1:c
+        if ~all(col(A(:,l,a,:)) == bcol(a))
+            bail = true;
+            break;
+        end
+    end
+    if bail
+        break;
+    end
+end
+bcol = A(ceil(end/2),w,:,1);
+bail = false;
+for r = w:-1:l
+    for a = 1:c
+        if ~all(col(A(:,r,a,:)) == bcol(a))
+            bail = true;
+            break;
+        end
+    end
+    if bail
+        break;
+    end
+end
+bcol = A(1,ceil(end/2),:,1);
+bail = false;
+for t = 1:h
+    for a = 1:c
+        if ~all(col(A(t,:,a,:)) == bcol(a))
+            bail = true;
+            break;
+        end
+    end
+    if bail
+        break;
+    end
+end
+bcol = A(h,ceil(end/2),:,1);
+bail = false;
+for b = h:-1:t
+    for a = 1:c
+        if ~all(col(A(b,:,a,:)) == bcol(a))
+            bail = true;
+            break;
+        end
+    end
+    if bail
+        break;
+    end
+end
+% Crop the background, leaving one boundary pixel to avoid bleeding on resize
+v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)];
+A = A(v(1):v(2),v(3):v(4),:,:);
+end
+
+function A = col(A)
+A = A(:);
+end
Index: /issm/trunk/externalpackages/export_fig/eps2pdf.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/eps2pdf.m	(revision 19104)
+++ /issm/trunk/externalpackages/export_fig/eps2pdf.m	(revision 19105)
@@ -84,9 +84,9 @@
     try
         % Convert to pdf using ghostscript
-        [status message] = ghostscript(options);
-    catch
+        [status, message] = ghostscript(options);
+    catch me
         % Delete the intermediate file
         delete(tmp_nam);
-        rethrow(lasterror);
+        rethrow(me);
     end
     % Delete the intermediate file
@@ -97,5 +97,5 @@
     options = [options ' -f "' source '"'];
     % Convert to pdf using ghostscript
-    [status message] = ghostscript(options);
+    [status, message] = ghostscript(options);
 end
 % Check for error
@@ -108,5 +108,5 @@
     end
 end
-return
+end
 
 % Function to return (and create, where necessary) the font path
@@ -132,3 +132,3 @@
 end
 user_string('gs_font_path', fp);
-return
+end
Index: /issm/trunk/externalpackages/export_fig/export_fig.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/export_fig.m	(revision 19104)
+++ /issm/trunk/externalpackages/export_fig/export_fig.m	(revision 19105)
@@ -13,4 +13,5 @@
 %   export_fig ... -a<val>
 %   export_fig ... -q<val>
+%   export_fig ... -p<val>
 %   export_fig ... -<renderer>
 %   export_fig ... -<colorspace>
@@ -85,11 +86,11 @@
 %                  made transparent (png, pdf and eps output only).
 %   -m<val> - option where val indicates the factor to magnify the
-%             on-screen figure dimensions by when generating bitmap
+%             on-screen figure pixel dimensions by when generating bitmap
 %             outputs. Default: '-m1'.
 %   -r<val> - option val indicates the resolution (in pixels per inch) to
-%             export bitmap outputs at, keeping the dimensions of the
-%             on-screen figure. Default: sprintf('-r%g', get(0,
-%             'ScreenPixelsPerInch')). Note that the -m and -r options
-%             change the same property.
+%             export bitmap and vector outputs at, keeping the dimensions
+%             of the on-screen figure. Default: '-r864' (for vector output
+%             only). Note that the -m option overides the -r option for
+%             bitmap outputs only.
 %   -native - option indicating that the output resolution (when outputting
 %             a bitmap format) should be such that the vertical resolution
@@ -118,4 +119,7 @@
 %             sometimes give a smaller file size than the default lossy
 %             compression, depending on the type of images.
+%   -p<val> - option to add a border of width val to eps and pdf files,
+%             where val is in units of the intermediate eps file. Default:
+%             0 (i.e. no padding).
 %   -append - option indicating that if the file (pdfs only) already
 %             exists, the figure is to be appended as a new page, instead
@@ -133,9 +137,9 @@
 %
 %   Some helpful examples and tips can be found at:
-%      http://sites.google.com/site/oliverwoodford/software/export_fig
+%      https://github.com/ojwoodford/export_fig
 %
 %   See also PRINT, SAVEAS.
 
-% Copyright (C) Oliver Woodford 2008-2012
+% Copyright (C) Oliver Woodford 2008-2014
 
 % The idea of using ghostscript is inspired by Peder Axensten's SAVEFIG
@@ -168,4 +172,8 @@
 % 12/12/12: Add support for isolating uipanels. Thanks to michael for
 %           suggesting it.
+% 25/09/13: Add support for changing resolution in vector formats. Thanks
+%           to Jan Jaap Meijer for suggesting it.
+% 07/05/14: Add support for '~' at start of path. Thanks to Sally Warner
+%           for suggesting it.
 
 function [im, alpha] = export_fig(varargin)
@@ -217,5 +225,8 @@
 end
 % Set all axes limit and tick modes to manual, so the limits and ticks can't change
-set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual', 'XTickMode', 'manual', 'YTickMode', 'manual', 'ZTickMode', 'manual');
+set(Hlims, 'XLimMode', 'manual', 'YLimMode', 'manual', 'ZLimMode', 'manual');
+set_tick_mode(Hlims, 'X');
+set_tick_mode(Hlims, 'Y');
+set_tick_mode(Hlims, 'Z');
 % Set to print exactly what is there
 set(fig, 'InvertHardcopy', 'off');
@@ -289,5 +300,5 @@
         % Crop the background
         if options.crop
-            [alpha, v] = crop_background(alpha, 0);
+            [alpha, v] = crop_borders(alpha, 0, 1);
             A = A(v(1):v(2),v(3):v(4),:);
         end
@@ -336,5 +347,5 @@
         % Crop the background
         if options.crop
-            A = crop_background(A, tcol);
+            A = crop_borders(A, tcol, 1);
         end
         % Downscale the image
@@ -406,5 +417,5 @@
     end
     % Generate the options for print
-    p2eArgs = {renderer};
+    p2eArgs = {renderer, sprintf('-r%d', options.resolution)};
     if options.colourspace == 1
         p2eArgs = [p2eArgs {'-cmyk'}];
@@ -415,8 +426,8 @@
     try
         % Generate an eps
-        print2eps(tmp_nam, fig, p2eArgs{:});
+        print2eps(tmp_nam, fig, options.bb_padding, p2eArgs{:});
         % Remove the background, if desired
         if options.transparent && ~isequal(get(fig, 'Color'), 'none')
-            eps_remove_background(tmp_nam);
+            eps_remove_background(tmp_nam, 1 + using_hg2(fig));
         end
         % Add a bookmark to the PDF if desired
@@ -465,5 +476,5 @@
     end
 end
-return
+end
 
 function [fig, options] = parse_args(nout, varargin)
@@ -485,6 +496,8 @@
                  'im', nout == 1, ...
                  'alpha', nout == 2, ...
-                 'aa_factor', 3, ...
-                 'magnify', 1, ...
+                 'aa_factor', 0, ...
+                 'bb_padding', 0, ...
+                 'magnify', [], ...
+                 'resolution', [], ...
                  'bookmark', false, ...
                  'quality', []);
@@ -535,5 +548,5 @@
                     native = true;
                 otherwise
-                    val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q))(\d*\.)?\d+(e-?\d+)?', 'match'));
+                    val = str2double(regexp(varargin{a}, '(?<=-(m|M|r|R|q|Q|p|P))-?\d*.?\d+', 'match'));
                     if ~isscalar(val)
                         error('option %s not recognised', varargin{a});
@@ -543,7 +556,9 @@
                             options.magnify = val;
                         case 'r'
-                            options.magnify = val ./ get(0, 'ScreenPixelsPerInch');
+                            options.resolution = val;
                         case 'q'
                             options.quality = max(val, 0);
+                        case 'p'
+                            options.bb_padding = val;
                     end
             end
@@ -573,4 +588,26 @@
 end
 
+% Set default anti-aliasing now we know the renderer
+if options.aa_factor == 0
+    options.aa_factor = 1 + 2 * (~(using_hg2(fig) && strcmp(get(ancestor(fig, 'figure'), 'GraphicsSmoothing'), 'on')) | (options.renderer == 3));
+end
+
+% Convert user dir '~' to full path
+if numel(options.name) > 2 && options.name(1) == '~' && (options.name(2) == '/' || options.name(2) == '\')
+    options.name = fullfile(char(java.lang.System.getProperty('user.home')), options.name(2:end));
+end
+
+% Compute the magnification and resolution
+if isempty(options.magnify)
+    if isempty(options.resolution)
+        options.magnify = 1;
+        options.resolution = 864;
+    else
+        options.magnify = options.resolution ./ get(0, 'ScreenPixelsPerInch');
+    end
+elseif isempty(options.resolution)
+    options.resolution = 864;
+end  
+
 % Check we have a figure handle
 if isempty(fig)
@@ -584,5 +621,5 @@
 
 % Check whether transparent background is wanted (old way)
-if isequal(get(ancestor(fig, 'figure'), 'Color'), 'none')
+if isequal(get(ancestor(fig(1), 'figure'), 'Color'), 'none')
     options.transparent = true;
 end
@@ -632,5 +669,5 @@
     end
 end
-return
+end
 
 function A = downsize(A, factor)
@@ -659,9 +696,9 @@
     A = A(1+floor(mod(end-1, factor)/2):factor:end,1+floor(mod(end-1, factor)/2):factor:end,:);
 end
-return
+end
 
 function A = rgb2grey(A)
 A = cast(reshape(reshape(single(A), [], 3) * single([0.299; 0.587; 0.114]), size(A, 1), size(A, 2)), class(A));
-return
+end
 
 function A = check_greyscale(A)
@@ -672,67 +709,7 @@
     A = A(:,:,1); % Save only one channel for 8-bit output
 end
-return
-
-function [A, v] = crop_background(A, bcol)
-% Map the foreground pixels
-[h, w, c] = size(A);
-if isscalar(bcol) && c > 1
-    bcol = bcol(ones(1, c));
-end
-bail = false;
-for l = 1:w
-    for a = 1:c
-        if ~all(A(:,l,a) == bcol(a))
-            bail = true;
-            break;
-        end
-    end
-    if bail
-        break;
-    end
-end
-bail = false;
-for r = w:-1:l
-    for a = 1:c
-        if ~all(A(:,r,a) == bcol(a))
-            bail = true;
-            break;
-        end
-    end
-    if bail
-        break;
-    end
-end
-bail = false;
-for t = 1:h
-    for a = 1:c
-        if ~all(A(t,:,a) == bcol(a))
-            bail = true;
-            break;
-        end
-    end
-    if bail
-        break;
-    end
-end
-bail = false;
-for b = h:-1:t
-    for a = 1:c
-        if ~all(A(b,:,a) == bcol(a))
-            bail = true;
-            break;
-        end
-    end
-    if bail
-        break;
-    end
-end
-% Crop the background, leaving one boundary pixel to avoid bleeding on
-% resize
-v = [max(t-1, 1) min(b+1, h) max(l-1, 1) min(r+1, w)];
-A = A(v(1):v(2),v(3):v(4),:);
-return
-
-function eps_remove_background(fname)
+end
+
+function eps_remove_background(fname, count)
 % Remove the background of an eps file
 % Open the file
@@ -742,5 +719,5 @@
 end
 % Read the file line by line
-while true
+while count
     % Get the next line
     l = fgets(fh);
@@ -749,23 +726,24 @@
     end
     % Check if the line contains the background rectangle
-    if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +rf *[\n\r]+', 'start'), 1)
+    if isequal(regexp(l, ' *0 +0 +\d+ +\d+ +r[fe] *[\n\r]+', 'start'), 1)
         % Set the line to whitespace and quit
         l(1:regexp(l, '[\n\r]', 'start', 'once')-1) = ' ';
         fseek(fh, -numel(l), 0);
         fprintf(fh, l);
-        break;
+        % Reduce the count
+        count = count - 1;
     end
 end
 % Close the file
 fclose(fh);
-return
+end
 
 function b = isvector(options)
 b = options.pdf || options.eps;
-return
+end
 
 function b = isbitmap(options)
 b = options.png || options.tif || options.jpg || options.bmp || options.im || options.alpha;
-return
+end
 
 % Helper function
@@ -774,5 +752,5 @@
     A = {A};
 end
-return
+end
 
 function add_bookmark(fname, bookmark_text)
@@ -808,3 +786,14 @@
 end
 fclose(fh);
-return
+end
+
+function set_tick_mode(Hlims, ax)
+% Set the tick mode of linear axes to manual
+% Leave log axes alone as these are tricky
+M = get(Hlims, [ax 'Scale']);
+if ~iscell(M)
+    M = {M};
+end
+M = cellfun(@(c) strcmp(c, 'linear'), M);
+set(Hlims(M), [ax 'TickMode'], 'manual');
+end
Index: /issm/trunk/externalpackages/export_fig/fix_lines.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/fix_lines.m	(revision 19104)
+++ /issm/trunk/externalpackages/export_fig/fix_lines.m	(revision 19105)
@@ -1,3 +1,2 @@
-function fix_lines(fname, fname2)
 %FIX_LINES  Improves the line style of eps files generated by print
 %
@@ -5,4 +4,5 @@
 %   fix_lines fname
 %   fix_lines fname fname2
+%   fstrm_out = fixlines(fstrm_in)
 %
 % This function improves the style of lines in eps files generated by
@@ -16,9 +16,13 @@
 % information.
 %
-% IN:
+%IN:
 %   fname - Name or path of source eps file.
 %   fname2 - Name or path of destination eps file. Default: same as fname.
+%   fstrm_in - File contents of a MATLAB-generated eps file.
+%
+%OUT:
+%   fstrm_out - Contents of the eps file with line styles fixed.
 
-% Copyright: (C) Oliver Woodford, 2008-2010
+% Copyright: (C) Oliver Woodford, 2008-2014
 
 % The idea of editing the EPS file to change line styles comes from Jiro
@@ -34,16 +38,14 @@
 % opened.
 
-% Read in the file
-fh = fopen(fname, 'r');
-if fh == -1
-    error('File %s not found.', fname);
+function fstrm = fix_lines(fstrm, fname2)
+
+if nargout == 0 || nargin > 1
+    if nargin < 2
+        % Overwrite the input file
+        fname2 = fstrm;
+    end
+    % Read in the file
+    fstrm = read_write_entire_textfile(fstrm);
 end
-try
-    fstrm = fread(fh, '*char')';
-catch ex
-    fclose(fh);
-    rethrow(ex);
-end
-fclose(fh);
 
 % Move any embedded fonts after the postscript header
@@ -51,5 +53,5 @@
     % Find the start and end of the header
     ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
-    [ind2 ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
+    [ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
     % Put the header first
     if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
@@ -67,5 +69,5 @@
 ind = sort(ind);
 % Find line width commands
-[ind2 ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
+[ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
 % Go through each line style section and swap with any line width commands
 % near by
@@ -114,6 +116,6 @@
 % Isolate line style definition section
 first_sec = strfind(fstrm, '% line types:');
-[second_sec remaining] = strtok(fstrm(first_sec+1:end), '/');
-[remaining remaining] = strtok(remaining, '%');
+[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
+[remaining, remaining] = strtok(remaining, '%');
 
 % Define the new styles, including the new GR format
@@ -132,23 +134,10 @@
              '/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
 
-if nargin < 2
-    % Overwrite the input file
-    fname2 = fname;
+% Construct the output
+fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
+
+% Write the output file
+if nargout == 0 || nargin > 1
+    read_write_entire_textfile(fname2, fstrm);
 end
-
-% Save the file with the section replaced
-fh = fopen(fname2, 'w');
-if fh == -1
-    error('Unable to open %s for writing.', fname2);
 end
-try
-    fwrite(fh, fstrm(1:first_sec), 'char*1');
-    fwrite(fh, second_sec, 'char*1');
-    fprintf(fh, '%s\r', new_style{:});
-    fwrite(fh, remaining, 'char*1');
-catch ex
-    fclose(fh);
-    rethrow(ex);
-end
-fclose(fh);
-return
Index: /issm/trunk/externalpackages/export_fig/ghostscript.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/ghostscript.m	(revision 19104)
+++ /issm/trunk/externalpackages/export_fig/ghostscript.m	(revision 19105)
@@ -20,5 +20,5 @@
 %   result - Output from ghostscript.
 
-% Copyright: Oliver Woodford, 2009-2010
+% Copyright: Oliver Woodford, 2009-2013
 
 % Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
@@ -32,9 +32,23 @@
 % 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
 % Punnoose for highlighting the issue.
+% 28/6/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
+% Steinbring for proposing the fix.
+% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes
+% for the fix.
+% 23/01/2014 - Add full path to ghostscript.txt in warning. Thanks to Koen
+% Vermeer for raising the issue.
 
 function varargout = ghostscript(cmd)
+% Initialize any required system calls before calling ghostscript
+shell_cmd = '';
+if isunix
+    shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
+end
+if ismac
+    shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';  % Avoids an error on Mac with GS 9.07
+end
 % Call ghostscript
-[varargout{1:nargout}] = system(sprintf('"%s" %s', gs_path, cmd));
-return
+[varargout{1:nargout}] = system(sprintf('%s"%s" %s', shell_cmd, gs_path, cmd));
+end
 
 function path_ = gs_path
@@ -85,7 +99,7 @@
     end
 else
-    bin = {'/usr/bin/gs', '/usr/local/bin/gs'};
-    for a = 1:numel(bin)
-        path_ = bin{a};
+    executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
+    for a = 1:numel(executable)
+        path_ = executable{a};
         if check_store_gs_path(path_)
             return
@@ -119,4 +133,5 @@
 end
 error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
+end
 
 function good = check_store_gs_path(path_)
@@ -128,12 +143,16 @@
 % Update the current default path to the path found
 if ~user_string('ghostscript', path_)
-    warning('Path to ghostscript installation could not be saved. Enter it manually in ghostscript.txt.');
+    warning('Path to ghostscript installation could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt'));
     return
 end
-return
+end
 
 function good = check_gs_path(path_)
 % Check the path is valid
-[good, message] = system(sprintf('"%s" -h', path_));
+shell_cmd = '';
+if ismac
+    shell_cmd = 'export DYLD_LIBRARY_PATH=""; ';  % Avoids an error on Mac with GS 9.07
+end
+[good, message] = system(sprintf('%s"%s" -h', shell_cmd, path_));
 good = good == 0;
-return
+end
Index: /issm/trunk/externalpackages/export_fig/im2gif.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/im2gif.m	(revision 19105)
+++ /issm/trunk/externalpackages/export_fig/im2gif.m	(revision 19105)
@@ -0,0 +1,186 @@
+%IM2GIF Convert a multiframe image to an animated GIF file
+%
+% Examples:
+%   im2gif infile
+%   im2gif infile outfile
+%   im2gif(A, outfile)
+%   im2gif(..., '-nocrop')
+%   im2gif(..., '-nodither')
+%   im2gif(..., '-ncolors', n)
+%   im2gif(..., '-loops', n)
+%   im2gif(..., '-delay', n) 
+%   
+% This function converts a multiframe image to an animated GIF.
+%
+% To create an animation from a series of figures, export to a multiframe
+% TIFF file using export_fig, then convert to a GIF, as follows:
+%
+%    for a = 2 .^ (3:6)
+%       peaks(a);
+%       export_fig test.tif -nocrop -append
+%    end
+%    im2gif('test.tif', '-delay', 0.5);
+%
+%IN:
+%   infile - string containing the name of the input image.
+%   outfile - string containing the name of the output image (must have the
+%             .gif extension). Default: infile, with .gif extension.
+%   A - HxWxCxN array of input images, stacked along fourth dimension, to
+%       be converted to gif.
+%   -nocrop - option indicating that the borders of the output are not to
+%             be cropped.
+%   -nodither - option indicating that dithering is not to be used when
+%               converting the image.
+%   -ncolors - option pair, the value of which indicates the maximum number
+%              of colors the GIF can have. This can also be a quantization
+%              tolerance, between 0 and 1. Default/maximum: 256.
+%   -loops - option pair, the value of which gives the number of times the
+%            animation is to be looped. Default: 65535.
+%   -delay - option pair, the value of which gives the time, in seconds,
+%            between frames. Default: 1/15.
+
+% Copyright (C) Oliver Woodford 2011
+
+function im2gif(A, varargin)
+
+% Parse the input arguments
+[A, options] = parse_args(A, varargin{:});
+
+if options.crop ~= 0
+    % Crop
+    A = crop_borders(A, A(ceil(end/2),1,:,1));
+end
+
+% Convert to indexed image
+[h, w, c, n] = size(A);
+A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
+map = unique(reshape(A, h*w*n, c), 'rows');
+if size(map, 1) > 256
+    dither_str = {'dither', 'nodither'};
+    dither_str = dither_str{1+(options.dither==0)};
+    if options.ncolors <= 1
+        [B, map] = rgb2ind(A, options.ncolors, dither_str);
+        if size(map, 1) > 256
+            [B, map] = rgb2ind(A, 256, dither_str);
+        end
+    else
+        [B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
+    end
+else
+    if max(map(:)) > 1
+        map = double(map) / 255;
+        A = double(A) / 255;
+    end
+    B = rgb2ind(im2double(A), map);
+end
+B = reshape(B, h, w, 1, n);
+
+% Bug fix to rgb2ind
+map(B(1)+1,:) = im2double(A(1,1,:));
+
+% Save as a gif
+imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
+end
+
+%% Parse the input arguments
+function [A, options] = parse_args(A, varargin)
+% Set the defaults
+options = struct('outfile', '', ...
+                 'dither', true, ...
+                 'crop', true, ...
+                 'ncolors', 256, ...
+                 'loops', 65535, ...
+                 'delay', 1/15);
+
+% Go through the arguments
+a = 0;
+n = numel(varargin);
+while a < n
+    a = a + 1;
+    if ischar(varargin{a}) && ~isempty(varargin{a})
+        if varargin{a}(1) == '-'
+            opt = lower(varargin{a}(2:end));
+            switch opt
+                case 'nocrop'
+                    options.crop = false;
+                case 'nodither'
+                    options.dither = false;
+                otherwise
+                    if ~isfield(options, opt)
+                        error('Option %s not recognized', varargin{a});
+                    end
+                    a = a + 1;
+                    if ischar(varargin{a}) && ~ischar(options.(opt))
+                        options.(opt) = str2double(varargin{a});
+                    else
+                        options.(opt) = varargin{a};
+                    end
+            end
+        else
+            options.outfile = varargin{a};
+        end
+    end
+end
+
+if isempty(options.outfile)
+    if ~ischar(A)
+        error('No output filename given.');
+    end
+    % Generate the output filename from the input filename
+    [path, outfile] = fileparts(A);
+    options.outfile = fullfile(path, [outfile '.gif']);
+end
+
+if ischar(A)
+    % Read in the image
+    A = imread_rgb(A);
+end
+end
+
+%% Read image to uint8 rgb array
+function [A, alpha] = imread_rgb(name)
+% Get file info
+info = imfinfo(name);
+% Special case formats
+switch lower(info(1).Format)
+    case 'gif'
+        [A, map] = imread(name, 'frames', 'all');
+        if ~isempty(map)
+            map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
+            A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
+            A = permute(A, [1 2 5 4 3]);
+        end
+    case {'tif', 'tiff'}
+        A = cell(numel(info), 1);
+        for a = 1:numel(A)
+            [A{a}, map] = imread(name, 'Index', a, 'Info', info);
+            if ~isempty(map)
+                map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
+                A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
+            end
+            if size(A{a}, 3) == 4
+                % TIFF in CMYK colourspace - convert to RGB
+                if isfloat(A{a})
+                    A{a} = A{a} * 255;
+                else
+                    A{a} = single(A{a});
+                end
+                A{a} = 255 - A{a};
+                A{a}(:,:,4) = A{a}(:,:,4) / 255;
+                A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
+            end
+        end
+        A = cat(4, A{:});
+    otherwise
+        [A, map, alpha] = imread(name);
+        A = A(:,:,:,1); % Keep only first frame of multi-frame files
+        if ~isempty(map)
+            map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
+            A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
+        elseif size(A, 3) == 4
+            % Assume 4th channel is an alpha matte
+            alpha = A(:,:,4);
+            A = A(:,:,1:3);
+        end
+end
+end
Index: /issm/trunk/externalpackages/export_fig/isolate_axes.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/isolate_axes.m	(revision 19104)
+++ /issm/trunk/externalpackages/export_fig/isolate_axes.m	(revision 19105)
@@ -19,5 +19,5 @@
 %    fh - The handle of the created figure.
 
-% Copyright (C) Oliver Woodford 2011-2012
+% Copyright (C) Oliver Woodford 2011-2013
 
 % Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
@@ -26,4 +26,7 @@
 % 12/12/12 - Add support for isolating uipanels. Thanks to michael for
 % suggesting it.
+% 08/10/13 - Bug fix to allchildren suggested by Will Grant (many thanks!).
+% 05/12/13 - Bug fix to axes having different units. Thanks to Remington
+% Reid for reporting the issue.
 
 function fh = isolate_axes(ah, vis)
@@ -72,4 +75,5 @@
 nLeg = numel(lh);
 if nLeg > 0
+    set([ah(:); lh(:)], 'Units', 'normalized');
     ax_pos = get(ah, 'OuterPosition');
     if nAx > 1
@@ -82,9 +86,11 @@
     end
     leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
-    for a = 1:nAx
-            % Overlap test
-            ah = [ah; lh(leg_pos(:,1) < ax_pos(a,3) & leg_pos(:,2) < ax_pos(a,4) &...
-                         leg_pos(:,3) > ax_pos(a,1) & leg_pos(:,4) > ax_pos(a,2))];
-    end
+    ax_pos = shiftdim(ax_pos, -1);
+    % Overlap test
+    M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
+        bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
+        bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
+        bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
+    ah = [ah; lh(any(M, 2))];
 end
 % Get all the objects in the figure
@@ -92,13 +98,13 @@
 % Delete everything except for the input objects and associated items
 delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
-return
+end
 
 function ah = allchildren(ah)
-ah = allchild(ah);
+ah = findall(ah);
 if iscell(ah)
     ah = cell2mat(ah);
 end
 ah = ah(:);
-return
+end
 
 function ph = allancestors(ah)
@@ -111,3 +117,3 @@
     end
 end
-return
+end
Index: /issm/trunk/externalpackages/export_fig/pdf2eps.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/pdf2eps.m	(revision 19104)
+++ /issm/trunk/externalpackages/export_fig/pdf2eps.m	(revision 19105)
@@ -25,5 +25,5 @@
 options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
 % Convert to eps using pdftops
-[status message] = pdftops(options);
+[status, message] = pdftops(options);
 % Check for error
 if status
@@ -48,4 +48,4 @@
 end
 fclose(fid);
-return
+end
 
Index: /issm/trunk/externalpackages/export_fig/pdftops.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/pdftops.m	(revision 19104)
+++ /issm/trunk/externalpackages/export_fig/pdftops.m	(revision 19105)
@@ -28,8 +28,9 @@
 % Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path
 % under linux.
+% 23/01/2014 - Add full path to pdftops.txt in warning.
 
 % Call pdftops
 [varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
-return
+end
 
 function path_ = xpdf_path
@@ -85,4 +86,5 @@
 end
 error('pdftops executable not found.');
+end
 
 function good = check_store_xpdf_path(path_)
@@ -94,14 +96,14 @@
 % Update the current default path to the path found
 if ~user_string('pdftops', path_)
-    warning('Path to pdftops executable could not be saved. Enter it manually in pdftops.txt.');
+    warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
     return
 end
-return
+end
 
 function good = check_xpdf_path(path_)
 % Check the path is valid
-[good message] = system(sprintf('"%s" -h', path_));
+[good, message] = system(sprintf('"%s" -h', path_));
 % system returns good = 1 even when the command runs
 % Look for something distinct in the help text
 good = ~isempty(strfind(message, 'PostScript'));
-return
+end
Index: /issm/trunk/externalpackages/export_fig/print2array.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/print2array.m	(revision 19104)
+++ /issm/trunk/externalpackages/export_fig/print2array.m	(revision 19105)
@@ -71,5 +71,5 @@
     % Print to eps file
     tmp_eps = [tempname '.eps'];
-    print2eps(tmp_eps, fig, renderer, '-loose');
+    print2eps(tmp_eps, fig, 0, renderer, '-loose');
     try
         % Initialize the command to export to tiff using ghostscript
@@ -172,5 +172,5 @@
     end
 end
-return
+end
 
 % Function to return (and create, where necessary) the font path
@@ -196,3 +196,3 @@
 end
 user_string('gs_font_path', fp);
-return
+end
Index: /issm/trunk/externalpackages/export_fig/print2eps.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/print2eps.m	(revision 19104)
+++ /issm/trunk/externalpackages/export_fig/print2eps.m	(revision 19105)
@@ -4,5 +4,6 @@
 %   print2eps filename
 %   print2eps(filename, fig_handle)
-%   print2eps(filename, fig_handle, options)
+%   print2eps(filename, fig_handle, bb_padding)
+%   print2eps(filename, fig_handle, bb_padding, options)
 %
 % This function saves a figure as an eps file, with two improvements over
@@ -18,8 +19,11 @@
 %              ".eps" extension is added if not there already. If a path is
 %              not specified, the figure is saved in the current directory.
-%   fig_handle - The handle of the figure to be saved. Default: gcf.
+%   fig_handle - The handle of the figure to be saved. Default: gcf().
+%   bb_padding - Scalar value of amount of padding to add to border around
+%                the figure, in points. Can be negative as well as
+%                positive. Default: 0.
 %   options - Additional parameter strings to be passed to print.
 
-% Copyright (C) Oliver Woodford 2008-2013
+% Copyright (C) Oliver Woodford 2008-2014
 
 % The idea of editing the EPS file to change line styles comes from Jiro
@@ -50,11 +54,18 @@
 % 22/03/13: Extend font swapping to axes labels. Thanks to Rasmus Ischebeck
 %           for reporting the issue.
-
-function print2eps(name, fig, varargin)
+% 23/07/13: Bug fix to font swapping. Thanks to George for reporting the
+%           issue.
+% 13/08/13: Fix MATLAB feature of not exporting white lines correctly.
+%           Thanks to Sebastian Heßlinger for reporting it.
+
+function print2eps(name, fig, bb_padding, varargin)
 options = {'-depsc2'};
-if nargin < 2
-    fig = gcf;
-elseif nargin > 2
+if nargin > 3
     options = [options varargin];
+elseif nargin < 3
+    bb_padding = 0;
+    if nargin < 2
+        fig = gcf();
+    end
 end
 % Construct the filename
@@ -62,4 +73,8 @@
     name = [name '.eps']; % Add the missing extension
 end
+% Set paper size
+old_pos_mode = get(fig, 'PaperPositionMode');
+old_orientation = get(fig, 'PaperOrientation');
+set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
 % Find all the used fonts in the figure
 font_handles = findall(fig, '-property', 'FontName');
@@ -95,5 +110,5 @@
     font_swap{1,a} = find(strcmp(fontslu{require_swap(a)}, fontsl));
     font_swap{2,a} = matlab_fonts{unused_fonts(a)};
-    font_swap{3,a} = fonts{font_swap{1,end}(1)};
+    font_swap{3,a} = fonts{font_swap{1,a}(1)};
     fonts_new(font_swap{1,a}) = {font_swap{2,a}};
 end
@@ -126,8 +141,4 @@
     update = reshape(update(M), 1, []);
 end
-% Set paper size
-old_pos_mode = get(fig, 'PaperPositionMode');
-old_orientation = get(fig, 'PaperOrientation');
-set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
 % MATLAB bug fix - black and white text can come out inverted sometimes
 % Find the white and black text
@@ -143,64 +154,60 @@
 set(black_text_handles, 'Color', [0 0 0] + eps);
 set(white_text_handles, 'Color', [1 1 1] - eps);
+% MATLAB bug fix - white lines can come out funny sometimes
+% Find the white lines
+white_line_handles = findobj(fig, 'Type', 'line');
+M = get(white_line_handles, 'Color');
+if iscell(M)
+    M = cell2mat(M);
+end
+white_line_handles = white_line_handles(sum(M, 2) == 3);
+% Set the line color slightly off white
+set(white_line_handles, 'Color', [1 1 1] - 0.00001);
 % Print to eps file
 print(fig, options{:}, name);
-% Reset the font colors
+% Reset the font and line colors
 set(black_text_handles, 'Color', [0 0 0]);
 set(white_text_handles, 'Color', [1 1 1]);
+set(white_line_handles, 'Color', [1 1 1]);
 % Reset paper size
 set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
-% Correct the fonts
+% Reset the font names in the figure
 if ~isempty(font_swap)
-    % Reset the font names in the figure
     for a = update
         set(font_handles(a), 'FontName', fonts{a}, 'FontSize', fonts_size(a));
     end
-    % Replace the font names in the eps file
-    font_swap = font_swap(2:3,:);
-    try
-        swap_fonts(name, font_swap{:});
-    catch
-        warning('swap_fonts() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
-        return
-    end
-end
-% Fix the line styles
+end
+% Do post-processing on the eps file
 try
-    fix_lines(name);
+    fstrm = read_write_entire_textfile(name);
 catch
-    warning('fix_lines() failed. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
-end
-return
-
-function swap_fonts(fname, varargin)
-% Read in the file
-fh = fopen(fname, 'r');
-if fh == -1
-    error('File %s not found.', fname);
-end
-try
-    fstrm = fread(fh, '*char')';
-catch ex
-    fclose(fh);
-    rethrow(ex);
-end
-fclose(fh);
-
+    warning('Loading EPS file failed, so unable to perform post-processing. This is usually because the figure contains a large number of patch objects. Consider exporting to a bitmap format in this case.');
+    return
+end
 % Replace the font names
-for a = 1:2:numel(varargin)
-    fstrm = regexprep(fstrm, [varargin{a} '-?[a-zA-Z]*\>'], varargin{a+1}(~isspace(varargin{a+1})));
-end
-
-% Write out the updated file
-fh = fopen(fname, 'w');
-if fh == -1
-    error('Unable to open %s for writing.', fname2);
-end
-try
-    fwrite(fh, fstrm, 'char*1');
-catch ex
-    fclose(fh);
-    rethrow(ex);
-end
-fclose(fh);
-return
+if ~isempty(font_swap)
+    for a = 1:size(font_swap, 2)
+        %fstrm = regexprep(fstrm, [font_swap{1,a} '-?[a-zA-Z]*\>'], font_swap{3,a}(~isspace(font_swap{3,a})));
+        fstrm = regexprep(fstrm, font_swap{2,a}, font_swap{3,a}(~isspace(font_swap{3,a})));
+    end
+end
+if using_hg2(fig)
+    % Convert miter joins to line joins
+    fstrm = regexprep(fstrm, '10.0 ML\n', '1 LJ\n');
+    % Move the bounding box to the top of the file
+    [s, e] = regexp(fstrm, '%%BoundingBox: [\w\s()]*%%');
+    if numel(s) == 2
+        fstrm = fstrm([1:s(1)-1 s(2):e(2)-2 e(1)-1:s(2)-1 e(2)-1:end]);
+    end
+else
+    % Fix the line styles
+    fstrm = fix_lines(fstrm);
+end
+% Apply the bounding box padding
+if bb_padding
+    add_padding = @(n1, n2, n3, n4) sprintf(' %d', str2double({n1, n2, n3, n4}) + [-bb_padding -bb_padding bb_padding bb_padding]);
+    fstrm = regexprep(fstrm, '%%BoundingBox:[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)[ ]+([-]?\d+)', '%%BoundingBox:${add_padding($1, $2, $3, $4)}');
+end
+% Write out the fixed eps file
+read_write_entire_textfile(name, fstrm);
+end
Index: /issm/trunk/externalpackages/export_fig/read_write_entire_textfile.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/read_write_entire_textfile.m	(revision 19105)
+++ /issm/trunk/externalpackages/export_fig/read_write_entire_textfile.m	(revision 19105)
@@ -0,0 +1,37 @@
+%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory
+%
+% Read or write an entire text file to/from memory, without leaving the
+% file open if an error occurs.
+%
+% Reading:
+%   fstrm = read_write_entire_textfile(fname)
+% Writing:
+%   read_write_entire_textfile(fname, fstrm)
+%
+%IN:
+%   fname - Pathname of text file to be read in.
+%   fstrm - String to be written to the file, including carriage returns.
+%
+%OUT:
+%   fstrm - String read from the file. If an fstrm input is given the
+%           output is the same as that input. 
+
+function fstrm = read_write_entire_textfile(fname, fstrm)
+modes = {'rt', 'wt'};
+writing = nargin > 1;
+fh = fopen(fname, modes{1+writing});
+if fh == -1
+    error('Unable to open file %s.', fname);
+end
+try
+    if writing
+        fwrite(fh, fstrm, 'char*1');
+    else
+        fstrm = fread(fh, '*char')';
+    end
+catch ex
+    fclose(fh);
+    rethrow(ex);
+end
+fclose(fh);
+end
Index: /issm/trunk/externalpackages/export_fig/user_string.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/user_string.m	(revision 19104)
+++ /issm/trunk/externalpackages/export_fig/user_string.m	(revision 19105)
@@ -85,3 +85,3 @@
     fclose(fid);
 end
-return
+end
Index: /issm/trunk/externalpackages/export_fig/using_hg2.m
===================================================================
--- /issm/trunk/externalpackages/export_fig/using_hg2.m	(revision 19105)
+++ /issm/trunk/externalpackages/export_fig/using_hg2.m	(revision 19105)
@@ -0,0 +1,18 @@
+%USING_HG2 Determine if the HG2 graphics pipeline is used
+%
+%   tf = using_hg2(fig)
+%
+%IN:
+%   fig - handle to the figure in question.
+%
+%OUT:
+%   tf - boolean indicating whether the HG2 graphics pipeline is being used
+%        (true) or not (false).
+
+function tf = using_hg2(fig)
+try
+    tf = ~graphicsversion(fig, 'handlegraphics');
+catch
+    tf = false;
+end
+end
Index: /issm/trunk/externalpackages/gmt/configs/ConfigUser.cmake
===================================================================
--- /issm/trunk/externalpackages/gmt/configs/ConfigUser.cmake	(revision 19105)
+++ /issm/trunk/externalpackages/gmt/configs/ConfigUser.cmake	(revision 19105)
@@ -0,0 +1,240 @@
+#
+# $Id: ConfigUserTemplate.cmake 12904 2014-02-17 20:52:35Z fwobbe $
+#
+# Copyright (c) 1991-2014 by P. Wessel, W. H. F. Smith, R. Scharroo, J. Luis and F. Wobbe
+# See LICENSE.TXT file for copying and redistribution conditions.
+#
+# This program is free software; you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by the
+# Free Software Foundation; version 3 or any later version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
+# for more details.
+#
+# Contact info: gmt.soest.hawaii.edu
+# ----------------------------------------------------------------------------
+
+# Use this file to override variables in 'ConfigDefault.cmake' on a per-user
+# basis.  First copy 'ConfigUserTemplate.cmake' to 'ConfigUser.cmake', then
+# edit 'ConfigUser.cmake'.  'ConfigUser.cmake' is not version controlled
+# (currently listed in svn:ignore property)
+#
+# Note: CMake considers an empty string, "FALSE", "OFF", "NO", or any string
+# ending in "-NOTFOUND" to be false (this happens to be case-insensitive, so
+# "False", "off", "no", and "something-NotFound" are all false).  Other values
+# are true.  Thus it does not matter whether you use TRUE and FALSE, ON and
+# OFF, or YES and NO for your booleans.
+
+##
+## Section 1: Installation paths
+##
+
+# ============================================================================
+# Basic setup begins here.  All settings are optional.  In most cases, setting
+# CMAKE_INSTALL_PREFIX should be all you need to do in order to build GMT with
+# reasonable defaults enabled.
+# ============================================================================
+
+# Installation path (usually defaults to /usr/local) [auto]:
+set (CMAKE_INSTALL_PREFIX "$ENV{ISSM_DIR}/externalpackages/gmt/install")
+
+# Set install name suffix used for directories and gmt executables
+# [undefined]:
+#set (GMT_INSTALL_NAME_SUFFIX "suffix")
+
+# Install into traditional directory structure. Disable to install a
+# distribution type directory structure (doc and share separated) [on]:
+#set (GMT_INSTALL_TRADITIONAL_FOLDERNAMES OFF)
+
+# Install convenience links for GMT modules. Disable to install only the main
+# gmt program and access modules as "gmt modulename options" [TRUE]:
+#set (GMT_INSTALL_MODULE_LINKS FALSE)
+
+# Make executables relocatable on supported platforms (relative RPATH) [TRUE]:
+#set (GMT_INSTALL_RELOCATABLE FALSE)
+
+# ============================================================================
+# Advanced configuration begins here.  Usually it is not necessary to edit any
+# settings below.  You should know what you are doing if you do though.  Note:
+# installation paths are relative to ${CMAKE_INSTALL_PREFIX} unless absolute
+# path is given.
+# ============================================================================
+
+# Set binary installation path [bin]:
+#set (GMT_BINDIR "bin")
+
+# Set library installation path [lib or lib64]:
+#set (GMT_LIBDIR "lib")
+
+# Set include installation path [include/gmt${GMT_INSTALL_NAME_SUFFIX}]:
+#set (GMT_INCLUDEDIR "include/gmt")
+
+# Set share installation path [share or share/gmt${GMT_INSTALL_NAME_SUFFIX}]:
+#set (GMT_DATADIR "share/gmt")
+
+# Set doc installation path [share/doc or
+# share/doc/gmt${GMT_INSTALL_NAME_SUFFIX}]:
+#set (GMT_DOCDIR "share/doc/gmt")
+
+# Set manpage installation path [share/man or
+# share/doc/gmt${GMT_INSTALL_NAME_SUFFIX}/man]:
+#set (GMT_MANDIR "share/doc/gmt/man")
+
+# Install documentation files from this external location instead of creating
+# new PDF and HTML documents from scratch [${GMT_SOURCE_DIR}/doc_release]:
+#set (GMT_INSTALL_EXTERNAL_DOC OFF)
+
+# Install manual pages from this external location instead of creating the
+# manpages from scratch [${GMT_SOURCE_DIR}/man_release]:
+#set (GMT_INSTALL_EXTERNAL_MAN OFF)
+
+##
+## Section 2: Build dependencies (should only be needed if CMake cannot
+## automatically detect the rights version or path.)
+##
+
+# Set path to GSHHG Shoreline Database [auto]:
+set (GSHHG_ROOT "$ENV{ISSM_DIR}/externalpackages/gshhg/install")
+
+# Copy GSHHG files to $/coast [FALSE]:
+#set (COPY_GSHHG TRUE)
+
+# Set path to DCW Digital Chart of the World for GMT [auto]:
+#set (DCW_ROOT "dcw-gmt_path")
+
+# Copy DCW files to $/dcw [FALSE]:
+#set (COPY_DCW TRUE)
+
+# Set location of NetCDF (can be root directory, path to header file or path
+# to nc-config) [auto]:
+set (NETCDF_ROOT "$ENV{ISSM_DIR}/externalpackages/netcdf/install")
+
+# Set location of GDAL (can be root directory, path to header file or path to
+# gdal-config) [auto]:
+set (GDAL_ROOT "$ENV{ISSM_DIR}/externalpackages/gdal/install")
+
+# Set location of PCRE (can be root directory, path to header file or path to
+# pcre-config) [auto]:
+#set (PCRE_ROOT "pcre_install_prefix")
+
+# Set location of single precision FFTW (can be root directory or path to
+# header file) [auto]:
+#set (FFTW3_ROOT "fftw_install_prefix")
+
+# Set location of ZLIB (can be root directory or path to header file) [auto]:
+#set (ZLIB_ROOT "zlib_install_prefix")
+
+##
+## Section 3: GMT features
+##
+
+# Enforce GPL or LGPL conformity. Use this to disable routines that cannot be
+# redistributed under the terms of the GPL or LGPL such as Shewchuk's
+# triangulation (valid values are GPL, LGPL and off) [off]:
+#set (LICENSE_RESTRICTED GPL)
+
+# Configure default units (possible values are SI and US) [SI]:
+#set (UNITS "US")
+
+# Enable building of shared libraries [TRUE] (disable to use static libraries;
+# not recommended):
+#set (BUILD_SHARED_LIBS FALSE)
+
+# Build GMT shared lib with supplemental modules [TRUE]:
+#set (BUILD_SUPPLEMENTS FALSE)
+
+##
+## Section 4: Advanced tweaking
+##
+
+#
+# Testing and development
+#
+
+# Enable running examples/tests with "ctest" or "make check" (out-of-source).
+# Need to set either DO_EXAMPLES, DO_TESTS or both and uncomment the following
+# line.
+#enable_testing()
+#set (DO_EXAMPLES TRUE)
+#set (DO_TESTS TRUE)
+# Number of parallel test jobs with "make check":
+#set (N_TEST_JOBS 4)
+
+# Enable this option to run GMT programs from within ${GMT_BINARY_DIR} without
+# installing or setting GMT_SHAREDIR and GMT_USERDIR first. This is required
+# for testing [OFF]:
+#set (SUPPORT_EXEC_IN_BINARY_DIR ON)
+
+# List extra sub-dirs of 'src' with a CMakeList.txt to build non-module codes
+# that link against the full gmt libs (not just the API; for building codes
+# that only need the GMT API, see the gmtextension project).
+#set (EXTRA_BUILD_DIRS apidemo)
+
+# Directory in which to install the release sources per default
+# [${GMT_BINARY_DIR}/gmt-${GMT_PACKAGE_VERSION}]:
+#set (GMT_RELEASE_PREFIX "release-src-prefix")
+
+# If set to false, image conversion from PS images to PNG and PDF does
+# not depend on the gmt binary target. Note: "make gmt" is then required
+# before docs_depends [TRUE].
+#set (GMT_DOCS_DEPEND_ON_GMT FALSE)
+
+#
+# Debugging
+#
+
+# Set build type can be: empty, Debug, Release, RelWithDebInfo or MinSizeRel
+# [Release]:
+#set (CMAKE_BUILD_TYPE Debug)
+
+# Extra debugging for developers:
+#add_definitions(-DDEBUG)
+#add_definitions(-DMEMDEBUG) # Turn on memory tracking see gmt_support.c for extra info
+#set (CMAKE_C_FLAGS "-Wall -Wdeclaration-after-statement") # recommended even for release build
+#set (CMAKE_C_FLAGS "-Wextra ${CMAKE_C_FLAGS}")            # extra warnings
+#set (CMAKE_C_FLAGS_DEBUG -ggdb3)                          # gdb debugging symbols
+#set (CMAKE_C_FLAGS_RELEASE "-ggdb3 -O2 -Wuninitialized")  # check uninitialized variables
+#set (CMAKE_LINK_DEPENDS_DEBUG_MODE TRUE)                  # debug link dependencies
+
+#
+# System specific tweaks
+#
+
+# This is for GCC on Solaris to avoid "relocations remain against allocatable
+# but non-writable sections" problems:
+#set (USER_GMTLIB_LINK_FLAGS -mimpure-text)
+
+# This may be needed to enable strdup and extended math functions with GCC and
+# Suncc on Solaris:
+#set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D__EXTENSIONS__")
+
+# Do not warn when building with Windows SDK or Visual Studio Express:
+#set (CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS ON)
+
+# Manually select runtime library when compiling with Windows SDK or Visual
+# Studio Express:
+#set (CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS c:/Windows/System32/msvcr100.dll)
+
+# If your NetCDF library is static (not recommended, applies to Windows only)
+#set (NETCDF_STATIC TRUE)
+
+# If want to rename the DLLs to something else than the default (e.g. to
+# append the bitness - Windows only)
+#if (WIN32)
+# set (BITAGE 32)
+# # Detect if we are building a 32 or 64 bits version
+# if (CMAKE_SIZEOF_VOID_P EQUAL 8)
+#   set (BITAGE 64)
+# endif ()
+# set (GMT_DLL_RENAME gmt_w${BITAGE})
+# set (PSL_DLL_RENAME psl_w${BITAGE})
+#endif(WIN32)
+
+# On Windows Visual C 2012 needs _ALLOW_KEYWORD_MACROS to build
+#if(MSVC11)
+#  add_definitions(/D_ALLOW_KEYWORD_MACROS)
+#endif(MSVC11)
+
+# vim: textwidth=78 noexpandtab tabstop=2 softtabstop=2 shiftwidth=2
Index: /issm/trunk/externalpackages/gmt/install.sh
===================================================================
--- /issm/trunk/externalpackages/gmt/install.sh	(revision 19105)
+++ /issm/trunk/externalpackages/gmt/install.sh	(revision 19105)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Erase install
+rm -rf install  src gmt
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gmt-5.1.1.tar.gz' 'gmt-5.1.1.tar.gz'
+
+#install directory
+mkdir src
+tar -zxvf gmt-5.1.1.tar.gz 
+mv gmt-5.1.1/* src
+rm -rf gmt-5.1.1
+
+#configure: 
+cp configs/ConfigUser.cmake ./src/cmake
+
+cd src
+mkdir build
+cd build
+cmake ../
+
+#compile
+if [ $# -eq 0 ]; then
+	make install
+else
+	make -j $1 install
+fi
+
+#come back: 
+cd ../../
Index: /issm/trunk/externalpackages/gshhg/install.sh
===================================================================
--- /issm/trunk/externalpackages/gshhg/install.sh	(revision 19105)
+++ /issm/trunk/externalpackages/gshhg/install.sh	(revision 19105)
@@ -0,0 +1,16 @@
+#!/bin/bash
+set -eu
+
+rm -rf gssh-gmt-2.3.3.tar.gz  src install
+
+#get gssh database from noaa's website:  http://www.ngdc.noaa.gov/mgg/shorelines/gshhs.html
+curl http://www.ngdc.noaa.gov/mgg/shorelines/data/gshhg/latest/gshhg-gmt-2.3.3.tar.gz > gshhg-gmt-2.3.3.tar.gz
+
+#Download from ISSM server
+#$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gshhg-gmt-2.3.3.tar.gz' 'gshhg-gmt-2.3.3.tar.gz'
+
+#untar: 
+tar -zxvf gshhg-gmt-2.3.3.tar.gz 
+
+#move: 
+mv gshhg-gmt-2.3.3 install
Index: /issm/trunk/externalpackages/gslib/install.sh
===================================================================
--- /issm/trunk/externalpackages/gslib/install.sh	(revision 19104)
+++ /issm/trunk/externalpackages/gslib/install.sh	(revision 19105)
@@ -18,7 +18,7 @@
 #Change compiler to gfortran
 cd install
-cat Makefile | sed -e "s/FC=g95/FC=gfortran/g" > Makefile.bak
+cat Makefile | sed -e "s/FC=g95/FC=ifort/g" > Makefile.bak
 mv Makefile.bak Makefile
-cat gslib/Makefile | sed -e "s/FC=g95/FC=gfortran/g" > Makefile.bak
+cat gslib/Makefile | sed -e "s/FC=g95/FC=ifort/g" > Makefile.bak
 mv Makefile.bak gslib/Makefile
 make 
Index: /issm/trunk/externalpackages/m1qn3/install.sh
===================================================================
--- /issm/trunk/externalpackages/m1qn3/install.sh	(revision 19104)
+++ /issm/trunk/externalpackages/m1qn3/install.sh	(revision 19105)
@@ -32,5 +32,5 @@
 	ranlib libm1qn3.\$(LIB_EXT) 
 %.o: %.f
-	\$(FC) \$(FFLAGS) -c $< -o \$@
+	\$(FC) \$(FFLAGS) -fPIC -c $< -o \$@
 clean: 
 	rm -rf *.o *.\$(LIB_EXT)
@@ -52,5 +52,5 @@
 	ranlib libddot.\$(LIB_EXT) 
 %.o: %.f
-	\$(FC) \$(FFLAGS) -c $< -o \$@
+	\$(FC) \$(FFLAGS) -fPIC -c $< -o \$@
 clean: 
 	rm -rf *.o *.\$(LIB_EXT)
Index: /issm/trunk/externalpackages/mpich/install-3.0-macosx64-nothreads.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-3.0-macosx64-nothreads.sh	(revision 19105)
+++ /issm/trunk/externalpackages/mpich/install-3.0-macosx64-nothreads.sh	(revision 19105)
@@ -0,0 +1,37 @@
+#!/bin/bash
+
+# includes following bug fix:
+# https://issm.ess.uci.edu/forum/viewtopic.php?f=10&t=49
+
+set -eu
+
+#Some cleanup
+rm -rf src install mpich-3.0.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich-3.0.4.tar.gz' 'mpich-3.0.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich-3.0.4.tar.gz
+
+#Move mpich into src directory
+mv mpich-3.0.4/* src
+rm -rf mpich-3.0.4
+
+#Configure mpich
+cd src
+export "ac_cv_tls=none"
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-shared
+
+	#CC=llvm-gcc \
+
+#Compile mpich (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/mpich/install-3.0-macosx64-static.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-3.0-macosx64-static.sh	(revision 19105)
+++ /issm/trunk/externalpackages/mpich/install-3.0-macosx64-static.sh	(revision 19105)
@@ -0,0 +1,29 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich-3.0.4
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich-3.0.4.tar.gz' 'mpich-3.0.4.tar.gz'
+
+#Untar 
+tar -zxvf  mpich-3.0.4.tar.gz
+
+#Move mpich into src directory
+mv mpich-3.0.4/* src
+rm -rf mpich-3.0.4
+
+#Configure mpich
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich/install"
+
+#Compile mpich (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/netcdf/install.sh
===================================================================
--- /issm/trunk/externalpackages/netcdf/install.sh	(revision 19104)
+++ /issm/trunk/externalpackages/netcdf/install.sh	(revision 19105)
@@ -4,17 +4,17 @@
 
 #Some cleanup
-rm -rf src install netcdf-4.2
+rm -rf src install netcdf-4.3.2
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py "http://issm.jpl.nasa.gov/files/externalpackages/netcdf-4.2.tar.gz" "netcdf-4.2.tar.gz"
+$ISSM_DIR/scripts/DownloadExternalPackage.py "http://issm.jpl.nasa.gov/files/externalpackages/netcdf-4.3.2.tar.gz" "netcdf-4.3.2.tar.gz"
 
 #Untar 
-tar -zxvf  netcdf-4.2.tar.gz
+tar -zxvf  netcdf-4.3.2.tar.gz
 
 #Move netcdf to install directory
 rm -rf src/*
-mv netcdf-4.2/* src/
-rm -rf netcdf-4.2
+mv netcdf-4.3.2/* src/
+rm -rf netcdf-4.3.2
 
 #Configure and compile
Index: /issm/trunk/externalpackages/petsc/install-3.5-greenplanet.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.5-greenplanet.sh	(revision 19105)
+++ /issm/trunk/externalpackages/petsc/install-3.5-greenplanet.sh	(revision 19105)
@@ -0,0 +1,54 @@
+#!/bin/bash
+set -eu
+
+#WARNING: make sure you have the right mpi
+
+#Some cleanup
+rm -rf install petsc-3.5.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.3.tar.gz' 'petsc-3.5.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.5.3.tar.gz
+mv petsc-3.5.3/* src/
+rm -rf petsc-3.5.3
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-blas-lapack-dir="/opt/intel/mkl/10.2.4.032/" \
+ --with-mpi-dir="/sopt/mpi/openmpi-1.5.4_psm/intel/" \
+ --known-mpi-shared-libraries=1 \
+ --with-debugging=0 \
+ --with-valgrind=0 \
+ --with-x=0 \
+ --with-ssl=0 \
+ --with-batch=1  \
+ --with-shared-libraries=1 \
+ --download-metis=1 \
+ --download-parmetis=1 \
+ --download-scalapack=1 \
+ --download-mumps=1 \
+ --COPTFLAGS="-lmpi -O3" \
+ --FOPTFLAGS="-lmpi -O3" \
+ --CXXOPTFLAGS="-lmpi -O3"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l nodes=1:ppn=1
+#PBS -q c6145
+#PBS -l walltime=10
+
+cd $(echo $ISSM_DIR)/externalpackages/petsc/src/
+mpiexec -np 1 ./conftest-arch-linux2-c-opt
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/trunk/externalpackages/petsc/install-3.5-hpc.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.5-hpc.sh	(revision 19105)
+++ /issm/trunk/externalpackages/petsc/install-3.5-hpc.sh	(revision 19105)
@@ -0,0 +1,50 @@
+#!/bin/bash
+set -eu
+
+#WARNING: make sure you have the right mpi:
+
+#Some cleanup
+rm -rf install petsc-3.5.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.3.tar.gz' 'petsc-3.5.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.5.3.tar.gz
+mv petsc-3.5.3/* src/
+rm -rf petsc-3.5.3
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-mpi-dir="/data/apps/mpi/openmpi-1.8.3/gcc/4.8.3/" \
+ --known-mpi-shared-libraries=1 \
+ --with-debugging=0 \
+ --with-valgrind=0 \
+ --with-x=0 \
+ --with-ssl=0 \
+ --with-batch=1  \
+ --with-shared-libraries=1 \
+ --download-metis=1 \
+ --download-parmetis=1 \
+ --download-scalapack=1 \
+ --download-fblaslapack=1 \
+ --download-mumps=1 
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#!/bin/bash
+#$ -N PETSC
+#$ -q free*,pub64
+
+cd $(echo $ISSM_DIR)/externalpackages/petsc/src/
+mpiexec -np 1 ./conftest-arch-linux2-c-opt
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/trunk/externalpackages/petsc/install-3.5-linux64-static.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.5-linux64-static.sh	(revision 19105)
+++ /issm/trunk/externalpackages/petsc/install-3.5-linux64-static.sh	(revision 19105)
@@ -0,0 +1,35 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.5.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.3.tar.gz' 'petsc-3.5.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.5.3.tar.gz
+mv petsc-3.5.3/* src/
+rm -rf petsc-3.5.3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+	--with-debugging=0 \
+	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
+	--with-shared-libraries=0 \
+	--download-metis=1 \
+	--download-parmetis=1 \
+	--download-mumps=1 \
+	--download-scalapack=1 \
+	--download-fblaslapack=1 
+
+#Compile and intall
+make
+make install
Index: /issm/trunk/externalpackages/petsc/install-3.5-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.5-linux64.sh	(revision 19104)
+++ /issm/trunk/externalpackages/petsc/install-3.5-linux64.sh	(revision 19105)
@@ -3,14 +3,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.5.1 src
+rm -rf install petsc-3.5.3 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.1.tar.gz' 'petsc-3.5.1.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.3.tar.gz' 'petsc-3.5.3.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.5.1.tar.gz
-mv petsc-3.5.1/* src/
-rm -rf petsc-3.5.1
+tar -zxvf  petsc-3.5.3.tar.gz
+mv petsc-3.5.3/* src/
+rm -rf petsc-3.5.3
 
 #configure
@@ -22,4 +22,6 @@
 	--with-debugging=0 \
 	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
 	--with-shared-libraries=1 \
 	--download-metis=1 \
Index: /issm/trunk/externalpackages/petsc/install-3.5-macosx64-static.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.5-macosx64-static.sh	(revision 19105)
+++ /issm/trunk/externalpackages/petsc/install-3.5-macosx64-static.sh	(revision 19105)
@@ -0,0 +1,36 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.5.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.3.tar.gz' 'petsc-3.5.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.5.3.tar.gz
+mv petsc-3.5.3/* src/
+rm -rf petsc-3.5.3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-mpi-dir="$ISSM_DIR/externalpackages/mpich/install" \
+	--with-debugging=0 \
+	--with-valgrind=0 \
+	--with-ssl=0 \
+	--with-x=0 \
+	--with-shared-libraries=0 \
+	--download-metis=1 \
+	--download-parmetis=1 \
+	--download-mumps=1 \
+	--download-fblaslapack=1 \
+	--download-scalapack=1
+
+
+#Compile and intall
+make
+make install
Index: /issm/trunk/externalpackages/petsc/install-3.5-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.5-macosx64.sh	(revision 19104)
+++ /issm/trunk/externalpackages/petsc/install-3.5-macosx64.sh	(revision 19105)
@@ -3,14 +3,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.5.1 src
+rm -rf install petsc-3.5.3 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.1.tar.gz' 'petsc-3.5.1.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.3.tar.gz' 'petsc-3.5.3.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.5.1.tar.gz
-mv petsc-3.5.1/* src/
-rm -rf petsc-3.5.1
+tar -zxvf  petsc-3.5.3.tar.gz
+mv petsc-3.5.3/* src/
+rm -rf petsc-3.5.3
 
 #configure
@@ -22,4 +22,6 @@
 	--with-debugging=0 \
 	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
 	--with-shared-libraries=1 \
 	--download-metis=1 \
Index: /issm/trunk/externalpackages/petsc/install-3.5-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.5-pleiades.sh	(revision 19104)
+++ /issm/trunk/externalpackages/petsc/install-3.5-pleiades.sh	(revision 19105)
@@ -3,14 +3,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.5.1 src
+rm -rf install petsc-3.5.3 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.1.tar.gz' 'petsc-3.5.1.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.3.tar.gz' 'petsc-3.5.3.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.5.1.tar.gz
-mv petsc-3.5.1/* src/
-rm -rf petsc-3.5.1
+tar -zxvf  petsc-3.5.3.tar.gz
+mv petsc-3.5.3/* src/
+rm -rf petsc-3.5.3
 
 #configure
@@ -19,10 +19,12 @@
 	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
 	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
-	--with-blas-lapack-dir="/nasa/intel/mkl/10.0.011/" \
-	--with-mpi-lib="/nasa/sgi/mpt/2.06rp16/lib/libmpi.so" \
-	--with-mpi-include="/nasa/sgi/mpt/2.06rp16/include" \
+	--with-blas-lapack-dir="/nasa/intel/Compiler/2015.0.090/composer_xe_2015.0.090/mkl/" \
+	--with-mpi-lib="/nasa/sgi/mpt/2.11r13/lib/libmpi.so" \
+	--with-mpi-include="/nasa/sgi/mpt/2.11r13/include" \
 	--known-mpi-shared-libraries=1 \
 	--with-debugging=0 \
 	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
 	--with-batch=1  \
 	--with-shared-libraries=1 \
@@ -31,8 +33,5 @@
 	--download-mumps=1 \
 	--download-scalapack=1 \
-	--download-fblaslapack=1 \
-	--COPTFLAGS="-lmpi -O3" \
-	--FOPTFLAGS="-lmpi -O3" \
-	--CXXOPTFLAGS="-lmpi -O3"
+	--download-fblaslapack=1
 
 #prepare script to reconfigure petsc
@@ -45,7 +44,6 @@
 
 . /usr/share/modules/init/bash 
-module load comp-intel/11.1.046
-module load math/intel_mkl_64_10.0.011
-module load mpi-sgi/mpt.2.06rp16
+module load comp-intel/2015.0.090
+module load mpi-sgi/mpt.2.11r13
 
 export PATH="$PATH:." 
Index: /issm/trunk/externalpackages/petsc/install-3.5-win7.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.5-win7.sh	(revision 19105)
+++ /issm/trunk/externalpackages/petsc/install-3.5-win7.sh	(revision 19105)
@@ -0,0 +1,41 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.5.3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.5.3.tar.gz' 'petsc-3.5.3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.5.3.tar.gz
+mv petsc-3.5.3/* src/
+rm -rf petsc-3.5.3
+
+export PETSC_DIR=`cygpath -u "$ISSM_DIR/externalpackages/petsc/src"`
+export PREFIX_DIR=`cygpath -u "$ISSM_DIR/externalpackages/petsc/install"`
+
+#configure
+cd src
+./config/configure.py  \
+	--with-parallel-no \
+	--prefix=$PREFIX_DIR \
+	--PETSC_ARCH=cygwin-intel \
+	--PETSC_DIR=$PETSC_DIR \
+	--with-mpi=0 \
+	--with-debugging=0 \
+	--with-valgrind=0 \
+	--with-x=0 \
+	--with-ssl=0 \
+	--download-f2cblaslapack=yes \
+	--with-cc='win32fe cl' \
+	--with-fc=0 \
+	--with-cxx='win32fe cl' \
+	--with-clanguage=cxx 
+
+#Compile petsc and install it
+make
+make install
+
+patch ../install/include/petscfix.h ../configs/3.1/win7/petscfix.h.patch
Index: /issm/trunk/externalpackages/triangle/install-win7.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-win7.sh	(revision 19104)
+++ /issm/trunk/externalpackages/triangle/install-win7.sh	(revision 19105)
@@ -23,2 +23,3 @@
 #Patch triangle.h
 patch triangle.h ../triangle.h.patch
+cat triangle.h
Index: /issm/trunk/externalpackages/triangle/install.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install.sh	(revision 19105)
+++ /issm/trunk/externalpackages/triangle/install.sh	(revision 19105)
@@ -0,0 +1,31 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup 
+rm -rf install src triangle
+mkdir install src ./src/m4
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/triangle.zip' 'triangle.zip'
+
+#Untar 
+cd src
+mkdir src
+cp ../triangle.zip ./
+unzip triangle.zip
+
+rm ./makefile
+mv ./*.c ./src
+mv ./*.h ./src
+
+cp ../configs/triangle-libtool.tar.gz ./
+tar -xvf ./triangle-libtool.tar.gz
+
+autoreconf -ivf
+./configure --prefix="${ISSM_DIR}/externalpackages/triangle/install" --disable-executables
+
+make 
+make install
+
+#Patch triangle.h
+patch ${ISSM_DIR}/externalpackages/triangle/install/include/triangle.h ${ISSM_DIR}/externalpackages/triangle/triangle.h.patch
Index: /issm/trunk/externalpackages/valgrind/install-altix64.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-altix64.sh	(revision 19104)
+++ /issm/trunk/externalpackages/valgrind/install-altix64.sh	(revision 19105)
@@ -3,16 +3,16 @@
 
 #Some cleanup
-rm -rf install valgrind-3.8.1
+rm -rf install valgrind-3.10.0
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.10.0.tar.bz2' 'valgrind-3.10.0.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.8.1.tar.bz2
+tar -jxvf  valgrind-3.10.0.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.8.1/* install
-rm -rf valgrind-3.8.1
+mv valgrind-3.10.0/* install
+rm -rf valgrind-3.10.0
 
 #configure
Index: /issm/trunk/externalpackages/valgrind/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-linux64.sh	(revision 19104)
+++ /issm/trunk/externalpackages/valgrind/install-linux64.sh	(revision 19105)
@@ -3,16 +3,16 @@
 
 #Some cleanup
-rm -rf install valgrind-3.8.1
+rm -rf install valgrind-3.10.0
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.10.0.tar.bz2' 'valgrind-3.10.0.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.8.1.tar.bz2
+tar -jxvf  valgrind-3.10.0.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.8.1/* install
-rm -rf valgrind-3.8.1
+mv valgrind-3.10.0/* install
+rm -rf valgrind-3.10.0
 
 #configure
Index: /issm/trunk/externalpackages/valgrind/install-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-macosx32.sh	(revision 19104)
+++ /issm/trunk/externalpackages/valgrind/install-macosx32.sh	(revision 19105)
@@ -3,16 +3,16 @@
 
 #Some cleanup
-rm -rf install valgrind-3.8.1
+rm -rf install valgrind-3.10.0
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.10.0.tar.bz2' 'valgrind-3.10.0.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.8.1.tar.bz2
+tar -jxvf  valgrind-3.10.0.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.8.1/* install
-rm -rf valgrind-3.8.1
+mv valgrind-3.10.0/* install
+rm -rf valgrind-3.10.0
 
 #configure
Index: /issm/trunk/externalpackages/valgrind/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-macosx64.sh	(revision 19104)
+++ /issm/trunk/externalpackages/valgrind/install-macosx64.sh	(revision 19105)
@@ -3,16 +3,16 @@
 
 #Some cleanup
-rm -rf install valgrind-3.8.1
+rm -rf install valgrind-3.10.0
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.10.0.tar.bz2' 'valgrind-3.10.0.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.8.1.tar.bz2
+tar -jxvf  valgrind-3.10.0.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.8.1/* install
-rm -rf valgrind-3.8.1
+mv valgrind-3.10.0/* install
+rm -rf valgrind-3.10.0
 
 #configure
@@ -21,4 +21,5 @@
 
 #Compile valgrind
+
 make  -j 8
 make install
Index: /issm/trunk/externalpackages/valgrind/install-win32.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-win32.sh	(revision 19104)
+++ /issm/trunk/externalpackages/valgrind/install-win32.sh	(revision 19105)
@@ -3,16 +3,16 @@
 
 #Some cleanup
-rm -rf install valgrind-3.8.1
+rm -rf install valgrind-3.10.0
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.10.0.tar.bz2' 'valgrind-3.10.0.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.8.1.tar.bz2
+tar -jxvf  valgrind-3.10.0.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.8.1/* install
-rm -rf valgrind-3.8.1
+mv valgrind-3.10.0/* install
+rm -rf valgrind-3.10.0
 
 #configure
Index: /issm/trunk/externalpackages/valgrind/issm.supp
===================================================================
--- /issm/trunk/externalpackages/valgrind/issm.supp	(revision 19104)
+++ /issm/trunk/externalpackages/valgrind/issm.supp	(revision 19105)
@@ -211,3 +211,19 @@
 	  fun:__dmumps_parallel_analysis_MOD_dmumps_715
 }
+{
+	<mump14>
+	  Memcheck:Leak
+	  fun:malloc
+	  fun:mumps_754_
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_781
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_720
+	  fun:__dmumps_parallel_analysis_MOD_dmumps_715
+	  fun:dmumps_26_
+	  fun:dmumps_
+	  fun:dmumps_f77_
+	  fun:dmumps_c
+	  fun:MatLUFactorSymbolic_AIJMUMPS
+	  fun:MatLUFactorSymbolic
+	  fun:PCSetUp_LU
+}
 #}}}
Index: /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 19104)
+++ /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 19105)
@@ -412,5 +412,4 @@
 syn keyword cType BoolInput
 syn keyword cType BoolParam
-syn keyword cType classes
 syn keyword cType Constraint
 syn keyword cType Constraints
@@ -418,6 +417,6 @@
 syn keyword cType Contours
 syn keyword cType ControlInput
+syn keyword cType DataSetParam
 syn keyword cType DatasetInput
-syn keyword cType DataSetParam
 syn keyword cType Definition
 syn keyword cType DependentObject
@@ -432,6 +431,6 @@
 syn keyword cType ElementHook
 syn keyword cType ElementMatrix
+syn keyword cType ElementVector
 syn keyword cType Elements
-syn keyword cType ElementVector
 syn keyword cType ExponentialVariogram
 syn keyword cType ExternalResult
@@ -440,10 +439,9 @@
 syn keyword cType Friction
 syn keyword cType Gauss
-syn keyword cType GaussianVariogram
-syn keyword cType gaussobjects
 syn keyword cType GaussPenta
 syn keyword cType GaussSeg
 syn keyword cType GaussTetra
 syn keyword cType GaussTria
+syn keyword cType GaussianVariogram
 syn keyword cType GenericExternalResult
 syn keyword cType GenericOption
@@ -459,5 +457,4 @@
 syn keyword cType IntVecParam
 syn keyword cType IoModel
-syn keyword cType krigingobjects
 syn keyword cType Load
 syn keyword cType Loads
@@ -467,6 +464,6 @@
 syn keyword cType Matice
 syn keyword cType Matpar
-syn keyword cType matrixobjects
 syn keyword cType MatrixParam
+syn keyword cType Matseaice
 syn keyword cType Misfit
 syn keyword cType Node
@@ -476,6 +473,6 @@
 syn keyword cType Observations
 syn keyword cType Option
+syn keyword cType OptionUtilities
 syn keyword cType Options
-syn keyword cType OptionUtilities
 syn keyword cType Param
 syn keyword cType Parameters
@@ -489,10 +486,10 @@
 syn keyword cType Quadtree
 syn keyword cType Results
+syn keyword cType RiftStruct
 syn keyword cType Riftfront
-syn keyword cType RiftStruct
 syn keyword cType Seg
 syn keyword cType SegInput
+syn keyword cType SegRef
 syn keyword cType Segment
-syn keyword cType SegRef
 syn keyword cType SpcDynamic
 syn keyword cType SpcStatic
@@ -514,4 +511,8 @@
 syn keyword cType Vertex
 syn keyword cType Vertices
+syn keyword cType classes
+syn keyword cType gaussobjects
+syn keyword cType krigingobjects
+syn keyword cType matrixobjects
 syn keyword cType AdjointBalancethickness2Analysis
 syn keyword cType AdjointBalancethicknessAnalysis
@@ -542,4 +543,5 @@
 syn keyword cType MeltingAnalysis
 syn keyword cType MeshdeformationAnalysis
+syn keyword cType SeaiceAnalysis
 syn keyword cType SmoothedSurfaceSlopeXAnalysis
 syn keyword cType SmoothedSurfaceSlopeYAnalysis
@@ -548,4 +550,5 @@
 syn keyword cType StressbalanceVerticalAnalysis
 syn keyword cType ThermalAnalysis
+syn keyword cType UzawaPressureAnalysis
 "ISSM's objects end
 "ISSM's Enums begin
@@ -708,5 +711,4 @@
 syn keyword cConstant InversionVzObsEnum
 syn keyword cConstant MaskIceLevelsetEnum
-syn keyword cConstant QmuMaskIceLevelsetEnum
 syn keyword cConstant MaterialsBetaEnum
 syn keyword cConstant MaterialsHeatcapacityEnum
@@ -721,5 +723,4 @@
 syn keyword cConstant DamageDEnum
 syn keyword cConstant DamageFEnum
-syn keyword cConstant QmuDamageDEnum
 syn keyword cConstant DamageDbarEnum
 syn keyword cConstant DamageLawEnum
@@ -741,4 +742,5 @@
 syn keyword cConstant DamageEvolutionNumRequestedOutputsEnum
 syn keyword cConstant DamageEvolutionRequestedOutputsEnum
+syn keyword cConstant NewDamageEnum
 syn keyword cConstant MaterialsRhoIceEnum
 syn keyword cConstant MaterialsRhoSeawaterEnum
@@ -794,5 +796,4 @@
 syn keyword cConstant QmuResponsedescriptorsEnum
 syn keyword cConstant QmuVariabledescriptorsEnum
-syn keyword cConstant QmuMaterialsRheologyBEnum
 syn keyword cConstant RiftsNumriftsEnum
 syn keyword cConstant RiftsRiftstructEnum
@@ -844,9 +845,5 @@
 syn keyword cConstant BalancethicknessApparentMassbalanceEnum
 syn keyword cConstant Balancethickness2MisfitEnum
-syn keyword cConstant BalancethicknessNuxEnum
-syn keyword cConstant BalancethicknessNuyEnum
-syn keyword cConstant BalancethicknessVxObsEnum
-syn keyword cConstant BalancethicknessVyObsEnum
-syn keyword cConstant BalancethicknessThicknessObsEnum
+syn keyword cConstant BalancethicknessDiffusionCoefficientEnum
 syn keyword cConstant SurfaceforcingsEnum
 syn keyword cConstant SMBEnum
@@ -926,6 +923,9 @@
 syn keyword cConstant ThermalSolutionEnum
 syn keyword cConstant TransientSolutionEnum
+syn keyword cConstant UzawaPressureAnalysisEnum
 syn keyword cConstant GiaSolutionEnum
 syn keyword cConstant GiaAnalysisEnum
+syn keyword cConstant SeaiceSolutionEnum
+syn keyword cConstant SeaiceAnalysisEnum
 syn keyword cConstant MeshdeformationSolutionEnum
 syn keyword cConstant MeshdeformationAnalysisEnum
@@ -1035,15 +1035,4 @@
 syn keyword cConstant PressureEnum
 syn keyword cConstant PressurePicardEnum
-syn keyword cConstant QmuPressureEnum
-syn keyword cConstant QmuVxEnum
-syn keyword cConstant QmuVyEnum
-syn keyword cConstant QmuVzEnum
-syn keyword cConstant QmuThicknessEnum
-syn keyword cConstant QmuBaseEnum
-syn keyword cConstant QmuSurfaceEnum
-syn keyword cConstant QmuMeltingEnum
-syn keyword cConstant QmuVxMeshEnum
-syn keyword cConstant QmuVyMeshEnum
-syn keyword cConstant QmuVzMeshEnum
 syn keyword cConstant AndroidFrictionCoefficientEnum
 syn keyword cConstant ResetPenaltiesEnum
@@ -1089,5 +1078,4 @@
 syn keyword cConstant BasalFrictionEnum
 syn keyword cConstant ViscousHeatingEnum
-syn keyword cConstant QmuTemperatureEnum
 syn keyword cConstant HydrologyWaterVxEnum
 syn keyword cConstant HydrologyWaterVyEnum
@@ -1100,4 +1088,5 @@
 syn keyword cConstant StressTensoryzEnum
 syn keyword cConstant StressTensorzzEnum
+syn keyword cConstant StressMaxPrincipalEnum
 syn keyword cConstant DeviatoricStressEnum
 syn keyword cConstant DeviatoricStressxxEnum
@@ -1135,7 +1124,9 @@
 syn keyword cConstant MINIcondensedEnum
 syn keyword cConstant TaylorHoodEnum
+syn keyword cConstant LATaylorHoodEnum
 syn keyword cConstant XTaylorHoodEnum
 syn keyword cConstant OneLayerP4zEnum
 syn keyword cConstant CrouzeixRaviartEnum
+syn keyword cConstant LACrouzeixRaviartEnum
 syn keyword cConstant SaveResultsEnum
 syn keyword cConstant BoolExternalResultEnum
@@ -1179,4 +1170,7 @@
 syn keyword cConstant IncrementalEnum
 syn keyword cConstant AugmentedLagrangianREnum
+syn keyword cConstant AugmentedLagrangianRhopEnum
+syn keyword cConstant AugmentedLagrangianRlambdaEnum
+syn keyword cConstant AugmentedLagrangianRholambdaEnum
 syn keyword cConstant AugmentedLagrangianThetaEnum
 syn keyword cConstant NoneEnum
@@ -1187,5 +1181,4 @@
 syn keyword cConstant ContactEnum
 syn keyword cConstant MaskGroundediceLevelsetEnum
-syn keyword cConstant QmuMaskGroundediceLevelsetEnum
 syn keyword cConstant GaussSegEnum
 syn keyword cConstant GaussTriaEnum
@@ -1247,4 +1240,36 @@
 syn keyword cConstant LevelsetfunctionSlopeYEnum
 syn keyword cConstant LevelsetfunctionPicardEnum
+syn keyword cConstant SeaiceatmEnum
+syn keyword cConstant SeaiceoceanEnum
+syn keyword cConstant SeaiceThicknessEnum
+syn keyword cConstant SeaiceConcentrationEnum
+syn keyword cConstant SeaiceSpcvxEnum
+syn keyword cConstant SeaiceSpcvyEnum
+syn keyword cConstant SeaiceCoriolisFactorEnum
+syn keyword cConstant BasalforcingsRhoOceanEnum
+syn keyword cConstant BasalforcingsOceanCoefEnum
+syn keyword cConstant BasalforcingsOceanLinDragCoefEnum
+syn keyword cConstant BasalforcingsOceanQuadDragCoefEnum
+syn keyword cConstant BasalforcingsOceanTurningAngleEnum
+syn keyword cConstant BasalforcingsOceanSshEnum
+syn keyword cConstant BasalforcingsOceanVxEnum
+syn keyword cConstant BasalforcingsOceanVyEnum
+syn keyword cConstant SurfaceforcingsRhoAirEnum
+syn keyword cConstant SurfaceforcingsAirCoefEnum
+syn keyword cConstant SurfaceforcingsAirLinDragCoefEnum
+syn keyword cConstant SurfaceforcingsAirQuadDragCoefEnum
+syn keyword cConstant SurfaceforcingsWindVxEnum
+syn keyword cConstant SurfaceforcingsWindVyEnum
+syn keyword cConstant MatseaiceEnum
+syn keyword cConstant MaterialsPoissonEnum
+syn keyword cConstant MaterialsYoungModulusEnum
+syn keyword cConstant MaterialsDamageEnum
+syn keyword cConstant MaterialsRidgingExponentEnum
+syn keyword cConstant MaterialsCohesionEnum
+syn keyword cConstant MaterialsInternalFrictionCoefEnum
+syn keyword cConstant MaterialsCompressionCoefEnum
+syn keyword cConstant MaterialsTractionCoefEnum
+syn keyword cConstant VxStarEnum
+syn keyword cConstant VyStarEnum
 "ISSM's Enums end
 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Index: /issm/trunk/jenkins/execute_shell
===================================================================
--- /issm/trunk/jenkins/execute_shell	(revision 19104)
+++ /issm/trunk/jenkins/execute_shell	(revision 19105)
@@ -10,6 +10,4 @@
 	imac-012301-gil )
 		configfile=imac-012301-gil ;;
-	larsen )
-		configfile=linux64_larsen ;;
 	windows )
 		configfile=windows
Index: /issm/trunk/jenkins/imac-012301-gil
===================================================================
--- /issm/trunk/jenkins/imac-012301-gil	(revision 19104)
+++ /issm/trunk/jenkins/imac-012301-gil	(revision 19105)
@@ -1,4 +1,2 @@
-#
-########### Configuration file for Eric Larour's Jenkins run on MaxOSX ############
 
 #-------------------------------#
@@ -6,25 +4,18 @@
 #-------------------------------#
 
-#Nightly run name
-NAME="ISSM matlab tests on MacOSX"
-
-#ISSM Architecture
-ISSM_ARCH="macosx-gnu"
-
 #ISSM CONFIGURATION 
 ISSM_CONFIG='--prefix=$ISSM_DIR \
 	--with-matlab-dir=$MATLAB_DIR \
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
-	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
 	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
-	--with-mpi-libflags=" $ISSM_DIR/externalpackages/mpich/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich/install/lib/libmpl.a " \
-	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-numthreads=8 \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lpmpich -lmpich -lmpl" \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
-	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
 	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-m1qn3-dir=$ISSM_DIR/externalpackages/m1qn3/install \
+	--with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
+	--with-numthreads=8 \
+	--enable-debugging \
 	--enable-development'
 
@@ -59,8 +50,9 @@
 						mpich     install-3.0-macosx64.sh    
 						cmake     install.sh                
-						petsc     install-3.5-macosx64.sh    
+						m1qn3     install.sh    
+						petsc     install-3.4-macosx64.sh
+						tao       install-2.2.sh
 						triangle  install-macosx64.sh 
 						shell2junit  install.sh "
-
 
 #---------------------#
@@ -73,20 +65,6 @@
 ISSM_COMPILATION="yes"
 
-#----------------------#
-# 5: Mail notification #
-#----------------------#
-
-#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
-#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
-SKIPMAIL="no"
-
-#Sender email address
-EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
-
-#Mailing list
-MAILINGLIST="eric.larour@jpl.nasa.gov"
-
 #------------------------#
-# 6: Nightly run options #
+# 5: Nightly run options #
 #------------------------#
 
Index: /issm/trunk/jenkins/jenkins.sh
===================================================================
--- /issm/trunk/jenkins/jenkins.sh	(revision 19104)
+++ /issm/trunk/jenkins/jenkins.sh	(revision 19105)
@@ -3,49 +3,4 @@
 #It then processes the results and sends an email to the Ice developpers.
 
-#some functions
-function timer() #{{{
-{
-	if [[ $# -eq 0 ]]; then
-		echo $(date '+%s')
-	else
-		local  stime=$1
-		etime=$(date '+%s')
-
-		if [[ -z "$stime" ]]; then stime=$etime; fi
-
-		dt=$((etime - stime))
-		ds=$((dt % 60))
-		dm=$(((dt / 60) % 60))
-		dh=$((dt / 3600))
-		printf '%d:%02d:%02d' $dh $dm $ds
-	fi
-} #}}}
-function todaydate() #{{{
-{
-	suffix=`date | awk '{printf("%s-%s-%s  %s",$2,$3,$6,$4);}'`			 
-	echo $suffix;			 
-} #}}}
-function host_name() #{{{
-{
-	#return host name depending on the OS
-	if [ "$1" = "win7" ] 
-	then
-		HOST_NAME=`hostname | sed 's/-//g'`;
-	else
-		HOST_NAME=`hostname -s | sed 's/-//g'`;
-	fi
-	echo $HOST_NAME;
-} #}}}
-function pause() #{{{
-{
-pid=`ps aux -W | grep $1 | awk '{printf("%s\n",$1);}'`
-
-while [ -n "$pid" ]
-do
-	pid=`ps aux -W | grep $1 | awk '{printf("%s\n",$1);}'`
-done
-}
-#}}}
-
 #Get configuration
 #Source config file{{{
@@ -63,15 +18,9 @@
 source $1;
 #}}}
-#Initialize variables {{{
-TODAY=$(todaydate);
+#Get Operating system (OS) name{{{
 OS=$(uname -s)
 if [[ $OS == "CYGWIN_NT-6.1-WOW64" ]]; then 
 	OS="win7";
 fi
-HOST_NAME=$(host_name $OS);
-START_TIME=$(timer);
-ISSM_RELEASE=$(basename $(echo $REPOSITORY));
-USER=$(whoami);
-INIT_PATH=$(pwd);
 #}}}
 
@@ -211,36 +160,15 @@
 echo "Cleaning up execution directory"
 rm -rf $ISSM_DIR/execution/*
-
-#Prepare info.log
-#{{{
 rm -rf $ISSM_DIR/nightlylog
 mkdir  $ISSM_DIR/nightlylog
-INSTALL_TIME=$(timer)
-ELAPSED=$(timer $START_TIME)
-VERSION=$(svnversion $ISSM_DIR)
-cat << END > $ISSM_DIR/nightlylog/info.log
-name:      $(echo $NAME)
-today:     $(echo $TODAY)
-user:      $(echo $USER)
-host:      $(echo $HOST_NAME)
-OS:        $(echo $OS)
-release:   $(echo $ISSM_RELEASE)
-init_path: $(echo $INIT_PATH)
-is_matlab: $(echo $MATLAB_TEST)
-is_python: $(echo $PYTHON_TEST)
-elapsed_install: $(echo $ELAPSED)
-version: $(echo $VERSION)
-END
-#}}}
 
 #matlab tests
 if [ $MATLAB_TEST -eq 1 ]; then
 #Launch all tests on different cpus {{{
-MATLAB_START_TIME=$(timer);
 for (( i=1;i<=$NUMCPUS_RUN;i++ ))
 do
 	#Launch matlab and the nightly run script
 	cat > $ISSM_DIR/nightlylog/matlab_run$i.m << EOF
-	warning off %necessary to avoid a info.log of several Go for parallel runs
+	warning off %necessary to avoid a log of several Go for parallel runs
 	try,
 	$(if [ "$MATLAB_NROPTIONS" = ""  ]
@@ -264,10 +192,17 @@
 EOF
 	cd $ISSM_DIR/test/NightlyRun
-	matlab -nojvm -nosplash -r "addpath $ISSM_DIR/src/m/dev; devpath; addpath $ISSM_DIR/nightlylog/; matlab_run$i" -logfile $ISSM_DIR/nightlylog/matlab_log$i.log &
+	$MATLAB_PATH/bin/matlab -nojvm -nosplash -r "addpath $ISSM_DIR/src/m/dev; devpath; addpath $ISSM_DIR/nightlylog/; matlab_run$i" -logfile $ISSM_DIR/nightlylog/matlab_log$i.log &
 done
 
 #wait until matlab closes
 if [ "$OS" = "win7" ]; then
-	pause MATLAB
+	echo "Waiting for matlab on windows"
+	pid=$(ps aux -W | grep MATLAB | awk '{printf("%s\n","MATLAB");}')
+	while [ -n "$pid" ]
+	do
+		pid=$(ps aux -W | grep MATLAB | awk '{printf("%s\n","MATLAB");}')
+		sleep 1;
+	done
+	echo "DONE!"
 else
 	wait
@@ -284,18 +219,4 @@
 #filter out windows characters: 
 cat matlab_log.log | tr -cd '\11\12\40-\176' > matlab_log.log2 && mv matlab_log.log2 matlab_log.log
-
-#}}}
-#Complete info.log {{{
-if [ $(cat matlab_log.log | grep "MATLABEXITEDCORRECTLY" | wc -l) -eq $NUMCPUS_RUN ]
-then
-	MATLABCRASH=0
-else
-	MATLABCRASH=1
-fi
-ELAPSED=$(timer $MATLAB_START_TIME)
-cat << END >>  $ISSM_DIR/nightlylog/info.log
-elapsed_matlab: $(echo $ELAPSED)
-matlab_crash:   $(echo $MATLABCRASH)
-END
 #}}}
 fi
@@ -312,11 +233,4 @@
 done
 
-#wait until python closes
-if [ "$OS" = "win7" ]; then
-	pause MATLAB
-else
-	wait
-fi
-
 #concatenate reports
 cd $ISSM_DIR/nightlylog/
@@ -327,26 +241,5 @@
 done
 #}}}
-#Complete info.log {{{
-if [ $(cat python_log.log | grep "PYTHONEXITEDCORRECTLY" | wc -l) -eq $NUMCPUS_RUN ]
-then
-	PYTHONCRASH=0
-else
-	PYTHONCRASH=1
-fi
-ELAPSED=$(timer $PYTHON_START_TIME)
-cat << END >>  $ISSM_DIR/nightlylog/info.log
-elapsed_python: $(echo $ELAPSED)
-python_crash:   $(echo $PYTHONCRASH)
-END
-#}}}
-fi
-
-#complete info.log
-#{{{
-ELAPSED=$(timer $START_TIME)
-cat << END >>  $ISSM_DIR/nightlylog/info.log
-elapsed_total:  $(echo $ELAPSED)
-END
-#}}}
+fi
 
 #process logs to be junit compatible
Index: sm/trunk/jenkins/linux64_larsen
===================================================================
--- /issm/trunk/jenkins/linux64_larsen	(revision 19104)
+++ 	(revision )
@@ -1,108 +1,0 @@
-#
-########### Configuration file for Eric Larour's Jenkins run on Murdo ############
-
-#-------------------------------#
-# 1: ISSM general configuration #
-#-------------------------------#
-
-#Nightly run name
-NAME="ISSM matlab tests on Linux64 (murdo)"
-
-#ISSM Architecture
-ISSM_ARCH="linux-gnu-amd64"
-
-#ISSM CONFIGURATION 
-ISSM_CONFIG='--prefix=$ISSM_DIR\
-	--with-matlab-dir=$MATLAB_DIR \
-	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
-	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
-	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
-	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
-	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
-	--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
-	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
-	--with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
-	--with-numthreads=18 \
-	--enable-development \
-	--enable-debugging '
-
-#MATLAB path
-MATLAB_PATH="/usr/local/matlab80/"
-
-#PYTHON and MATLAB testing
-MATLAB_TEST=1
-PYTHON_TEST=0
-
-#execution path used for parallel runs
-EXECUTION_PATH=$ISSM_DIR/execution
-
-#repo:
-REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
-
-#-----------------------------------#
-# 3: External packages installation #
-#-----------------------------------#
-
-#ISSM_EXTERNALPACKAGES can have 3 values:
-# - "install" install all external packages listed below
-# - "copy"    copy existing directories (EXTERNALPACKAGESDIR)
-# - "none"    leave external packages as is
-#             ->skip to section 4
-ISSM_EXTERNALPACKAGES="install"
-EXTERNALPACKAGESDIR=$ISSM_DIR/externalpackages
-
-#List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="autotools install.sh                
-						matlab    install.sh                
-						mpich     install-3.0-linux64.sh    
-						cmake     install.sh                
-						petsc     install-3.5-linux64.sh    
-						triangle  install-linux64.sh        
-						boost     install.sh                
-						dakota    install-5.3.1-linux64.sh  
-						chaco     install.sh 
-						shell2junit install.sh"
-
-#---------------------#
-# 4: ISSM Compilation #
-#---------------------#
-
-#ISSM_COMPILATION can have 2 values:
-# - "yes" compile ISSM
-# - "no"  do not compile ISSM
-ISSM_COMPILATION="yes"
-
-#----------------------#
-# 5: Mail notification #
-#----------------------#
-
-#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
-#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
-SKIPMAIL="no"
-
-#Sender email address
-EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
-
-#Mailing list
-MAILINGLIST="eric.larour@jpl.nasa.gov"
-
-#------------------------#
-# 6: Nightly run options #
-#------------------------#
-
-#number of cpus used in ISSM installation and compilation (one is usually
-#safer as some packages are very sensitive to parallel compilation)
-NUMCPUS_INSTALL=8
-
-#number of cpus used in the nightly runs.
-NUMCPUS_RUN=8
-
-#Nightly run options. The matlab routine runme.m will be called
-#as follows: runme($MATLAB_NROPTIONS). The options must be understandable
-#by Matlab and runme.m
-#ex: "'id',[101 102 103]"
-MATLAB_NROPTIONS=""
-PYTHON_NROPTIONS=""
Index: /issm/trunk/jenkins/linux64_murdo
===================================================================
--- /issm/trunk/jenkins/linux64_murdo	(revision 19104)
+++ /issm/trunk/jenkins/linux64_murdo	(revision 19105)
@@ -1,4 +1,2 @@
-#
-########### Configuration file for Eric Larour's Jenkins run on Murdo ############
 
 #-------------------------------#
@@ -6,26 +4,21 @@
 #-------------------------------#
 
-#Nightly run name
-NAME="ISSM matlab tests on Linux64 (murdo)"
-
-#ISSM Architecture
-ISSM_ARCH="linux-gnu-amd64"
-
 #ISSM CONFIGURATION 
 ISSM_CONFIG='--prefix=$ISSM_DIR\
 	--with-matlab-dir=$MATLAB_DIR \
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
-	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
 	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
-	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpich" \
 	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
 	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy\
-	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
-	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
 	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
-	--with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
 	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
 	--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
+	--with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.6/ -lgfortran" \
+	--with-m1qn3-dir=$ISSM_DIR/externalpackages/m1qn3/install \
 	--with-numthreads=18 \
 	--enable-development \
@@ -58,13 +51,13 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES="autotools install.sh                
-						matlab    install.sh                
-						mpich     install-3.0-linux64.sh    
-						cmake     install.sh                
-						petsc     install-3.5-linux64.sh    
-						triangle  install-linux64.sh        
-						boost     install.sh                
-						dakota    install-5.3.1-linux64.sh  
-						chaco     install.sh 
+EXTERNALPACKAGES="autotools     install.sh                
+						matlab        install.sh                
+						mpich         install-3.0-linux64.sh    
+						cmake         install.sh                
+						petsc         install-3.5-linux64.sh    
+						triangle      install-linux64.sh        
+						boost         install.sh                
+						dakota        install-5.3.1-linux64.sh  
+						chaco         install.sh 
 						python        install-2.7.3-linux64.sh    
 						nose          install-linux64-python2.sh  
@@ -72,4 +65,5 @@
 						lapack        install-linux64.sh          
 						git           install.sh                  
+						m1qn3         install.sh          
 						numpy         install-linux64.sh          
 						scipy         install-linux64.sh          
@@ -77,5 +71,5 @@
 						netcdf        install.sh                  
 						netcdf-python install.sh
-						shell2junit install.sh"
+						shell2junit   install.sh"
 
 
@@ -89,20 +83,6 @@
 ISSM_COMPILATION="yes"
 
-#----------------------#
-# 5: Mail notification #
-#----------------------#
-
-#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
-#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
-SKIPMAIL="no"
-
-#Sender email address
-EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
-
-#Mailing list
-MAILINGLIST="eric.larour@jpl.nasa.gov"
-
 #------------------------#
-# 6: Nightly run options #
+# 5: Nightly run options #
 #------------------------#
 
Index: /issm/trunk/jenkins/linux64_murdo_ad
===================================================================
--- /issm/trunk/jenkins/linux64_murdo_ad	(revision 19104)
+++ /issm/trunk/jenkins/linux64_murdo_ad	(revision 19105)
@@ -1,13 +1,6 @@
-########### Configuration file for Eric Larour's Jenkins runs on Linux. Automatic differentiation ############
-
+#
 #-------------------------------#
 # 1: ISSM general configuration #
 #-------------------------------#
-
-#Nightly run name
-NAME="ISSM tests on Linux64 (murdo). Automatic differentiation validation tests"
-
-#ISSM Architecture
-ISSM_ARCH="linux-gnu-amd64"
 
 #ISSM CONFIGURATION 
@@ -68,20 +61,6 @@
 ISSM_COMPILATION="yes"
 
-#----------------------#
-# 5: Mail notification #
-#----------------------#
-
-#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
-#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
-SKIPMAIL="no"
-
-#Sender email address
-EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
-
-#Mailing list
-MAILINGLIST="eric.larour@jpl.nasa.gov"
-
 #------------------------#
-# 6: Nightly run options #
+# 5: Nightly run options #
 #------------------------#
 
Index: /issm/trunk/jenkins/linux64_murdo_ampi
===================================================================
--- /issm/trunk/jenkins/linux64_murdo_ampi	(revision 19104)
+++ /issm/trunk/jenkins/linux64_murdo_ampi	(revision 19105)
@@ -1,14 +1,6 @@
-#
-########### Configuration file for Eric Larour's Jenkins run on Murdo ############
 
 #-------------------------------#
 # 1: ISSM general configuration #
 #-------------------------------#
-
-#Nightly run name
-NAME="ISSM tests on Linux64 (murdo). Automatic differentiation validation tests with ampi"
-
-#ISSM Architecture
-ISSM_ARCH="linux-gnu-amd64"
 
 #ISSM CONFIGURATION 
@@ -24,5 +16,4 @@
 				  --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
 				  --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
-				  --with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
 				  --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
 				  --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
@@ -30,4 +21,5 @@
 				  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
 				  --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+				  --with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.6/ -lgfortran" \
 				  --enable-development \
 				  --enable-debugging CXXFLAGS="-g -O0" '
@@ -81,25 +73,11 @@
 ISSM_COMPILATION="yes"
 
-#----------------------#
-# 5: Mail notification #
-#----------------------#
-
-#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
-#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
-SKIPMAIL="no"
-
-#Sender email address
-EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
-
-#Mailing list
-MAILINGLIST="eric.larour@jpl.nasa.gov"
-
 #------------------------#
-# 6: Nightly run options #
+# 5: Nightly run options #
 #------------------------#
 
 #number of cpus used in ISSM installation and compilation (one is usually
 #safer as some packages are very sensitive to parallel compilation)
-NUMCPUS_INSTALL=8
+NUMCPUS_INSTALL=1
 
 #number of cpus used in the nightly runs.
Index: /issm/trunk/jenkins/linux64_murdo_gia
===================================================================
--- /issm/trunk/jenkins/linux64_murdo_gia	(revision 19105)
+++ /issm/trunk/jenkins/linux64_murdo_gia	(revision 19105)
@@ -0,0 +1,84 @@
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM CONFIGURATION 
+ISSM_CONFIG='--prefix=$ISSM_DIR\
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpich" \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-math77-dir=$ISSM_DIR/externalpackages/math77/install \
+	--with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.6/ -lgfortran" \
+	--with-gia=yes \
+	--with-numthreads=18 \
+	--enable-development \
+	--enable-debugging '
+
+#MATLAB path
+MATLAB_PATH="/usr/local/matlab80/"
+
+#PYTHON and MATLAB testing
+MATLAB_TEST=1
+PYTHON_TEST=0
+
+#execution path used for parallel runs
+EXECUTION_PATH=$ISSM_DIR/execution
+
+#repo:
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+
+#-----------------------------------#
+# 3: External packages installation #
+#-----------------------------------#
+
+#ISSM_EXTERNALPACKAGES can have 3 values:
+# - "install" install all external packages listed below
+# - "copy"    copy existing directories (EXTERNALPACKAGESDIR)
+# - "none"    leave external packages as is
+#             ->skip to section 4
+ISSM_EXTERNALPACKAGES="install"
+EXTERNALPACKAGESDIR=$ISSM_DIR/externalpackages
+
+#List of external pakages to be installed and their installation scripts
+EXTERNALPACKAGES="autotools     install.sh                
+						matlab        install.sh                
+						mpich         install-3.0-linux64.sh    
+						cmake         install.sh                
+						petsc         install-3.5-linux64.sh    
+						triangle      install-linux64.sh        
+						math77        install.sh
+						shell2junit   install.sh"
+
+
+#---------------------#
+# 4: ISSM Compilation #
+#---------------------#
+
+#ISSM_COMPILATION can have 2 values:
+# - "yes" compile ISSM
+# - "no"  do not compile ISSM
+ISSM_COMPILATION="yes"
+
+#------------------------#
+# 5: Nightly run options #
+#------------------------#
+
+#number of cpus used in ISSM installation and compilation (one is usually
+#safer as some packages are very sensitive to parallel compilation)
+NUMCPUS_INSTALL=8
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=1
+
+#Nightly run options. The matlab routine runme.m will be called
+#as follows: runme($MATLAB_NROPTIONS). The options must be understandable
+#by Matlab and runme.m
+#ex: "'id',[101 102 103]"
+MATLAB_NROPTIONS="'benchmark','all','id',[2001:2100]"
+PYTHON_NROPTIONS=""
Index: /issm/trunk/jenkins/linux64_murdo_iceocean
===================================================================
--- /issm/trunk/jenkins/linux64_murdo_iceocean	(revision 19105)
+++ /issm/trunk/jenkins/linux64_murdo_iceocean	(revision 19105)
@@ -0,0 +1,81 @@
+
+#-------------------------------#
+# 1: ISSM general configuration #
+#-------------------------------#
+
+#ISSM CONFIGURATION 
+ISSM_CONFIG='--prefix=$ISSM_DIR\
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+	--with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib -lmpich" \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.6/ -lgfortran" \
+	--with-numthreads=18 \
+	--enable-development \
+	--enable-debugging '
+
+#MATLAB path
+MATLAB_PATH="/usr/local/matlab80/"
+
+#PYTHON and MATLAB testing
+MATLAB_TEST=1
+PYTHON_TEST=0
+
+#execution path used for parallel runs
+EXECUTION_PATH=$ISSM_DIR/execution
+
+#repo:
+REPOSITORY="https://issm.ess.uci.edu/svn/issm/issm/trunk-jpl"
+
+#-----------------------------------#
+# 3: External packages installation #
+#-----------------------------------#
+
+#ISSM_EXTERNALPACKAGES can have 3 values:
+# - "install" install all external packages listed below
+# - "copy"    copy existing directories (EXTERNALPACKAGESDIR)
+# - "none"    leave external packages as is
+#             ->skip to section 4
+ISSM_EXTERNALPACKAGES="install"
+EXTERNALPACKAGESDIR=$ISSM_DIR/externalpackages
+
+#List of external pakages to be installed and their installation scripts
+EXTERNALPACKAGES="autotools     install.sh                
+						matlab        install.sh                
+						mpich         install-3.0-linux64.sh    
+						cmake         install.sh                
+						petsc         install-3.5-linux64.sh    
+						triangle      install-linux64.sh        
+						shell2junit   install.sh"
+
+
+#---------------------#
+# 4: ISSM Compilation #
+#---------------------#
+
+#ISSM_COMPILATION can have 2 values:
+# - "yes" compile ISSM
+# - "no"  do not compile ISSM
+ISSM_COMPILATION="yes"
+
+#------------------------#
+# 5: Nightly run options #
+#------------------------#
+
+#number of cpus used in ISSM installation and compilation (one is usually
+#safer as some packages are very sensitive to parallel compilation)
+NUMCPUS_INSTALL=8
+
+#number of cpus used in the nightly runs.
+NUMCPUS_RUN=1
+
+#Nightly run options. The matlab routine runme.m will be called
+#as follows: runme($MATLAB_NROPTIONS). The options must be understandable
+#by Matlab and runme.m
+#ex: "'id',[101 102 103]"
+MATLAB_NROPTIONS="'benchmark','all','id',4001"
+PYTHON_NROPTIONS=""
Index: /issm/trunk/jenkins/parsing_rules
===================================================================
--- /issm/trunk/jenkins/parsing_rules	(revision 19104)
+++ /issm/trunk/jenkins/parsing_rules	(revision 19105)
@@ -1,6 +1,6 @@
-ok /not really/
-
 # match line starting with 'error ', case-insensitive
 error /.*\\berror:\\b.*/
+error /FAILURE/
+error /failed/
 
 # list of warnings here...
Index: /issm/trunk/jenkins/windows
===================================================================
--- /issm/trunk/jenkins/windows	(revision 19104)
+++ /issm/trunk/jenkins/windows	(revision 19105)
@@ -1,4 +1,2 @@
-#
-########### Configuration file for Eric Larour's Jenkins run on Windows ############
 
 #-------------------------------#
@@ -6,20 +4,13 @@
 #-------------------------------#
 
-#Nightly run name
-NAME="ISSM matlab tests on Windows"
-
-#ISSM Architecture
-ISSM_ARCH="cygwin-intel"
-
 #ISSM CONFIGURATION 
 ISSM_CONFIG='--prefix=$ISSM_DIR \
    --disable-static \
+	--enable-standalone-libraries \
 	--without-Gia \
 	--with-vendor=intel-win7-64  \
 	--with-matlab-dir=""$ISSM_DIR/externalpackages/matlab/install"" \
 	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
-	--with-metis-dir="$ISSM_DIR/externalpackages/metis/install" \
 	--with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-petsc-arch=$ISSM_ARCH  \
 	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install/lib/  \
 	--with-mpi-libdir="$ISSM_DIR/externalpackages/petsc/install/lib" \
@@ -54,9 +45,9 @@
 
 #List of external pakages to be installed and their installation scripts
-EXTERNALPACKAGES=" cccl install-win7.sh
-						petsc     install-3.1-win7.sh
-						triangle  install-win7.sh        
-						matlab install.sh
-						metis install-4.0-win7.sh
+EXTERNALPACKAGES="cccl        install-win7.sh
+						cmake       install.sh                
+						petsc       install-3.5-win7.sh
+						triangle    install-win7.sh        
+						matlab      install.sh
 						shell2junit install.sh"
 
@@ -70,20 +61,6 @@
 ISSM_COMPILATION="yes"
 
-#----------------------#
-# 5: Mail notification #
-#----------------------#
-
-#Mail delivery. If SKIPMAIL="no", the html nightly run report will be
-#sent to the adresses present in $ISSM_DIR/cron/mailinglist.
-SKIPMAIL="no"
-
-#Sender email address
-EMAIL_ADRESS="eric.larour@jpl.nasa.gov"
-
-#Mailing list
-MAILINGLIST="eric.larour@jpl.nasa.gov"
-
 #------------------------#
-# 6: Nightly run options #
+# 5: Nightly run options #
 #------------------------#
 
@@ -103,4 +80,2 @@
 MATLAB_NROPTIONS="'exclude',[104, 124, 204, 211, 215, 220, 221, 285, 290, 308, 322, 404, 421, 422, 503, 507, 510, 511, 701, 702, 703, 218, 234, 235, 412, 413, 414, 417, 418, 420, 205, 274, 331, 405, 409, 455, 612, 514, 435, 280,801,802,803,804,805,291]"
 PYTHON_NROPTIONS=""
-
-
Index: /issm/trunk/m4/analyses.m4
===================================================================
--- /issm/trunk/m4/analyses.m4	(revision 19104)
+++ /issm/trunk/m4/analyses.m4	(revision 19105)
@@ -346,31 +346,31 @@
 AC_MSG_RESULT($HAVE_DEPTHAVERAGE)
 dnl }}}
-dnl with-SmoothedSurfaceSlopeX{{{
-AC_ARG_WITH([SmoothedSurfaceSlopeX],
-	AS_HELP_STRING([--with-SmoothedSurfaceSlopeX = YES], [compile with SmoothedSurfaceSlopeX capabilities (default is yes)]),
-	[SMOOTHEDSURFACESLOPEX=$withval],[SMOOTHEDSURFACESLOPEX=yes])
-AC_MSG_CHECKING(for SmoothedSurfaceSlopeX capability compilation)
-
-HAVE_SMOOTHEDSURFACESLOPEX=no 
-if test "x$SMOOTHEDSURFACESLOPEX" = "xyes"; then
-	HAVE_SMOOTHEDSURFACESLOPEX=yes
-	AC_DEFINE([_HAVE_SMOOTHEDSURFACESLOPEX_],[1],[with SmoothedSurfaceSlopeXcapability])
-fi
-AM_CONDITIONAL([SMOOTHEDSURFACESLOPEX], [test x$HAVE_SMOOTHEDSURFACESLOPEX = xyes])
-AC_MSG_RESULT($HAVE_SMOOTHEDSURFACESLOPEX)
-dnl }}}
-dnl with-SmoothedSurfaceSlopeY{{{
-AC_ARG_WITH([SmoothedSurfaceSlopeY],
-	AS_HELP_STRING([--with-SmoothedSurfaceSlopeY = YES], [compile with SmoothedSurfaceSlopeY capabilities (default is yes)]),
-	[SMOOTHEDSURFACESLOPEY=$withval],[SMOOTHEDSURFACESLOPEY=yes])
-AC_MSG_CHECKING(for SmoothedSurfaceSlopeY capability compilation)
-
-HAVE_SMOOTHEDSURFACESLOPEY=no 
-if test "x$SMOOTHEDSURFACESLOPEY" = "xyes"; then
-	HAVE_SMOOTHEDSURFACESLOPEY=yes
-	AC_DEFINE([_HAVE_SMOOTHEDSURFACESLOPEY_],[1],[with SmoothedSurfaceSlopeYcapability])
-fi
-AM_CONDITIONAL([SMOOTHEDSURFACESLOPEY], [test x$HAVE_SMOOTHEDSURFACESLOPEY = xyes])
-AC_MSG_RESULT($HAVE_SMOOTHEDSURFACESLOPEY)
+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 Smoothcapability])
+fi
+AM_CONDITIONAL([SMOOTH], [test x$HAVE_SMOOTH = xyes])
+AC_MSG_RESULT($HAVE_SMOOTH)
+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 Thermalcapability])
+fi
+AM_CONDITIONAL([THERMAL], [test x$HAVE_THERMAL = xyes])
+AC_MSG_RESULT($HAVE_THERMAL)
 dnl }}}
 dnl with-UzawaPressure{{{
@@ -388,18 +388,4 @@
 AC_MSG_RESULT($HAVE_UZAWAPRESSURE)
 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 Thermalcapability])
-fi
-AM_CONDITIONAL([THERMAL], [test x$HAVE_THERMAL = xyes])
-AC_MSG_RESULT($HAVE_THERMAL)
-dnl }}}
 dnl with-Gia{{{
 AC_ARG_WITH([Gia],
@@ -416,4 +402,18 @@
 AC_MSG_RESULT($HAVE_GIA)
 dnl }}}
+dnl with-Seaice{{{
+AC_ARG_WITH([Seaice],
+	AS_HELP_STRING([--with-Seaice = YES], [compile with Seaice capabilities (default is yes)]),
+	[SEAICE=$withval],[SEAICE=yes])
+AC_MSG_CHECKING(for Seaice capability compilation)
+
+HAVE_SEAICE=no 
+if test "x$SEAICE" = "xyes"; then
+	HAVE_SEAICE=yes
+	AC_DEFINE([_HAVE_SEAICE_],[1],[with Seaicecapability])
+fi
+AM_CONDITIONAL([SEAICE], [test x$HAVE_SEAICE = xyes])
+AC_MSG_RESULT($HAVE_SEAICE)
+dnl }}}
 dnl with-Meshdeformation{{{
 AC_ARG_WITH([Meshdeformation],
Index: /issm/trunk/m4/issm_options.m4
===================================================================
--- /issm/trunk/m4/issm_options.m4	(revision 19104)
+++ /issm/trunk/m4/issm_options.m4	(revision 19105)
@@ -9,7 +9,8 @@
 	dnl ISSM's internal options
 	dnl Build info{{{
+	
+	dnl build date
 	AC_PATH_PROGS(DATE, date)
 	AC_MSG_CHECKING(for build date)
-	dnl system checks require uname
 	if test "$DATE" ; then
 		PACKAGE_DATE=`date`
@@ -19,4 +20,72 @@
 	AC_DEFINE_UNQUOTED(PACKAGE_BUILD_DATE,"$PACKAGE_DATE", Build date)
 	AC_MSG_RESULT($PACKAGE_DATE)
+
+	dnl user name
+	AC_MSG_CHECKING([user name])
+	if test -n "$USER"
+	then
+		user_name="$USER"
+	else
+		if test -n "$LOGNAME"
+		then
+			user_name="$LOGNAME"
+		else
+		   user_name=`(whoami) 2>/dev/null` || user_name=unknown
+		fi
+	fi
+	AC_DEFINE_UNQUOTED(USER_NAME, "$user_name", Build user name)
+	AC_MSG_RESULT($user_name)
+
+	AC_MSG_CHECKING([host full OS name and version])
+	dnl normalize some host OS names
+	case ${host_os} in
+	  dnl linux is linux is linux, regardless of RMS.
+	  linux-gnu* | lignux* )	host_os=linux ;;
+	esac
+	AC_DEFINE_UNQUOTED(HOST_OS, "$host_os", Host full OS name and version)
+	AC_MSG_RESULT($host_os)
+
+  AC_MSG_CHECKING([host cpu])
+  AC_DEFINE_UNQUOTED(HOST_CPU, "$host_cpu",Host cpu)
+  AC_MSG_RESULT($host_cpu)
+
+  AC_MSG_CHECKING([vendor])
+  AC_DEFINE_UNQUOTED(HOST_VENDOR, "$host_vendor",Host vendor)
+  AC_MSG_RESULT($host_vendor)
+
+  AC_MSG_CHECKING([host OS name])
+  host_os_name=`echo $host_os | sed 's/\..*//g'`
+  dnl normalize some OS names
+  case ${host_os_name} in
+	dnl linux is linux is linux, regardless of RMS.
+	linux-gnu* | lignux* )	host_os_name=linux ;;
+  esac
+  AC_DEFINE_UNQUOTED(HOST_OS_NAME, "$host_os_name", Host OS name)
+  AC_MSG_RESULT($host_os_name)
+
+	dnl parse out the OS version of the host
+  AC_MSG_CHECKING([host OS version])
+  host_os_version=`echo $host_os | sed 's/^[[^0-9]]*//g'`
+  if test -z "$host_os_version"
+  then
+	host_os_version=`(uname -r) 2>/dev/null` || host_os_version=unknown
+  fi
+  AC_DEFINE_UNQUOTED(HOST_OS_VERSION, "$host_os_version", Host OS version)
+  AC_MSG_RESULT($host_os_version)
+
+
+	dnl figure out host architecture (different than CPU)
+  AC_MSG_CHECKING([host OS architecture])
+  host_arch=`(uname -m) 2>/dev/null` || host_arch=unknown
+  dnl normalize some names
+  case ${host_arch} in
+	sun4* )	host_arch=sun4 ;;
+	sun3x )	host_arch=sun3 ;;
+	sun )	host_arch=`(arch) 2>/dev/null` || host_arch=unknown ;;
+	i?86 )	host_arch=i386 ;; # all x86 should show up as i386
+  esac
+  AC_DEFINE_UNQUOTED(HOST_ARCH, "$host_arch",Host Archictecture)
+  AC_MSG_RESULT($host_arch)
+
 	dnl }}}
 	dnl Debugging {{{
@@ -45,12 +114,28 @@
 	AC_MSG_RESULT($enable_development)
 	 dnl }}}
-    dnl Shared build {{{
-    AC_ARG_ENABLE([sharedlibs],                                                dnl feature
-        AS_HELP_STRING([--enable-sharedlibs], [produce libISSM.so.0]),         dnl help string
-        [enable_sharedlibs=$enableval],                                        dnl action if given
-        [enable_sharedlibs=no])                                                dnl action if not given
-	 AC_MSG_CHECKING(for shared library build)
-    AM_CONDITIONAL([SHAREDLIBS], [test x$enable_sharedlibs = xyes])
-	 AC_MSG_RESULT($enable_sharedlibs)
+    dnl Standalone Options {{{
+    AC_ARG_ENABLE([standalone-modules],                                                      dnl feature
+        AS_HELP_STRING([--enable-standalone-modules], [produce standalone modules]),         dnl help string
+        [enable_standalone_modules=$enableval],                                              dnl action if given
+        [enable_standalone_modules=no])                                                      dnl action if not given
+	AC_MSG_CHECKING(for standalone modules build)
+    AM_CONDITIONAL([STANDALONE_MODULES], [test x$enable_standalone_modules = xyes])
+	AC_MSG_RESULT($enable_standalone_modules)
+
+    AC_ARG_ENABLE([standalone-executables],                                                  dnl feature
+        AS_HELP_STRING([--enable-standalone-executables], [produce standalone executables]), dnl help string
+        [enable_standalone_executables=$enableval],                                          dnl action if given
+        [enable_standalone_executables=no])                                                  dnl action if not given
+	AC_MSG_CHECKING(for standalone executables build)
+    AM_CONDITIONAL([STANDALONE_EXECUTABLES], [test x$enable_standalone_executables = xyes])
+	AC_MSG_RESULT($enable_standalone_executables)
+
+    AC_ARG_ENABLE([standalone-libraries],                                                    dnl feature
+        AS_HELP_STRING([--enable-standalone-libraries], [produce standalone libraries]),     dnl help string
+        [enable_standalone_libraries=$enableval],                                            dnl action if given
+        [enable_standalone_libraries=no])                                                    dnl action if not given
+	AC_MSG_CHECKING(for standalone libraries build)
+    AM_CONDITIONAL([STANDALONE_LIBRARIES], [test x$enable_standalone_libraries = xyes])
+	AC_MSG_RESULT($enable_standalone_libraries)
     dnl }}}
     dnl Version{{{
@@ -111,4 +196,9 @@
 			export CFLAGS=" -D_INTEL_LINUX_"
 			export CXXFLAGS=" -D_INTEL_LINUX_"
+		elif test $VENDOR = intel-gp; then
+			export CC=icc
+			export CXX=icpc
+			export CFLAGS=" -D_INTEL_LINUX_"
+			export CXXFLAGS=" -D_INTEL_LINUX_"
 		elif test $VENDOR = intel-discover; then
 			export CC=icc
@@ -173,17 +263,18 @@
   				if  test $VENDOR = intel-win7-32; then
   					MEXLIB="-Wl,./../../c/libISSMCore.a -Wl,libISSMApi.a -Wl,libISSMMatlab.a -Wl,./../../c/libISSMModules.a -Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib" 
-               MEXLINK="-Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win32/microsoft` -no-undefined -Wl,/export:mexFunction" 
+               MEXLINK="-Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win32/microsoft` -no-undefined -Wl,/export:mexFunction -Wl,/LD"
+					MEXEXT=`$MATLAB_ROOT/bin/mexext.bat`
+					MEXEXT=".$MEXEXT"
   				elif  test l-win7-64; then
   					MEXLIB="-Wl,./../../c/libISSMCore.a -Wl,libISSMApi.a -Wl,libISSMMatlab.a -Wl,./../../c/libISSMModules.a -Wl,libmx.lib -Wl,libmex.lib -Wl,libmat.lib ${OSLIBS} -Wl,libf2cblas.lib -Wl,libf2clapack.lib" 
-               MEXLINK="-Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win64/microsoft` -no-undefined -Wl,/export:mexFunction" 
+               MEXLINK="-Wl,/LIBPATH:`cygpath -m ${MATLAB_ROOT}/extern/lib/win64/microsoft` -no-undefined -Wl,/export:mexFunction -Wl,/LD" 
+					MEXEXT=".mexw64"
   				fi
-  				MEXEXT=`$MATLAB_ROOT/bin/mexext.bat`
-  				MEXEXT=".$MEXEXT"
+
   			;;
 		   *)
-		      MEXLINK=$($MATLAB_ROOT/bin/mex -v 2>&1 < /dev/null | grep LDFLAGS     | sed -e "s/         LDFLAGS            = //g")
-	         MEXLIB=$( $MATLAB_ROOT/bin/mex -v 2>&1 < /dev/null | grep CXXLIBS     | sed -e "s/         CXXLIBS            = //g")
-		      MEXEXT=$( $MATLAB_ROOT/bin/mex -v 2>&1 < /dev/null | grep LDEXTENSION | sed -e "s/         LDEXTENSION        = //g")
-
+           MEXLINK=$($MATLAB_ROOT/bin/mex -v 2>&1 < /dev/null | grep LDFLAGS     | sed -e "s/         LDFLAGS            = //g")
+           MEXLIB=$( $MATLAB_ROOT/bin/mex -v 2>&1 < /dev/null | grep CXXLIBS     | sed -e "s/         CXXLIBS            = //g")
+		     MEXEXT=$( $MATLAB_ROOT/bin/mex -v 2>&1 < /dev/null | grep LDEXTENSION | sed -e "s/         LDEXTENSION        = //g")
 				dnl version 2014 and up
 				if test "x$MEXEXT" = "x" ; then
@@ -197,4 +288,7 @@
 					 rm -f conftest.tmp
 				fi
+
+				dnl Make sure mexFunction.map is not in MEXLIB to avoid problems with global variables
+				MEXLINK=$(echo $MEXLINK | sed -e "s/,-expo.*mexFunction\\.map\"//g" | sed -e "s/-[[^ ]]*mexFunction\\.map//g")
 
   			;;
@@ -319,5 +413,5 @@
 					DAKOTALIB="-L$DAKOTA_ROOT/lib -ldakota -lteuchos -lpecos -lfftw3 -llhs -levidence -lsurfpack -lconmin -lddace -lfsudace -ljega -lcport -lopt -lpsuade -lnewmat -lncsuopt -lgsl -lquadrature -lcoliny -lcolin -lpebbl -lutilib -l3po -lnappspack -lappspack -lconveyor -lshared -lcdd -lamplsolver"
 				else if test x$DAKOTA_VERSION = x5.1 || test x$DAKOTA_VERSION = x5.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"
+					DAKOTALIB="-L$DAKOTA_ROOT/lib -L$BOOST_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"
 				else
 					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
@@ -332,5 +426,5 @@
 				else if test x$DAKOTA_VERSION = x5.3 || test x$DAKOTA_VERSION = x5.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 -ldakota_src -ldakota_src_fortran -lnidr -lteuchos -lpecos -lpecos_src -llhs -lmods -lmod -ldfftpack -lsparsegrid -lsurfpack -lsurfpack_fortran -lutilib -lcolin -linterfaces -lscolib -l3po -lpebbl -ltinyxml -lconmin -ldace -lanalyzer -lrandom -lsampling -lbose -lfsudace -lhopspack -ljega -ljega_fe -lmoga -lsoga -leutils -lutilities -lncsuopt -lcport -loptpp -lpsuade -lamplsolver -L$BOOST_ROOT/lib -lboost_signals -lboost_regex -lboost_filesystem -lboost_system "
+					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"
 				else
 					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
@@ -348,5 +442,5 @@
 				else if test x$DAKOTA_VERSION = x5.3 || test x$DAKOTA_VERSION = x5.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 -ldakota_src -ldakota_src_fortran -lnidr -lteuchos -lpecos -lpecos_src -llhs -lmods -lmod -ldfftpack -lsparsegrid -lsurfpack -lsurfpack_fortran -lutilib -lcolin -linterfaces -lscolib -l3po -lpebbl -ltinyxml -lconmin -ldace -lanalyzer -lrandom -lsampling -lbose -lfsudace -lhopspack -ljega -ljega_fe -lmoga -lsoga -leutils -lutilities -lncsuopt -lcport -loptpp -lpsuade -lamplsolver -L$BOOST_ROOT/lib -lboost_signals -lboost_regex -lboost_filesystem -lboost_system "
+					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"
 				else
 					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
@@ -652,5 +746,5 @@
 			GSLLIB="-dy -L$GSL_ROOT/lib -lgsl -L$ATLAS_ROOT/lib -lcblas -latlas -lm"
 		else
-			GSLLIB="-dy -L$GSL_ROOT/lib -lgsl -lgslcblas -lm"
+			GSLLIB="-L$GSL_ROOT/lib -lgsl -lgslcblas -lm"
 		fi
 		AC_DEFINE([_HAVE_GSL_],[1],[with gsl in ISSM src])
@@ -987,7 +1081,34 @@
 	if test "x$HAVE_M1QN3" == "xyes"; then
 	  M1QN3LIB="$M1QN3_ROOT/libm1qn3.a $M1QN3_ROOT//libddot.a"
-	  AC_DEFINE([_HAVE_M1QN3_],[1],[with M1QN3I in ISSM src])
+	  AC_DEFINE([_HAVE_M1QN3_],[1],[with M1QN3 in ISSM src])
 	  AC_SUBST([M1QN3LIB])
 	fi
+	dnl }}}
+	dnl proj.4{{{
+	AC_ARG_WITH([proj4-dir],
+		AS_HELP_STRING([--with-proj4-dir=DIR], [proj4 root directory.]),
+		[PROJ4_ROOT=$withval],[PROJ4_ROOT="no"]) 
+
+	dnl Check whether proj4 is enabled
+	AC_MSG_CHECKING([for proj.4])
+	if test "x$PROJ4_ROOT" = "xno" ; then
+		HAVE_PROJ4=no
+	else
+		HAVE_PROJ4=yes
+		if ! test -d "$PROJ4_ROOT"; then
+			AC_MSG_ERROR([proj4 directory provided ($PROJ4_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_PROJ4)
+	
+	dnl proj4 headers and libraries
+	if test "x$HAVE_PROJ4" == "xyes"; then
+	  PROJ4INCL="-I$PROJ4_ROOT/include "
+	  PROJ4LIB="-L$PROJ4_ROOT/lib -lproj"
+	  AC_DEFINE([_HAVE_PROJ4_],[1],[with PROJ4 in ISSM src])
+	  AC_SUBST([PROJ4INCL])
+	  AC_SUBST([PROJ4LIB])
+	fi
+	AM_CONDITIONAL([PROJ4],[test x$HAVE_PROJ4 = xyes])
 	dnl }}}
 	dnl slepc{{{
@@ -1133,6 +1254,8 @@
 		MKLINCL=""
 		if test x$VENDOR = xintel-pleiades; then
-			MKLLIB=-L"$MKL_ROOT -lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -liomp5 -lpthread"
+			MKLLIB=-L"$MKL_ROOT -lmkl_core -lmkl_blas95_lp64 -lmkl_lapack95_lp64 -liomp5 -lpthread -lmkl_intel_thread -lmkl_intel_sp2dp"
 		elif test x$VENDOR = xintel-acenet; then
+			MKLLIB=-L"$MKL_ROOT -lmkl_intel_lp64 -lmkl_sequential -lmkl_core -lpthread -lm"
+		elif test x$VENDOR = xintel-gp; then
 			MKLLIB=-L"$MKL_ROOT -lmkl_intel_lp64 -lmkl_sequential -lmkl_core -lpthread -lm"
 		else
@@ -1194,8 +1317,8 @@
 		MUMPSINCL=-I"$MUMPS_ROOT/include"
 		if test "$PETSC_MAJOR" = "2" ; then
-			MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lpord "
+			MUMPSLIB=-L"$MUMPS_ROOT/lib "
 		else
-			dnl MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lmumps_common -lpord -lparmetis -lzmumps"
-			MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lmumps_common -lpord -lparmetis"
+			MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lmumps_common -lpord -lparmetis -lzmumps -lmetis"
+			dnl MUMPSLIB=-L"$MUMPS_ROOT/lib "
 		fi
 		AC_DEFINE([_HAVE_MUMPS_],[1],[with Mumps in ISSM src])
@@ -1608,4 +1731,18 @@
 
 	dnl Capabilities
+	dnl with-bamg{{{
+	AC_ARG_WITH([bamg],
+		AS_HELP_STRING([--with-bamg = YES],[compile with bamg capabilities (default is yes)]),
+		[BAMG=$withval],[BAMG=yes]) 
+	AC_MSG_CHECKING(for bamg capability compilation)
+
+	HAVE_BAMG=no
+	if test "x$BAMG" = "xyes"; then
+		HAVE_BAMG=yes
+		AC_DEFINE([_HAVE_BAMG_],[1],[with bamg meshing capability])
+	fi
+	AM_CONDITIONAL([BAMG], [test x$HAVE_BAMG = xyes])
+	AC_MSG_RESULT($HAVE_BAMG)
+	dnl }}}
 	dnl with-kml{{{
 	AC_ARG_WITH([kml],
@@ -1734,5 +1871,5 @@
 		;;
 		*darwin*)
-		MULTITHREADINGLIB="-lpthread"
+		MULTITHREADINGLIB="-L/usr/lib/ -lpthread"
 		;;
 		esac
Index: sm/trunk/packagers/macosx/ISSM.appscript
===================================================================
--- /issm/trunk/packagers/macosx/ISSM.appscript	(revision 19104)
+++ 	(revision )
@@ -1,1 +1,0 @@
-do shell script "open ~/ISSM/bin/matlabissm"
Index: sm/trunk/packagers/macosx/README
===================================================================
--- /issm/trunk/packagers/macosx/README	(revision 19104)
+++ 	(revision )
@@ -1,16 +1,0 @@
-Files needsed to package ISSM into a MacOSX delivery: 
-
-ISSM.appscript : applescript file used by Script Editor to build ISSM.app. Just edit using applescript, and save 
-as application. 
-
-ISSM.app: result of above. 
-
-ISSM.pmdoc: Package Maker project, which outputs ISSM.pkg
-
-ISSM.pkg: result of above. 
-
-Package Maker can be command line driven, using the pmdoc project directly. This is what package.sh does.
-
-issm.icns: icon file for ISSM install.
-matlabissm: used by the Package Maker to launch matlab with ISSM path sourced. 
-startup.m: needed to be sourced by Matlab to point towards mac executables.
Index: /issm/trunk/packagers/macosx/install.sh
===================================================================
--- /issm/trunk/packagers/macosx/install.sh	(revision 19105)
+++ /issm/trunk/packagers/macosx/install.sh	(revision 19105)
@@ -0,0 +1,128 @@
+#!/bin/bash
+
+# ISSM_DIR and MATLAB_DIR must be set correctly.
+# {{{
+if [ "${ISSM_DIR}x" == "x" ]; then
+   echo "ISSM_DIR is not set!" >&2
+   exit 1;
+elif [ -d ${ISSM_DIR} ]; then
+   echo "ISSM_DIR: ${ISSM_DIR}"
+else
+   echo "ISSM_DIR: ${ISSM_DIR} does not exist!" >&2
+   exit 1;
+fi
+
+if [ "${MATLAB_DIR}x" == "x" ]; then
+   echo "MATLAB_DIR is not set!"
+   exit 1;
+elif [ -d ${MATLAB_DIR} ]; then
+   echo "MATLAB_DIR: ${MATLAB_DIR}"
+else
+   echo "MATLAB_DIR: ${MATLAB_DIR} does not exist!" >&2
+   exit 1;
+fi
+# }}}
+
+#List of external pakages to be installed and their installation scripts
+EXTERNALPACKAGES="autotools install.sh                
+                  mpich     install-3.0-macosx64-static.sh
+                  cmake     install.sh                
+                  petsc     install-3.5-macosx64-static.sh
+                  triangle  install-macosx64.sh "
+
+# Install Externalpackages
+# {{{
+
+#Files source environment to make sure installed packages are in PATH
+source $ISSM_DIR/etc/environment.sh
+
+#number of packages: 
+NUMPACKAGES=$(($(echo $EXTERNALPACKAGES | wc -w )/2))
+
+for ((i=1;i<=$NUMPACKAGES;i++))
+do
+	NUM1=$((2*$i-1))
+	NUM2=$((2*$i))
+	PACKAGENAME=$(echo $EXTERNALPACKAGES | cut -d " " -f $NUM1-$NUM1)
+	PACKAGEINST=$(echo $EXTERNALPACKAGES | cut -d " " -f $NUM2-$NUM2)
+
+	cd $ISSM_DIR/externalpackages/$PACKAGENAME
+
+	if [[ $PACKAGEINST -nt  install ]]; then 
+		#go ahead and reinstall. 
+		echo "Triggering new install of $PACKAGENAME"
+		install_test=1
+	else
+		#ok, we want to skip, unless the package is not installed: 
+		if [ -d install ]; then 
+			#could be empty, signaling a failed previous install: 
+			if [ "$(ls -A install)" ];then
+				echo "and install directory exists, so skipping install of $PACKAGENAME"
+				install_test=0;
+			else
+				echo "and install directory exists, however, it is empty, so triggering install of $PACKAGENAME"
+				install_test=1;
+			fi
+		else
+			echo "However, install directory does not exist, so triggering install of $PACKAGENAME"
+			install_test=1;
+		fi
+	fi
+
+	if [[ $install_test == 1 ]]; then 
+		echo "======================================================";
+		echo "       Installing $PACKAGENAME                        ";
+		echo "======================================================";
+		./$PACKAGEINST |  tee compil.log
+		if [ $? -ne 0 ]; then
+			echo "======================================================";
+			echo "    ERROR: installation of $PACKAGENAME failed        ";
+			echo "======================================================";
+			#erase install directory, so that next time, we still try and compile this!
+			rm -rf install
+		fi
+		source $ISSM_DIR/etc/environment.sh
+	else
+		echo "======================================================";
+		echo "       Skipping install of $PACKAGENAME                        ";
+		echo "======================================================";
+	fi
+	cd ..
+done
+# }}}
+
+# Compile ISSM
+#{{{
+cd $ISSM_DIR
+echo "Aureconf..."
+autoreconf -if
+echo "Configuring..."
+./configure \
+	--prefix=$ISSM_DIR \
+	--disable-static \
+	--enable-standalone-executables \
+	--enable-standalone-libraries \
+	--with-matlab-dir="/Applications/MATLAB_R2011b.app/" \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
+	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+	--with-mpi-libflags=" -L$ISSM_DIR/externalpackages/mpich/install/lib -lmpich -lpmpich" \
+	--with-fortran-lib="/usr/local/lib/libgfortran.a" \
+	--enable-debugging \
+	--with-numthreads=4
+
+
+if [ $? -ne 0 ]; then echo "FAILED TO CONFIGURE!" && exit 1; fi
+
+echo "Building..."
+make -j 4 
+if [ $? -ne 0 ]; then echo "FAILED TO BUILD!" && exit 1; fi
+
+echo "Installing..."
+make install 
+if [ $? -ne 0 ]; then echo "FAILED TO INSTALL!" && exit 1; fi
+#}}}
Index: sm/trunk/packagers/macosx/matlabissm
===================================================================
--- /issm/trunk/packagers/macosx/matlabissm	(revision 19104)
+++ 	(revision )
@@ -1,4 +1,0 @@
-#/bin/bash
-user_home=`echo ~`;
-export  ISSM_TIER="$user_home/ISSM"
-matlab -r "name=getenv('USER'); issm=['/Users/' name '/ISSM']; cd(issm); cd bin; startup; cd ../;"
Index: /issm/trunk/packagers/macosx/package.sh
===================================================================
--- /issm/trunk/packagers/macosx/package.sh	(revision 19104)
+++ /issm/trunk/packagers/macosx/package.sh	(revision 19105)
@@ -1,25 +1,38 @@
-#/bin/bash
+#!/bin/bash
+
+echo "modify generic" 
+cd $ISSM_DIR/bin
+cat generic_static.m | sed -e "s/generic_static/generic/g" > generic.m
+echo "move mpiexec to bin" 
+cp ../externalpackages/mpich/install/bin/mpiexec .
+cp ../externalpackages/mpich/install/bin/hydra_pmi_proxy .
+
+#Check that test101 runs
+cd $ISSM_DIR/test/NightlyRun
+rm matlab.log
+$MATLAB_DIR/bin/matlab -nojvm -nosplash -r "try, addpath $ISSM_DIR/bin $ISSM_DIR/lib; runme('id',101);exit; catch me,fprintf('%s',getReport(me)); exit; end" -logfile matlab.log
+
+if [[ $(cat matlab.log | grep -c SUCCESS) -lt 10 ]]; then
+	echo "test101 FAILED"
+	exit 1;
+else
+	echo "test101 passed"
+fi
 
 #Package using the Package Maker from OSX, driven by command line.
+tarball_name='issm-mac-static_build.tar.gz'
+
 echo "Cleanup first" 
-sudo sh -c "rm -rf ISSM-MacOSX.pkg bin test"
+cd $ISSM_DIR
+rm $tarball_name
 
-#We need to copy all the relevant files and set the permissions, as PackageMaker 
-#is not good at that. 
-echo "Copy bin" 
-cp -Rf $ISSM_TIER/bin ./
-echo "Copy test" 
-cp -Rf $ISSM_TIER/test ./
-cp matlabissm startup.m ./bin
+echo "Creating tarball: ${tarball_name}"
+cd $ISSM_DIR
+rm -rf trunk
+mkdir trunk
+cp -rf bin lib test examples trunk/
+tar -czf $tarball_name trunk
+ls -lah $tarball_name
 
-#Now change group and ownership: 
-echo "Change group and ownership" 
-sudo sh -c "chown -R root ./bin && chgrp -R admin ./bin"
-sudo sh -c "chown -R root ./test && chgrp -R admin ./test"
-
-echo "Launch packagemaker" 
-PackageMaker -d ISSM.pmdoc -o ISSM-MacOSX.pkg
-
-#cleanup
-echo "Final cleanup"
-sudo sh -c "rm -rf ./bin && rm -rf ./test"
+echo "Shipping binaries to website"
+scp $tarball_name websites.jpl.nasa.gov:/home/larour/files/$tarball_name
Index: sm/trunk/packagers/macosx/package_incomplete.sh
===================================================================
--- /issm/trunk/packagers/macosx/package_incomplete.sh	(revision 19104)
+++ 	(revision )
@@ -1,16 +1,0 @@
-#/bin/bash
-
-#Package using the Package Maker from OSX, driven by command line.
-sudo sh -c "rm -rf ISSM-MacOSX.pkg bin test"
-
-#We need to copy all the relevant files and set the permissions, as PackageMaker 
-#is not good at that. 
-cp -Rf $ISSM_TIER/bin ./
-cp -Rf $ISSM_TIER/test ./
-cp matlabissm startup.m ./bin
-
-#Now change group and ownership: 
-sudo sh -c "chown -R root ./bin && chgrp -R admin ./bin"
-sudo sh -c "chown -R root ./test && chgrp -R admin ./test"
-
-#Run PackageMaker now, using the ISSM.pmdoc project
Index: sm/trunk/packagers/macosx/startup.m
===================================================================
--- /issm/trunk/packagers/macosx/startup.m	(revision 19104)
+++ 	(revision )
@@ -1,45 +1,0 @@
-%STARTUP - Matlab startup script
-%
-%   startup.m is a script run by matlab at the beginning of a session, just
-%   before handing over the prompt to the user. This delivery startup.m script
-%   has been customized here for the ISSM code. This startup script should be
-%   run by users before trying to use ISSM. The best way to do that is to put
-%   the startup file in the location where Matlab starts and established its
-%   root directory.
-
-% clear the last warning to focus on the warnings of the ISSM path
-lastwarn(''); 
-
-%Recover ISSM_TIER , or if on a Windows machine, ISSM_TIER_WIN
-ISSM_TIER=getenv('ISSM_TIER');
-
-if (isempty(ISSM_TIER)),
-	error('issmdir error message: ''ISSM_TIER'' environment variable is empty! You should define ISSM_TIER in your .cshrc or .bashrc!');
-end
-
-%Now add all issm code paths necessary to run issm smoothly. 
-%We capture the error output, so that we can warn the user to update 
-%the variable ISSM_TIER in this file, in case it is not correctly setup. 
-
-%ISSM path
-addpath(pwd); %add current path first
-
-%Check on any warning messages that might indicate that the paths were not correct. 
-if ~isempty(lastwarn),
-	fprintf('\n  Error trying to setup ''ISSM'' code paths. Try and update the ISSM_TIER variable in your .cshrc or .bashrc!\n');
-	fprintf('  ''ISSM'' will not  work at all until this is resolved\n\n');
-else
-	fprintf('\n  To get started with ISSM, type issmdoc at the command prompt.\n\n');
-end
-
-%disable matlab bell!
-beep off;
-
-% no warning if we try to plot while in nojvm (will not be supported in future releases)
-warning off MATLAB:HandleGraphics:noJVM
-
-%at the end, get to tests directory if ISSM_TESTS exists: 
-ISSM_TESTS=getenv('ISSM_TESTS');
-if ~isempty(ISSM_TESTS),
-	cd(ISSM_TESTS);
-end
Index: sm/trunk/packagers/ubuntu/README
===================================================================
--- /issm/trunk/packagers/ubuntu/README	(revision 19104)
+++ 	(revision )
@@ -1,60 +1,0 @@
-TARBALL INSTALLATION:
-
-To install ISSM, untar ISSM-Ubuntu32.tar.gz 
-You will get an ISSM directory. 
-
-You then need to setup the following environment variable in your 
-.bashrc or .cshrc: 
-
-in your .bashrc: 
-export ISSM_TIER='path_to_untarred_ISSM/bin'
-
-or in your .cshrc: 
-setenv ISSM_TIER 'path_to_untarred_ISSM'
-
-Once this is done, fireup matlab from inside the ISSM directory: 
-matlab -nojvm -r "startup;"
-
-
-UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION 
--------------------------------------------------------------------------------
-				OR THE RIGHT WAY....
-DPKG/DEB INSTALLATION:
-
-To install from deb archives (*.deb), use:
-
-	> sudo dpkg --install <debarchive>
-
-That's it! But not really. Do make sure that you install petsc and metis first.
-When you first try to install issm, dpkg will tell you that you are missing
-dependencies. Just:
-
-	> sudo apt-get install -f
-
-to fix the dependencies and complete the install. When apt-get is done, you 
-should see something that says that ISSM is installed correctly on your 
-machine. That's it! For real this time.
-
-Uninstalling is simple too:
-
-	> sudo apt-get remove <issmPackageName>
-
-That'll do all the work for you. This won't delete any configuration or user
-defined environment stuff. Just swap "remove" out for "purge" and that'll
-delete everything. And apt-get might ask you to remove unneeded dependencies,
-so you should probably do that to keep your system clean.
-
-To create your own custom debian archive, see the README in issmpkg.
-
--------------------------------------------------------------------------------
-
-APT-GET INSTALLATION: (this doesnot work yet)
-
-To install from apt-get:
-
-	> sudo add-apt-repository <issm_PPA_URL>
-	> sudo apt-get install <issmPackageName>
-
-Just say yes to everything apt asks you, and you're good.
-
-UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION 
Index: /issm/trunk/packagers/ubuntu/install.sh
===================================================================
--- /issm/trunk/packagers/ubuntu/install.sh	(revision 19105)
+++ /issm/trunk/packagers/ubuntu/install.sh	(revision 19105)
@@ -0,0 +1,128 @@
+#!/bin/bash
+
+# ISSM_DIR and MATLAB_DIR must be set correctly.
+# {{{
+if [ "${ISSM_DIR}x" == "x" ]; then
+   echo "ISSM_DIR is not set!" >&2
+   exit 1;
+elif [ -d ${ISSM_DIR} ]; then
+   echo "ISSM_DIR: ${ISSM_DIR}"
+else
+   echo "ISSM_DIR: ${ISSM_DIR} does not exist!" >&2
+   exit 1;
+fi
+
+if [ "${MATLAB_DIR}x" == "x" ]; then
+   echo "MATLAB_DIR is not set!"
+   exit 1;
+elif [ -d ${MATLAB_DIR} ]; then
+   echo "MATLAB_DIR: ${MATLAB_DIR}"
+else
+   echo "MATLAB_DIR: ${MATLAB_DIR} does not exist!" >&2
+   exit 1;
+fi
+# }}}
+
+#List of external pakages to be installed and their installation scripts
+EXTERNALPACKAGES="autotools install.sh                
+						mpich     install-3.0-linux64.sh
+                  cmake     install.sh                
+                  petsc     install-3.5-linux64-static.sh
+                  triangle  install-linux64.sh "
+
+# Install Externalpackages
+# {{{
+
+#Files source environment to make sure installed packages are in PATH
+source $ISSM_DIR/etc/environment.sh
+
+#number of packages: 
+NUMPACKAGES=$(($(echo $EXTERNALPACKAGES | wc -w )/2))
+
+for ((i=1;i<=$NUMPACKAGES;i++))
+do
+	NUM1=$((2*$i-1))
+	NUM2=$((2*$i))
+	PACKAGENAME=$(echo $EXTERNALPACKAGES | cut -d " " -f $NUM1-$NUM1)
+	PACKAGEINST=$(echo $EXTERNALPACKAGES | cut -d " " -f $NUM2-$NUM2)
+
+	cd $ISSM_DIR/externalpackages/$PACKAGENAME
+
+	if [[ $PACKAGEINST -nt  install ]]; then 
+		#go ahead and reinstall. 
+		echo "Triggering new install of $PACKAGENAME"
+		install_test=1
+	else
+		#ok, we want to skip, unless the package is not installed: 
+		if [ -d install ]; then 
+			#could be empty, signaling a failed previous install: 
+			if [ "$(ls -A install)" ];then
+				echo "and install directory exists, so skipping install of $PACKAGENAME"
+				install_test=0;
+			else
+				echo "and install directory exists, however, it is empty, so triggering install of $PACKAGENAME"
+				install_test=1;
+			fi
+		else
+			echo "However, install directory does not exist, so triggering install of $PACKAGENAME"
+			install_test=1;
+		fi
+	fi
+
+	if [[ $install_test == 1 ]]; then 
+		echo "======================================================";
+		echo "       Installing $PACKAGENAME                        ";
+		echo "======================================================";
+		./$PACKAGEINST |  tee compil.log
+		if [ $? -ne 0 ]; then
+			echo "======================================================";
+			echo "    ERROR: installation of $PACKAGENAME failed        ";
+			echo "======================================================";
+			#erase install directory, so that next time, we still try and compile this!
+			rm -rf install
+		fi
+		source $ISSM_DIR/etc/environment.sh
+	else
+		echo "======================================================";
+		echo "       Skipping install of $PACKAGENAME                        ";
+		echo "======================================================";
+	fi
+	cd ..
+done
+# }}}
+
+# Compile ISSM
+#{{{
+cd $ISSM_DIR
+echo "Aureconf..."
+autoreconf -if
+echo "Configuring..."
+./configure \
+	--prefix=$ISSM_DIR \
+	--disable-static \
+	--enable-standalone-executables \
+	--enable-standalone-libraries \
+	--with-matlab-dir="/usr/local/matlab80/" \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
+	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
+	--with-mpi-libflags=" -L$ISSM_DIR/externalpackages/mpich/install/lib -lmpich -lmpl " \
+	--with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.6/ -lgfortran" \
+	--enable-debugging \
+	--with-numthreads=4
+
+
+if [ $? -ne 0 ]; then echo "FAILED TO CONFIGURE!" && exit 1; fi
+
+echo "Building..."
+make -j 8
+if [ $? -ne 0 ]; then echo "FAILED TO BUILD!" && exit 1; fi
+
+echo "Installing..."
+make install 
+if [ $? -ne 0 ]; then echo "FAILED TO INSTALL!" && exit 1; fi
+#}}}
Index: /issm/trunk/packagers/ubuntu/package.sh
===================================================================
--- /issm/trunk/packagers/ubuntu/package.sh	(revision 19104)
+++ /issm/trunk/packagers/ubuntu/package.sh	(revision 19105)
@@ -1,15 +1,36 @@
-#/bin/bash
+#!/bin/bash
 
-#Just tar gz the bin/ directory and test/ directory and put a startup.m file.
+echo "modify generic" 
+cd $ISSM_DIR/bin
+cat generic_static.m | sed -e "s/generic_static/generic/g" > generic.m
+echo "move mpiexec to bin" 
+cp ../externalpackages/mpich/install/bin/mpiexec .
+cp ../externalpackages/mpich/install/bin/hydra_pmi_proxy .
 
-rm -rf ISSM ISSM-Ubuntu32.tar.gz
+#Check that test101 runs
+cd $ISSM_DIR/test/NightlyRun
+rm matlab.log
+$MATLAB_DIR/bin/matlab -nojvm -nosplash -r "try, addpath $ISSM_DIR/bin $ISSM_DIR/lib; runme('id',101);exit; catch me,fprintf('%s',getReport(me)); exit; end" -logfile matlab.log
 
-mkdir ISSM
-cd ISSM
-ln -s $ISSM_TIER/bin ./bin
-ln -s $ISSM_TIER/test ./test
-cp ../startup.m ./
-cp ../README.m ./
-cd ..
-tar  zcvfh  ISSM-Ubuntu32.tar.gz --exclude='.svn' ./ISSM
-rm -rf ISSM
+if [[ $(cat matlab.log | grep -c SUCCESS) -lt 10 ]]; then
+	echo "test101 FAILED"
+	exit 1;
+else
+	echo "test101 passed"
+fi
+
+tarball_name='issm-ubuntu-static_build.tar.gz'
+
+echo "Cleanup first" 
+cd $ISSM_DIR
+rm $tarball_name
+
+echo "Creating tarball: ${tarball_name}"
+cd $ISSM_DIR
+tar -czf $tarball_name ./bin ./lib ./test ./examples
+ls -lah $tarball_name
+
+echo "Shipping binaries to website"
+cp $tarball_name /u/astrid-r1b/morlighe/public/
+chmod 777 /u/astrid-r1b/morlighe/public/$tarball_name
+scp $tarball_name websites.jpl.nasa.gov:/home/larour/files/$tarball_name
Index: sm/trunk/packagers/ubuntu/startup.m
===================================================================
--- /issm/trunk/packagers/ubuntu/startup.m	(revision 19104)
+++ 	(revision )
@@ -1,40 +1,0 @@
-%STARTUP - Matlab startup script
-%
-%   startup.m is a script run by matlab at the beginning of a session, just
-%   before handing over the prompt to the user. This delivery startup.m script
-%   has been customized here for the ISSM code. This startup script should be
-%   run by users before trying to use ISSM. The best way to do that is to put
-%   the startup file in the location where Matlab starts and established its
-%   root directory.
-
-% clear the last warning to focus on the warnings of the ISSM path
-lastwarn(''); 
-
-%Recover ISSM_TIER , or if on a Windows machine, ISSM_TIER_WIN
-ISSM_TIER=getenv('ISSM_TIER');
-
-if (isempty(ISSM_TIER)),
-	error('issmdir error message: ''ISSM_TIER'' environment variable is empty! You should define ISSM_TIER in your .cshrc or .bashrc!');
-end
-
-%Now add all issm code paths necessary to run issm smoothly. 
-%We capture the error output, so that we can warn the user to update 
-%the variable ISSM_TIER in this file, in case it is not correctly setup. 
-
-%ISSM path
-addpath(ISSM_TIER);
-addpath([ISSM_TIER '/bin']);
-
-%Check on any warning messages that might indicate that the paths were not correct. 
-if ~isempty(lastwarn),
-	fprintf('\n  Error trying to setup ''ISSM'' code paths. Try and update the ISSM_TIER variable in your .cshrc or .bashrc!\n');
-	fprintf('  ''ISSM'' will not  work at all until this is resolved\n\n');
-else
-	fprintf('\n  To get started with ISSM, type issmdoc at the command prompt.\n\n');
-end
-
-%disable matlab bell!
-beep off;
-
-% no warning if we try to plot while in nojvm (will not be supported in future releases)
-warning off MATLAB:HandleGraphics:noJVM
Index: /issm/trunk/scripts/ol.m
===================================================================
--- /issm/trunk/scripts/ol.m	(revision 19104)
+++ /issm/trunk/scripts/ol.m	(revision 19105)
@@ -1,1 +1,14 @@
-system('ol');
+
+fid=fopen('runme.m','r');
+
+tline = fgets(fid);
+count=1;
+while ischar(tline)
+	tline = fgets(fid);
+	if length(tline)>16,
+		if strcmpi(tline(1:16),'if perform(org,'''),
+			disp(sprintf('%i: %s',count,tline(17:end-8)));
+			count=count+1;
+		end
+	end
+end
Index: /issm/trunk/src/c/Makefile.am
===================================================================
--- /issm/trunk/src/c/Makefile.am	(revision 19104)
+++ /issm/trunk/src/c/Makefile.am	(revision 19105)
@@ -1,3 +1,4 @@
-AM_CPPFLAGS = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @AMPIINCL@ @MPIINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@ @ANDROID_NDKINCL@ @METEOIOINCL@ @SNOWPACKINCL@
+AM_CPPFLAGS = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @AMPIINCL@ @MPIINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@ @ANDROID_NDKINCL@ @METEOIOINCL@ @SNOWPACKINCL@ @PROJ4INCL@
+
 AUTOMAKE_OPTIONS = subdir-objects
 
@@ -5,14 +6,8 @@
 
 #Library declaration {{{
-lib_LIBRARIES = libISSMCore.a libISSMOverload.a
-
-if SHAREDLIBS
-lib_LTLIBRARIES = libISSMCore.la libISSMOverload.la libISSM.la
-endif
+
+lib_LTLIBRARIES = libISSMCore.la libISSMOverload.la 
 if WRAPPERS
-if SHAREDLIBS
 lib_LTLIBRARIES += libISSMModules.la
-endif
-lib_LIBRARIES += libISSMModules.a 
 endif
 #}}}
@@ -20,188 +15,87 @@
 #Core sources
 #Core sources{{{
-issm_sources = ./datastructures/DataSet.h\
-					./datastructures/DataSet.cpp\
-					./datastructures/Object.h\
-					./datastructures/datastructures.h\
-					./classes/classes.h\
-					./classes/gauss/Gauss.h\
-					./classes/gauss/GaussSeg.h\
+issm_sources = ./datastructures/DataSet.cpp\
 					./classes/gauss/GaussSeg.cpp\
-					./classes/gauss/GaussTria.h\
 					./classes/gauss/GaussTria.cpp\
-					./classes/gauss/GaussTetra.h\
 					./classes/gauss/GaussTetra.cpp\
-					./classes/gauss/GaussPenta.h\
 					./classes/gauss/GaussPenta.cpp\
-					./classes/Update.h\
-					./classes/FemModel.h\
 					./classes/FemModel.cpp\
-					./classes/Material.h\
-					./classes/Load.h\
-					./classes/Contour.h\
-					./classes/Loads/Friction.h\
 					./classes/Loads/Friction.cpp\
-					./classes/Inputs/TransientInput.h\
 					./classes/Inputs/TransientInput.cpp\
 					./classes/Constraints/SpcTransient.cpp\
-					./classes/Constraints/SpcTransient.h\
-					./classes/IndependentObject.h\
 					./classes/IndependentObject.cpp\
-					./classes/DependentObject.h\
 					./classes/DependentObject.cpp\
-					./classes/DofIndexing.h\
 					./classes/DofIndexing.cpp\
-					./classes/IoModel.h\
 					./classes/IoModel.cpp\
-					./classes/Contours.h\
 					./classes/Contours.cpp\
-					./classes/Nodes.h\
 					./classes/Nodes.cpp\
-					./classes/Vertices.h\
 					./classes/Vertices.cpp\
-					./classes/Node.h\
 					./classes/Node.cpp\
-					./classes/Segment.h\
-					./classes/Vertex.h\
 					./classes/Vertex.cpp\
-					./classes/Hook.h\
 					./classes/Hook.cpp\
-					./classes/ExternalResults/Results.h\
 					./classes/ExternalResults/Results.cpp\
-					./classes/ExternalResults/ExternalResult.h\
-					./classes/ExternalResults/GenericExternalResult.h\
-					./classes/Elements/Element.h\
 					./classes/Elements/Element.cpp\
-					./classes/Elements/Elements.h\
 					./classes/Elements/Elements.cpp\
-					./classes/Elements/ElementHook.h\
 					./classes/Elements/ElementHook.cpp\
-					./classes/Elements/Seg.h\
 					./classes/Elements/Seg.cpp\
-					./classes/Elements/SegRef.h\
 					./classes/Elements/SegRef.cpp\
-					./classes/Elements/Tria.h\
 					./classes/Elements/Tria.cpp\
-					./classes/Elements/TriaRef.h\
 					./classes/Elements/TriaRef.cpp\
-					./classes/Elements/Tetra.h\
 					./classes/Elements/Tetra.cpp\
-					./classes/Elements/TetraRef.h\
 					./classes/Elements/TetraRef.cpp\
-					./classes/Elements/Penta.h\
 					./classes/Elements/Penta.cpp\
-					./classes/Elements/PentaRef.h\
 					./classes/Elements/PentaRef.cpp\
-					./classes/Inputs/Inputs.h\
 					./classes/Inputs/Inputs.cpp\
-					./classes/Inputs/Input.h\
-					./classes/Inputs/InputLocal.h\
-					./classes/Inputs/SegInput.h\
 					./classes/Inputs/SegInput.cpp\
-					./classes/Inputs/TriaInput.h\
 					./classes/Inputs/TriaInput.cpp\
-					./classes/Inputs/BoolInput.h\
 					./classes/Inputs/BoolInput.cpp\
-					./classes/Inputs/IntInput.h\
 					./classes/Inputs/IntInput.cpp\
-					./classes/Inputs/DoubleInput.h\
 					./classes/Inputs/DoubleInput.cpp\
-					./classes/Inputs/DatasetInput.h\
 					./classes/Inputs/DatasetInput.cpp\
-					./classes/Materials/Materials.h\
 					./classes/Materials/Materials.cpp\
-					./classes/Materials/Matice.h\
 					./classes/Materials/Matice.cpp\
-					./classes/Materials/Matpar.h\
 					./classes/Materials/Matpar.cpp\
-					./classes/Constraints/Constraints.h\
 					./classes/Constraints/Constraints.cpp\
-					./classes/Constraints/Constraint.h\
 					./classes/Constraints/SpcStatic.cpp\
-					./classes/Constraints/SpcStatic.h\
 					./classes/Constraints/SpcDynamic.cpp\
-					./classes/Constraints/SpcDynamic.h\
-					./classes/Loads/Loads.h\
 					./classes/Loads/Loads.cpp\
 					./classes/Loads/Penpair.cpp\
-					./classes/Loads/Penpair.h\
 					./classes/Loads/Pengrid.cpp\
-					./classes/Loads/Pengrid.h\
 					./classes/Loads/Numericalflux.cpp\
-					./classes/Loads/Numericalflux.h\
-					./classes/matrix/matrixobjects.h\
-					./classes/matrix/ElementMatrix.h\
 					./classes/matrix/ElementMatrix.cpp\
-					./classes/matrix/ElementVector.h\
 					./classes/matrix/ElementVector.cpp\
-					./classes/Params/Parameters.h\
 					./classes/Params/Parameters.cpp\
-					./classes/Params/Param.h\
-					./classes/Params/GenericParam.h\
 					./classes/Params/BoolParam.cpp\
-					./classes/Params/BoolParam.h\
 					./classes/Params/IntParam.cpp\
-					./classes/Params/IntParam.h\
 					./classes/Params/IntVecParam.cpp\
-					./classes/Params/IntVecParam.h\
 					./classes/Params/IntMatParam.cpp\
-					./classes/Params/IntMatParam.h\
 					./classes/Params/DoubleParam.cpp\
-					./classes/Params/DoubleParam.h\
 					./classes/Params/FileParam.cpp\
-					./classes/Params/FileParam.h\
 					./classes/Params/StringArrayParam.cpp\
-					./classes/Params/StringArrayParam.h\
 					./classes/Params/DoubleMatParam.cpp\
-					./classes/Params/DoubleMatParam.h\
 					./classes/Params/DoubleTransientMatParam.cpp\
-					./classes/Params/DoubleTransientMatParam.h\
 					./classes/Params/DoubleMatArrayParam.cpp\
-					./classes/Params/DoubleMatArrayParam.h\
 					./classes/Params/DoubleVecParam.cpp\
-					./classes/Params/DoubleVecParam.h\
 					./classes/Params/StringParam.cpp\
-					./classes/Params/StringParam.h\
-					./classes/Params/MatrixParam.h\
 					./classes/Params/MatrixParam.cpp\
-					./classes/Params/VectorParam.h\
 					./classes/Params/VectorParam.cpp\
-					./classes/Params/TransientParam.h\
 					./classes/Params/TransientParam.cpp\
-					./classes/Params/DataSetParam.h\
 					./classes/Params/DataSetParam.cpp\
-					./classes/Profiler.h\
 					./classes/Profiler.cpp\
-					./shared/shared.h\
-					./shared/MemOps/MemOps.h\
 					./shared/MemOps/MemOps.cpp\
-					./shared/Matrix/matrix.h\
 					./shared/Matrix/MatrixUtils.cpp\
-					./shared/io/io.h\
-					./shared/io/Disk/diskio.h\
 					./shared/io/Disk/pfopen.cpp\
 					./shared/io/Disk/pfclose.cpp\
 					./shared/io/Disk/WriteLockFile.cpp\
 					./shared/io/Print/PrintfFunction.cpp\
-					./shared/io/Print/Print.h\
-					./shared/io/Comm/IssmComm.h\
 					./shared/io/Comm/IssmComm.cpp\
 					./shared/LatLong/Ll2xyx.cpp\
 					./shared/LatLong/Xy2llx.cpp\
-					./shared/FSanalyticals/fsanalyticals.h\
 					./shared/FSanalyticals/fsanalyticals.cpp\
-					./shared/Enum/Enum.h\
-					./shared/Enum/EnumDefinitions.h\
 					./shared/Enum/EnumToStringx.cpp\
 					./shared/Enum/StringToEnumx.cpp\
-					./shared/Numerics/numerics.h\
-					./shared/Numerics/types.h\
-					./shared/Numerics/constants.h\
-					./shared/Numerics/Verbosity.h\
 					./shared/Numerics/Verbosity.cpp\
-					./shared/Numerics/GaussPoints.h\
 					./shared/Numerics/GaussPoints.cpp\
 					./shared/Numerics/cross.cpp\
-					./shared/Numerics/isnan.h\
 					./shared/Numerics/isnan.cpp\
 					./shared/Numerics/cubic.cpp\
@@ -209,11 +103,8 @@
 					./shared/Numerics/extrema.cpp\
 					./shared/Numerics/XZvectorsToCoordinateSystem.cpp\
-					./shared/Numerics/OptPars.h\
-					./shared/Exceptions/exceptions.h\
 					./shared/Exceptions/Exceptions.cpp\
 					./shared/Sorting/binary_search.cpp\
-					./shared/Sorting/sorting.h\
-					./shared/Elements/elements.h\
 					./shared/Elements/Cuffey.cpp\
+					./shared/Elements/StressIntensityIntegralWeight.cpp\
 					./shared/Elements/Paterson.cpp\
 					./shared/Elements/Arrhenius.cpp\
@@ -222,40 +113,15 @@
 					./shared/Elements/PddSurfaceMassBalance.cpp\
 					./shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp\
+					./shared/Elements/ComputeMungsmTemperaturePrecipitation.cpp\
 					./shared/Elements/DrainageFunctionWaterfraction.cpp\
-					./shared/String/sharedstring.h\
 					./shared/String/DescriptorIndex.cpp\
-					./toolkits/metis/metisincludes.h\
-					./toolkits/issm/issmtoolkit.h\
-					./toolkits/issm/IssmToolkitUtils.h\
 					./toolkits/issm/IssmToolkitUtils.cpp\
-					./toolkits/issm/IssmAbsMat.h\
-					./toolkits/issm/IssmAbsVec.h\
-					./toolkits/issm/IssmDenseMat.h\
-					./toolkits/issm/IssmMat.h\
-					./toolkits/issm/IssmSeqVec.h\
-					./toolkits/issm/IssmVec.h\
-					./toolkits/issm/IssmSolver.h\
 					./toolkits/issm/IssmSolver.cpp\
-					./toolkits/issm/SparseRow.h\
-					./toolkits/issm/Bucket.h\
-					./toolkits/mpi/issmmpi.h\
 					./toolkits/mpi/issmmpi.cpp\
-					./toolkits/mpi/commops/commops.h\
 					./toolkits/mpi/commops/DetermineLocalSize.cpp\
 					./toolkits/mpi/commops/DetermineGlobalSize.cpp\
 					./toolkits/mpi/commops/DetermineRowRankFromLocalSize.cpp\
 					./toolkits/mpi/commops/GetOwnershipBoundariesFromRange.cpp\
-					./toolkits/adolc/adolcincludes.h\
-					./toolkits/adolc/AdolcEdf.h\
-					./toolkits/ToolkitOptions.h\
 					./toolkits/ToolkitOptions.cpp\
-					./toolkits/triangle/triangleincludes.h\
-					./toolkits/objects/toolkitobjects.h\
-					./toolkits/objects/Matrix.h\
-					./toolkits/objects/Vector.h\
-					./toolkits/objects/Solver.h\
-					./toolkitsenums.h\
-					./toolkits.h\
-					./modules/ModelProcessorx/ModelProcessorx.h\
 					./modules/ModelProcessorx/ModelProcessorx.cpp\
 					./modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp\
@@ -271,87 +137,48 @@
 					./modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp\
 					./modules/ModelProcessorx/CreateNodes.cpp\
-					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h\
 					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp\
-					./modules/NodesDofx/NodesDofx.h\
 					./modules/NodesDofx/NodesDofx.cpp\
-					./modules/NodalValuex/NodalValuex.h\
 					./modules/NodalValuex/NodalValuex.cpp\
-					./modules/VerticesDofx/VerticesDofx.h\
 					./modules/VerticesDofx/VerticesDofx.cpp\
-					./modules/VertexCoordinatesx/VertexCoordinatesx.h\
 					./modules/VertexCoordinatesx/VertexCoordinatesx.cpp\
-					./modules/OutputResultsx/OutputResultsx.h\
 					./modules/OutputResultsx/OutputResultsx.cpp\
-					./modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.h\
 					./modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.cpp\
-					./modules/InputDuplicatex/InputDuplicatex.h\
 					./modules/InputDuplicatex/InputDuplicatex.cpp\
-					./modules/InputExtrudex/InputExtrudex.h\
 					./modules/InputExtrudex/InputExtrudex.cpp\
-					./modules/InputScalex/InputScalex.h\
 					./modules/InputScalex/InputScalex.cpp\
-					./modules/SurfaceAreax/SurfaceAreax.h\
 					./modules/SurfaceAreax/SurfaceAreax.cpp\
-					./modules/AllocateSystemMatricesx/AllocateSystemMatricesx.h\
 					./modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp\
-					./modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h\
 					./modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp\
-					./modules/SystemMatricesx/SystemMatricesx.h\
 					./modules/SystemMatricesx/SystemMatricesx.cpp\
-					./modules/CreateNodalConstraintsx/CreateNodalConstraintsx.h\
 					./modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp\
-					./modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h\
 					./modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp\
-					./modules/IoModelToConstraintsx/IoModelToConstraintsx.h\
 					./modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp\
-					./modules/SetActiveNodesLSMx/SetActiveNodesLSMx.h\
 					./modules/SetActiveNodesLSMx/SetActiveNodesLSMx.cpp\
-					./modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h\
 					./modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp\
-					./modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h\
 					./modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp\
-					./modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h\
 					./modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp\
-					./modules/GetVectorFromInputsx/GetVectorFromInputsx.h\
 					./modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp\
-					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h\
 					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp\
-					./modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h\
 					./modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp\
-					./modules/ConfigureObjectsx/ConfigureObjectsx.h\
 					./modules/ConfigureObjectsx/ConfigureObjectsx.cpp\
-					./modules/SpcNodesx/SpcNodesx.h\
 					./modules/SpcNodesx/SpcNodesx.cpp\
-					./modules/SurfaceMassBalancex/SurfaceMassBalancex.h\
 					./modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp\
-					./modules/MeshPartitionx/MeshPartitionx.h\
 					./modules/Reducevectorgtofx/Reducevectorgtofx.cpp\
-					./modules/Reducevectorgtofx/Reducevectorgtofx.h\
-					./modules/Reduceloadx/Reduceloadx.h\
 					./modules/Reduceloadx/Reduceloadx.cpp\
 					./modules/ConstraintsStatex/ConstraintsStatex.cpp\
-					./modules/ConstraintsStatex/ConstraintsStatex.h\
-					./modules/ConstraintsStatex/ConstraintsStateLocal.h\
-					./modules/ResetConstraintsx/ResetConstraintsx.h\
 					./modules/ResetConstraintsx/ResetConstraintsx.cpp\
-					./modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.h\
 					./modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.cpp\
 					./modules/Solverx/Solverx.cpp\
-					./modules/Solverx/Solverx.h\
 					./modules/VecMergex/VecMergex.cpp\
-					./modules/VecMergex/VecMergex.h\
 					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp\
-					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h\
 					./cores/ProcessArguments.cpp\
 					./cores/ResetBoundaryConditions.cpp\
-					./cores/AnalysisConfiguration.cpp\
 					./cores/WrapperCorePointerFromSolutionEnum.cpp\
 					./cores/CorePointerFromSolutionEnum.cpp\
 					./cores/ad_core.cpp\
+					./cores/adgradient_core.cpp\
 					./main/EnvironmentInit.cpp\
 					./main/EnvironmentFinalize.cpp\
-					./analyses/EnumToAnalysis.h\
 					./analyses/EnumToAnalysis.cpp\
-					./analyses/Analysis.h\
 					./solutionsequences/solutionsequence_la.cpp\
 					./solutionsequences/solutionsequence_la_theta.cpp\
@@ -359,13 +186,9 @@
 					./solutionsequences/solutionsequence_nonlinear.cpp\
 					./solutionsequences/solutionsequence_newton.cpp\
+					./solutionsequences/solutionsequence_fct.cpp\
 					./solutionsequences/convergence.cpp\
-					./classes/Options/Options.h\
 					./classes/Options/Options.cpp\
-					./classes/Options/Option.h\
-					./classes/Options/GenericOption.h\
 					./classes/Options/OptionUtilities.cpp\
-					./classes/Options/OptionUtilities.h\
 					./classes/RiftStruct.cpp\
-					./classes/RiftStruct.h\
 					./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp \
 					./cores/transient_core.cpp\
@@ -378,40 +201,26 @@
 					./solutionsequences/solutionsequence_thermal_nonlinear.cpp\
 					./modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp\
-					./modules/ControlInputSetGradientx/ControlInputSetGradientx.h\
 					./modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp\
-					./modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h\
 					./modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp\
-					./modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h\
 					./modules/ModelProcessorx/Control/CreateParametersControl.cpp\
 					./modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp\
-					./modules/InputControlUpdatex/InputControlUpdatex.h\
 					./modules/InputControlUpdatex/InputControlUpdatex.cpp\
-					./modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h\
 					./modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp\
-					./modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h\
 					./modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp\
-					./modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.h\
 					./modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp\
-					./modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.h\
 					./modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp\
-					./modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h\
 					./modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp\
-					./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h\
 					./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp\
-					./modules/Gradjx/Gradjx.h\
 					./modules/Gradjx/Gradjx.cpp\
 					./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp\
-					./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h\
 					./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp\
-					./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h\
 					./modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp\
-					./modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.h\
 					./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp\
-					./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h\
-					./classes/Inputs/ControlInput.h\
+					./modules/RheologyBAbsGradientx/RheologyBAbsGradientx.cpp\
 					./classes/Inputs/ControlInput.cpp\
 					./shared/Numerics/BrentSearch.cpp\
 					./cores/control_core.cpp\
 					./cores/controltao_core.cpp\
+					./cores/controlad_core.cpp\
 					./cores/controlm1qn3_core.cpp\
 					./cores/controlvalidation_core.cpp\
@@ -437,29 +246,51 @@
 					./classes/Loads/Riftfront.cpp\
 					./modules/ConstraintsStatex/RiftConstraintsState.cpp\
-					./classes/Massfluxatgate.h \
-					./classes/Misfit.h \
 					./modules/ModelProcessorx/CreateOutputDefinitions.cpp\
-					./modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h\
 					./modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp\
-					./classes/Inputs/PentaInput.h\
 					./classes/Inputs/PentaInput.cpp\
-					./classes/Inputs/TetraInput.h\
-					./classes/Inputs/TetraInput.cpp\
-					#}}}
+					./classes/Inputs/TetraInput.cpp
+#}}}
 #DAKOTA sources  {{{
 if DAKOTA
-issm_sources +=  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
-					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
-					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h\
+issm_sources +=  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
 					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp\
-					  ./modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h\
 					  ./modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp\
 					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp\
-					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h\
 					  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp\
 					  ./modules/ModelProcessorx/Dakota/UpdateElementsAndMaterialsDakota.cpp\
 					  ./cores/dakota_core.cpp\
-					  ./cores/DakotaSpawnCore.h\
 					  ./cores/DakotaSpawnCore.cpp
+endif
+#}}}
+#BAMG sources  {{{
+if BAMG
+issm_sources += ./bamg/BamgGeom.cpp\
+					 ./bamg/BamgMesh.cpp\
+					 ./bamg/BamgOpts.cpp\
+					 ./bamg/CrackedEdge.cpp\
+					 ./bamg/Curve.cpp\
+					 ./bamg/Direction.cpp\
+					 ./bamg/Edge.cpp\
+					 ./bamg/GeomEdge.cpp\
+					 ./bamg/GeomSubDomain.cpp\
+					 ./bamg/GeomVertex.cpp\
+					 ./bamg/Geometry.cpp\
+					 ./bamg/ListofIntersectionTriangles.cpp\
+					 ./bamg/EigenMetric.cpp\
+					 ./bamg/Metric.cpp\
+					 ./bamg/BamgQuadtree.cpp\
+					 ./bamg/SetOfE4.cpp\
+					 ./bamg/SubDomain.cpp\
+					 ./bamg/AdjacentTriangle.cpp\
+					 ./bamg/Triangle.cpp\
+					 ./bamg/BamgVertex.cpp\
+					 ./bamg/VertexOnEdge.cpp\
+					 ./bamg/VertexOnGeom.cpp\
+					 ./bamg/VertexOnVertex.cpp\
+					 ./bamg/Mesh.cpp\
+					 ./shared/Bamg/BigPrimeNumber.cpp\
+					 ./modules/Bamgx/Bamgx.cpp\
+					 ./modules/BamgConvertMeshx/BamgConvertMeshx.cpp\
+					 ./modules/BamgTriangulatex/BamgTriangulatex.cpp
 endif
 #}}}
@@ -468,6 +299,4 @@
 issm_sources += ./toolkits/petsc\
 					./toolkits/petsc/patches\
-					./toolkits/petsc/patches/SolverEnum.h\
-					./toolkits/petsc/patches/petscpatches.h\
 					./toolkits/petsc/patches/VecToMPISerial.cpp\
 					./toolkits/petsc/patches/MatToSerial.cpp\
@@ -484,26 +313,22 @@
 					./toolkits/petsc/patches/ISSMToPetscInsertMode.cpp\
 					./toolkits/petsc/patches/ISSMToPetscNormMode.cpp\
-					./toolkits/petsc/objects/petscobjects.h\
-					./toolkits/petsc/objects/PetscMat.h\
 					./toolkits/petsc/objects/PetscMat.cpp\
-					./toolkits/petsc/objects/PetscVec.h\
 					./toolkits/petsc/objects/PetscVec.cpp\
-					./toolkits/petsc/objects/PetscSolver.cpp\
-					./toolkits/petsc/objects/PetscSolver.h\
-					./toolkits/petsc/petscincludes.h
+					./toolkits/petsc/objects/PetscSolver.cpp
 endif
 #}}}
 #Mumps sources  {{{
 if MUMPS
-issm_sources += ./toolkits/mumps\
-					./toolkits/mumps/mumpsincludes.h\
-					./toolkits/mumps/MumpsSolve.cpp
+issm_sources += ./toolkits/mumps/MumpsSolve.cpp
 endif
 #}}}
 #Gsl sources  {{{
 if GSL
-issm_sources += ./toolkits/gsl\
-					./toolkits/gsl/gslincludes.h\
-					./toolkits/gsl/DenseGslSolve.cpp
+issm_sources += ./toolkits/gsl/DenseGslSolve.cpp
+endif
+#}}}
+#proj.4 sources  {{{
+if PROJ4
+issm_sources += ./modules/CoordinateSystemTransformx/CoordinateSystemTransformx.cpp
 endif
 #}}}
@@ -587,9 +412,6 @@
 issm_sources += ./analyses/ThermalAnalysis.cpp
 endif
-if SMOOTHEDSURFACESLOPEX
-issm_sources += ./analyses/SmoothedSurfaceSlopeXAnalysis.cpp
-endif
-if SMOOTHEDSURFACESLOPEY
-issm_sources += ./analyses/SmoothedSurfaceSlopeYAnalysis.cpp
+if SMOOTH
+issm_sources += ./analyses/SmoothAnalysis.cpp
 endif
 if MESHDEFORMATION
@@ -598,4 +420,5 @@
 if LEVELSET
 issm_sources += ./analyses/LevelsetAnalysis.cpp
+issm_sources += ./modules/Calvingx/Calvingx.cpp
 endif
 if EXTRAPOLATION
@@ -620,14 +443,7 @@
 endif
 #}}}
-#Mpi sources  {{{
-if MPI
-issm_sources += ./toolkits/issm/IssmMpiDenseMat.h\
-					 ./toolkits/issm/IssmMpiVec.h
-endif
-#}}}
 #Metis sources  {{{
 if METIS
-issm_sources += ./toolkits/metis/patches/metispatches.h\
-					./toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
+issm_sources += ./toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
 endif
 #}}}
@@ -635,169 +451,45 @@
 #Wrapper sources
 #Bamg sources  {{{
-bamg_sources =  ./bamg/bamgobjects.h\
-					 ./bamg/BamgGeom.h\
-					 ./bamg/BamgGeom.cpp\
-					 ./bamg/BamgMesh.h\
-					 ./bamg/BamgMesh.cpp\
-					 ./bamg/BamgOpts.h\
-					 ./bamg/BamgOpts.cpp\
-					 ./bamg/CrackedEdge.h\
-					 ./bamg/CrackedEdge.cpp\
-					 ./bamg/Curve.h\
-					 ./bamg/Curve.cpp\
-					 ./bamg/Direction.h\
-					 ./bamg/Direction.cpp\
-					 ./bamg/DoubleAndInt.h\
-					 ./bamg/Edge.h\
-					 ./bamg/Edge.cpp\
-					 ./bamg/GeomEdge.h\
-					 ./bamg/GeomEdge.cpp\
-					 ./bamg/GeomSubDomain.h\
-					 ./bamg/GeomSubDomain.cpp\
-					 ./bamg/GeomVertex.h\
-					 ./bamg/GeomVertex.cpp\
-					 ./bamg/Geometry.cpp\
-					 ./bamg/Geometry.h\
-					 ./bamg/ListofIntersectionTriangles.cpp\
-					 ./bamg/ListofIntersectionTriangles.h\
-					 ./bamg/EigenMetric.cpp\
-					 ./bamg/Metric.cpp\
-					 ./bamg/Metric.h\
-					 ./bamg/BamgQuadtree.cpp\
-					 ./bamg/BamgQuadtree.h\
-					 ./bamg/R2.h\
-					 ./bamg/SetOfE4.cpp\
-					 ./bamg/SetOfE4.h\
-					 ./bamg/SubDomain.h\
-					 ./bamg/SubDomain.cpp\
-					 ./bamg/AdjacentTriangle.h\
-					 ./bamg/AdjacentTriangle.cpp\
-					 ./bamg/Triangle.cpp\
-					 ./bamg/det.h \
-					 ./bamg/Triangle.h\
-					 ./bamg/BamgVertex.cpp\
-					 ./bamg/BamgVertex.h\
-					 ./bamg/VertexOnEdge.h\
-					 ./bamg/VertexOnEdge.cpp\
-					 ./bamg/VertexOnGeom.h\
-					 ./bamg/VertexOnGeom.cpp\
-					 ./bamg/VertexOnVertex.h\
-					 ./bamg/VertexOnVertex.cpp\
-					 ./bamg/Mesh.cpp\
-					 ./bamg/Mesh.h\
-					 ./shared/Bamg/Abs.h \
-					 ./shared/Bamg/BigPrimeNumber.h\
-					 ./shared/Bamg/BigPrimeNumber.cpp\
-					 ./shared/Bamg/BinaryRand.h \
-					 ./shared/Bamg/Exchange.h \
-					 ./shared/Bamg/extrema.h \
-					 ./shared/Bamg/HeapSort.h \
-					 ./shared/Bamg/OppositeAngle.h \
-					 ./modules/Bamgx/Bamgx.cpp\
-					 ./modules/Bamgx/Bamgx.h\
-					 ./modules/BamgConvertMeshx/BamgConvertMeshx.cpp\
-					 ./modules/BamgConvertMeshx/BamgConvertMeshx.h\
-					 ./modules/BamgTriangulatex/BamgTriangulatex.cpp\
-					 ./modules/BamgTriangulatex/BamgTriangulatex.h
-#}}}
-#Kriging sources  {{{
-if KRIGING
-kriging_sources = ./classes/kriging/Observations.h\
-					./classes/kriging/Observations.cpp\
-					./classes/kriging/Variogram.h \
-					./classes/kriging/GaussianVariogram.h\
-					./classes/kriging/GaussianVariogram.cpp\
-					./classes/kriging/ExponentialVariogram.h\
-					./classes/kriging/ExponentialVariogram.cpp\
-					./classes/kriging/SphericalVariogram.h\
-					./classes/kriging/SphericalVariogram.cpp\
-					./classes/kriging/PowerVariogram.h\
-					./classes/kriging/PowerVariogram.cpp\
-					./classes/kriging/Quadtree.h\
-					./classes/kriging/Quadtree.cpp\
-					./classes/kriging/Observation.h\
-					./classes/kriging/Observation.cpp\
-					./modules/Krigingx/Krigingx.cpp\
-					./modules/Krigingx/Krigingx.h
-issm_sources +=$(kriging_sources)
-issm_sources +=./modules/Krigingx/pKrigingx.cpp
-endif
+
 #}}}
 #Kml sources  {{{
-kml_sources = ./modules/Exp2Kmlx/Exp2Kmlx.h\
-				  ./modules/Exp2Kmlx/Exp2Kmlx.cpp\
-				  ./modules/Kml2Expx/Kml2Expx.h\
+kml_sources = ./modules/Exp2Kmlx/Exp2Kmlx.cpp\
 				  ./modules/Kml2Expx/Kml2Expx.cpp\
-				  ./modules/Shp2Kmlx/Shp2Kmlx.h\
 				  ./modules/Shp2Kmlx/Shp2Kmlx.cpp\
-				  ./modules/KMLFileReadx/KMLFileReadx.h\
 				  ./modules/KMLFileReadx/KMLFileReadx.cpp\
-				  ./modules/KMLMeshWritex/KMLMeshWritex.h\
 				  ./modules/KMLMeshWritex/KMLMeshWritex.cpp\
-				  ./modules/KMLOverlayx/KMLOverlayx.h\
 				  ./modules/KMLOverlayx/KMLOverlayx.cpp\
-				  ./kml/kmlobjects.h\
 				  ./kml/KML_Attribute.cpp\
-				  ./kml/KML_Attribute.h\
 				  ./kml/KML_Comment.cpp\
-				  ./kml/KML_Comment.h\
 				  ./kml/KML_ColorStyle.cpp\
-				  ./kml/KML_ColorStyle.h\
 				  ./kml/KML_Container.cpp\
-				  ./kml/KML_Container.h\
 				  ./kml/KML_Document.cpp\
-				  ./kml/KML_Document.h\
 				  ./kml/KML_Feature.cpp\
-				  ./kml/KML_Feature.h\
 				  ./kml/KML_File.cpp\
-				  ./kml/KML_File.h\
 				  ./kml/KML_Folder.cpp\
-				  ./kml/KML_Folder.h\
 				  ./kml/KML_Geometry.cpp\
-				  ./kml/KML_Geometry.h\
 				  ./kml/KML_GroundOverlay.cpp\
-				  ./kml/KML_GroundOverlay.h\
 				  ./kml/KML_Icon.cpp\
-				  ./kml/KML_Icon.h\
 				  ./kml/KML_LatLonBox.cpp\
-				  ./kml/KML_LatLonBox.h\
 				  ./kml/KML_LinearRing.cpp\
-				  ./kml/KML_LinearRing.h\
 				  ./kml/KML_LineString.cpp\
-				  ./kml/KML_LineString.h\
 				  ./kml/KML_LineStyle.cpp\
-				  ./kml/KML_LineStyle.h\
 				  ./kml/KML_MultiGeometry.cpp\
-				  ./kml/KML_MultiGeometry.h\
 				  ./kml/KML_Object.cpp\
-				  ./kml/KML_Object.h\
 				  ./kml/KML_Overlay.cpp\
-				  ./kml/KML_Overlay.h\
 				  ./kml/KML_Point.cpp\
-				  ./kml/KML_Point.h\
 				  ./kml/KML_Placemark.cpp\
-				  ./kml/KML_Placemark.h\
 				  ./kml/KML_Polygon.cpp\
-				  ./kml/KML_Polygon.h\
 				  ./kml/KML_PolyStyle.cpp\
-				  ./kml/KML_PolyStyle.h\
 				  ./kml/KML_Style.cpp\
-				  ./kml/KML_Style.h\
 				  ./kml/KML_StyleSelector.cpp\
-				  ./kml/KML_StyleSelector.h\
 				  ./kml/KML_SubStyle.cpp\
-				  ./kml/KML_SubStyle.h\
 				  ./kml/KML_Unknown.cpp\
-				  ./kml/KML_Unknown.h\
-				  ./kml/KMLFileReadUtils.cpp\
-				  ./kml/KMLFileReadUtils.h
+				  ./kml/KMLFileReadUtils.cpp
 #}}}
 #Modules sources{{{
-modules_sources= ./shared/Threads/issm_threads.h\
-			./shared/Threads/LaunchThread.cpp\
+modules_sources= ./shared/Threads/LaunchThread.cpp\
 			./shared/Threads/PartitionRange.cpp\
-			./shared/Exp/exp.h\
 			./shared/Exp/exp.cpp\
-			./shared/TriMesh/trimesh.h\
 			./shared/TriMesh/AssociateSegmentToElement.cpp\
 			./shared/TriMesh/GridInsideHole.cpp\
@@ -805,40 +497,26 @@
 			./shared/TriMesh/SplitMeshForRifts.cpp\
 			./shared/TriMesh/TriMeshUtils.cpp\
-			./modules/TriaSearchx/TriaSearchx.h\
 			./modules/TriaSearchx/TriaSearchx.cpp\
-			./modules/TriMeshx/TriMeshx.h\
 			./modules/TriMeshx/TriMeshx.cpp\
-			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h\
 			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp\
-			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h\
 			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp\
 			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp\
 			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp\
-			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.h\
 			./modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp\
 			./modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp\
-			./modules/InterpFromMesh2dx/InterpFromMesh2dx.h\
 			./modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp\
-			./modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.h\
 			./modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp\
-			./modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.h\
 			./modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp\
-			./modules/InterpFromMeshToGridx/InterpFromMeshToGridx.h\
 			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp\
-			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h\
 			./modules/ContourToMeshx/ContourToMeshx.cpp\
 			./modules/ContourToMeshx/ContourToMeshxt.cpp\
-			./modules/ContourToMeshx/ContourToMeshx.h\
+			./modules/ExpToLevelSetx/ExpToLevelSetx.cpp\
+			./modules/ExpToLevelSetx/ExpToLevelSetxt.cpp\
 			./modules/ContourToNodesx/ContourToNodesx.cpp\
-			./modules/ContourToNodesx/ContourToNodesx.h\
 			./modules/NodeConnectivityx/NodeConnectivityx.cpp\
-			./modules/NodeConnectivityx/NodeConnectivityx.h\
 			./modules/ElementConnectivityx/ElementConnectivityx.cpp\
-			./modules/ElementConnectivityx/ElementConnectivityx.h\
-			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp\
-			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h
+			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp
 if CHACO
-modules_sources+= ./modules/Chacox/Chacox.h\
-						./modules/Chacox/Chacox.cpp\
+modules_sources+= ./modules/Chacox/Chacox.cpp\
 						./modules/Chacox/input_parse.cpp\
 						./modules/Chacox/chaco_seconds.cpp\
@@ -846,38 +524,48 @@
 endif
 if SCOTCH
-modules_sources+= ./modules/Scotchx/Scotchx.cpp\
-						./modules/Scotchx/Scotchx.h
-endif
-#}}}
+modules_sources+= ./modules/Scotchx/Scotchx.cpp
+endif
+#}}}
+
+#kriging (WRAPPER and executable)
+#Kriging sources  {{{
+if KRIGING
+issm_sources += ./classes/kriging/Observations.cpp\
+					./classes/kriging/GaussianVariogram.cpp\
+					./classes/kriging/ExponentialVariogram.cpp\
+					./classes/kriging/SphericalVariogram.cpp\
+					./classes/kriging/PowerVariogram.cpp\
+					./classes/kriging/Quadtree.cpp\
+					./classes/kriging/Covertree.cpp\
+					./classes/kriging/Observation.cpp\
+					./modules/Krigingx/pKrigingx.cpp
+
+modules_sources +=./modules/Krigingx/Krigingx.cpp\
+						./modules/Krigingx/pKrigingx.cpp
+endif
 #}}}
 #Library flags and sources {{{
-ALLCXXFLAGS= -fPIC -D_GNU_SOURCE -fno-omit-frame-pointer -pthread -D_CPP_  $(CXXFLAGS) $(CXXOPTFLAGS) 
-
-libISSMCore_a_SOURCES  = $(issm_sources)
-libISSMCore_a_CXXFLAGS = $(ALLCXXFLAGS) $(DAKOTAFLAGS)
-libISSMCore_a_FFLAGS = $(AM_FFLAGS)
-
-if SHAREDLIBS
-libISSM_la_SOURCES = main/issm.cpp
-libISSM_la_LIBADD = libISSMCore.la libISSMOverload.la
+ALLCXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) 
 
 libISSMCore_la_SOURCES  = $(issm_sources)
-libISSMCore_la_LIBADD = $(PETSCLIB) $(TAOLIB) $(M1QN3LIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB)   $(ADOLCLIB) $(AMPILIB) $(METEOIOLIB) $(SNOWPACKLIB) 
+libISSMCore_la_CXXFLAGS = $(ALLCXXFLAGS) $(DAKOTAFLAGS)
 libISSMCore_la_FFLAGS = $(AM_FFLAGS)
-endif
+
+libISSMCore_la_LIBADD = $(PETSCLIB) $(TAOLIB) $(M1QN3LIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB)   $(ADOLCLIB) $(AMPILIB) $(METEOIOLIB) $(SNOWPACKLIB)
 
 if WRAPPERS
-libISSMModules_a_SOURCES = $(modules_sources)
-libISSMModules_a_SOURCES += $(bamg_sources)
+libISSMModules_la_SOURCES = $(modules_sources)
+libISSMModules_la_SOURCES += $(bamg_sources)
 if KRIGING
-libISSMModules_a_SOURCES += $(kriging_sources)
+libISSMModules_la_SOURCES += $(kriging_sources)
 endif
 if KML
-libISSMModules_a_SOURCES += $(kml_sources)
-endif
-libISSMModules_a_CXXFLAGS = $(ALLCXXFLAGS)
-libISSMModules_a_LIBADD = ./libISSMCore.a
-if SHAREDLIBS
-libISSMModules_la_SOURCES = $(libISSMModules_a_SOURCES)
+libISSMModules_la_SOURCES += $(kml_sources)
+endif
+libISSMModules_la_CXXFLAGS = $(ALLCXXFLAGS)
+if STANDALONE_LIBRARIES
+libISSMModules_la_LIBADD = ./libISSMCore.la
+else
+libISSMModules_la_LIBADD = ./libISSMCore.la $(TRIANGLELIB)
 endif
 endif
@@ -888,9 +576,22 @@
 AM_LDFLAGS = -avoid-version
 endif
+
+if STANDALONE_EXECUTABLES
+issm_LDFLAGS = -static
+endif
+
+if STANDALONE_LIBRARIES
+libISSMCore_la_LDFLAGS = -static
+libISSMOverload_la_LDFLAGS = -static
+if WRAPPERS
+libISSMModules_la_LDFLAGS = -static
+endif
+endif
+
 #}}}
 #Overload library, to overload any non-standard symbols. {{{
-libISSMOverload_a_SOURCES = ./shared/String/ApiPrintf.cpp
-
-libISSMOverload_a_CFLAGS  = -fPIC -D_C_ $(COPTFLAGS) $(CFLAGS)
+libISSMOverload_la_SOURCES = ./shared/String/ApiPrintf.cpp
+
+libISSMOverload_la_CFLAGS  = -fPIC -D_C_ $(COPTFLAGS) $(CFLAGS)
 #}}}
 
@@ -907,8 +608,11 @@
 
 #Standard libraries
-LDADD = ./libISSMCore.a ./libISSMOverload.a
+LDADD = ./libISSMCore.la ./libISSMOverload.la
+if WRAPPERS
+LDADD += ./libISSMModules.la $(TRIANGLELIB)
+endif
 
 #External packages
-LDADD += $(PETSCLIB) $(TAOLIB) $(M1QN3LIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB)  $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(AMPILIB) $(ADOLCLIB) $(MPILIB) $(METEOIOLIB) $(SNOWPACKLIB)
+LDADD += $(PETSCLIB) $(TAOLIB) $(M1QN3LIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB)  $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(AMPILIB) $(ADOLCLIB) $(MPILIB) $(METEOIOLIB) $(SNOWPACKLIB) $(PROJ4LIB)
 
 if FORTRAN
@@ -916,10 +620,10 @@
 endif
 
-issm_SOURCES = main/issm.h main/globals.h main/issm.cpp
-issm_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
+issm_SOURCES = main/issm.cpp
+issm_CXXFLAGS= -fPIC
 
 if KRIGING
 bin_PROGRAMS += kriging
-kriging_SOURCES = main/issm.h main/globals.h main/kriging.cpp
+kriging_SOURCES = main/kriging.cpp
 kriging_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
 endif
@@ -927,16 +631,16 @@
 #Automatic differentiation (must be done at the end) {{{
 if ADIC2 
-lib_LIBRARIES += libAD.a libISSMRose.a
+lib_LTLIBRARIES += libAD.la libISSMRose.la
 
 #ADIC2 library, for automatic differentiation 
 #libAD_a_SOURCES = ./mini1.ad.c
-libAD_a_SOURCES = 
-libAD_a_CFLAGS = -fPIC -D_C_ $(COPTFLAGS)
+libAD_la_SOURCES = 
+libAD_la_CFLAGS = -fPIC -D_C_ $(COPTFLAGS)
 
 #test rose preprocessing 
 %.r2cpp.cpp : %.cpp
 	testTranslator -rose:o $@ -rose:skipfinalCompileStep -DHAVE_CONFIG_H -D_C_ -I. -I../.. $(INCLUDES) $<
-libISSMRose_a_SOURCES = $(libISSMCore_a_SOURCES:.cpp=.r2cpp.cpp)
-libISSMRose_a_CXXFLAGS= -fPIC -D_C_ $(CXXOPTFLAGS)
+libISSMRose_la_SOURCES = $(libISSMCore_a_SOURCES:.cpp=.r2cpp.cpp)
+libISSMRose_la_CXXFLAGS= -fPIC -D_C_ $(CXXOPTFLAGS)
 
 #Automatic differentiation rules: 
@@ -950,4 +654,3 @@
 issmRose_exe_CXXFLAGS= -fPIC $(CXXOPTFLAGS) $(COPTFLAGS) 
 LDADD +=  $(ADIC2LIB) 
-
 endif #}}}
Index: /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.cpp	(revision 19105)
@@ -6,20 +6,20 @@
 
 /*Model processor*/
+void AdjointBalancethickness2Analysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethickness2Analysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethickness2Analysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
 int  AdjointBalancethickness2Analysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
 }/*}}}*/
+void AdjointBalancethickness2Analysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
 void AdjointBalancethickness2Analysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-void AdjointBalancethickness2Analysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-void AdjointBalancethickness2Analysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-void AdjointBalancethickness2Analysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-void AdjointBalancethickness2Analysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
 	_error_("not implemented yet");
 }/*}}}*/
@@ -48,9 +48,6 @@
 	/*Intermediaries */
 	int         num_responses,i;
-	IssmDouble  hobs,hu2,weight,Jdet;
-	IssmDouble  NUMxH2,NUMyH2,DENH2;
-	IssmDouble  NUMxUbar,NUMyUbar,DENUbar;
-	IssmDouble  vxobs,vyobs,vxobsbar,vyobsbar,vbarobs2,vbarobs;
-	IssmDouble  nux,nuy,phi,dphi[2];
+	IssmDouble  vx,vy,vel,Jdet;
+	IssmDouble  surface,surfaceobs,weight;
 	int        *responses = NULL;
 	IssmDouble *xyz_list  = NULL;
@@ -68,11 +65,9 @@
 	element->FindParam(&num_responses,InversionNumCostFunctionsEnum);
 	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
-	Input* thicknessobs_input = element->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
+	Input* surface_input      = element->GetInput(SurfaceEnum);                          _assert_(surface_input);
+	Input* surfaceobs_input   = element->GetInput(InversionSurfaceObsEnum);              _assert_(surfaceobs_input);
 	Input* weights_input      = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
-	Input* potential_input = element->GetInput(PotentialEnum);             _assert_(potential_input);
-	Input* vxobs_input     = element->GetInput(BalancethicknessVxObsEnum); _assert_(vxobs_input);
-	Input* vyobs_input     = element->GetInput(BalancethicknessVyObsEnum); _assert_(vyobs_input);
-	Input* nux_input       = element->GetInput(BalancethicknessNuxEnum);   _assert_(nux_input);
-	Input* nuy_input       = element->GetInput(BalancethicknessNuyEnum);   _assert_(nuy_input);
+	Input* vx_input           = element->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input           = element->GetInput(VyEnum);                                 _assert_(vy_input);
 
 	/* Start  looping on the number of gaussian points: */
@@ -85,28 +80,6 @@
 		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 
-		vxobs_input->GetInputValue(&vxobs,gauss);
-		vyobs_input->GetInputValue(&vyobs,gauss);
-		nux_input->GetInputValue(&nux,gauss);
-		nuy_input->GetInputValue(&nuy,gauss);
-		potential_input->GetInputValue(&phi,gauss);
-		potential_input->GetInputDerivativeValue(&dphi[0],xyz_list,gauss);
-		thicknessobs_input->GetInputValue(&hobs,gauss);
-
-		vxobsbar = nux*vxobs;
-		vyobsbar = nuy*vyobs;
-
-		vbarobs2 = (nux*nux*vxobs*vxobs + nuy*nuy*vyobs*vyobs);
-		vbarobs  = sqrt(vbarobs2);
-		hu2 = hobs*hobs*vbarobs2;
-
-		/*H^2 - Hobs^2*/
-		NUMxH2 = 2.*dbasis[0]*dphi[0]*(dphi[0]*dphi[0] + dphi[1]*dphi[1] - hu2);
-		NUMyH2 = 2.*dbasis[1]*dphi[1]*(dphi[0]*dphi[0] + dphi[1]*dphi[1] - hu2);
-		DENH2 = vbarobs2*vbarobs2+1.e-14;
-
-		/*Ubar-Ubar_obs*/
-		NUMxUbar = (vyobsbar*dphi[0]*dphi[1] - vxobsbar*dphi[1]*dphi[1])*vbarobs*dbasis[0];
-		NUMyUbar = (vyobsbar*dphi[0]*dphi[0] - vxobsbar*dphi[0]*dphi[1])*vbarobs*dbasis[1];
-		DENUbar  = pow(dphi[0]*dphi[0] + dphi[1]*dphi[1],3./2.)+1.e-14;
+		surface_input->GetInputValue(&surface, gauss);
+		surfaceobs_input->GetInputValue(&surfaceobs, gauss);
 
 		/*Loop over all requested responses*/
@@ -115,11 +88,6 @@
 
 			switch(responses[resp]){
-				case Balancethickness2MisfitEnum:
-					/*J = (H^2 - Hobs^2)^2*/
-					//for(i=0;i<numnodes;i++) pe->values[i]+=(NUMxH2+NUMyH2)/DENH2 *weight*Jdet*gauss->weight; NOT WORKING
-					/*J = phi^2*/
-					//for(i=0;i<numnodes;i++) pe->values[i]+= phi*basis[i]*weight*Jdet*gauss->weight; OK
-					/*J = (ubar - nux*uobs)^2*/
-					for(i=0;i<numnodes;i++) pe->values[i]+=(NUMxUbar-NUMyUbar)/DENUbar *weight*Jdet*gauss->weight;
+				case SurfaceAbsMisfitEnum:
+					for(i=0;i<numnodes;i++) pe->values[i]+=(surfaceobs-surface)*weight*Jdet*gauss->weight*basis[i];
 					break;
 				default:
@@ -136,9 +104,10 @@
 	delete gauss;
 	return pe;
-}/*}}}*/
-void AdjointBalancethickness2Analysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-void AdjointBalancethickness2Analysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+
+}/*}}}*/
+void           AdjointBalancethickness2Analysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void           AdjointBalancethickness2Analysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	/*The gradient of the cost function is calculated in 2 parts.
 	 *
@@ -158,12 +127,9 @@
 	element->FindParam(&responses,NULL,InversionCostFunctionsEnum);
 
-	/*Check that control_type is supported*/
-	if(control_type!=BalancethicknessApparentMassbalanceEnum){
-		_error_("Control "<<EnumToStringx(control_type)<<" not supported");
-	}
-
 	/*Deal with first part (partial derivative a J with respect to k)*/
 	for(resp=0;resp<num_responses;resp++) switch(responses[resp]){
-		case Balancethickness2MisfitEnum: /*Nothing, \partial J/\partial k = 0*/ break;
+		case SurfaceAbsMisfitEnum:
+			/*Nothing, \partial J/\partial k = 0*/
+			break;
 		default: _error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
 	}
@@ -171,5 +137,6 @@
 	/*Deal with second term*/
 	switch(control_type){
-		case BalancethicknessApparentMassbalanceEnum: GradientJAdot(element,gradient,control_index); break;
+		case BalancethicknessOmegaEnum:           GradientJOmega(element,gradient,control_index); break;
+		case BalancethicknessThickeningRateEnum:  GradientJdHdt( element,gradient,control_index); break;
 		default: _error_("control type not supported yet: " << EnumToStringx(control_type));
 	}
@@ -179,9 +146,8 @@
 
 }/*}}}*/
-void AdjointBalancethickness2Analysis::GradientJAdot(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+void           AdjointBalancethickness2Analysis::GradientJdHdt(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
 
 	/*Intermediaries*/
-	IssmDouble Jdet,weight;
-	IssmDouble lambda; 
+	IssmDouble lambda,Jdet; 
 	IssmDouble *xyz_list= NULL;
 
@@ -197,6 +163,5 @@
 	element->GetVerticesCoordinates(&xyz_list);
 	element->GradientIndexing(&vertexpidlist[0],control_index);
-	Input* adjoint_input = element->GetInput(AdjointEnum);                            _assert_(adjoint_input);
-	Input* weights_input = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* adjoint_input = element->GetInput(AdjointEnum);            _assert_(adjoint_input);
 
 	Gauss* gauss=element->NewGauss(2);
@@ -206,10 +171,10 @@
 		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
 		element->NodalFunctionsP1(basis,gauss);
-		weights_input->GetInputValue(&weight,gauss,Balancethickness2MisfitEnum);
+
 		adjoint_input->GetInputValue(&lambda,gauss);
 
 		/*Build gradient vector (actually -dJ/da): */
 		for(int i=0;i<numvertices;i++){
-			ge[i]+= - weight*Jdet*gauss->weight*basis[i]*lambda;
+			ge[i]+= -Jdet*gauss->weight*basis[i]*lambda;
 			_assert_(!xIsNan<IssmDouble>(ge[i]));
 		}
@@ -224,8 +189,57 @@
 	delete gauss;
 }/*}}}*/
-void AdjointBalancethickness2Analysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           AdjointBalancethickness2Analysis::GradientJOmega(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dlambda[2],ds[2],D0,omega,Jdet; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* adjoint_input = element->GetInput(AdjointEnum);            _assert_(adjoint_input);
+	Input* s_input       = element->GetInput(SurfaceEnum);            _assert_(s_input);
+	Input* D0_input      = element->GetInput(BalancethicknessD0Enum); _assert_(D0_input);
+	Input* omega_input   = element->GetInput(BalancethicknessOmegaEnum); _assert_(omega_input);
+
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		D0_input->GetInputValue(&D0,gauss);
+		omega_input->GetInputValue(&omega,gauss);
+		adjoint_input->GetInputDerivativeValue(&dlambda[0],xyz_list,gauss);
+		s_input->GetInputDerivativeValue(&ds[0],xyz_list,gauss);
+
+		/*Build gradient vector (actually -dJ/da): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+= -Jdet*gauss->weight*basis[i]*exp(omega)*D0*(ds[0]*dlambda[0] + ds[1]*dlambda[1]);
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(ge);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+}/*}}}*/
+void           AdjointBalancethickness2Analysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	element->InputUpdateFromSolutionOneDof(solution,AdjointEnum);
 }/*}}}*/
-void AdjointBalancethickness2Analysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           AdjointBalancethickness2Analysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.h
===================================================================
--- /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/AdjointBalancethickness2Analysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,9 +26,10 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void GradientJAdot(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           GradientJdHdt(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJOmega(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.cpp	(revision 19105)
@@ -6,20 +6,20 @@
 
 /*Model processor*/
+void AdjointBalancethicknessAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void AdjointBalancethicknessAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
 int  AdjointBalancethicknessAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
 }/*}}}*/
+void AdjointBalancethicknessAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
 void AdjointBalancethicknessAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-void AdjointBalancethicknessAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-void AdjointBalancethicknessAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-void AdjointBalancethicknessAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-void AdjointBalancethicknessAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
 	_error_("not implemented yet");
 }/*}}}*/
@@ -147,8 +147,8 @@
 	return pe;
 }/*}}}*/
-void AdjointBalancethicknessAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
-	_error_("not implemented yet");
-}/*}}}*/
-void AdjointBalancethicknessAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           AdjointBalancethicknessAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	_error_("not implemented yet");
+}/*}}}*/
+void           AdjointBalancethicknessAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	/*The gradient of the cost function is calculated in 2 parts.
 	 *
@@ -196,101 +196,5 @@
 
 }/*}}}*/
-void AdjointBalancethicknessAnalysis::GradientJVx(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Intermediaries*/
-	IssmDouble Jdet,weight;
-	IssmDouble thickness,Dlambda[3],dp[3];
-	IssmDouble *xyz_list= NULL;
-
-	/*Fetch number of vertices for this finite element*/
-	int numvertices = element->GetNumberOfVertices();
-
-	/*Initialize some vectors*/
-	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
-	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
-	int*        vertexpidlist = xNew<int>(numvertices);
-
-	/*Retrieve all inputs we will be needing: */
-	element->GetVerticesCoordinates(&xyz_list);
-	element->GradientIndexing(&vertexpidlist[0],control_index);
-	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
-	Input* adjoint_input   = element->GetInput(AdjointEnum);   _assert_(adjoint_input);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(4);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		adjoint_input->GetInputDerivativeValue(&Dlambda[0],xyz_list,gauss);
-		thickness_input->GetInputValue(&thickness, gauss);
-		thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
-
-		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		element->NodalFunctionsP1(basis,gauss);
-
-		/*Build gradient vector (actually -dJ/dD): */
-		for(int i=0;i<numvertices;i++){
-			ge[i]+=thickness*Dlambda[0]*Jdet*gauss->weight*basis[i];
-			_assert_(!xIsNan<IssmDouble>(ge[i]));
-		}
-	}
-	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(basis);
-	xDelete<IssmDouble>(ge);
-	xDelete<int>(vertexpidlist);
-	delete gauss;
-}/*}}}*/
-void AdjointBalancethicknessAnalysis::GradientJVy(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Intermediaries*/
-	IssmDouble Jdet,weight;
-	IssmDouble thickness,Dlambda[3],dp[3];
-	IssmDouble *xyz_list= NULL;
-
-	/*Fetch number of vertices for this finite element*/
-	int numvertices = element->GetNumberOfVertices();
-
-	/*Initialize some vectors*/
-	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
-	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
-	int*        vertexpidlist = xNew<int>(numvertices);
-
-	/*Retrieve all inputs we will be needing: */
-	element->GetVerticesCoordinates(&xyz_list);
-	element->GradientIndexing(&vertexpidlist[0],control_index);
-	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
-	Input* adjoint_input   = element->GetInput(AdjointEnum);   _assert_(adjoint_input);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(4);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		adjoint_input->GetInputDerivativeValue(&Dlambda[0],xyz_list,gauss);
-		thickness_input->GetInputValue(&thickness, gauss);
-		thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
-
-		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		element->NodalFunctionsP1(basis,gauss);
-
-		/*Build gradient vector (actually -dJ/dvy): */
-		for(int i=0;i<numvertices;i++){
-			ge[i]+=thickness*Dlambda[1]*Jdet*gauss->weight*basis[i];
-			_assert_(!xIsNan<IssmDouble>(ge[i]));
-		}
-	}
-	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(basis);
-	xDelete<IssmDouble>(ge);
-	xDelete<int>(vertexpidlist);
-	delete gauss;
-}/*}}}*/
-void AdjointBalancethicknessAnalysis::GradientJDhDt(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+void           AdjointBalancethicknessAnalysis::GradientJDhDt(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
 
 	/*Fetch number of vertices for this finite element*/
@@ -316,5 +220,99 @@
 	xDelete<int>(vertexpidlist);
 }/*}}}*/
-void AdjointBalancethicknessAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           AdjointBalancethicknessAnalysis::GradientJVx(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble thickness,Jdet,Dlambda[3],dp[3];
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* adjoint_input   = element->GetInput(AdjointEnum);   _assert_(adjoint_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjoint_input->GetInputDerivativeValue(&Dlambda[0],xyz_list,gauss);
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dD): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=thickness*Dlambda[0]*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+}/*}}}*/
+void           AdjointBalancethicknessAnalysis::GradientJVy(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble thickness,Jdet,Dlambda[3],dp[3];
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* adjoint_input   = element->GetInput(AdjointEnum);   _assert_(adjoint_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjoint_input->GetInputDerivativeValue(&Dlambda[0],xyz_list,gauss);
+		thickness_input->GetInputValue(&thickness, gauss);
+		thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dvy): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=thickness*Dlambda[1]*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+}/*}}}*/
+void           AdjointBalancethicknessAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int domaintype;
@@ -330,5 +328,5 @@
 	}
 }/*}}}*/
-void AdjointBalancethicknessAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           AdjointBalancethicknessAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/AdjointBalancethicknessAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,11 +26,11 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void GradientJVx(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void GradientJVy(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void GradientJDhDt(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           GradientJDhDt(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJVx(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJVy(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp	(revision 19105)
@@ -6,25 +6,25 @@
 
 /*Model processing*/
+void AdjointHorizAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void AdjointHorizAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void AdjointHorizAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
 int  AdjointHorizAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	_error_("not implemented");
 }/*}}}*/
+void AdjointHorizAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
 void AdjointHorizAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void AdjointHorizAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void AdjointHorizAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void AdjointHorizAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void AdjointHorizAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
 
 /*Finite Element Analysis*/
-void           AdjointHorizAnalysis::Core(FemModel* femmodel){/*{{{*/
+void AdjointHorizAnalysis::Core(FemModel* femmodel){/*{{{*/
 	_error_("not implemented");
 }/*}}}*/
@@ -42,4 +42,6 @@
 		case SSAApproximationEnum: 
 			return CreateKMatrixSSA(element);
+		case L1L2ApproximationEnum: 
+			return CreateKMatrixL1L2(element);
 		case HOApproximationEnum: 
 			return CreateKMatrixHO(element);
@@ -52,4 +54,175 @@
 	}
 }/*}}}*/
+ElementMatrix* AdjointHorizAnalysis::CreateKMatrixFS(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	bool        incomplete_adjoint;
+	int         dim,epssize;
+	IssmDouble  Jdet,mu_prime;
+	IssmDouble  eps1dotdphii,eps1dotdphij,eps2dotdphii,eps2dotdphij,eps3dotdphii,eps3dotdphij;
+	IssmDouble  eps1[3],eps2[3],eps3[3],epsilon[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble *xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	if(dim==2) epssize = 3;
+	else       epssize = 6;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numdof    = vnumnodes*dim + pnumnodes;
+
+	/*Initialize Jacobian with regular FS (first part of the Gateau derivative)*/
+	element->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
+	StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
+	ElementMatrix* Ke=analysis->CreateKMatrix(element);
+	delete analysis;
+	if(incomplete_adjoint) return Ke;
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* vx_input = element->GetInput(VxEnum);_assert_(vx_input);
+	Input* vy_input = element->GetInput(VyEnum);_assert_(vy_input);
+	Input* vz_input = NULL;
+	if(dim==3){
+		vz_input = element->GetInput(VzEnum);
+	}
+	else{
+		_error_("Not implemented yet");
+	}
+
+	/*Allocate dbasis*/
+	IssmDouble* dbasis = xNew<IssmDouble>(dim*vnumnodes);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		element->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		element->ViscosityFSDerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=epsilon[0];   eps2[0]=epsilon[2];   eps3[0]=epsilon[3];
+		eps1[1]=epsilon[2];   eps2[1]=epsilon[1];   eps3[1]=epsilon[4];
+		eps1[2]=epsilon[3];   eps2[2]=epsilon[4];   eps3[2]= -epsilon[0] -epsilon[1];
+
+		for(int i=0;i<vnumnodes;i++){
+			for(int j=0;j<vnumnodes;j++){
+				eps1dotdphii=eps1[0]*dbasis[0*vnumnodes+i]+eps1[1]*dbasis[1*vnumnodes+i]+eps1[2]*dbasis[2*vnumnodes+i];
+				eps1dotdphij=eps1[0]*dbasis[0*vnumnodes+j]+eps1[1]*dbasis[1*vnumnodes+j]+eps1[2]*dbasis[2*vnumnodes+j];
+				eps2dotdphii=eps2[0]*dbasis[0*vnumnodes+i]+eps2[1]*dbasis[1*vnumnodes+i]+eps2[2]*dbasis[2*vnumnodes+i];
+				eps2dotdphij=eps2[0]*dbasis[0*vnumnodes+j]+eps2[1]*dbasis[1*vnumnodes+j]+eps2[2]*dbasis[2*vnumnodes+j];
+				eps3dotdphii=eps3[0]*dbasis[0*vnumnodes+i]+eps3[1]*dbasis[1*vnumnodes+i]+eps3[2]*dbasis[2*vnumnodes+i];
+				eps3dotdphij=eps3[0]*dbasis[0*vnumnodes+j]+eps3[1]*dbasis[1*vnumnodes+j]+eps3[2]*dbasis[2*vnumnodes+j];
+
+				Ke->values[numdof*(4*i+0)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[numdof*(4*i+0)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[numdof*(4*i+0)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps1dotdphii;
+
+				Ke->values[numdof*(4*i+1)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[numdof*(4*i+1)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+				Ke->values[numdof*(4*i+1)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps2dotdphii;
+
+				Ke->values[numdof*(4*i+2)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps3dotdphii;
+				Ke->values[numdof*(4*i+2)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps3dotdphii;
+				Ke->values[numdof*(4*i+2)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps3dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,XYZEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(xyz_list);
+	return Ke;
+}/*}}}*/
+ElementMatrix* AdjointHorizAnalysis::CreateKMatrixHO(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	bool        incomplete_adjoint;
+	IssmDouble  Jdet,mu_prime;
+	IssmDouble  eps1dotdphii,eps1dotdphij,eps2dotdphii,eps2dotdphij;
+	IssmDouble  eps1[3],eps2[3],epsilon[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Jacobian with regular HO (first part of the Gateau derivative)*/
+	element->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
+	StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
+	ElementMatrix* Ke=analysis->CreateKMatrix(element);
+	delete analysis;
+	if(incomplete_adjoint) return Ke;
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* vx_input = element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input = element->GetInput(VyEnum); _assert_(vy_input);
+
+	/*Allocate dbasis*/
+	IssmDouble* dbasis = xNew<IssmDouble>(3*numnodes);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		element->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		element->ViscosityHODerivativeEpsSquare(&mu_prime,&epsilon[0]);
+		eps1[0]=2.*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
+		eps1[1]=epsilon[2];                 eps2[1]=epsilon[0]+2.*epsilon[1];
+		eps1[2]=epsilon[3];                 eps2[2]=epsilon[4];
+
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				eps1dotdphii=eps1[0]*dbasis[0*numnodes+i]+eps1[1]*dbasis[1*numnodes+i]+eps1[2]*dbasis[2*numnodes+i];
+				eps1dotdphij=eps1[0]*dbasis[0*numnodes+j]+eps1[1]*dbasis[1*numnodes+j]+eps1[2]*dbasis[2*numnodes+j];
+				eps2dotdphii=eps2[0]*dbasis[0*numnodes+i]+eps2[1]*dbasis[1*numnodes+i]+eps2[2]*dbasis[2*numnodes+i];
+				eps2dotdphij=eps2[0]*dbasis[0*numnodes+j]+eps2[1]*dbasis[1*numnodes+j]+eps2[2]*dbasis[2*numnodes+j];
+
+				Ke->values[2*numnodes*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+			}
+		}
+	}
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(xyz_list);
+	return Ke;
+}/*}}}*/
+ElementMatrix* AdjointHorizAnalysis::CreateKMatrixL1L2(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	bool incomplete_adjoint;
+
+	/*Initialize Jacobian with regular L1L2 (first part of the Gateau derivative)*/
+	StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
+	ElementMatrix* Ke=analysis->CreateKMatrix(element);
+	delete analysis;
+
+	/*return*/
+	element->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
+	if(!incomplete_adjoint){
+		_error_("Exact adjoint not supported yet for L1L2 model");
+	}
+	return Ke;
+}/*}}}*/
 ElementMatrix* AdjointHorizAnalysis::CreateKMatrixSSA(Element* element){/*{{{*/
 
@@ -139,158 +312,4 @@
 	return Ke;
 }/*}}}*/
-ElementMatrix* AdjointHorizAnalysis::CreateKMatrixHO(Element* element){/*{{{*/
-
-	/*Intermediaries */
-	bool        incomplete_adjoint;
-	IssmDouble  Jdet,mu_prime;
-	IssmDouble  eps1dotdphii,eps1dotdphij,eps2dotdphii,eps2dotdphij;
-	IssmDouble  eps1[3],eps2[3],epsilon[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
-	IssmDouble *xyz_list = NULL;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Initialize Jacobian with regular HO (first part of the Gateau derivative)*/
-	element->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
-	StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
-	ElementMatrix* Ke=analysis->CreateKMatrix(element);
-	delete analysis;
-	if(incomplete_adjoint) return Ke;
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	Input* vx_input = element->GetInput(VxEnum); _assert_(vx_input);
-	Input* vy_input = element->GetInput(VyEnum); _assert_(vy_input);
-
-	/*Allocate dbasis*/
-	IssmDouble* dbasis = xNew<IssmDouble>(3*numnodes);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(5);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-		element->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
-		element->ViscosityHODerivativeEpsSquare(&mu_prime,&epsilon[0]);
-		eps1[0]=2.*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
-		eps1[1]=epsilon[2];                 eps2[1]=epsilon[0]+2.*epsilon[1];
-		eps1[2]=epsilon[3];                 eps2[2]=epsilon[4];
-
-		for(int i=0;i<numnodes;i++){
-			for(int j=0;j<numnodes;j++){
-				eps1dotdphii=eps1[0]*dbasis[0*numnodes+i]+eps1[1]*dbasis[1*numnodes+i]+eps1[2]*dbasis[2*numnodes+i];
-				eps1dotdphij=eps1[0]*dbasis[0*numnodes+j]+eps1[1]*dbasis[1*numnodes+j]+eps1[2]*dbasis[2*numnodes+j];
-				eps2dotdphii=eps2[0]*dbasis[0*numnodes+i]+eps2[1]*dbasis[1*numnodes+i]+eps2[2]*dbasis[2*numnodes+i];
-				eps2dotdphij=eps2[0]*dbasis[0*numnodes+j]+eps2[1]*dbasis[1*numnodes+j]+eps2[2]*dbasis[2*numnodes+j];
-
-				Ke->values[2*numnodes*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
-				Ke->values[2*numnodes*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
-				Ke->values[2*numnodes*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
-				Ke->values[2*numnodes*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
-			}
-		}
-	}
-
-	/*Transform Coordinate System*/
-	element->TransformStiffnessMatrixCoord(Ke,XYEnum);
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<IssmDouble>(dbasis);
-	xDelete<IssmDouble>(xyz_list);
-	return Ke;
-}/*}}}*/
-ElementMatrix* AdjointHorizAnalysis::CreateKMatrixFS(Element* element){/*{{{*/
-
-	/*Intermediaries */
-	bool        incomplete_adjoint;
-	int         dim,epssize;
-	IssmDouble  Jdet,mu_prime;
-	IssmDouble  eps1dotdphii,eps1dotdphij,eps2dotdphii,eps2dotdphij,eps3dotdphii,eps3dotdphij;
-	IssmDouble  eps1[3],eps2[3],eps3[3],epsilon[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
-	IssmDouble *xyz_list = NULL;
-
-	/*Get problem dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
-	if(dim==2) epssize = 3;
-	else       epssize = 6;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int vnumnodes = element->NumberofNodesVelocity();
-	int pnumnodes = element->NumberofNodesPressure();
-	int numdof    = vnumnodes*dim + pnumnodes;
-
-	/*Initialize Jacobian with regular FS (first part of the Gateau derivative)*/
-	element->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
-	StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
-	ElementMatrix* Ke=analysis->CreateKMatrix(element);
-	delete analysis;
-	if(incomplete_adjoint) return Ke;
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	Input* vx_input = element->GetInput(VxEnum);_assert_(vx_input);
-	Input* vy_input = element->GetInput(VyEnum);_assert_(vy_input);
-	Input* vz_input = NULL;
-	if(dim==3){
-		vz_input = element->GetInput(VzEnum);
-	}
-	else{
-		_error_("Not implemented yet");
-	}
-
-	/*Allocate dbasis*/
-	IssmDouble* dbasis = xNew<IssmDouble>(dim*vnumnodes);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(5);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-		element->StrainRateHO(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
-		element->ViscosityFSDerivativeEpsSquare(&mu_prime,&epsilon[0]);
-		eps1[0]=epsilon[0];   eps2[0]=epsilon[2];   eps3[0]=epsilon[3];
-		eps1[1]=epsilon[2];   eps2[1]=epsilon[1];   eps3[1]=epsilon[4];
-		eps1[2]=epsilon[3];   eps2[2]=epsilon[4];   eps3[2]= -epsilon[0] -epsilon[1];
-
-		for(int i=0;i<vnumnodes;i++){
-			for(int j=0;j<vnumnodes;j++){
-				eps1dotdphii=eps1[0]*dbasis[0*vnumnodes+i]+eps1[1]*dbasis[1*vnumnodes+i]+eps1[2]*dbasis[2*vnumnodes+i];
-				eps1dotdphij=eps1[0]*dbasis[0*vnumnodes+j]+eps1[1]*dbasis[1*vnumnodes+j]+eps1[2]*dbasis[2*vnumnodes+j];
-				eps2dotdphii=eps2[0]*dbasis[0*vnumnodes+i]+eps2[1]*dbasis[1*vnumnodes+i]+eps2[2]*dbasis[2*vnumnodes+i];
-				eps2dotdphij=eps2[0]*dbasis[0*vnumnodes+j]+eps2[1]*dbasis[1*vnumnodes+j]+eps2[2]*dbasis[2*vnumnodes+j];
-				eps3dotdphii=eps3[0]*dbasis[0*vnumnodes+i]+eps3[1]*dbasis[1*vnumnodes+i]+eps3[2]*dbasis[2*vnumnodes+i];
-				eps3dotdphij=eps3[0]*dbasis[0*vnumnodes+j]+eps3[1]*dbasis[1*vnumnodes+j]+eps3[2]*dbasis[2*vnumnodes+j];
-
-				Ke->values[numdof*(4*i+0)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
-				Ke->values[numdof*(4*i+0)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
-				Ke->values[numdof*(4*i+0)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps1dotdphii;
-
-				Ke->values[numdof*(4*i+1)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
-				Ke->values[numdof*(4*i+1)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
-				Ke->values[numdof*(4*i+1)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps2dotdphii;
-
-				Ke->values[numdof*(4*i+2)+4*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps3dotdphii;
-				Ke->values[numdof*(4*i+2)+4*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps3dotdphii;
-				Ke->values[numdof*(4*i+2)+4*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps3dotdphii;
-			}
-		}
-	}
-
-	/*Transform Coordinate System*/
-	element->TransformStiffnessMatrixCoord(Ke,XYZEnum);
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<IssmDouble>(dbasis);
-	xDelete<IssmDouble>(xyz_list);
-	return Ke;
-}/*}}}*/
 ElementVector* AdjointHorizAnalysis::CreatePVector(Element* element){/*{{{*/
 
@@ -300,4 +319,6 @@
 		case SSAApproximationEnum: 
 			return CreatePVectorSSA(element);
+		case L1L2ApproximationEnum: 
+			return CreatePVectorL1L2(element);
 		case HOApproximationEnum: 
 			return CreatePVectorHO(element);
@@ -316,5 +337,5 @@
 
 	/*Intermediaries */
-	int        num_responses,i,dim;
+	int        num_responses,i,domaintype;
 	IssmDouble Jdet,obs_velocity_mag,velocity_mag;
 	IssmDouble vx,vy,vxobs,vyobs,dux,duy,weight;
@@ -323,6 +344,6 @@
 	IssmDouble *xyz_list_top = NULL;
 
-	/*Get problem dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
+	/* Get domaintype*/
+	element->FindParam(&domaintype,DomainTypeEnum);
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -332,5 +353,5 @@
 	/*Prepare coordinate system list*/
 	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
-	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	if(domaintype==Domain2DverticalEnum) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
 	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
 	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
@@ -346,7 +367,11 @@
 	Input* weights_input = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
 	Input* vx_input      = element->GetInput(VxEnum);                                 _assert_(vx_input);
-	Input* vy_input      = element->GetInput(VyEnum);                                 _assert_(vy_input);
 	Input* vxobs_input   = element->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
-	Input* vyobs_input   = element->GetInput(InversionVyObsEnum);                     _assert_(vyobs_input);
+	Input* vy_input    = NULL;
+	Input* vyobs_input = NULL;
+	if(domaintype!=Domain2DverticalEnum){
+		vy_input      = element->GetInput(VyEnum);                                 _assert_(vy_input);
+		vyobs_input   = element->GetInput(InversionVyObsEnum);                     _assert_(vyobs_input);
+	}
 	IssmDouble epsvel  = 2.220446049250313e-16;
 	IssmDouble meanvel = 3.170979198376458e-05; /*1000 m/yr*/
@@ -368,7 +393,9 @@
 
 		vx_input->GetInputValue(&vx,gauss);
-		vy_input->GetInputValue(&vy,gauss);
 		vxobs_input->GetInputValue(&vxobs,gauss);
-		vyobs_input->GetInputValue(&vyobs,gauss);
+		if(domaintype!=Domain2DverticalEnum) {
+			vy_input->GetInputValue(&vy,gauss);
+			vyobs_input->GetInputValue(&vyobs,gauss);
+		}
 
 		/*Loop over all requested responses*/
@@ -388,9 +415,13 @@
 					 */
 					for(i=0;i<vnumnodes;i++){
-						dux=vxobs-vx;
-						pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
-						if(dim==3){
+						if(domaintype!=Domain2DverticalEnum){
+							dux=vxobs-vx;
+							pe->values[i*3+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
 							duy=vyobs-vy;
-							pe->values[i*dim+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+							pe->values[i*3+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+						}
+						else{
+							dux=vxobs-vx;
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
 						}
 					}
@@ -409,10 +440,18 @@
 					 */
 					for(i=0;i<vnumnodes;i++){
-						scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
-						scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
-						dux=scalex*(vxobs-vx);
-						duy=scaley*(vyobs-vy);
-						pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
-						pe->values[i*dim+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+							scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
+							dux=scalex*(vxobs-vx);
+							duy=scaley*(vyobs-vy);
+							pe->values[i*3+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+							pe->values[i*3+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+						}
+						else{
+							scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+							dux=scalex*(vxobs-vx);
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+							pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+						}
 					}
 					break;
@@ -430,5 +469,5 @@
 					 */
 					for(i=0;i<vnumnodes;i++){
-						if(dim==3){
+						if(domaintype!=Domain2DverticalEnum){
 							velocity_mag    =sqrt(vx*vx+vy*vy)+epsvel;
 							obs_velocity_mag=sqrt(vxobs*vxobs+vyobs*vyobs)+epsvel;
@@ -436,6 +475,6 @@
 							dux=scale*vx;
 							duy=scale*vy;
-							pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
-							pe->values[i*dim+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+							pe->values[i*3+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+							pe->values[i*3+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
 						}
 						else{
@@ -444,5 +483,5 @@
 							scale=-8.*meanvel*meanvel/(velocity_mag*velocity_mag)*log(velocity_mag/obs_velocity_mag);
 							dux=scale*vx;
-							pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
 						}
 					}
@@ -459,9 +498,16 @@
 					 */
 					for(i=0;i<vnumnodes;i++){
-						scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
-						dux=scale*(vxobs-vx);
-						duy=scale*(vyobs-vy);
-						pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
-						pe->values[i*dim+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+						if (domaintype!=Domain2DverticalEnum){
+							scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
+							dux=scale*(vxobs-vx);
+							duy=scale*(vyobs-vy);
+							pe->values[i*3+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+							pe->values[i*3+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+						}
+						else{
+							scale=1./(S*2*fabs(vx-vxobs)+epsvel);
+							dux=scale*(vxobs-vx);
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+						}
 					}
 					break;
@@ -477,8 +523,14 @@
 					 */
 					for(i=0;i<vnumnodes;i++){
-						dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
-						duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
-						pe->values[i*dim+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
-						pe->values[i*dim+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+							duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+							pe->values[i*3+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+							pe->values[i*3+1]+=duy*weight*Jdet*gauss->weight*vbasis[i]; 
+						}
+						else{
+							dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*vbasis[i]; 
+						}
 					}
 					break;
@@ -515,4 +567,9 @@
 	return pe;
 }/*}}}*/
+ElementVector* AdjointHorizAnalysis::CreatePVectorL1L2(Element* element){/*{{{*/
+
+	/*Same as SSA*/
+	return this->CreatePVectorSSA(element);
+}/*}}}*/
 ElementVector* AdjointHorizAnalysis::CreatePVectorHO(Element* element){/*{{{*/
 
@@ -521,5 +578,5 @@
 
 	/*Intermediaries */
-	int        num_responses,i;
+	int        num_responses,i,domaintype;
 	IssmDouble Jdet,obs_velocity_mag,velocity_mag;
 	IssmDouble vx,vy,vxobs,vyobs,dux,duy,weight;
@@ -527,4 +584,7 @@
 	int        *responses    = NULL;
 	IssmDouble *xyz_list_top = NULL;
+
+	/* Get domaintype*/
+	element->FindParam(&domaintype,DomainTypeEnum);
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -541,7 +601,11 @@
 	Input* weights_input = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
 	Input* vx_input      = element->GetInput(VxEnum);                                 _assert_(vx_input);
-	Input* vy_input      = element->GetInput(VyEnum);                                 _assert_(vy_input);
 	Input* vxobs_input   = element->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
-	Input* vyobs_input   = element->GetInput(InversionVyObsEnum);                     _assert_(vyobs_input);
+	Input* vy_input=NULL;
+	Input* vyobs_input=NULL;
+	if(domaintype!=Domain2DverticalEnum){
+		vy_input      = element->GetInput(VyEnum);                                 _assert_(vy_input);
+		vyobs_input   = element->GetInput(InversionVyObsEnum);                     _assert_(vyobs_input);
+	}
 	IssmDouble epsvel  = 2.220446049250313e-16;
 	IssmDouble meanvel = 3.170979198376458e-05; /*1000 m/yr*/
@@ -563,8 +627,9 @@
 
 		vx_input->GetInputValue(&vx,gauss);
-		vy_input->GetInputValue(&vy,gauss);
 		vxobs_input->GetInputValue(&vxobs,gauss);
-		vyobs_input->GetInputValue(&vyobs,gauss);
-
+		if(domaintype!=Domain2DverticalEnum){
+			vy_input->GetInputValue(&vy,gauss);
+			vyobs_input->GetInputValue(&vyobs,gauss);
+		}
 		/*Loop over all requested responses*/
 		for(int resp=0;resp<num_responses;resp++){
@@ -583,8 +648,14 @@
 					 */
 					for(i=0;i<numnodes;i++){
-						dux=vxobs-vx;
-						duy=vyobs-vy;
-						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							dux=vxobs-vx;
+							duy=vyobs-vy;
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+							pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						}
+						else{ 
+							dux=vxobs-vx;
+							pe->values[i]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						}
 					}
 					break;
@@ -602,10 +673,17 @@
 					 */
 					for(i=0;i<numnodes;i++){
-						scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
-						scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
-						dux=scalex*(vxobs-vx);
-						duy=scaley*(vyobs-vy);
-						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+							scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
+							dux=scalex*(vxobs-vx);
+							duy=scaley*(vyobs-vy);
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+							pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						}
+						else{
+							scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+							dux=scalex*(vxobs-vx);
+							pe->values[i]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						}
 					}
 					break;
@@ -623,11 +701,20 @@
 					 */
 					for(i=0;i<numnodes;i++){
-						velocity_mag    =sqrt(pow(vx,   2)+pow(vy,   2))+epsvel;
-						obs_velocity_mag=sqrt(pow(vxobs,2)+pow(vyobs,2))+epsvel;
-						scale=-8*pow(meanvel,2)/pow(velocity_mag,2)*log(velocity_mag/obs_velocity_mag);
-						dux=scale*vx;
-						duy=scale*vy;
-						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							velocity_mag    =sqrt(pow(vx,   2)+pow(vy,   2))+epsvel;
+							obs_velocity_mag=sqrt(pow(vxobs,2)+pow(vyobs,2))+epsvel;
+							scale=-8*pow(meanvel,2)/pow(velocity_mag,2)*log(velocity_mag/obs_velocity_mag);
+							dux=scale*vx;
+							duy=scale*vy;
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+							pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						}
+						else{
+							velocity_mag    =fabs(vx)+epsvel;
+							obs_velocity_mag=fabs(vxobs)+epsvel;
+							scale=-8*pow(meanvel,2)/pow(velocity_mag,2)*log(velocity_mag/obs_velocity_mag);
+							dux=scale*vx;
+							pe->values[i]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						}
 					}
 					break;
@@ -643,9 +730,16 @@
 					 */
 					for(i=0;i<numnodes;i++){
-						scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
-						dux=scale*(vxobs-vx);
-						duy=scale*(vyobs-vy);
-						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
+							dux=scale*(vxobs-vx);
+							duy=scale*(vyobs-vy);
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+							pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						}
+						else{
+							scale=1./(S*2*fabs(vx-vxobs)+epsvel);
+							dux=scale*(vxobs-vx);
+							pe->values[i]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						}
 					}
 					break;
@@ -661,8 +755,14 @@
 					 */
 					for(i=0;i<numnodes;i++){
-						dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
-						duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
-						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+							duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+							pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						}
+						else{
+							dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+							pe->values[i]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						}
 					}
 					break;
@@ -680,4 +780,7 @@
 					break;
 				case RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case RheologyBAbsGradientEnum:
 					/*Nothing in P vector*/
 					break;
@@ -689,5 +792,5 @@
 
 	/*Transform coordinate system*/
-	element->TransformLoadVectorCoord(pe,XYEnum);
+	if(domaintype!=Domain2DverticalEnum) element->TransformLoadVectorCoord(pe,XYEnum);
 
 	/*Clean up and return*/
@@ -710,4 +813,8 @@
 		case Domain2DhorizontalEnum:
 			basalelement = element;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return NULL;
+			basalelement = element->SpawnBasalElement();
 			break;
 		case Domain3DEnum:
@@ -739,7 +846,11 @@
 	Input* weights_input = basalelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
 	Input* vx_input      = basalelement->GetInput(VxEnum);                                 _assert_(vx_input);
-	Input* vy_input      = basalelement->GetInput(VyEnum);                                 _assert_(vy_input);
 	Input* vxobs_input   = basalelement->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
-	Input* vyobs_input   = basalelement->GetInput(InversionVyObsEnum);                     _assert_(vyobs_input);
+	Input* vy_input=NULL;
+	Input* vyobs_input=NULL;
+	if(domaintype!=Domain2DverticalEnum){
+		vy_input      = basalelement->GetInput(VyEnum);                                 _assert_(vy_input);
+		vyobs_input   = basalelement->GetInput(InversionVyObsEnum);                     _assert_(vyobs_input);
+	}
 	IssmDouble epsvel  = 2.220446049250313e-16;
 	IssmDouble meanvel = 3.170979198376458e-05; /*1000 m/yr*/
@@ -761,8 +872,9 @@
 
 		vx_input->GetInputValue(&vx,gauss);
-		vy_input->GetInputValue(&vy,gauss);
 		vxobs_input->GetInputValue(&vxobs,gauss);
-		vyobs_input->GetInputValue(&vyobs,gauss);
-
+		if(domaintype!=Domain2DverticalEnum){
+			vy_input->GetInputValue(&vy,gauss);
+			vyobs_input->GetInputValue(&vyobs,gauss);
+		}
 		/*Loop over all requested responses*/
 		for(int resp=0;resp<num_responses;resp++){
@@ -781,8 +893,14 @@
 					 */
 					for(i=0;i<numnodes;i++){
-						dux=vxobs-vx;
-						duy=vyobs-vy;
-						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							dux=vxobs-vx;
+							duy=vyobs-vy;
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+							pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						}
+						else {
+							dux=vxobs-vx;
+							pe->values[i]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						}
 					}
 					break;
@@ -800,10 +918,17 @@
 					 */
 					for(i=0;i<numnodes;i++){
-						scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
-						scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
-						dux=scalex*(vxobs-vx);
-						duy=scaley*(vyobs-vy);
-						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+							scaley=pow(meanvel/(vyobs+epsvel),2); if(vyobs==0)scaley=0;
+							dux=scalex*(vxobs-vx);
+							duy=scaley*(vyobs-vy);
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+							pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						}
+						else{
+							scalex=pow(meanvel/(vxobs+epsvel),2); if(vxobs==0)scalex=0;
+							dux=scalex*(vxobs-vx);
+							pe->values[i]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						}
 					}
 					break;
@@ -821,11 +946,20 @@
 					 */
 					for(i=0;i<numnodes;i++){
-						velocity_mag    =sqrt(pow(vx,   2)+pow(vy,   2))+epsvel;
-						obs_velocity_mag=sqrt(pow(vxobs,2)+pow(vyobs,2))+epsvel;
-						scale=-8*pow(meanvel,2)/pow(velocity_mag,2)*log(velocity_mag/obs_velocity_mag);
-						dux=scale*vx;
-						duy=scale*vy;
-						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							velocity_mag    =sqrt(pow(vx,   2)+pow(vy,   2))+epsvel;
+							obs_velocity_mag=sqrt(pow(vxobs,2)+pow(vyobs,2))+epsvel;
+							scale=-8*pow(meanvel,2)/pow(velocity_mag,2)*log(velocity_mag/obs_velocity_mag);
+							dux=scale*vx;
+							duy=scale*vy;
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+							pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						}
+						else{
+							velocity_mag    =fabs(vx)+epsvel;
+							obs_velocity_mag=fabs(vxobs)+epsvel;
+							scale=-8*pow(meanvel,2)/pow(velocity_mag,2)*log(velocity_mag/obs_velocity_mag);
+							dux=scale*vx;
+							pe->values[i]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						}
 					}
 					break;
@@ -841,9 +975,16 @@
 					 */
 					for(i=0;i<numnodes;i++){
-						scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
-						dux=scale*(vxobs-vx);
-						duy=scale*(vyobs-vy);
-						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
+							dux=scale*(vxobs-vx);
+							duy=scale*(vyobs-vy);
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+							pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						}
+						else{
+							scale=1./(S*2*fabs(vx-vxobs)+epsvel);
+							dux=scale*(vxobs-vx);
+							pe->values[i]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						}
 					}
 					break;
@@ -859,8 +1000,14 @@
 					 */
 					for(i=0;i<numnodes;i++){
-						dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
-						duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
-						pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						if(domaintype!=Domain2DverticalEnum){
+							dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+							duy = - meanvel*meanvel * log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)) / (vy+epsvel);
+							pe->values[i*2+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+							pe->values[i*2+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
+						}
+						else{
+							dux = - meanvel*meanvel * log((fabs(vx)+epsvel)/(fabs(vxobs)+epsvel)) / (vx+epsvel);
+							pe->values[i]+=dux*weight*Jdet*gauss->weight*basis[i]; 
+						}
 					}
 					break;
@@ -878,4 +1025,7 @@
 					break;
 				case RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case RheologyBAbsGradientEnum:
 					/*Nothing in P vector*/
 					break;
@@ -887,5 +1037,5 @@
 
 	/*Transform coordinate system*/
-	basalelement->TransformLoadVectorCoord(pe,XYEnum);
+	if(domaintype!=Domain2DverticalEnum)	basalelement->TransformLoadVectorCoord(pe,XYEnum);
 
 	/*Clean up and return*/
@@ -897,8 +1047,8 @@
 	return pe;
 }/*}}}*/
-void AdjointHorizAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           AdjointHorizAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void AdjointHorizAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           AdjointHorizAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	/*The gradient of the cost function is calculated in 2 parts.
 	 *
@@ -924,6 +1074,8 @@
 	/*Check that control_type is supported*/
 	if(control_type!=MaterialsRheologyBbarEnum && 
-		control_type!=FrictionCoefficientEnum   && 
-		control_type!=DamageDbarEnum){
+		control_type!=FrictionCoefficientEnum   &&
+		control_type!=FrictionAsEnum   && 
+		control_type!=DamageDbarEnum            &&
+		control_type!=MaterialsRheologyBEnum){
 		_error_("Control "<<EnumToStringx(control_type)<<" not supported");
 	}
@@ -937,5 +1089,6 @@
 		case SurfaceAverageVelMisfitEnum: /*Nothing, \partial J/\partial k = 0*/ break;
 		case DragCoefficientAbsGradientEnum: GradientJDragGradient(element,gradient,control_index); break;
-		case RheologyBbarAbsGradientEnum:    GradientJBGradient(element,gradient,control_index);    break;
+		case RheologyBbarAbsGradientEnum:    GradientJBbarGradient(element,gradient,control_index); break;
+		case RheologyBAbsGradientEnum:       GradientJBGradient(element,gradient,control_index);    break;
 		default: _error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
 	}
@@ -946,4 +1099,5 @@
 			switch(approximation){
 				case SSAApproximationEnum: GradientJDragSSA(element,gradient,control_index); break;
+				case L1L2ApproximationEnum:GradientJDragL1L2(element,gradient,control_index); break;
 				case HOApproximationEnum:  GradientJDragHO( element,gradient,control_index); break;
 				case FSApproximationEnum:  GradientJDragFS( element,gradient,control_index); break;
@@ -952,9 +1106,29 @@
 			}
 			break;
+		case FrictionAsEnum:
+			switch(approximation){
+				case SSAApproximationEnum: GradientJDragHydroSSA(element,gradient,control_index); break;
+				case L1L2ApproximationEnum:GradientJDragHydroL1L2(element,gradient,control_index); break;
+				case HOApproximationEnum:  GradientJDragHydroHO( element,gradient,control_index); break;
+				case FSApproximationEnum:  GradientJDragHydroFS( element,gradient,control_index); break;
+				case NoneApproximationEnum: /*Gradient is 0*/                    break;
+				default: _error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
 		case MaterialsRheologyBbarEnum:
 			switch(approximation){
 				case SSAApproximationEnum: GradientJBbarSSA(element,gradient,control_index); break;
+				case L1L2ApproximationEnum:GradientJBbarL1L2(element,gradient,control_index); break;
 				case HOApproximationEnum:  GradientJBbarHO( element,gradient,control_index); break;
 				case FSApproximationEnum:  GradientJBbarFS( element,gradient,control_index); break;
+				case NoneApproximationEnum: /*Gradient is 0*/                    break;
+				default: _error_("approximation " << EnumToStringx(approximation) << " not supported yet");
+			}
+			break;
+		case MaterialsRheologyBEnum:
+			switch(approximation){
+				case SSAApproximationEnum: GradientJBSSA(element,gradient,control_index); break;
+				case HOApproximationEnum:  GradientJBHO( element,gradient,control_index); break;
+				case FSApproximationEnum:  GradientJBFS( element,gradient,control_index); break;
 				case NoneApproximationEnum: /*Gradient is 0*/                    break;
 				default: _error_("approximation " << EnumToStringx(approximation) << " not supported yet");
@@ -975,5 +1149,408 @@
                          
 }/*}}}*/
-void AdjointHorizAnalysis::GradientJDragGradient(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+void           AdjointHorizAnalysis::GradientJBbarFS(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+	/*WARNING: We use SSA as an estimate for now*/
+	this->GradientJBbarSSA(element,gradient,control_index);
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJBbarGradient(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble dk[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* dbasis        = xNew<IssmDouble>(2*numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* rheologyb_input = basalelement->GetInput(MaterialsRheologyBbarEnum);              _assert_(rheologyb_input);
+	Input* weights_input   = basalelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1Derivatives(dbasis,xyz_list,gauss);
+		weights_input->GetInputValue(&weight,gauss,RheologyBbarAbsGradientEnum);
+
+		/*Build alpha_complement_list: */
+		rheologyb_input->GetInputDerivativeValue(&dk[0],xyz_list,gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for(int i=0;i<numvertices;i++){
+			if(domaintype!=Domain2DverticalEnum){
+				ge[i]+=-weight*Jdet*gauss->weight*(dbasis[0*numvertices+i]*dk[0]+dbasis[1*numvertices+i]*dk[1]);
+			}
+			else{
+				ge[i]+=-weight*Jdet*gauss->weight*dbasis[0*numvertices+i]*dk[0];
+			}
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJBbarL1L2(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	   /*Same as SSA*/
+	   return this->GradientJBbarSSA(element,gradient,control_index);
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJBbarHO(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*WARNING: We use SSA as an estimate for now*/
+	this->GradientJBbarSSA(element,gradient,control_index);
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJBbarSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,dmudB;
+	IssmDouble dvx[3],dvy[3],dadjx[3],dadjy[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = basalelement->GetInput(ThicknessEnum);             _assert_(thickness_input);
+	Input* vx_input        = basalelement->GetInput(VxEnum);                    _assert_(vx_input);
+	Input* vy_input        = basalelement->GetInput(VyEnum);                    _assert_(vy_input);
+	Input* adjointx_input  = basalelement->GetInput(AdjointxEnum);              _assert_(adjointx_input);
+	Input* adjointy_input  = basalelement->GetInput(AdjointyEnum);              _assert_(adjointy_input);
+	Input* rheologyb_input = basalelement->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		adjointx_input->GetInputDerivativeValue(&dadjx[0],xyz_list,gauss);
+		adjointy_input->GetInputDerivativeValue(&dadjy[0],xyz_list,gauss);
+
+		basalelement->dViscositydBSSA(&dmudB,dim,xyz_list,gauss,vx_input,vy_input);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dB): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-dmudB*thickness*(
+						(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
+						)*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJBFS(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+	/*WARNING: We use HO as an estimate for now*/
+	this->GradientJBHO(element,gradient,control_index);
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJBGradient(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			break;
+		case Domain2DverticalEnum:
+			break;
+		case Domain3DEnum:
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble dk[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* dbasis        = xNew<IssmDouble>(3*numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* rheology_input = element->GetInput(MaterialsRheologyBEnum);              _assert_(rheology_input);
+	Input* weights_input   = element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1Derivatives(dbasis,xyz_list,gauss);
+		weights_input->GetInputValue(&weight,gauss,RheologyBAbsGradientEnum);
+
+		/*Build alpha_complement_list: */
+		rheology_input->GetInputDerivativeValue(&dk[0],xyz_list,gauss);
+
+		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
+		for(int i=0;i<numvertices;i++){
+			if(domaintype!=Domain2DverticalEnum){
+				ge[i]+=-weight*Jdet*gauss->weight*(dbasis[0*numvertices+i]*dk[0]+dbasis[1*numvertices+i]*dk[1]);
+			}
+			else{
+				ge[i]+=-weight*Jdet*gauss->weight*(dbasis[0*numvertices+i]*dk[0]+dbasis[1*numvertices+i]*dk[1]+dbasis[2*numvertices+i]*dk[2]);
+			}
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJBHO(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+	/*Intermediaries*/
+	int      domaintype,dim;
+
+	/*Get domaintype*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,dmudB;
+	IssmDouble dvx[3],dvy[3],dadjx[3],dadjy[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = element->GetInput(ThicknessEnum);             _assert_(thickness_input);
+	Input* vx_input        = element->GetInput(VxEnum);                    _assert_(vx_input);
+	Input* vy_input        = NULL;
+	Input* adjointx_input  = element->GetInput(AdjointxEnum);              _assert_(adjointx_input);
+	Input* adjointy_input  = NULL;
+	Input* rheologyb_input = element->GetInput(MaterialsRheologyBEnum); _assert_(rheologyb_input);
+	if(domaintype!=Domain2DverticalEnum){
+		vy_input        = element->GetInput(VyEnum);                   _assert_(vy_input);
+		adjointy_input  = element->GetInput(AdjointyEnum);             _assert_(adjointy_input);
+	}
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		adjointx_input->GetInputDerivativeValue(&dadjx[0],xyz_list,gauss);
+		dim=2;
+		if(domaintype!=Domain2DverticalEnum){
+			adjointy_input->GetInputDerivativeValue(&dadjy[0],xyz_list, gauss);
+			vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+			dim=3;
+		}
+
+		element->dViscositydBHO(&dmudB,dim,xyz_list,gauss,vx_input,vy_input);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dB): */
+		for(int i=0;i<numvertices;i++){
+			if(domaintype!=Domain2DverticalEnum){
+				ge[i]+=-dmudB*thickness*(
+							(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
+							)*Jdet*gauss->weight*basis[i];
+			}
+			else{
+				ge[i]+=-dmudB*thickness*4*dvx[0]*dadjx[0]*Jdet*gauss->weight*basis[i];
+			}
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJBSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,dmudB;
+	IssmDouble dvx[3],dvy[3],dadjx[3],dadjy[3]; 
+	IssmDouble *xyz_list= NULL;
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* thickness_input = basalelement->GetInput(ThicknessEnum);             _assert_(thickness_input);
+	Input* vx_input        = basalelement->GetInput(VxEnum);                    _assert_(vx_input);
+	Input* vy_input        = basalelement->GetInput(VyEnum);                    _assert_(vy_input);
+	Input* adjointx_input  = basalelement->GetInput(AdjointxEnum);              _assert_(adjointx_input);
+	Input* adjointy_input  = basalelement->GetInput(AdjointyEnum);              _assert_(adjointy_input);
+	Input* rheologyb_input = basalelement->GetInput(MaterialsRheologyBEnum); _assert_(rheologyb_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+		adjointx_input->GetInputDerivativeValue(&dadjx[0],xyz_list,gauss);
+		adjointy_input->GetInputDerivativeValue(&dadjy[0],xyz_list,gauss);
+
+		basalelement->dViscositydBSSA(&dmudB,dim,xyz_list,gauss,vx_input,vy_input);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dB): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-dmudB*thickness*(
+						(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
+						)*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJDragGradient(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
 
 	/*return if floating (gradient is 0)*/
@@ -1057,70 +1634,88 @@
 
 }/*}}}*/
-void AdjointHorizAnalysis::GradientJBGradient(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+void           AdjointHorizAnalysis::GradientJDragFS(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*return if floating or not on bed (gradient is 0)*/
+	if(element->IsFloating()) return;
+	if(!element->IsOnBase()) return;
 
 	/*Intermediaries*/
-	int      domaintype,dim;
-	Element* basalelement;
-
-	/*Get basal element*/
-	element->FindParam(&domaintype,DomainTypeEnum);
-	switch(domaintype){
-		case Domain2DhorizontalEnum:
-			basalelement = element;
-			dim          = 2;
-			break;
-		case Domain2DverticalEnum:
-			if(!element->IsOnBase()) return;
-			basalelement = element->SpawnBasalElement();
-			dim          = 1;
-			break;
-		case Domain3DEnum:
-			if(!element->IsOnBase()) return;
-			basalelement = element->SpawnBasalElement();
-			dim          = 2;
-			break;
-		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
-	}
-
-	/*Intermediaries*/
+	int        domaintype,dim;
 	IssmDouble Jdet,weight;
-	IssmDouble dk[3]; 
-	IssmDouble *xyz_list= NULL;
+	IssmDouble drag,dalpha2dk,normal[3];
+	IssmDouble vx,vy,vz,lambda,mu,xi;
+	IssmDouble *xyz_list_base= NULL;
 
 	/*Fetch number of vertices for this finite element*/
-	int numvertices = basalelement->GetNumberOfVertices();
+	int numvertices = element->GetNumberOfVertices();
 
 	/*Initialize some vectors*/
-	IssmDouble* dbasis        = xNew<IssmDouble>(2*numvertices);
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
 	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
 	int*        vertexpidlist = xNew<int>(numvertices);
 
+	/* get domaintype */
+	element->FindParam(&domaintype,DomainTypeEnum);
+
+	/*Build friction element, needed later: */
+	if(domaintype!=Domain2DverticalEnum) dim=3;
+	else dim=2;
+	Friction* friction=new Friction(element,dim);
+
 	/*Retrieve all inputs we will be needing: */
-	basalelement->GetVerticesCoordinates(&xyz_list);
-	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
-	Input* rheologyb_input = basalelement->GetInput(MaterialsRheologyBbarEnum);              _assert_(rheologyb_input);
-	Input* weights_input   = basalelement->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* vx_input        = element->GetInput(VxEnum);                   _assert_(vx_input);
+	Input* vy_input        = element->GetInput(VyEnum);                   _assert_(vy_input);
+	Input* adjointx_input  = element->GetInput(AdjointxEnum);             _assert_(adjointx_input);
+	Input* adjointy_input  = element->GetInput(AdjointyEnum);             _assert_(adjointy_input);
+	Input* vz_input        = NULL;
+	Input* adjointz_input  = NULL;
+	if(domaintype!=Domain2DverticalEnum){
+		vz_input        = element->GetInput(VzEnum);                   _assert_(vy_input);
+		adjointz_input  = element->GetInput(AdjointzEnum);             _assert_(adjointz_input);
+	}
+	Input* dragcoeff_input = element->GetInput(FrictionCoefficientEnum);  _assert_(dragcoeff_input);
 
 	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=basalelement->NewGauss(2);
+	Gauss* gauss=element->NewGaussBase(4);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 		gauss->GaussPoint(ig);
 
-		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		basalelement->NodalFunctionsP1Derivatives(dbasis,xyz_list,gauss);
-		weights_input->GetInputValue(&weight,gauss,RheologyBbarAbsGradientEnum);
-
-		/*Build alpha_complement_list: */
-		rheologyb_input->GetInputDerivativeValue(&dk[0],xyz_list,gauss);
-
-		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
-		for(int i=0;i<numvertices;i++){
-			if(dim==2){
-				ge[i]+=-weight*Jdet*gauss->weight*(dbasis[0*numvertices+i]*dk[0]+dbasis[1*numvertices+i]*dk[1]);
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		if(domaintype!=Domain2DverticalEnum){
+			adjointz_input->GetInputValue(&xi    ,gauss);
+			vz_input->GetInputValue(&vz,gauss);
+		}
+		dragcoeff_input->GetInputValue(&drag, gauss);
+
+		friction->GetAlphaComplement(&dalpha2dk,gauss);
+		element->NormalBase(&normal[0],xyz_list_base);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dk): */
+		if(domaintype!=Domain2DverticalEnum){
+			for(int i=0;i<numvertices;i++){
+				ge[i]+=(
+							-lambda*(2*drag*dalpha2dk*(vx - vz*normal[0]*normal[2]))
+							-mu    *(2*drag*dalpha2dk*(vy - vz*normal[1]*normal[2]))
+							-xi    *(2*drag*dalpha2dk*(-vx*normal[0]*normal[2]-vy*normal[1]*normal[2]))
+						 )*Jdet*gauss->weight*basis[i];
+				_assert_(!xIsNan<IssmDouble>(ge[i]));
 			}
-			else{
-				ge[i]+=-weight*Jdet*gauss->weight*dbasis[0*numvertices+i]*dk[0];
+		}
+		else{
+			for(int i=0;i<numvertices;i++){
+				ge[i]+=(
+							-lambda*2*drag*dalpha2dk*vx
+							-mu    *2*drag*dalpha2dk*vy
+						 )*Jdet*gauss->weight*basis[i];
+				_assert_(!xIsNan<IssmDouble>(ge[i]));
 			}
-			_assert_(!xIsNan<IssmDouble>(ge[i]));
 		}
 	}
@@ -1128,12 +1723,91 @@
 
 	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(basis);
 	xDelete<IssmDouble>(ge);
 	xDelete<int>(vertexpidlist);
 	delete gauss;
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
-}/*}}}*/
-void AdjointHorizAnalysis::GradientJDragSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+	delete friction;
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJDragL1L2(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Same as SSA*/
+	return this->GradientJDragSSA(element,gradient,control_index);
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJDragHO(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*return if floating or not on bed (gradient is 0)*/
+	if(element->IsFloating()) return;
+	if(!element->IsOnBase()) return;
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble drag,dalpha2dk;
+	IssmDouble vx,vy,lambda,mu;
+	IssmDouble *xyz_list_base= NULL;
+
+	int      domaintype,dim;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Build friction element, needed later: */
+	if(domaintype!=Domain2DverticalEnum) dim=3;
+	else dim=2;
+	Friction* friction=new Friction(element,dim);
+
+	/*Retrieve all inputs we will be needing: */
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* vx_input        = element->GetInput(VxEnum);                   _assert_(vx_input);
+	Input* vy_input        = NULL;
+	Input* adjointx_input  = element->GetInput(AdjointxEnum);             _assert_(adjointx_input);
+	Input* adjointy_input  = NULL;
+	Input* dragcoeff_input = element->GetInput(FrictionCoefficientEnum);  _assert_(dragcoeff_input);
+	if(domaintype!=Domain2DverticalEnum){
+		vy_input        = element->GetInput(VyEnum);                   _assert_(vy_input);
+		adjointy_input  = element->GetInput(AdjointyEnum);             _assert_(adjointy_input);
+	}
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjointx_input->GetInputValue(&lambda, gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		if(domaintype!=Domain2DverticalEnum){
+			adjointy_input->GetInputValue(&mu, gauss);
+			vy_input->GetInputValue(&vy,gauss);
+		}
+		dragcoeff_input->GetInputValue(&drag, gauss);
+
+		friction->GetAlphaComplement(&dalpha2dk,gauss);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsP1(basis,gauss);
+
+		/*Build gradient vector (actually -dJ/dD): */
+		for(int i=0;i<numvertices;i++){
+			if(domaintype!=Domain2DverticalEnum) ge[i]+=-2.*drag*dalpha2dk*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
+			else ge[i]+=-2.*drag*dalpha2dk*(lambda*vx)*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	delete friction;
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJDragSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
 
 	/*return if floating (gradient is 0)*/
@@ -1223,5 +1897,6 @@
 	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
 }/*}}}*/
-void AdjointHorizAnalysis::GradientJDragHO(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+void AdjointHorizAnalysis::GradientJDragHydroFS(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
 
 	/*return if floating or not on bed (gradient is 0)*/
@@ -1230,8 +1905,8 @@
 
 	/*Intermediaries*/
-	int        dim=3;
+	int        domaintype,dim;
 	IssmDouble Jdet,weight;
-	IssmDouble drag,dalpha2dk;
-	IssmDouble vx,vy,lambda,mu;
+	IssmDouble drag,dalpha2dk,normal[3];
+	IssmDouble vx,vy,vz,lambda,mu,xi;
 	IssmDouble *xyz_list_base= NULL;
 
@@ -1244,5 +1919,10 @@
 	int*        vertexpidlist = xNew<int>(numvertices);
 
+	/* get domaintype */
+	element->FindParam(&domaintype,DomainTypeEnum);
+
 	/*Build friction element, needed later: */
+	if(domaintype!=Domain2DverticalEnum) dim=3;
+	else dim=2;
 	Friction* friction=new Friction(element,dim);
 
@@ -1254,5 +1934,10 @@
 	Input* adjointx_input  = element->GetInput(AdjointxEnum);             _assert_(adjointx_input);
 	Input* adjointy_input  = element->GetInput(AdjointyEnum);             _assert_(adjointy_input);
-	Input* dragcoeff_input = element->GetInput(FrictionCoefficientEnum);  _assert_(dragcoeff_input);
+	Input* vz_input        = NULL;
+	Input* adjointz_input  = NULL;
+	if(domaintype!=Domain2DverticalEnum){
+		vz_input        = element->GetInput(VzEnum);                   _assert_(vy_input);
+		adjointz_input  = element->GetInput(AdjointzEnum);             _assert_(adjointz_input);
+	}
 
 	/* Start  looping on the number of gaussian points: */
@@ -1265,15 +1950,34 @@
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
-		dragcoeff_input->GetInputValue(&drag, gauss);
+		if(domaintype!=Domain2DverticalEnum){
+			adjointz_input->GetInputValue(&xi    ,gauss);
+			vz_input->GetInputValue(&vz,gauss);
+		}
 
 		friction->GetAlphaComplement(&dalpha2dk,gauss);
+		element->NormalBase(&normal[0],xyz_list_base);
 
 		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
 		element->NodalFunctionsP1(basis,gauss);
 
-		/*Build gradient vector (actually -dJ/dD): */
-		for(int i=0;i<numvertices;i++){
-			ge[i]+=-2.*drag*dalpha2dk*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
-			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		/*Build gradient vector (actually -dJ/dk): */
+		if(domaintype!=Domain2DverticalEnum){
+			for(int i=0;i<numvertices;i++){
+				ge[i]+=(
+							-lambda*(dalpha2dk*(vx - vz*normal[0]*normal[2]))
+							-mu    *(dalpha2dk*(vy - vz*normal[1]*normal[2]))
+							-xi    *(dalpha2dk*(-vx*normal[0]*normal[2]-vy*normal[1]*normal[2]))
+						 )*Jdet*gauss->weight*basis[i];
+				_assert_(!xIsNan<IssmDouble>(ge[i]));
+			}
+		}
+		else{
+			for(int i=0;i<numvertices;i++){
+				ge[i]+=(
+							-lambda*dalpha2dk*vx
+							-mu    *dalpha2dk*vy
+						 )*Jdet*gauss->weight*basis[i];
+				_assert_(!xIsNan<IssmDouble>(ge[i]));
+			}
 		}
 	}
@@ -1288,5 +1992,10 @@
 	delete friction;
 }/*}}}*/
-void AdjointHorizAnalysis::GradientJDragFS(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+void           AdjointHorizAnalysis::GradientJDragHydroL1L2(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Same as SSA*/
+	return this->GradientJDragSSA(element,gradient,control_index);
+}/*}}}*/
+void           AdjointHorizAnalysis::GradientJDragHydroHO(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
 
 	/*return if floating or not on bed (gradient is 0)*/
@@ -1295,10 +2004,11 @@
 
 	/*Intermediaries*/
-	int        dim=3;
 	IssmDouble Jdet,weight;
-	IssmDouble drag,dalpha2dk,normal[3];
-	IssmDouble vx,vy,vz,lambda,mu,xi;
+	IssmDouble drag,dalpha2dk;
+	IssmDouble vx,vy,lambda,mu;
 	IssmDouble *xyz_list_base= NULL;
 
+	int      domaintype,dim;
+	element->FindParam(&domaintype,DomainTypeEnum);
 	/*Fetch number of vertices for this finite element*/
 	int numvertices = element->GetNumberOfVertices();
@@ -1310,4 +2020,6 @@
 
 	/*Build friction element, needed later: */
+	if(domaintype!=Domain2DverticalEnum) dim=3;
+	else dim=2;
 	Friction* friction=new Friction(element,dim);
 
@@ -1316,11 +2028,11 @@
 	element->GradientIndexing(&vertexpidlist[0],control_index);
 	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_(vy_input);
+	Input* vy_input        = NULL;
 	Input* adjointx_input  = element->GetInput(AdjointxEnum);             _assert_(adjointx_input);
-	Input* adjointy_input  = element->GetInput(AdjointyEnum);             _assert_(adjointy_input);
-	Input* adjointz_input  = element->GetInput(AdjointzEnum);             _assert_(adjointz_input);
-	Input* dragcoeff_input = element->GetInput(FrictionCoefficientEnum);  _assert_(dragcoeff_input);
-
+	Input* adjointy_input  = NULL;
+	if(domaintype!=Domain2DverticalEnum){
+		vy_input        = element->GetInput(VyEnum);                   _assert_(vy_input);
+		adjointy_input  = element->GetInput(AdjointyEnum);             _assert_(adjointy_input);
+	}
 	/* Start  looping on the number of gaussian points: */
 	Gauss* gauss=element->NewGaussBase(4);
@@ -1329,24 +2041,19 @@
 
 		adjointx_input->GetInputValue(&lambda, gauss);
-		adjointy_input->GetInputValue(&mu, gauss);
-		adjointz_input->GetInputValue(&xi    ,gauss);
 		vx_input->GetInputValue(&vx,gauss);
-		vy_input->GetInputValue(&vy,gauss);
-		vz_input->GetInputValue(&vz,gauss);
-		dragcoeff_input->GetInputValue(&drag, gauss);
+		if(domaintype!=Domain2DverticalEnum){
+			adjointy_input->GetInputValue(&mu, gauss);
+			vy_input->GetInputValue(&vy,gauss);
+		}
 
 		friction->GetAlphaComplement(&dalpha2dk,gauss);
-		element->NormalBase(&normal[0],xyz_list_base);
 
 		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
 		element->NodalFunctionsP1(basis,gauss);
 
-		/*Build gradient vector (actually -dJ/dk): */
+		/*Build gradient vector (actually -dJ/dD): */
 		for(int i=0;i<numvertices;i++){
-			ge[i]+=(
-						-lambda*(2*drag*dalpha2dk*(vx - vz*normal[0]*normal[2]))
-						-mu    *(2*drag*dalpha2dk*(vy - vz*normal[1]*normal[2]))
-						-xi    *(2*drag*dalpha2dk*(-vx*normal[0]*normal[2]-vy*normal[1]*normal[2]))
-						)*Jdet*gauss->weight*basis[i];
+			if(domaintype!=Domain2DverticalEnum) ge[i]+=-dalpha2dk*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
+			else ge[i]+=-dalpha2dk*(lambda*vx)*Jdet*gauss->weight*basis[i];
 			_assert_(!xIsNan<IssmDouble>(ge[i]));
 		}
@@ -1362,5 +2069,9 @@
 	delete friction;
 }/*}}}*/
-void AdjointHorizAnalysis::GradientJBbarSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+void AdjointHorizAnalysis::GradientJDragHydroSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*return if floating (gradient is 0)*/
+	if(element->IsFloating()) return;
 
 	/*Intermediaries*/
@@ -1390,5 +2101,129 @@
 	/*Intermediaries*/
 	IssmDouble Jdet,weight;
-	IssmDouble thickness,dmudB;
+	IssmDouble dalpha2dk;
+	IssmDouble vx,vy,lambda,mu;
+	IssmDouble *xyz_list= NULL;
+
+
+	/*Fetch number of vertices for this finite element*/
+	int numvertices = basalelement->GetNumberOfVertices();
+
+	/*Initialize some vectors*/
+	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
+	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
+	int*        vertexpidlist = xNew<int>(numvertices);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(basalelement,dim);
+
+	/*Retrieve all inputs we will be needing: */
+	basalelement->GetVerticesCoordinates(&xyz_list);
+	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
+	Input* vx_input        = basalelement->GetInput(VxEnum);          _assert_(vx_input);
+	Input* vy_input        = basalelement->GetInput(VyEnum);          _assert_(vy_input);
+	Input* adjointx_input  = basalelement->GetInput(AdjointxEnum);    _assert_(adjointx_input);
+	Input* adjointy_input  = basalelement->GetInput(AdjointyEnum);    _assert_(adjointy_input);
+
+
+
+	IssmDouble  q_exp;
+	IssmDouble  C_param;
+	IssmDouble  As;
+	IssmDouble  Neff;
+	IssmDouble  n;
+	IssmDouble  alpha;
+	IssmDouble  Chi,Gamma;
+	IssmDouble  vz,vmag;
+	IssmDouble  Uder;
+
+	/*Recover parameters: */
+	Input* qinput = basalelement->GetInput(FrictionQEnum);
+	Input* cinput = basalelement->GetInput(FrictionCEnum);
+	Input* Asinput = basalelement->GetInput(FrictionAsEnum);
+	Input* Ninput = basalelement->GetInput(FrictionEffectivePressureEnum);
+	Input* nInput =basalelement->GetInput(MaterialsRheologyNEnum);
+	
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=basalelement->NewGauss(4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		adjointx_input->GetInputValue(&lambda, gauss);
+		adjointy_input->GetInputValue(&mu, gauss);
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+
+		friction->GetAlphaComplement(&dalpha2dk,gauss);
+
+		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		basalelement->NodalFunctionsP1(basis,gauss);
+
+		/*Dealing with dalpha/du*/
+		qinput->GetInputValue(&q_exp,gauss);
+		cinput->GetInputValue(&C_param,gauss);
+		Asinput->GetInputValue(&As,gauss);
+		Ninput->GetInputValue(&Neff,gauss);
+		nInput->GetInputValue(&n,gauss);
+
+		if (q_exp==1){
+			alpha=1;
+		}
+		else{
+			alpha=(pow(q_exp-1,q_exp-1))/pow(q_exp,q_exp);
+		}
+		Chi   = vmag/(pow(C_param,n)*pow(Neff,n)*As);
+		Gamma = (Chi/(1.+alpha*pow(Chi,q_exp)));
+		
+		Uder =Neff*C_param/(vmag*vmag*n) *
+			(Gamma-alpha*q_exp*pow(Chi,q_exp-1.)*Gamma*Gamma* pow(Gamma,(1.-n)/n) -
+			 n* pow(Gamma,1./n));
+		
+		/*Build gradient vector (actually -dJ/dD): */
+		for(int i=0;i<numvertices;i++){
+			ge[i]+=-dalpha2dk*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
+			_assert_(!xIsNan<IssmDouble>(ge[i]));
+		}
+	}
+	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(ge);
+	xDelete<int>(vertexpidlist);
+	delete gauss;
+	delete friction;
+	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
+}/*}}}*/
+
+void           AdjointHorizAnalysis::GradientJDSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
+
+	/*Intermediaries*/
+	int      domaintype,dim;
+	Element* basalelement;
+
+	/*Get basal element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			basalelement = element;
+			dim          = 2;
+			break;
+		case Domain2DverticalEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 1;
+			break;
+		case Domain3DEnum:
+			if(!element->IsOnBase()) return;
+			basalelement = element->SpawnBasalElement();
+			dim          = 2;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries*/
+	IssmDouble Jdet,weight;
+	IssmDouble thickness,dmudD;
 	IssmDouble dvx[3],dvy[3],dadjx[3],dadjy[3]; 
 	IssmDouble *xyz_list= NULL;
@@ -1423,12 +2258,11 @@
 		adjointy_input->GetInputDerivativeValue(&dadjy[0],xyz_list,gauss);
 
-		basalelement->dViscositydBSSA(&dmudB,dim,xyz_list,gauss,vx_input,vy_input);
+		basalelement->dViscositydDSSA(&dmudD,dim,xyz_list,gauss,vx_input,vy_input);
 
 		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
 		basalelement->NodalFunctionsP1(basis,gauss);
 
-		/*Build gradient vector (actually -dJ/dB): */
 		for(int i=0;i<numvertices;i++){
-			ge[i]+=-dmudB*thickness*(
+			ge[i]+=-dmudD*thickness*(
 						(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
 						)*Jdet*gauss->weight*basis[i];
@@ -1446,97 +2280,5 @@
 	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
 }/*}}}*/
-void AdjointHorizAnalysis::GradientJBbarHO(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*WARNING: We use SSA as an estimate for now*/
-	this->GradientJBbarSSA(element,gradient,control_index);
-}/*}}}*/
-void AdjointHorizAnalysis::GradientJBbarFS(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-	/*WARNING: We use SSA as an estimate for now*/
-	this->GradientJBbarSSA(element,gradient,control_index);
-}/*}}}*/
-void AdjointHorizAnalysis::GradientJDSSA(Element* element,Vector<IssmDouble>* gradient,int control_index){/*{{{*/
-
-	/*Intermediaries*/
-	int      domaintype,dim;
-	Element* basalelement;
-
-	/*Get basal element*/
-	element->FindParam(&domaintype,DomainTypeEnum);
-	switch(domaintype){
-		case Domain2DhorizontalEnum:
-			basalelement = element;
-			dim          = 2;
-			break;
-		case Domain2DverticalEnum:
-			if(!element->IsOnBase()) return;
-			basalelement = element->SpawnBasalElement();
-			dim          = 1;
-			break;
-		case Domain3DEnum:
-			if(!element->IsOnBase()) return;
-			basalelement = element->SpawnBasalElement();
-			dim          = 2;
-			break;
-		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
-	}
-
-	/*Intermediaries*/
-	IssmDouble Jdet,weight;
-	IssmDouble thickness,dmudD;
-	IssmDouble dvx[3],dvy[3],dadjx[3],dadjy[3]; 
-	IssmDouble *xyz_list= NULL;
-
-	/*Fetch number of vertices for this finite element*/
-	int numvertices = basalelement->GetNumberOfVertices();
-
-	/*Initialize some vectors*/
-	IssmDouble* basis         = xNew<IssmDouble>(numvertices);
-	IssmDouble* ge            = xNewZeroInit<IssmDouble>(numvertices);
-	int*        vertexpidlist = xNew<int>(numvertices);
-
-	/*Retrieve all inputs we will be needing: */
-	basalelement->GetVerticesCoordinates(&xyz_list);
-	basalelement->GradientIndexing(&vertexpidlist[0],control_index);
-	Input* thickness_input = basalelement->GetInput(ThicknessEnum);             _assert_(thickness_input);
-	Input* vx_input        = basalelement->GetInput(VxEnum);                    _assert_(vx_input);
-	Input* vy_input        = basalelement->GetInput(VyEnum);                    _assert_(vy_input);
-	Input* adjointx_input  = basalelement->GetInput(AdjointxEnum);              _assert_(adjointx_input);
-	Input* adjointy_input  = basalelement->GetInput(AdjointyEnum);              _assert_(adjointy_input);
-	Input* rheologyb_input = basalelement->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=basalelement->NewGauss(4);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		thickness_input->GetInputValue(&thickness,gauss);
-		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
-		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
-		adjointx_input->GetInputDerivativeValue(&dadjx[0],xyz_list,gauss);
-		adjointy_input->GetInputDerivativeValue(&dadjy[0],xyz_list,gauss);
-
-		basalelement->dViscositydDSSA(&dmudD,dim,xyz_list,gauss,vx_input,vy_input);
-
-		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		basalelement->NodalFunctionsP1(basis,gauss);
-
-		for(int i=0;i<numvertices;i++){
-			ge[i]+=-dmudD*thickness*(
-						(2*dvx[0]+dvy[1])*2*dadjx[0]+(dvx[1]+dvy[0])*(dadjx[1]+dadjy[0])+(2*dvy[1]+dvx[0])*2*dadjy[1]
-						)*Jdet*gauss->weight*basis[i];
-			_assert_(!xIsNan<IssmDouble>(ge[i]));
-		}
-	}
-	gradient->SetValues(numvertices,vertexpidlist,ge,ADD_VAL);
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(basis);
-	xDelete<IssmDouble>(ge);
-	xDelete<int>(vertexpidlist);
-	delete gauss;
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
-}/*}}}*/
-void AdjointHorizAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           AdjointHorizAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	int approximation;
 	element->GetInputValue(&approximation,ApproximationEnum);
@@ -1548,51 +2290,25 @@
 	}
 }/*}}}*/
-void AdjointHorizAnalysis::InputUpdateFromSolutionHoriz(IssmDouble* solution,Element* element){/*{{{*/
-	int  i;
-	int* doflist=NULL;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-	int numdof   = numnodes*2;
-
-	/*Fetch dof list and allocate solution vectors*/
-	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	IssmDouble* values  = xNew<IssmDouble>(numdof);
-	IssmDouble* lambdax = xNew<IssmDouble>(numnodes);
-	IssmDouble* lambday = xNew<IssmDouble>(numnodes);
-
-	/*Use the dof list to index into the solution vector: */
-	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
-
-	/*Transform solution in Cartesian Space*/
-	element->TransformSolutionCoord(&values[0],XYEnum);
-
-	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
-	for(i=0;i<numnodes;i++){
-		lambdax[i]=values[i*NDOF2+0];
-		lambday[i]=values[i*NDOF2+1];
-
-		/*Check solution*/
-		if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
-	}
-
-	/*Add vx and vy as inputs to the tria element: */
-	element->AddInput(AdjointxEnum,lambdax,element->GetElementType());
-	element->AddInput(AdjointyEnum,lambday,element->GetElementType());
-
-	/*Free ressources:*/
-	xDelete<IssmDouble>(values);
-	xDelete<IssmDouble>(lambdax);
-	xDelete<IssmDouble>(lambday);
-	xDelete<int>(doflist);
-}/*}}}*/
-void AdjointHorizAnalysis::InputUpdateFromSolutionFS(IssmDouble* solution,Element* element){/*{{{*/
-	int          i,dim;
+void           AdjointHorizAnalysis::InputUpdateFromSolutionFS(IssmDouble* solution,Element* element){/*{{{*/
+	int          i,fe_FS;
 	int*         vdoflist=NULL;
 	int*         pdoflist=NULL;
 	IssmDouble   FSreconditioning;
 
-	element->FindParam(&dim,DomainDimensionEnum);
+	int      domaintype,dim;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			dim          = 3;
+			break;
+		case Domain2DverticalEnum:
+			dim          = 2;
+			break;
+		case Domain3DEnum:
+			dim          = 3;
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -1627,7 +2343,9 @@
 	/*fill in all arrays: */
 	for(i=0;i<vnumnodes;i++){
-		lambdax[i] = values[i*NDOF3+0]; if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
-		lambday[i] = values[i*NDOF3+1]; if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
-		lambdaz[i] = values[i*NDOF3+2]; if(xIsNan<IssmDouble>(lambdaz[i])) _error_("NaN found in solution vector");
+		lambdax[i] = values[i*dim+0]; if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
+		lambday[i] = values[i*dim+1]; if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
+		if(dim==3){
+			lambdaz[i] = values[i*dim+2]; if(xIsNan<IssmDouble>(lambdaz[i])) _error_("NaN found in solution vector");
+		}
 	}
 	for(i=0;i<pnumnodes;i++){
@@ -1642,6 +2360,9 @@
 	element->AddInput(AdjointxEnum,lambdax,element->VelocityInterpolation());
 	element->AddInput(AdjointyEnum,lambday,element->VelocityInterpolation());
-	element->AddInput(AdjointzEnum,lambdaz,element->VelocityInterpolation());
-	element->AddInput(AdjointpEnum,lambdap,element->PressureInterpolation());
+	if(domaintype!=Domain2DverticalEnum) element->AddInput(AdjointzEnum,lambdaz,element->VelocityInterpolation());
+
+	element->FindParam(&fe_FS,FlowequationFeFSEnum);
+	if(fe_FS!=LATaylorHoodEnum && fe_FS!=LACrouzeixRaviartEnum)	
+	 element->AddInput(AdjointpEnum,lambdap,element->PressureInterpolation());	
 
 	/*Free ressources:*/
@@ -1655,5 +2376,51 @@
 	xDelete<IssmDouble>(values);
 }/*}}}*/
-void AdjointHorizAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           AdjointHorizAnalysis::InputUpdateFromSolutionHoriz(IssmDouble* solution,Element* element){/*{{{*/
+	int  i;
+	int* doflist=NULL;
+
+	int    domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int numdof;
+	if(domaintype!=Domain2DverticalEnum)  numdof   = numnodes*2;
+	else			                          numdof   = numnodes*1;
+	/*Fetch dof list and allocate solution vectors*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values  = xNew<IssmDouble>(numdof);
+	IssmDouble* lambdax = xNew<IssmDouble>(numnodes);
+	IssmDouble* lambday = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	if(domaintype!=Domain2DverticalEnum)	element->TransformSolutionCoord(&values[0],XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<numnodes;i++){
+		if(domaintype!=Domain2DverticalEnum){
+			lambdax[i]=values[i*NDOF2+0];
+			lambday[i]=values[i*NDOF2+1];
+		}
+		else {lambdax[i]=values[i];lambday[i]=0;}
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
+		if(domaintype!=Domain2DverticalEnum && xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	element->AddInput(AdjointxEnum,lambdax,element->GetElementType());
+	element->AddInput(AdjointyEnum,lambday,element->GetElementType());
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(lambdax);
+	xDelete<IssmDouble>(lambday);
+	xDelete<int>(doflist);
+}/*}}}*/
+void           AdjointHorizAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/AdjointHorizAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/AdjointHorizAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/AdjointHorizAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -25,26 +25,38 @@
 		ElementMatrix* CreateJacobianMatrix(Element* element);
 		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixFS(Element* element);
+		ElementMatrix* CreateKMatrixHO(Element* element);
+		ElementMatrix* CreateKMatrixL1L2(Element* element);
 		ElementMatrix* CreateKMatrixSSA(Element* element);
-		ElementMatrix* CreateKMatrixHO(Element* element);
-		ElementMatrix* CreateKMatrixFS(Element* element);
 		ElementVector* CreatePVector(Element* element);
+		ElementVector* CreatePVectorFS(Element* element);
+		ElementVector* CreatePVectorL1L2(Element* element);
+		ElementVector* CreatePVectorHO(Element* element);
 		ElementVector* CreatePVectorSSA(Element* element);
-		ElementVector* CreatePVectorHO(Element* element);
-		ElementVector* CreatePVectorFS(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void GradientJDragGradient(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void GradientJBGradient(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void GradientJDragSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void GradientJDragHO(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void GradientJDragFS(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void GradientJBbarSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void GradientJBbarHO(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void GradientJBbarFS(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void GradientJDSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
-		void InputUpdateFromSolutionHoriz(IssmDouble* solution,Element* element);
-		void InputUpdateFromSolutionFS(IssmDouble* solution,Element* element);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           GradientJBbarFS(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJBbarGradient(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJBbarL1L2(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJBbarHO(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJBbarSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJBFS(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJBGradient(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJBHO(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJBSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJDragFS(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJDragGradient(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJDragL1L2(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJDragHO(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJDragSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJDragHydroFS(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJDragHydroL1L2(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJDragHydroHO(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJDragHydroSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           GradientJDSSA(Element* element,Vector<IssmDouble>* gradient,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           InputUpdateFromSolutionFS(IssmDouble* solution,Element* element);
+		void           InputUpdateFromSolutionHoriz(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/Analysis.h
===================================================================
--- /issm/trunk/src/c/analyses/Analysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/Analysis.h	(revision 19105)
@@ -26,10 +26,10 @@
 
 		/*Model processing*/
-		virtual int  DofsPerNode(int** doflist,int domaintype,int approximation)=0;
-		virtual void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum)=0;
-		virtual void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type)=0;
-		virtual void CreateNodes(Nodes* nodes,IoModel* iomodel)=0;
 		virtual void CreateConstraints(Constraints* constraints,IoModel* iomodel)=0;
 		virtual void CreateLoads(Loads* loads, IoModel* iomodel)=0;
+		virtual void CreateNodes(Nodes* nodes,IoModel* iomodel)=0;
+		virtual int  DofsPerNode(int** doflist,int domaintype,int approximation)=0;
+		virtual void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type)=0;
+		virtual void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum)=0;
 
 		/*Finite element Analysis*/
@@ -39,8 +39,8 @@
 		virtual ElementMatrix* CreateKMatrix(Element* element)=0;
 		virtual ElementVector* CreatePVector(Element* element)=0;
-		virtual void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element)=0;
-		virtual void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index)=0;
-		virtual void InputUpdateFromSolution(IssmDouble* solution,Element* element)=0;
-		virtual void UpdateConstraints(FemModel* femmodel)=0;
+		virtual void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element)=0;
+		virtual void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index)=0;
+		virtual void           InputUpdateFromSolution(IssmDouble* solution,Element* element)=0;
+		virtual void           UpdateConstraints(FemModel* femmodel)=0;
 };
 #endif
Index: /issm/trunk/src/c/analyses/Balancethickness2Analysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/Balancethickness2Analysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/Balancethickness2Analysis.cpp	(revision 19105)
@@ -6,13 +6,36 @@
 
 /*Model processing*/
+void Balancethickness2Analysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+
+	int finiteelement = P1Enum;
+	IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,Balancethickness2AnalysisEnum,finiteelement);
+
+}/*}}}*/
+void Balancethickness2Analysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+}/*}}}*/
+void Balancethickness2Analysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int finiteelement = P1Enum;
+	::CreateNodes(nodes,iomodel,Balancethickness2AnalysisEnum,finiteelement);
+}/*}}}*/
 int  Balancethickness2Analysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
 }/*}}}*/
-void Balancethickness2Analysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-}/*}}}*/
 void Balancethickness2Analysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
 
 	/*Finite element type*/
 	int finiteelement = P1Enum;
+
+	/*Load variables in element*/
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessThickeningRateEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessOmegaEnum);
 
 	/*Update elements: */
@@ -22,31 +45,11 @@
 			Element* element=(Element*)elements->GetObjectByOffset(counter);
 			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+
 			counter++;
 		}
 	}
 
-	iomodel->FetchDataToInput(elements,BalancethicknessApparentMassbalanceEnum);
-	iomodel->FetchDataToInput(elements,BalancethicknessNuxEnum);
-	iomodel->FetchDataToInput(elements,BalancethicknessNuyEnum);
-	iomodel->FetchDataToInput(elements,BalancethicknessVxObsEnum);
-	iomodel->FetchDataToInput(elements,BalancethicknessVyObsEnum);
-	iomodel->FetchDataToInput(elements,BalancethicknessThicknessObsEnum);
-	iomodel->FetchDataToInput(elements,MeshVertexonboundaryEnum);
-	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
-}/*}}}*/
-void Balancethickness2Analysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	int finiteelement = P1Enum;
-	::CreateNodes(nodes,iomodel,Balancethickness2AnalysisEnum,finiteelement);
-}/*}}}*/
-void Balancethickness2Analysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-
-
-	int finiteelement = P1Enum;
-	IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcpotentialEnum,Balancethickness2AnalysisEnum,finiteelement);
-
-}/*}}}*/
-void Balancethickness2Analysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
+}/*}}}*/
+void Balancethickness2Analysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 
@@ -59,4 +62,68 @@
 	return NULL;
 }/*}}}*/
+void           Balancethickness2Analysis::CreateD0(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble       Gamma,h,mu0,ds[2],Cmu,B,k,s,b,normds;
+	const int        n = 3;
+	const IssmDouble Hstar = 500.;
+	const IssmDouble Lstar = 500.e+3;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of vertices and allocate output*/
+	int  numnodes = element->GetNumberOfNodes();
+	IssmDouble* D0     = xNew<IssmDouble>(numnodes);
+
+	/*retrieve what we need: */
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* surfaceslopex_input = element->GetInput(SurfaceSlopeXEnum);
+	Input* surfaceslopey_input = element->GetInput(SurfaceSlopeYEnum);
+	Input* surface_input       = element->GetInput(SurfaceEnum);            _assert_(surface_input);
+	Input* B_input             = element->GetInput(MaterialsRheologyBEnum); _assert_(B_input);
+	IssmDouble rhog            = element->GetMaterialParameter(MaterialsRhoIceEnum)*element->GetMaterialParameter(ConstantsGEnum);
+
+	/*Calculate damage evolution source term: */
+	Gauss* gauss=element->NewGauss();
+	for (int i=0;i<numnodes;i++){
+		gauss->GaussNode(element->GetElementType(),i);
+		
+		B_input->GetInputValue(&B,gauss);
+		if(surfaceslopex_input && surfaceslopey_input){
+			surfaceslopex_input->GetInputValue(&ds[0],gauss);
+			surfaceslopey_input->GetInputValue(&ds[1],gauss);
+		}
+		else{
+			surface_input->GetInputDerivativeValue(&ds[0],xyz_list,gauss);
+		}
+
+		/*check slopes*/
+		normds = sqrt(ds[0]*ds[0]+ds[1]*ds[1]);
+		if (normds==0.){
+			_error_("surface slope is zero");
+		}
+		if(normds<1.e-5){
+			ds[0] = ds[0]/normds*1.e+5;
+			ds[1] = ds[1]/normds*1.e+5;
+			normds = 1.e-5;
+		}
+
+		mu0   = pow(2.,(1-3*n)/(2.*n)) * B;
+		Gamma = pow(rhog,n) * pow(Hstar,2*(n+1)) * pow(Hstar/Lstar,2*(n+1)) * 1./pow(mu0,n);
+
+		D0[i] = Gamma*pow(ds[0]*ds[0]+ds[1]*ds[1],(n-1)/2)/(n+2);
+	}
+
+	/*Add input*/
+	element->AddInput(BalancethicknessD0Enum,D0,element->GetElementType());
+	//if(surfaceslopex_input && surfaceslopey_input){
+	//	element->DeleteInput(SurfaceSlopeXEnum);
+	//	element->DeleteInput(SurfaceSlopeYEnum);
+	//}
+	
+	/*Clean up and return*/
+	xDelete<IssmDouble>(D0);
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+}/*}}}*/
 ElementMatrix* Balancethickness2Analysis::CreateJacobianMatrix(Element* element){/*{{{*/
 _error_("Not implemented");
@@ -65,5 +132,5 @@
 
 	/*Intermediaries */
-	IssmDouble Jdet,D_scalar;
+	IssmDouble  Jdet,D0,omega;
 	IssmDouble* xyz_list = NULL;
 
@@ -77,4 +144,10 @@
 	/*Retrieve all inputs and parameters*/
 	element->GetVerticesCoordinates(&xyz_list);
+	Input* omega_input = element->GetInput(BalancethicknessOmegaEnum); _assert_(omega_input);
+	Input* D0_input    = element->GetInput(BalancethicknessD0Enum);
+	if(!D0_input){
+		this->CreateD0(element);
+		D0_input = element->GetInput(BalancethicknessD0Enum); _assert_(D0_input);
+	}
 
 	/* Start  looping on the number of gaussian points: */
@@ -84,8 +157,10 @@
 		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		D0_input->GetInputValue(&D0,gauss);
+		omega_input->GetInputValue(&omega,gauss);
 
 		for(int i=0;i<numnodes;i++){
 			for(int j=0;j<numnodes;j++){
-				Ke->values[i*numnodes+j] += gauss->weight*Jdet*(dbasis[0*numnodes+i]*dbasis[0*numnodes+j] + dbasis[1*numnodes+i]*dbasis[1*numnodes+j]);
+				Ke->values[i*numnodes+j] += D0*exp(omega)*gauss->weight*Jdet*(dbasis[0*numnodes+i]*dbasis[0*numnodes+j] + dbasis[1*numnodes+i]*dbasis[1*numnodes+j]);
 			}
 		}
@@ -100,18 +175,6 @@
 ElementVector* Balancethickness2Analysis::CreatePVector(Element* element){/*{{{*/
 
-	/*compute all load vectors for this element*/
-	ElementVector* pe1=CreatePVectorVolume(element);
-	ElementVector* pe2=CreatePVectorBoundary(element);
-	ElementVector* pe =new ElementVector(pe1,pe2);
-
-	/*clean-up and return*/
-	delete pe1;
-	delete pe2;
-	return pe;
-}/*}}}*/
-ElementVector* Balancethickness2Analysis::CreatePVectorVolume(Element* element){/*{{{*/
-
 	/*Intermediaries */
-	IssmDouble  adot,Jdet;
+	IssmDouble  dhdt,mb,ms,Jdet;
 	IssmDouble* xyz_list = NULL;
 
@@ -125,5 +188,7 @@
 	/*Retrieve all inputs and parameters*/
 	element->GetVerticesCoordinates(&xyz_list);
-	Input* adot_input   = element->GetInput(BalancethicknessApparentMassbalanceEnum); _assert_(adot_input);
+	Input* ms_input   = element->GetInput(SurfaceforcingsMassBalanceEnum);                _assert_(ms_input);
+	Input* mb_input   = element->GetInput(BasalforcingsGroundediceMeltingRateEnum);       _assert_(mb_input);
+	Input* dhdt_input = element->GetInput(BalancethicknessThickeningRateEnum);            _assert_(dhdt_input);
 
 	/* Start  looping on the number of gaussian points: */
@@ -134,7 +199,12 @@
 		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
 		element->NodalFunctions(basis,gauss);
-		adot_input->GetInputValue(&adot,gauss);
-
-		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*adot*basis[i];
+
+		ms_input->GetInputValue(&ms,gauss);
+		mb_input->GetInputValue(&mb,gauss);
+		dhdt_input->GetInputValue(&dhdt,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(
+					(ms-mb-dhdt)*basis[i]
+					);
 	}
 
@@ -145,132 +215,65 @@
 	return pe;
 }/*}}}*/
-ElementVector* Balancethickness2Analysis::CreatePVectorBoundary(Element* element){/*{{{*/
-
-	/*If no front, return NULL*/
-	if(!element->IsFaceOnBoundary()) return NULL;
+void           Balancethickness2Analysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+		element->GetSolutionFromInputsOneDof(solution,SurfaceEnum);
+}/*}}}*/
+void           Balancethickness2Analysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void           Balancethickness2Analysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	/*Intermediaries*/
-	IssmDouble  Jdet,thickness,vx,vy;
-	IssmDouble *xyz_list = NULL;
-	IssmDouble *xyz_list_front = NULL;
-	IssmDouble  normal[2];
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Initialize Element vector and other vectors*/
-	ElementVector* pe    = element->NewElementVector();
-	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+	IssmDouble  ds[2],s,b,D;
+	IssmDouble* xyz_list = NULL;
+
+	//element->InputUpdateFromSolutionOneDof(solution,ThicknessEnum);
+	element->InputUpdateFromSolutionOneDof(solution,SurfaceEnum);
+
+	/*Fetch number of vertices and allocate velocity vectors*/
+	int numvertices = element->GetNumberOfVertices();
+	IssmDouble* vel_list = xNew<IssmDouble>(numvertices);
+	IssmDouble* vx_list  = xNew<IssmDouble>(numvertices);
+	IssmDouble* vy_list  = xNew<IssmDouble>(numvertices);
 
 	/*Retrieve all inputs and parameters*/
-	Input* thickness_input = element->GetInput(BalancethicknessThicknessObsEnum); _assert_(thickness_input);
-	Input* vx_input        = element->GetInput(BalancethicknessVxObsEnum);        _assert_(vx_input);
-	Input* vy_input        = element->GetInput(BalancethicknessVyObsEnum);        _assert_(vy_input);
-
-	element->GetVerticesCoordinates(&xyz_list);
-	element->GetIcefrontCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
-	element->NormalSection(&normal[0],xyz_list_front);
-
-	/*Start looping on Gaussian points*/
-	Gauss* gauss=element->NewGauss(xyz_list,xyz_list_front,3);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-		thickness_input->GetInputValue(&thickness,gauss);
-		vx_input->GetInputValue(&vx,gauss);
-		vy_input->GetInputValue(&vy,gauss);
-		element->JacobianDeterminantSurface(&Jdet,xyz_list_front,gauss);
-		element->NodalFunctions(basis,gauss);
-
-		for(int i=0;i<numnodes;i++) pe->values[i] += Jdet*gauss->weight*thickness*(vx*normal[0] + vy*normal[1])*basis[i];
-	}
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(xyz_list_front);
-	xDelete<IssmDouble>(basis);
-	delete gauss;
-	return pe;
-}/*}}}*/
-void Balancethickness2Analysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void Balancethickness2Analysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
-	_error_("Not implemented yet");
-}/*}}}*/
-void Balancethickness2Analysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
-
-	/*Intermediaries */
-	int         Hinterpolation;
-	IssmDouble  vx,vy,vbar,nux,nuy,normdphi,dphi[2];
-	IssmDouble* xyz_list = NULL;
-	int       * doflist  = NULL;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes    = element->GetNumberOfNodes();
-	int numvertices = element->GetNumberOfVertices();
-
-	/*Fetch dof list and allocate solution vector*/
-	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	IssmDouble* values         = xNew<IssmDouble>(numnodes);
-	IssmDouble* thickness_list = xNew<IssmDouble>(numvertices);
-	IssmDouble* vx_list        = xNew<IssmDouble>(numvertices);
-	IssmDouble* vy_list        = xNew<IssmDouble>(numvertices);
-
-	/*Use the dof list to index into the solution vector: */
-	for(int i=0;i<numnodes;i++){
-		values[i]=solution[doflist[i]];
-
-		/*Check solution*/
-		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
-	}
-
-	element->AddInput(PotentialEnum,values,element->GetElementType());
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	Input* potential_input = element->GetInput(PotentialEnum);             _assert_(potential_input);
-	Input* vx_input        = element->GetInput(BalancethicknessVxObsEnum); _assert_(vx_input);
-	Input* vy_input        = element->GetInput(BalancethicknessVyObsEnum); _assert_(vy_input);
-	Input* nux_input       = element->GetInput(BalancethicknessNuxEnum);   _assert_(nux_input);
-	Input* nuy_input       = element->GetInput(BalancethicknessNuyEnum);   _assert_(nuy_input);
-
-	switch(element->GetElementType()){
-		case P1Enum: Hinterpolation = P0Enum; break;
-		default:     _error_("not implemented");
-	}
-
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* D_input   = element->GetInput(BalancethicknessDiffusionCoefficientEnum);
+	Input* H_input   = element->GetInput(ThicknessEnum);                            _assert_(H_input);
+	Input* s_input   = element->GetInput(SurfaceEnum);                              _assert_(s_input);
+	Input* b_input   = element->GetInput(BaseEnum);                                 _assert_(b_input);
+
+	/*Calculate velocities*/
 	Gauss* gauss=element->NewGauss();
-	for (int iv=0;iv<1;iv++){
-		gauss->GaussNode(Hinterpolation,iv);//P0 Only for now
-
-		vx_input->GetInputValue(&vx,gauss);
-		vy_input->GetInputValue(&vy,gauss);
-		nux_input->GetInputValue(&nux,gauss);
-		nuy_input->GetInputValue(&nuy,gauss);
-		potential_input->GetInputDerivativeValue(&dphi[0],xyz_list,gauss);
-
-		vx = vx*nux; vy = vy*nuy;
-		vbar = sqrt(vx*vx + vy*vy) + 1.e-10;
-		normdphi = sqrt(dphi[0]*dphi[0] + dphi[1]*dphi[1]);
-
-		thickness_list[iv] = normdphi/vbar;
-		vx_list[iv]        = -1./thickness_list[iv] * dphi[0];
-		vy_list[iv]        = -1./thickness_list[iv] * dphi[1];
-	}
-	element->AddInput(ThicknessEnum,thickness_list,Hinterpolation);
-	element->AddInput(VxEnum,vx_list,Hinterpolation);
-	element->AddInput(VyEnum,vy_list,Hinterpolation);
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<int>(doflist);
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(values);
-	xDelete<IssmDouble>(thickness_list);
+	for(int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+
+		if(D_input){
+			D_input->GetInputValue(&D,gauss);
+		}
+		else{
+			D = 0.;
+		}
+		b_input->GetInputValue(&b,gauss);
+		s_input->GetInputValue(&s,gauss);
+		s_input->GetInputDerivativeValue(&ds[0],xyz_list,gauss);
+
+		vx_list[iv] = -1./(s-b)*D*ds[0];
+		vy_list[iv] = -1./(s-b)*D*ds[1];
+		vel_list[iv] = sqrt(pow(vx_list[iv],2) + pow(vy_list[iv],2));
+	}
+
+	/*Add vx and vy as inputs to the tria element: */
+	element->AddInput(VxEnum,vx_list,P1Enum);
+	element->AddInput(VyEnum,vy_list,P1Enum);
+	element->AddInput(VelEnum,vel_list,P1Enum);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<IssmDouble>(vy_list);
 	xDelete<IssmDouble>(vx_list);
-	xDelete<IssmDouble>(vy_list);
-}/*}}}*/
-void Balancethickness2Analysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	xDelete<IssmDouble>(vel_list);
+	xDelete<IssmDouble>(xyz_list);
+}/*}}}*/
+void           Balancethickness2Analysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/Balancethickness2Analysis.h
===================================================================
--- /issm/trunk/src/c/analyses/Balancethickness2Analysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/Balancethickness2Analysis.h	(revision 19105)
@@ -13,23 +13,22 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,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);
 		ElementVector* CreateDVector(Element* element);
+		void           CreateD0(Element* element);
 		ElementMatrix* CreateJacobianMatrix(Element* element);
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		ElementVector* CreatePVectorVolume(Element* element);
-		ElementVector* CreatePVectorBoundary(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/BalancethicknessAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/BalancethicknessAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/BalancethicknessAnalysis.cpp	(revision 19105)
@@ -6,9 +6,69 @@
 
 /*Model processing*/
+void BalancethicknessAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int    stabilization;	
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Do not add constraints in DG*/
+	if(stabilization!=3){
+		IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancethicknessAnalysisEnum,P1Enum);
+	}
+
+}/*}}}*/
+void BalancethicknessAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int element;
+	int stabilization;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Loads only in DG*/
+	if (stabilization==3){
+
+		/*Get faces and elements*/
+		CreateFaces(iomodel);
+		iomodel->FetchData(1,ThicknessEnum);
+
+		/*First load data:*/
+		for(int i=0;i<iomodel->numberoffaces;i++){
+
+			/*Get left and right elements*/
+			element=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
+
+			/*Now, if this element is not in the partition, pass: */
+			if(!iomodel->my_elements[element]) continue;
+
+			/* Add load */
+			loads->AddObject(new Numericalflux(iomodel->loadcounter+i+1,i,i,iomodel,BalancethicknessAnalysisEnum));
+		}
+
+		/*Free data: */
+		iomodel->DeleteData(1,ThicknessEnum);
+	}
+}/*}}}*/
+void BalancethicknessAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int  stabilization;
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Check in 3d*/
+	if(stabilization==3 && iomodel->domaintype==Domain3DEnum) _error_("DG 3d not implemented yet");
+
+	/*First fetch data: */
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	if(stabilization!=3){
+		::CreateNodes(nodes,iomodel,BalancethicknessAnalysisEnum,P1Enum);
+	}
+	else{
+		::CreateNodes(nodes,iomodel,BalancethicknessAnalysisEnum,P1DGEnum);
+	}
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
 int  BalancethicknessAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void BalancethicknessAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-	parameters->AddObject(iomodel->CopyConstantObject(BalancethicknessStabilizationEnum));
 }/*}}}*/
 void BalancethicknessAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -50,66 +110,6 @@
 	}
 }/*}}}*/
-void BalancethicknessAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	int  stabilization;
-	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
-
-	/*Check in 3d*/
-	if(stabilization==3 && iomodel->domaintype==Domain3DEnum) _error_("DG 3d not implemented yet");
-
-	/*First fetch data: */
-	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	if(stabilization!=3){
-		::CreateNodes(nodes,iomodel,BalancethicknessAnalysisEnum,P1Enum);
-	}
-	else{
-		::CreateNodes(nodes,iomodel,BalancethicknessAnalysisEnum,P1DGEnum);
-	}
-	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-}/*}}}*/
-void BalancethicknessAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-
-	/*Fetch parameters: */
-	int    stabilization;	
-	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
-
-	/*Do not add constraints in DG*/
-	if(stabilization!=3){
-		IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancethicknessAnalysisEnum,P1Enum);
-	}
-
-}/*}}}*/
-void BalancethicknessAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
-	/*Intermediary*/
-	int element;
-	int stabilization;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
-
-	/*Loads only in DG*/
-	if (stabilization==3){
-
-		/*Get faces and elements*/
-		CreateFaces(iomodel);
-		iomodel->FetchData(1,ThicknessEnum);
-
-		/*First load data:*/
-		for(int i=0;i<iomodel->numberoffaces;i++){
-
-			/*Get left and right elements*/
-			element=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
-
-			/*Now, if this element is not in the partition, pass: */
-			if(!iomodel->my_elements[element]) continue;
-
-			/* Add load */
-			loads->AddObject(new Numericalflux(iomodel->loadcounter+i+1,i,i,iomodel,BalancethicknessAnalysisEnum));
-		}
-
-		/*Free data: */
-		iomodel->DeleteData(1,ThicknessEnum);
-	}
+void BalancethicknessAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	parameters->AddObject(iomodel->CopyConstantObject(BalancethicknessStabilizationEnum));
 }/*}}}*/
 
@@ -421,5 +421,5 @@
 	return pe;
 }/*}}}*/
-void BalancethicknessAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           BalancethicknessAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
 	 * For node i, Bi can be expressed in the actual coordinate system
@@ -448,5 +448,5 @@
 	xDelete<IssmDouble>(basis);
 }/*}}}*/
-void BalancethicknessAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           BalancethicknessAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
 	 * For node i, Bi' can be expressed in the actual coordinate system
@@ -476,8 +476,8 @@
 
 }/*}}}*/
-void BalancethicknessAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           BalancethicknessAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void BalancethicknessAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           BalancethicknessAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	/* WARNING: this gradient is valid for Soft balance thickness only */
 
@@ -595,5 +595,5 @@
 
 }/*}}}*/
-void BalancethicknessAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           BalancethicknessAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int domaintype;
@@ -609,5 +609,5 @@
 	}
 }/*}}}*/
-void BalancethicknessAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           BalancethicknessAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/BalancethicknessAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/BalancethicknessAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/BalancethicknessAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -30,10 +30,10 @@
 		ElementVector* CreatePVectorCG(Element* element);
 		ElementVector* CreatePVectorDG(Element* element);
-		void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/BalancevelocityAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/BalancevelocityAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/BalancevelocityAnalysis.cpp	(revision 19105)
@@ -6,8 +6,23 @@
 
 /*Model processing*/
+void BalancevelocityAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*No constraints for now*/
+	//IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancevelocityAnalysisEnum,P1Enum);
+}/*}}}*/
+void BalancevelocityAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+}/*}}}*/
+void BalancevelocityAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Check in 3d*/
+	if(iomodel->domaintype==Domain3DEnum) _error_("DG 3d not implemented yet");
+
+	/*First fetch data: */
+	::CreateNodes(nodes,iomodel,BalancevelocityAnalysisEnum,P1Enum);
+}/*}}}*/
 int  BalancevelocityAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void BalancevelocityAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 void BalancevelocityAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -38,20 +53,5 @@
 	}
 }/*}}}*/
-void BalancevelocityAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	/*Check in 3d*/
-	if(iomodel->domaintype==Domain3DEnum) _error_("DG 3d not implemented yet");
-
-	/*First fetch data: */
-	::CreateNodes(nodes,iomodel,BalancevelocityAnalysisEnum,P1Enum);
-}/*}}}*/
-void BalancevelocityAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-
-	/*No constraints for now*/
-	//IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancevelocityAnalysisEnum,P1Enum);
-}/*}}}*/
-void BalancevelocityAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
-	/*No loads*/
+void BalancevelocityAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 
@@ -95,6 +95,6 @@
 
 	/*Get vector N for all nodes and build HNx and HNy*/
-	element->GetInputListOnNodes(Nx,SurfaceSlopeXEnum);
-	element->GetInputListOnNodes(Ny,SurfaceSlopeYEnum);
+	element->GetInputListOnNodes(Nx,DrivingStressXEnum);
+	element->GetInputListOnNodes(Ny,DrivingStressYEnum);
 	element->GetInputListOnNodes(H,ThicknessEnum);
 	for(int i=0;i<numnodes;i++){
@@ -190,6 +190,6 @@
 
 	/*Get vector N for all nodes*/
-	basalelement->GetInputListOnNodes(Nx,SurfaceSlopeXEnum);
-	basalelement->GetInputListOnNodes(Ny,SurfaceSlopeYEnum);
+	basalelement->GetInputListOnNodes(Nx,DrivingStressXEnum);
+	basalelement->GetInputListOnNodes(Ny,DrivingStressYEnum);
 	basalelement->GetInputListOnNodes(H,ThicknessEnum);
 	for(int i=0;i<numnodes;i++){
@@ -238,11 +238,11 @@
 	return pe;
 }/*}}}*/
-void BalancevelocityAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           BalancevelocityAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void BalancevelocityAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           BalancevelocityAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void BalancevelocityAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           BalancevelocityAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int domaintype;
@@ -258,5 +258,5 @@
 	}
 }/*}}}*/
-void BalancevelocityAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           BalancevelocityAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/BalancevelocityAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/BalancevelocityAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/BalancevelocityAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,8 +26,8 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,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 19104)
+++ /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.cpp	(revision 19105)
@@ -6,6 +6,57 @@
 
 /*Model processing*/
+void DamageEvolutionAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	int finiteelement;
+	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
+
+	IoModelToConstraintsx(constraints,iomodel,DamageSpcdamageEnum,DamageEvolutionAnalysisEnum,finiteelement);
+
+}/*}}}*/
+void DamageEvolutionAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Nothing for now*/
+
+}/*}}}*/
+void DamageEvolutionAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int finiteelement;
+
+	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
+	::CreateNodes(nodes,iomodel,DamageEvolutionAnalysisEnum,finiteelement);
+}/*}}}*/
 int  DamageEvolutionAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
+}/*}}}*/
+void DamageEvolutionAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int finiteelement;
+	bool   islevelset;
+
+	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
+	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
+			counter++;
+		}
+	}
+
+	/*What input do I need to run my damage evolution model?*/
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchDataToInput(elements,VzEnum);
+	iomodel->FetchDataToInput(elements,DamageDEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,PressureEnum);
+
+	if(islevelset){
+		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
+	}
+
 }/*}}}*/
 void DamageEvolutionAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
@@ -45,52 +96,4 @@
 
 }/*}}}*/
-void DamageEvolutionAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-
-	int finiteelement;
-
-	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
-
-	/*Update elements: */
-	int counter=0;
-	for(int i=0;i<iomodel->numberofelements;i++){
-		if(iomodel->my_elements[i]){
-			Element* element=(Element*)elements->GetObjectByOffset(counter);
-			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
-			counter++;
-		}
-	}
-
-	/*What input do I need to run my damage evolution model?*/
-	iomodel->FetchDataToInput(elements,VxEnum);
-	iomodel->FetchDataToInput(elements,VyEnum);
-	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchDataToInput(elements,VzEnum);
-	iomodel->FetchDataToInput(elements,DamageDEnum);
-	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
-	iomodel->FetchDataToInput(elements,PressureEnum);
-
-}/*}}}*/
-void DamageEvolutionAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	int finiteelement;
-
-	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
-
-	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(1,MeshVertexonbaseEnum);
-	::CreateNodes(nodes,iomodel,DamageEvolutionAnalysisEnum,finiteelement);
-	iomodel->DeleteData(1,MeshVertexonbaseEnum);
-}/*}}}*/
-void DamageEvolutionAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-
-	int finiteelement;
-	iomodel->Constant(&finiteelement,DamageElementinterpEnum);
-
-	IoModelToConstraintsx(constraints,iomodel,DamageSpcdamageEnum,DamageEvolutionAnalysisEnum,finiteelement);
-
-}/*}}}*/
-void DamageEvolutionAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
-	/*Nothing for now*/
-
-}/*}}}*/
 
 /*Finite Element Analysis*/
@@ -98,436 +101,5 @@
 	_error_("not implemented");
 }/*}}}*/
-ElementVector* DamageEvolutionAnalysis::CreateDVector(Element* element){/*{{{*/
-	/*Default, return NULL*/
-	return NULL;
-}/*}}}*/
-ElementMatrix* DamageEvolutionAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
-_error_("Not implemented");
-}/*}}}*/
-ElementMatrix* DamageEvolutionAnalysis::CreateKMatrix(Element* element){/*{{{*/
-
-	/* Check if ice in element */
-	if(!element->IsIceInElement()) return NULL;
-
-	/*Intermediaries*/
-	Element*    basalelement;
-	int         domaintype,dim;
-	int         stabilization;
-	IssmDouble  Jdet,dt,D_scalar,h;
-	IssmDouble  vel,vx,vy,dvxdx,dvydy,dvx[2],dvy[2];
-	IssmDouble *xyz_list  = NULL;
-
-	/*Get problem dimension and basal element*/
-	element->FindParam(&domaintype,DomainTypeEnum);
-	switch(domaintype){
-		case Domain2DhorizontalEnum:
-			basalelement = element;
-			dim = 2;
-			break;
-		case Domain3DEnum:
-			if(!element->IsOnBase()) return NULL;
-			basalelement = element->SpawnBasalElement();
-			dim = 2;
-			break;
-		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
-	}
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = basalelement->GetNumberOfNodes();
-
-	/*Initialize Element vector*/
-	ElementMatrix* Ke     = basalelement->NewElementMatrix();
-	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
-	IssmDouble*    B      = xNew<IssmDouble>(dim*numnodes);
-	IssmDouble*    Bprime = xNew<IssmDouble>(dim*numnodes);
-	IssmDouble*    D      = xNewZeroInit<IssmDouble>(dim*dim);
-
-	/*Retrieve all inputs and parameters*/
-	basalelement->GetVerticesCoordinates(&xyz_list);
-	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
-	basalelement->FindParam(&stabilization,DamageStabilizationEnum);
-	Input* vxaverage_input=NULL;
-	Input* vyaverage_input=NULL;
-	if(domaintype==Domain2DhorizontalEnum){
-		vxaverage_input=basalelement->GetInput(VxEnum); _assert_(vxaverage_input);
-		vyaverage_input=basalelement->GetInput(VyEnum); _assert_(vyaverage_input);
-	}
-	else{
-		if(dim==1){
-			vxaverage_input=element->GetInput(VxEnum); _assert_(vxaverage_input);
-		}
-		if(dim==2){
-			vxaverage_input=element->GetInput(VxAverageEnum); _assert_(vxaverage_input);
-			vyaverage_input=element->GetInput(VyAverageEnum); _assert_(vyaverage_input);
-		}
-	}
-	h=basalelement->CharacteristicLength();
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=basalelement->NewGauss(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		basalelement->NodalFunctions(basis,gauss);
-		
-		vxaverage_input->GetInputValue(&vx,gauss);
-		vxaverage_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
-		if(dim==2){
-			vyaverage_input->GetInputValue(&vy,gauss);
-			vyaverage_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
-		}
-
-		D_scalar=gauss->weight*Jdet;
-		TripleMultiply(basis,1,numnodes,1,
-					&D_scalar,1,1,0,
-					basis,1,numnodes,0,
-					&Ke->values[0],1);
-
-		GetB(B,basalelement,dim,xyz_list,gauss);
-		GetBprime(Bprime,basalelement,dim,xyz_list,gauss);
-
-		dvxdx=dvx[0];
-		if(dim==2) dvydy=dvy[1];
-		D_scalar=dt*gauss->weight*Jdet;
-
-		D[0*dim+0]=D_scalar*dvxdx;
-		if(dim==2) D[1*dim+1]=D_scalar*dvydy;
-
-		TripleMultiply(B,dim,numnodes,1,
-					D,dim,dim,0,
-					B,dim,numnodes,0,
-					&Ke->values[0],1);
-
-		D[0*dim+0]=D_scalar*vx;
-		if(dim==2) D[1*dim+1]=D_scalar*vy;
-
-		TripleMultiply(B,dim,numnodes,1,
-					D,dim,dim,0,
-					Bprime,dim,numnodes,0,
-					&Ke->values[0],1);
-
-		if(stabilization==2){
-			if(dim==1){
-				vel=fabs(vx)+1.e-8;
-				D[0]=h/(2.0*vel)*vx*vx;
-			}
-			else{
-				/*Streamline upwinding*/
-				vel=sqrt(vx*vx+vy*vy)+1.e-8;
-				D[0*dim+0]=h/(2.0*vel)*vx*vx;
-				D[1*dim+0]=h/(2.0*vel)*vy*vx;
-				D[0*dim+1]=h/(2.0*vel)*vx*vy;
-				D[1*dim+1]=h/(2.0*vel)*vy*vy;
-			}
-		}
-		else if(stabilization==1){
-			vxaverage_input->GetInputAverage(&vx);
-			if(dim==2) vyaverage_input->GetInputAverage(&vy);
-			D[0*dim+0]=h/2.0*fabs(vx);
-			if(dim==2) D[1*dim+1]=h/2.0*fabs(vy);
-		}
-		if(stabilization==1 || stabilization==2){
-			if(dim==1) D[0]=D_scalar*D[0];
-			else{
-				D[0*dim+0]=D_scalar*D[0*dim+0];
-				D[1*dim+0]=D_scalar*D[1*dim+0];
-				D[0*dim+1]=D_scalar*D[0*dim+1];
-				D[1*dim+1]=D_scalar*D[1*dim+1];
-			}
-
-			TripleMultiply(Bprime,dim,numnodes,1,
-						D,dim,dim,0,
-						Bprime,dim,numnodes,0,
-						&Ke->values[0],1);
-		}
-
-	}
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(basis);
-	xDelete<IssmDouble>(B);
-	xDelete<IssmDouble>(Bprime);
-	xDelete<IssmDouble>(D);
-	delete gauss;
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
-	return Ke;
-}/*}}}*/
-ElementVector* DamageEvolutionAnalysis::CreatePVector(Element* element){/*{{{*/
-
-	/* Check if ice in element */
-	if(!element->IsIceInElement()) return NULL;
-
-	/*Intermediaries*/
-	int      domaintype,damagelaw;
-	Element* basalelement;
-	IssmDouble  Jdet,dt;
-	IssmDouble  f,damage;
-	IssmDouble* xyz_list = NULL;
-
-	/*Get basal element*/
-	element->FindParam(&domaintype,DomainTypeEnum);
-	switch(domaintype){
-		case Domain2DhorizontalEnum:
-			basalelement = element;
-			break;
-		case Domain3DEnum:
-			if(!element->IsOnBase()) return NULL;
-			basalelement = element->SpawnBasalElement();
-			break;
-		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
-	}
-
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = basalelement->GetNumberOfNodes();
-
-	/*Initialize Element vector and other vectors*/
-	ElementVector* pe    = basalelement->NewElementVector();
-	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
-
-	/*Retrieve all inputs and parameters*/
-	basalelement->GetVerticesCoordinates(&xyz_list);
-	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
-	basalelement->FindParam(&damagelaw,DamageLawEnum);
-	if(damagelaw==1 | damagelaw==2){
-		this->CreateDamageFInputPralong(basalelement);
-	}
-	else if(damagelaw==3){
-		this->CreateDamageFInputExp(basalelement);
-	}
-	Input* damaged_input = basalelement->GetInput(DamageDEnum); _assert_(damaged_input);
-	Input* damagef_input = basalelement->GetInput(DamageFEnum); _assert_(damagef_input);
-
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=basalelement->NewGauss(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		basalelement->NodalFunctions(basis,gauss);
-
-		damaged_input->GetInputValue(&damage,gauss);
-		damagef_input->GetInputValue(&f,gauss);
-
-		for(int i=0;i<numnodes;i++){
-			pe->values[i]+=Jdet*gauss->weight*(damage+dt*f)*basis[i];
-		}
-	}
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(basis);
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
-	delete gauss;
-	return pe;
-}/*}}}*/
-void DamageEvolutionAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
-	 * For node i, Bi can be expressed in the actual coordinate system
-	 * by: 
-	 *       Bi=[ N ]
-	 *          [ N ]
-	 * where N is the finiteelement function for node i.
-	 *
-	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions*/
-	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	element->NodalFunctions(basis,gauss);
-
-	/*Build B: */
-	for(int i=0;i<numnodes;i++){
-		for(int j=0;j<dim;j++){
-			B[numnodes*j+i] = basis[i];
-		}
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(basis);
-}/*}}}*/
-void DamageEvolutionAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
-	 * For node i, Bi' can be expressed in the actual coordinate system
-	 * by: 
-	 *       Bi_prime=[ dN/dx ]
-	 *                [ dN/dy ]
-	 * where N is the finiteelement function for node i.
-	 *
-	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
-	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-	/*Build B': */
-	for(int i=0;i<numnodes;i++){
-		for(int j=0;j<dim;j++){
-			Bprime[numnodes*j+i] = dbasis[j*numnodes+i];
-		}
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(dbasis);
-
-}/*}}}*/
-void DamageEvolutionAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void DamageEvolutionAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
-	_error_("Not implemented yet");
-}/*}}}*/
-void DamageEvolutionAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
-
-	int domaintype;
-	IssmDouble  max_damage;
-	int			*doflist = NULL;
-	Element*   basalelement=NULL;
-
-	element->FindParam(&domaintype,DomainTypeEnum);
-	if(domaintype!=Domain2DhorizontalEnum){
-		if(!element->IsOnBase()) return;
-		basalelement=element->SpawnBasalElement();
-	}
-	else{
-		basalelement = element;
-	}
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = basalelement->GetNumberOfNodes();
-
-	/*Fetch dof list and allocate solution vector*/
-	basalelement->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	IssmDouble* newdamage = xNew<IssmDouble>(numnodes);
-
-	/*Get user-supplied max_damage: */
-	basalelement->FindParam(&max_damage,DamageMaxDamageEnum);
-
-	/*Use the dof list to index into the solution vector: */
-	for(int i=0;i<numnodes;i++){
-		newdamage[i]=solution[doflist[i]];
-		/*Check solution*/
-		if(xIsNan<IssmDouble>(newdamage[i])) _error_("NaN found in solution vector");
-		/*Enforce D < max_damage and D > 0 */
-		if(newdamage[i]>max_damage) newdamage[i]=max_damage;
-		else if(newdamage[i]<0.)    newdamage[i]=0.;
-	}
-
-	/*Get all inputs and parameters*/
-	if(domaintype==Domain2DhorizontalEnum){
-		basalelement->AddInput(DamageDbarEnum,newdamage,element->GetElementType());
-	}
-	else{
-		basalelement->AddBasalInput(DamageDEnum,newdamage,element->GetElementType());
-	}
-
-	/*Free ressources:*/
-	xDelete<IssmDouble>(newdamage);
-	xDelete<int>(doflist);
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
-}/*}}}*/
-void DamageEvolutionAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
-	/*Default, do nothing*/
-	return;
-}/*}}}*/
-
-/*Intermediaries*/
-void DamageEvolutionAnalysis::CreateDamageFInputPralong(Element* element){/*{{{*/
-
-	/*Intermediaries */
-	IssmDouble c1,c2,c3,healing,stress_threshold;
-	IssmDouble s_xx,s_xy,s_yy,s1,s2,stmp;
-	IssmDouble J2s,Chi,Psi,PosPsi,NegPsi;
-	IssmDouble damage,tau_xx,tau_xy,tau_yy;
-	int equivstress,domaintype,damagelaw;
-
-	/*Fetch number of vertices and allocate output*/
-	int numnodes = element->GetNumberOfNodes();
-	IssmDouble* f   = xNew<IssmDouble>(numnodes);
-
-	/*retrieve parameters:*/
-	element->FindParam(&c1,DamageC1Enum);
-	element->FindParam(&c2,DamageC2Enum);
-	element->FindParam(&c3,DamageC3Enum);
-	element->FindParam(&healing,DamageHealingEnum);
-	element->FindParam(&stress_threshold,DamageStressThresholdEnum);
-	element->FindParam(&domaintype,DomainTypeEnum);
-	element->FindParam(&damagelaw,DamageLawEnum);
-
-	/*Compute stress tensor: */
-	element->ComputeDeviatoricStressTensor();
-
-	/*retrieve what we need: */
-	Input* tau_xx_input  = element->GetInput(DeviatoricStressxxEnum);     _assert_(tau_xx_input);
-	Input* tau_xy_input  = element->GetInput(DeviatoricStressxyEnum);     _assert_(tau_xy_input);
-	Input* tau_yy_input  = element->GetInput(DeviatoricStressyyEnum);     _assert_(tau_yy_input);
-	Input* damage_input = NULL;
-	if(domaintype==Domain2DhorizontalEnum){
-		damage_input = element->GetInput(DamageDbarEnum); 	_assert_(damage_input);
-	}
-	else{
-		damage_input = element->GetInput(DamageDEnum);   _assert_(damage_input);
-	}
-
-	/*retrieve the desired type of equivalent stress*/
-	element->FindParam(&equivstress,DamageEquivStressEnum);
-
-	/*Calculate damage evolution source term: */
-	Gauss* gauss=element->NewGauss();
-	for (int i=0;i<numnodes;i++){
-		gauss->GaussNode(element->GetElementType(),i);
-		
-		damage_input->GetInputValue(&damage,gauss);
-		tau_xx_input->GetInputValue(&tau_xx,gauss);
-		tau_xy_input->GetInputValue(&tau_xy,gauss);
-		tau_yy_input->GetInputValue(&tau_yy,gauss);
-	
-		/*Calculate effective stress components*/
-		s_xx=tau_xx/(1.-damage);
-		s_xy=tau_xy/(1.-damage);
-		s_yy=tau_yy/(1.-damage);
-
-		/*Calculate principal effective stresses*/
-		s1=(s_xx+s_yy)/2.+sqrt(pow((s_xx-s_yy)/2.,2)+pow(s_xy,2));
-		s2=(s_xx+s_yy)/2.-sqrt(pow((s_xx-s_yy)/2.,2)+pow(s_xy,2));
-		if(fabs(s2)>fabs(s1)){stmp=s2; s2=s1; s1=stmp;}
-
-		if(equivstress==0){ /* von Mises */
-			Chi=sqrt(s1*s1-s1*s2+s2*s2);
-		}
-		else if(equivstress==1){ /* max principal stress */
-			Chi=s1;
-		}
-		Psi=Chi-stress_threshold;
-		NegPsi=max(-Chi,0.); /* healing only for compressive stresses */
-
-		if(damagelaw==1){
-			PosPsi=max(Psi,0.);
-			f[i]= c1*(pow(PosPsi,c2) - healing*pow(NegPsi,c2))*pow((1./(1.-damage)),c3);
-		}
-		else if(damagelaw==2){
-			PosPsi=max(Psi,1.);
-			f[i]= c1*(pow(log10(PosPsi),c2) - healing*pow(NegPsi,c2))*pow((1./(1.-damage)),c3);
-		}
-		else _error_("damage law not supported");
-	}
-
-	/*Add input*/
-	element->AddInput(DamageFEnum,f,element->GetElementType());
-	
-	/*Clean up and return*/
-	xDelete<IssmDouble>(f);
-	delete gauss;
-}/*}}}*/
-void DamageEvolutionAnalysis::CreateDamageFInputExp(Element* element){/*{{{*/
+void           DamageEvolutionAnalysis::CreateDamageFInputExp(Element* element){/*{{{*/
 
 	/*Intermediaries */
@@ -600,2 +172,490 @@
 	delete gauss;
 }/*}}}*/
+void           DamageEvolutionAnalysis::CreateDamageFInputPralong(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	IssmDouble c1,c2,c3,healing,stress_threshold;
+	IssmDouble s_xx,s_xy,s_xz,s_yy,s_yz,s_zz,s1,s2,s3,stmp;
+	IssmDouble J2s,Chi,Psi,PosPsi,NegPsi;
+	IssmDouble damage,tau_xx,tau_xy,tau_xz,tau_yy,tau_yz,tau_zz,stressMaxPrincipal;
+	int equivstress,domaintype,damagelaw,dim;
+
+	/*Fetch number of vertices and allocate output*/
+	int numnodes = element->GetNumberOfNodes();
+	IssmDouble* f   = xNew<IssmDouble>(numnodes);
+
+	/*retrieve parameters:*/
+	element->FindParam(&c1,DamageC1Enum);
+	element->FindParam(&c2,DamageC2Enum);
+	element->FindParam(&c3,DamageC3Enum);
+	element->FindParam(&healing,DamageHealingEnum);
+	element->FindParam(&stress_threshold,DamageStressThresholdEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	element->FindParam(&damagelaw,DamageLawEnum);
+
+	/*Get problem dimension*/
+	switch(domaintype){
+		case Domain2DhorizontalEnum: dim = 2; break;
+		case Domain3DEnum:           dim = 3; break;
+		default: _error_("not implemented");
+	}
+	/*Compute stress tensor and Stress Max Principal: */
+	element->ComputeDeviatoricStressTensor();
+	if(dim==3){
+		/*Only works in 3d because the pressure is defined*/
+		element->StressMaxPrincipalCreateInput();
+	}
+	/*retrieve what we need: */
+	Input* tau_xx_input  = element->GetInput(DeviatoricStressxxEnum);     _assert_(tau_xx_input);
+	Input* tau_xy_input  = element->GetInput(DeviatoricStressxyEnum);     _assert_(tau_xy_input);
+	Input* tau_yy_input  = element->GetInput(DeviatoricStressyyEnum);     _assert_(tau_yy_input);
+	Input* tau_xz_input  = NULL;
+	Input* tau_yz_input  = NULL;
+	Input* tau_zz_input  = NULL;
+	Input* stressMaxPrincipal_input = NULL;
+	if(dim==3){
+		tau_xz_input  = element->GetInput(DeviatoricStressxzEnum);     _assert_(tau_xz_input);
+		tau_yz_input  = element->GetInput(DeviatoricStressyzEnum);     _assert_(tau_yz_input);
+		tau_zz_input  = element->GetInput(DeviatoricStresszzEnum);     _assert_(tau_zz_input);
+		stressMaxPrincipal_input = element->GetInput(StressMaxPrincipalEnum); _assert_(stressMaxPrincipal_input);
+	}
+	Input* damage_input = NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		damage_input = element->GetInput(DamageDbarEnum); 	_assert_(damage_input);
+	}
+	else{
+		damage_input = element->GetInput(DamageDEnum);   _assert_(damage_input);
+	}
+
+	/*retrieve the desired type of equivalent stress*/
+	element->FindParam(&equivstress,DamageEquivStressEnum);
+
+	/*Calculate damage evolution source term: */
+	Gauss* gauss=element->NewGauss();
+	for (int i=0;i<numnodes;i++){
+		gauss->GaussNode(element->GetElementType(),i);
+		
+		damage_input->GetInputValue(&damage,gauss);
+		tau_xx_input->GetInputValue(&tau_xx,gauss);
+		tau_xy_input->GetInputValue(&tau_xy,gauss);
+		tau_yy_input->GetInputValue(&tau_yy,gauss);
+		if(dim==3){
+			tau_xz_input->GetInputValue(&tau_xz,gauss);
+			tau_yz_input->GetInputValue(&tau_yz,gauss);
+			tau_zz_input->GetInputValue(&tau_zz,gauss);
+		}
+		/*Calculate effective stress components*/
+		s_xx=tau_xx/(1.-damage);
+		s_xy=tau_xy/(1.-damage);
+		s_yy=tau_yy/(1.-damage);
+		if(dim==3){
+			s_xz=tau_xz/(1.-damage);
+			s_yz=tau_yz/(1.-damage);
+			s_zz=tau_zz/(1.-damage);
+		}
+		/*Calculate principal effective stresses*/
+		if(dim==2){
+			s1=(s_xx+s_yy)/2.+sqrt(pow((s_xx-s_yy)/2.,2)+pow(s_xy,2));
+			s2=(s_xx+s_yy)/2.-sqrt(pow((s_xx-s_yy)/2.,2)+pow(s_xy,2));
+			if(fabs(s2)>fabs(s1)){stmp=s2; s2=s1; s1=stmp;}
+
+			if(equivstress==0){ /* von Mises */
+				Chi=sqrt(s1*s1-s1*s2+s2*s2);
+			}
+			else if(equivstress==1){ /* max principal stress */
+				Chi=s1;
+			}
+			Psi=Chi-stress_threshold;
+			NegPsi=max(-Chi,0.); /* healing only for compressive stresses */
+
+			if(damagelaw==1){
+				PosPsi=max(Psi,0.);
+				f[i]= c1*(pow(PosPsi,c2) - healing*pow(NegPsi,c2))*pow((1./(1.-damage)),c3);
+			}
+			else if(damagelaw==2){
+				PosPsi=max(Psi,1.);
+				f[i]= c1*(pow(log10(PosPsi),c2) - healing*pow(NegPsi,c2))*pow((1./(1.-damage)),c3);
+			}
+			else _error_("damage law not supported");
+		}
+		else{
+			if(equivstress==1){/* max principal stress */
+				stressMaxPrincipal_input->GetInputValue(&stressMaxPrincipal,gauss);
+				Chi=stressMaxPrincipal/(1.-damage);
+			}
+			else if(equivstress==0){/* von Mises */
+				Chi=sqrt(((s_xx-s_yy)*(s_xx-s_yy)+(s_yy-s_zz)*(s_yy-s_zz)+(s_zz-s_xx)*(s_zz-s_xx)+6.*(s_xy*s_xy+s_yz*s_yz+s_xz*s_xz))/2.);
+			}
+			Psi=Chi-stress_threshold;
+			NegPsi=max(-Chi,0.); /* healing only for compressive stresses */
+			if(damagelaw==1){
+				PosPsi=max(Psi,0.);
+				f[i]= c1*(pow(PosPsi,c2) - healing*pow(NegPsi,c2))*pow((1./(1.-damage)),c3);
+			}
+			else if(damagelaw==2){
+				PosPsi=max(Psi,1.);
+				f[i]= c1*(pow(log10(PosPsi),c2) - healing*pow(NegPsi,c2))*pow((1./(1.-damage)),c3);
+			}
+			else _error_("damage law not supported");
+		}
+	}
+	/*Add input*/
+	element->AddInput(DamageFEnum,f,element->GetElementType());
+	
+	/*Clean up and return*/
+	xDelete<IssmDouble>(f);
+	delete gauss;
+}/*}}}*/
+ElementVector* DamageEvolutionAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* DamageEvolutionAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* DamageEvolutionAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+	/*Intermediaries*/
+	int         domaintype,dim;
+	int         stabilization;
+	IssmDouble  Jdet,dt,D_scalar,h,hx,hy,hz;
+	IssmDouble  vel,vx,vy,vz,dvxdx,dvydy,dvzdz,dvx[3],dvy[3],dvz[3];
+	IssmDouble *xyz_list  = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum: dim = 2; break;
+		case Domain3DEnum:           dim = 3; break;
+		default: _error_("Not implemented yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(dim*dim);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&stabilization,DamageStabilizationEnum);
+	Input* vx_input = element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input = element->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input = NULL;
+	if(dim==3){
+		vz_input=element->GetInput(VzEnum); _assert_(vz_input);
+	}
+
+	if(dim==2) h=element->CharacteristicLength();
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		
+		vx_input->GetInputValue(&vx,gauss);
+		vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+
+		if(dim==3){
+			vz_input->GetInputValue(&vz,gauss);
+			vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
+		}
+
+		D_scalar=gauss->weight*Jdet;
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+		GetB(B,element,dim,xyz_list,gauss);
+		GetBprime(Bprime,element,dim,xyz_list,gauss);
+
+		dvxdx=dvx[0];
+		dvydy=dvy[1];
+		if(dim==3) dvzdz=dvz[2];
+		D_scalar=dt*gauss->weight*Jdet;
+
+		D[0*dim+0]=D_scalar*dvxdx;
+		D[1*dim+1]=D_scalar*dvydy;
+		if(dim==3) D[2*dim+2]=D_scalar*dvzdz;
+
+		TripleMultiply(B,dim,numnodes,1,
+					D,dim,dim,0,
+					B,dim,numnodes,0,
+					&Ke->values[0],1);
+
+		D[0*dim+0]=D_scalar*vx;
+		D[1*dim+1]=D_scalar*vy;
+		if(dim==3) D[2*dim+2]=D_scalar*vz;
+
+		TripleMultiply(B,dim,numnodes,1,
+					D,dim,dim,0,
+					Bprime,dim,numnodes,0,
+					&Ke->values[0],1);
+
+		if(stabilization==2){
+			if(dim==3){
+				vel=sqrt(vx*vx+vy*vy+vz*vz)+1.e-8;
+				D[0*dim+0]=h/(2.0*vel)*vx*vx;
+				D[1*dim+0]=h/(2.0*vel)*vy*vx;
+				D[2*dim+0]=h/(2.0*vel)*vz*vx;
+				D[0*dim+1]=h/(2.0*vel)*vx*vy;
+				D[1*dim+1]=h/(2.0*vel)*vy*vy;
+				D[2*dim+1]=h/(2.0*vel)*vy*vz;
+				D[0*dim+2]=h/(2.0*vel)*vx*vz;
+				D[1*dim+2]=h/(2.0*vel)*vy*vz;
+				D[2*dim+2]=h/(2.0*vel)*vz*vz;
+			}
+			else{
+				/*Streamline upwinding*/
+				vel=sqrt(vx*vx+vy*vy)+1.e-8;
+				D[0*dim+0]=h/(2.0*vel)*vx*vx;
+				D[1*dim+0]=h/(2.0*vel)*vy*vx;
+				D[0*dim+1]=h/(2.0*vel)*vx*vy;
+				D[1*dim+1]=h/(2.0*vel)*vy*vy;
+			}
+		}
+		else if(stabilization==1){
+			if(dim==2){
+				vx_input->GetInputAverage(&vx);
+				vy_input->GetInputAverage(&vy);
+				D[0*dim+0]=h/2.0*fabs(vx);
+				D[1*dim+1]=h/2.0*fabs(vy);
+			}
+			else if(dim==3){ 
+				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));
+				D[0*dim+0]=h/(2.*vel)*fabs(vx*vx);  D[0*dim+1]=h/(2.*vel)*fabs(vx*vy); D[0*dim+2]=h/(2.*vel)*fabs(vx*vz);
+				D[1*dim+0]=h/(2.*vel)*fabs(vy*vx);  D[1*dim+1]=h/(2.*vel)*fabs(vy*vy); D[1*dim+2]=h/(2.*vel)*fabs(vy*vz);
+				D[2*dim+0]=h/(2.*vel)*fabs(vz*vx);  D[2*dim+1]=h/(2.*vel)*fabs(vz*vy); D[2*dim+2]=h/(2.*vel)*fabs(vz*vz);
+			}
+		}
+		if(stabilization==1 || stabilization==2){
+			if(dim==2){
+				D[0*dim+0]=D_scalar*D[0*dim+0];
+				D[1*dim+0]=D_scalar*D[1*dim+0];
+				D[0*dim+1]=D_scalar*D[0*dim+1];
+				D[1*dim+1]=D_scalar*D[1*dim+1];
+			}
+			else if(dim==3){
+				D[0*dim+0]=D_scalar*D[0*dim+0];
+				D[1*dim+0]=D_scalar*D[1*dim+0];
+				D[2*dim+0]=D_scalar*D[2*dim+0];
+				D[0*dim+1]=D_scalar*D[0*dim+1];
+				D[1*dim+1]=D_scalar*D[1*dim+1];
+				D[2*dim+1]=D_scalar*D[2*dim+1];
+				D[0*dim+2]=D_scalar*D[0*dim+2];
+				D[1*dim+2]=D_scalar*D[1*dim+2];
+				D[2*dim+2]=D_scalar*D[2*dim+2];
+			}
+			TripleMultiply(Bprime,dim,numnodes,1,
+						D,dim,dim,0,
+						Bprime,dim,numnodes,0,
+						&Ke->values[0],1);
+		}
+
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(D);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementVector* DamageEvolutionAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	int      domaintype,damagelaw;
+	IssmDouble  Jdet,dt;
+	IssmDouble  f,damage;
+	IssmDouble* xyz_list = NULL;
+	/*Get element*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&damagelaw,DamageLawEnum);
+	switch(damagelaw){
+		case 1:
+			this->CreateDamageFInputPralong(element);
+			break;
+		case 2:
+			this->CreateDamageFInputPralong(element);
+			break;
+		case 3:
+			this->CreateDamageFInputExp(element);
+			break;
+		default:
+			_error_("not implemented yet");
+	}
+
+	Input* damaged_input = NULL;
+	Input* damagef_input = element->GetInput(DamageFEnum); _assert_(damagef_input);
+	if(domaintype==Domain2DhorizontalEnum){
+		damaged_input = element->GetInput(DamageDbarEnum); _assert_(damaged_input);
+	}
+	else{
+		damaged_input = element->GetInput(DamageDEnum); _assert_(damaged_input);
+	}
+
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		damaged_input->GetInputValue(&damage,gauss);
+		damagef_input->GetInputValue(&f,gauss);
+
+		for(int i=0;i<numnodes;i++){
+			pe->values[i]+=Jdet*gauss->weight*(damage+dt*f)*basis[i];
+		}
+	}
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void           DamageEvolutionAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		for(int j=0;j<dim;j++){
+			B[numnodes*j+i] = basis[i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void           DamageEvolutionAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(dim*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		for(int j=0;j<dim;j++){
+			Bprime[numnodes*j+i] = dbasis[j*numnodes+i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+void           DamageEvolutionAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void           DamageEvolutionAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void           DamageEvolutionAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	int domaintype;
+	IssmDouble  max_damage;
+	int			*doflist = NULL;
+
+	element->FindParam(&domaintype,DomainTypeEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* newdamage = xNew<IssmDouble>(numnodes);
+
+	/*Get user-supplied max_damage: */
+	element->FindParam(&max_damage,DamageMaxDamageEnum);
+
+	/*Use the dof list to index into the solution vector: */
+	for(int i=0;i<numnodes;i++){
+		newdamage[i]=solution[doflist[i]];
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(newdamage[i])) _error_("NaN found in solution vector");
+		/*Enforce D < max_damage and D > 0 */
+		if(newdamage[i]>max_damage) newdamage[i]=max_damage;
+		else if(newdamage[i]<0.)    newdamage[i]=0.;
+	}
+
+	/*Get all inputs and parameters*/
+	if(domaintype==Domain2DhorizontalEnum){
+		element->AddInput(DamageDbarEnum,newdamage,element->GetElementType());
+	}
+	else{
+		element->AddInput(DamageDEnum,newdamage,element->GetElementType());
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(newdamage);
+	xDelete<int>(doflist);
+}/*}}}*/
+void           DamageEvolutionAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	bool islevelset;
+	femmodel->parameters->FindParam(&islevelset,TransientIslevelsetEnum);
+	if(islevelset){
+		SetActiveNodesLSMx(femmodel);
+	}
+	return;
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/DamageEvolutionAnalysis.h	(revision 19105)
@@ -13,27 +13,25 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,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           CreateDamageFInputExp(Element* element);
+		void           CreateDamageFInputPralong(Element* element);
 		ElementVector* CreateDVector(Element* element);
 		ElementMatrix* CreateJacobianMatrix(Element* element);
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
-
-		/*Intermediaries*/
-		void CreateDamageFInputPralong(Element* element);
-		void CreateDamageFInputExp(Element* element);
+		void           GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/DepthAverageAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/DepthAverageAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/DepthAverageAnalysis.cpp	(revision 19105)
@@ -6,8 +6,15 @@
 
 /*Model processing*/
+void DepthAverageAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void DepthAverageAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void DepthAverageAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	::CreateNodes(nodes,iomodel,DepthAverageAnalysisEnum,P1Enum);
+
+}/*}}}*/
 int  DepthAverageAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void DepthAverageAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 void DepthAverageAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -26,12 +33,5 @@
 	}
 }/*}}}*/
-void DepthAverageAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	::CreateNodes(nodes,iomodel,DepthAverageAnalysisEnum,P1Enum);
-
-}/*}}}*/
-void DepthAverageAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-}/*}}}*/
-void DepthAverageAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+void DepthAverageAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 
@@ -137,5 +137,5 @@
 	return pe;
 }/*}}}*/
-void DepthAverageAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           DepthAverageAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
 		where hi is the interpolation function for node i.*/
@@ -157,11 +157,11 @@
 }
 /*}}}*/
-void DepthAverageAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           DepthAverageAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void DepthAverageAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           DepthAverageAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void DepthAverageAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           DepthAverageAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int inputenum;
@@ -169,5 +169,5 @@
 	element->InputUpdateFromSolutionOneDof(solution,inputenum);
 }/*}}}*/
-void DepthAverageAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           DepthAverageAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/DepthAverageAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/DepthAverageAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/DepthAverageAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,9 +26,9 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/EnthalpyAnalysis.cpp	(revision 19105)
@@ -4,23 +4,104 @@
 #include "../shared/shared.h"
 #include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
 
 /*Model processing*/
+void EnthalpyAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int        count;
+	int        M,N;
+	bool       spcpresent = false;
+	IssmDouble heatcapacity;
+	IssmDouble referencetemperature;
+
+	/*Output*/
+	IssmDouble *spcvector  = NULL;
+	IssmDouble* times=NULL;
+	IssmDouble* values=NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&heatcapacity,MaterialsHeatcapacityEnum);
+	iomodel->Constant(&referencetemperature,ConstantsReferencetemperatureEnum);
+
+	/*return if 2d mesh*/
+	if(iomodel->domaintype==Domain2DhorizontalEnum) return;
+
+	/*Fetch data: */
+	iomodel->FetchData(&spcvector,&M,&N,ThermalSpctemperatureEnum);
+
+	//FIX ME: SHOULD USE IOMODELCREATECONSTRAINTS 
+	/*Transient or static?:*/
+	if(M==iomodel->numberofvertices){
+		/*static: just create Constraints objects*/
+		count=0;
+
+		for(int i=0;i<iomodel->numberofvertices;i++){
+			/*keep only this partition's nodes:*/
+			if((iomodel->my_vertices[i])){
+
+				if (!xIsNan<IssmDouble>(spcvector[i])){
+
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,heatcapacity*(spcvector[i]-referencetemperature),EnthalpyAnalysisEnum));
+					count++;
+
+				}
+			}
+		}
+	}
+	else if (M==(iomodel->numberofvertices+1)){
+		/*transient: create transient SpcTransient objects. Same logic, except we need to retrieve 
+		 * various times and values to initialize an SpcTransient object: */
+		count=0;
+
+		/*figure out times: */
+		times=xNew<IssmDouble>(N);
+		for(int j=0;j<N;j++){
+			times[j]=spcvector[(M-1)*N+j];
+		}
+
+		/*Create constraints from x,y,z: */
+		for(int i=0;i<iomodel->numberofvertices;i++){
+
+			/*keep only this partition's nodes:*/
+			if((iomodel->my_vertices[i])){
+
+				/*figure out times and values: */
+				values=xNew<IssmDouble>(N);
+				spcpresent=false;
+				for(int j=0;j<N;j++){
+					values[j]=heatcapacity*(spcvector[i*N+j]-referencetemperature);
+					if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+				}
+
+				if(spcpresent){
+					constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,N,times,values,EnthalpyAnalysisEnum));
+					count++;
+				}
+				xDelete<IssmDouble>(values);
+			}
+		}
+	}
+	else{
+		_error_("Size of field " << EnumToStringx(ThermalSpctemperatureEnum) << " not supported");
+	}
+
+	/*Free ressources:*/
+	iomodel->DeleteData(spcvector,ThermalSpctemperatureEnum);
+	xDelete<IssmDouble>(times);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
+void EnthalpyAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads */
+}/*}}}*/
+void EnthalpyAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,EnthalpyAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
 int  EnthalpyAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void EnthalpyAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-
-	int     numoutputs;
-	char**  requestedoutputs = NULL;
-
-	parameters->AddObject(iomodel->CopyConstantObject(ThermalStabilizationEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsenthalpyEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsdynamicbasalspcEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(FrictionLawEnum));
-
-	iomodel->FetchData(&requestedoutputs,&numoutputs,ThermalRequestedOutputsEnum);
-	parameters->AddObject(new IntParam(ThermalNumRequestedOutputsEnum,numoutputs));
-	if(numoutputs)parameters->AddObject(new StringArrayParam(ThermalRequestedOutputsEnum,requestedoutputs,numoutputs));
-	iomodel->DeleteData(&requestedoutputs,numoutputs,ThermalRequestedOutputsEnum);
 }/*}}}*/
 void EnthalpyAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -62,5 +143,4 @@
 		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
 	}
-	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
 	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
 	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
@@ -94,4 +174,29 @@
 			iomodel->FetchDataToInput(elements,FrictionMEnum);
 			break;
+		case 3:
+			iomodel->FetchDataToInput(elements,FrictionCEnum);
+			iomodel->FetchDataToInput(elements,FrictionAsEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			iomodel->FetchDataToInput(elements,FrictionEffectivePressureEnum);
+			break;
+		case 4:
+			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,FrictionPEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			iomodel->FetchDataToInput(elements,PressureEnum);
+			iomodel->FetchDataToInput(elements,TemperatureEnum);
+			break;
+		case 5:
+			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,FrictionPEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			iomodel->FetchDataToInput(elements,FrictionWaterLayerEnum);
+			break;
+		case 6:
+			iomodel->FetchDataToInput(elements,FrictionCEnum);
+			iomodel->FetchDataToInput(elements,FrictionMEnum);
+			iomodel->FetchDataToInput(elements,PressureEnum);
+			iomodel->FetchDataToInput(elements,TemperatureEnum);
+			break;
 		default:
 			_error_("not supported");
@@ -100,103 +205,255 @@
 	iomodel->DeleteData(3,TemperatureEnum,WaterfractionEnum,PressureEnum);
 }/*}}}*/
-void EnthalpyAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	::CreateNodes(nodes,iomodel,EnthalpyAnalysisEnum,P1Enum);
-	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-}/*}}}*/
-void EnthalpyAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+void EnthalpyAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	int     numoutputs;
+	char**  requestedoutputs = NULL;
+
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalStabilizationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalReltolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsenthalpyEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsdynamicbasalspcEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FrictionLawEnum));
+
+	iomodel->FetchData(&requestedoutputs,&numoutputs,ThermalRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(ThermalNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(ThermalRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,ThermalRequestedOutputsEnum);
+
+	/*Deal with friction parameters*/
+	int frictionlaw;
+	iomodel->Constant(&frictionlaw,FrictionLawEnum);
+	if(frictionlaw==4 || frictionlaw==6) parameters->AddObject(iomodel->CopyConstantObject(FrictionGammaEnum));
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           EnthalpyAnalysis::ApplyBasalConstraints(IssmDouble* serial_spc,Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return;
+
+	/* Only update Constraints at the base of grounded ice*/
+	if(!(element->IsOnBase()) || element->IsFloating()) return;
 
 	/*Intermediary*/
-	int        count;
-	int        M,N;
-	bool       spcpresent = false;
-	IssmDouble heatcapacity;
-	IssmDouble referencetemperature;
-
-	/*Output*/
-	IssmDouble *spcvector  = NULL;
-	IssmDouble* times=NULL;
-	IssmDouble* values=NULL;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&heatcapacity,MaterialsHeatcapacityEnum);
-	iomodel->Constant(&referencetemperature,ConstantsReferencetemperatureEnum);
-
-	/*return if 2d mesh*/
-	if(iomodel->domaintype==Domain2DhorizontalEnum) return;
-
-	/*Fetch data: */
-	iomodel->FetchData(&spcvector,&M,&N,ThermalSpctemperatureEnum);
-
-	//FIX ME: SHOULD USE IOMODELCREATECONSTRAINTS 
-	/*Transient or static?:*/
-	if(M==iomodel->numberofvertices){
-		/*static: just create Constraints objects*/
-		count=0;
-
-		for(int i=0;i<iomodel->numberofvertices;i++){
-			/*keep only this partition's nodes:*/
-			if((iomodel->my_vertices[i])){
-
-				if (!xIsNan<IssmDouble>(spcvector[i])){
-
-					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,heatcapacity*(spcvector[i]-referencetemperature),EnthalpyAnalysisEnum));
-					count++;
-
-				}
+	bool        isdynamicbasalspc;
+	int         numindices;
+	int        *indices = NULL;
+	Node*       node = NULL;
+	IssmDouble	pressure;
+
+	/*Check wether dynamic basal boundary conditions are activated */
+	element->FindParam(&isdynamicbasalspc,ThermalIsdynamicbasalspcEnum);
+	if(!isdynamicbasalspc) return;
+
+	/*Get parameters and inputs: */
+	Input* pressure_input		 = element->GetInput(PressureEnum);							 _assert_(pressure_input);
+
+	/*Fetch indices of basal & surface nodes for this finite element*/
+	Penta *penta =  (Penta *) element; // TODO: add Basal-/SurfaceNodeIndices to element.h, and change this to Element*
+	penta->BasalNodeIndices(&numindices,&indices,element->GetElementType());
+
+	GaussPenta* gauss=new GaussPenta();
+	for(int i=0;i<numindices;i++){
+		gauss->GaussNode(element->GetElementType(),indices[i]);
+
+		pressure_input->GetInputValue(&pressure,gauss);
+
+		/*apply or release spc*/
+		node=element->GetNode(indices[i]);
+		if(serial_spc[node->Sid()]==1.){
+			pressure_input->GetInputValue(&pressure, gauss);
+			node->ApplyConstraint(0,PureIceEnthalpy(element,pressure));
+		}
+		else			
+			node->DofInFSet(0);
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(indices);
+	delete gauss;
+}/*}}}*/
+void           EnthalpyAnalysis::ComputeBasalMeltingrate(FemModel* femmodel){/*{{{*/
+	/*Compute basal melting rates: */
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		ComputeBasalMeltingrate(element);
+	}
+}/*}}}*/
+void           EnthalpyAnalysis::ComputeBasalMeltingrate(Element* element){/*{{{*/
+	/*Calculate the basal melt rates of the enthalpy model after Aschwanden 2012*/
+	/* melting rate is positive when melting, negative when refreezing*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return;
+
+	/* Only compute melt rates at the base of grounded ice*/
+	if(!element->IsOnBase() || element->IsFloating()) return;
+
+	/* Intermediaries */
+	bool			converged;
+	const int   dim=3;
+	int         i,is,state;
+	int			vertexdown,vertexup,numvertices,numsegments;
+	int			enthalpy_enum;
+	IssmDouble  vec_heatflux[dim],normal_base[dim],d1enthalpy[dim],d1pressure[dim];
+	IssmDouble  basalfriction,alpha2,geothermalflux,heatflux;
+	IssmDouble  dt,yts;
+	IssmDouble  melting_overshoot,lambda;
+	IssmDouble  vx,vy,vz;
+	IssmDouble *xyz_list      = NULL;
+	IssmDouble *xyz_list_base = NULL;
+	int        *pairindices   = NULL;
+
+	/*Fetch parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->GetInputValue(&converged,ConvergedEnum);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&yts, ConstantsYtsEnum);
+
+	if(dt==0. && !converged) enthalpy_enum=EnthalpyPicardEnum;
+	else enthalpy_enum=EnthalpyEnum;
+
+	IssmDouble latentheat = element->GetMaterialParameter(MaterialsLatentheatEnum);
+	IssmDouble rho_ice    = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble rho_water  = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
+	IssmDouble beta		 = element->GetMaterialParameter(MaterialsBetaEnum);
+	IssmDouble kappa		 = EnthalpyDiffusionParameterVolume(element,enthalpy_enum);     _assert_(kappa>=0.);
+	IssmDouble kappa_mix;
+
+	/*retrieve inputs*/
+	Input* enthalpy_input         = element->GetInput(enthalpy_enum);                    _assert_(enthalpy_input);
+	Input* pressure_input			= element->GetInput(PressureEnum);							 _assert_(pressure_input);
+	Input* geothermalflux_input   = element->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
+	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);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(element,dim);
+
+	/******** MELTING RATES  ************************************//*{{{*/
+	element->NormalBase(&normal_base[0],xyz_list_base);
+	element->VerticalSegmentIndices(&pairindices,&numsegments);
+	IssmDouble* meltingrate_enthalpy = xNew<IssmDouble>(numsegments);
+	IssmDouble* heating = xNew<IssmDouble>(numsegments);	
+
+	numvertices=element->GetNumberOfVertices();
+	IssmDouble* enthalpies = xNew<IssmDouble>(numvertices);
+	IssmDouble* pressures = xNew<IssmDouble>(numvertices);
+	IssmDouble* watercolumns = xNew<IssmDouble>(numvertices);
+	IssmDouble* basalmeltingrates = xNew<IssmDouble>(numvertices);
+	element->GetInputListOnVertices(enthalpies,enthalpy_enum);
+	element->GetInputListOnVertices(pressures,PressureEnum);
+	element->GetInputListOnVertices(watercolumns,WatercolumnEnum);
+	element->GetInputListOnVertices(basalmeltingrates,BasalforcingsGroundediceMeltingRateEnum);
+
+	Gauss* gauss=element->NewGauss();
+	for(is=0;is<numsegments;is++){
+		vertexdown = pairindices[is*2+0];
+		vertexup   = pairindices[is*2+1];
+		gauss->GaussVertex(vertexdown);
+
+		state=GetThermalBasalCondition(element, enthalpies[vertexdown], enthalpies[vertexup], pressures[vertexdown], pressures[vertexup], watercolumns[vertexdown], basalmeltingrates[vertexdown]);
+		switch (state) {
+			case 0:
+				// cold, dry base: apply basal surface forcing
+				for(i=0;i<3;i++) vec_heatflux[i]=0.;
+				break;
+			case 1: case 2: case 3: 
+				// case 1 : cold, wet base: keep at pressure melting point 
+				// case 2: temperate, thin refreezing base: release spc
+				// case 3: temperate, thin melting base: set spc
+				enthalpy_input->GetInputDerivativeValue(&d1enthalpy[0],xyz_list,gauss);
+				for(i=0;i<3;i++) vec_heatflux[i]=-kappa*d1enthalpy[i];
+				break;
+			case 4:
+				// temperate, thick melting base: set grad H*n=0
+				kappa_mix=GetWetIceConductivity(element, enthalpies[vertexdown], pressures[vertexdown]);
+				pressure_input->GetInputDerivativeValue(&d1pressure[0],xyz_list,gauss);
+				for(i=0;i<3;i++) vec_heatflux[i]=kappa_mix*beta*d1pressure[i];
+				break;
+			default:
+				_printf0_("	unknown thermal basal state found!");
+		}
+		if(state==0) meltingrate_enthalpy[is]=0.;
+		else{
+			/*heat flux along normal*/
+			heatflux=0.;
+			for(i=0;i<3;i++) heatflux+=(vec_heatflux[i])*normal_base[i];
+
+			/*basal friction*/
+			friction->GetAlpha2(&alpha2,gauss);
+			vx_input->GetInputValue(&vx,gauss);		vy_input->GetInputValue(&vy,gauss);		vz_input->GetInputValue(&vz,gauss);
+			basalfriction=alpha2*(vx*vx + vy*vy + vz*vz);
+			geothermalflux_input->GetInputValue(&geothermalflux,gauss);
+			/* -Mb= Fb-(q-q_geo)/((1-w)*L*rho), and (1-w)*rho=rho_ice, cf Aschwanden 2012, eqs.1, 2, 66*/
+			heating[is]=(heatflux+basalfriction+geothermalflux);
+			meltingrate_enthalpy[is]=heating[is]/(latentheat*rho_ice); // m/s water equivalent
+		}
+	}/*}}}*/
+
+	/******** UPDATE MELTINGRATES AND WATERCOLUMN **************//*{{{*/
+	for(is=0;is<numsegments;is++){
+		vertexdown = pairindices[is*2+0];
+		vertexup   = pairindices[is*2+1];
+		if(dt!=0.){
+			if(watercolumns[vertexdown]+meltingrate_enthalpy[is]*dt<0.){	// prevent too much freeze on			
+				lambda = -watercolumns[vertexdown]/(dt*meltingrate_enthalpy[is]); _assert_(lambda>=0.); _assert_(lambda<1.);
+				watercolumns[vertexdown]=0.;
+				basalmeltingrates[vertexdown]=lambda*meltingrate_enthalpy[is]; // restrict freeze on only to size of watercolumn
+				enthalpies[vertexdown]+=(1.-lambda)*dt/yts*meltingrate_enthalpy[is]*latentheat*rho_ice; // use rest of energy to cool down base: dE=L*m, m=(1-lambda)*meltingrate*rho_ice
 			}
-		}
-	}
-	else if (M==(iomodel->numberofvertices+1)){
-		/*transient: create transient SpcTransient objects. Same logic, except we need to retrieve 
-		 * various times and values to initialize an SpcTransient object: */
-		count=0;
-
-		/*figure out times: */
-		times=xNew<IssmDouble>(N);
-		for(int j=0;j<N;j++){
-			times[j]=spcvector[(M-1)*N+j];
-		}
-
-		/*Create constraints from x,y,z: */
-		for(int i=0;i<iomodel->numberofvertices;i++){
-
-			/*keep only this partition's nodes:*/
-			if((iomodel->my_vertices[i])){
-
-				/*figure out times and values: */
-				values=xNew<IssmDouble>(N);
-				spcpresent=false;
-				for(int j=0;j<N;j++){
-					values[j]=heatcapacity*(spcvector[i*N+j]-referencetemperature);
-					if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
-				}
-
-				if(spcpresent){
-					constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,N,times,values,EnthalpyAnalysisEnum));
-					count++;
-				}
-				xDelete<IssmDouble>(values);
+			else{
+				basalmeltingrates[vertexdown]=meltingrate_enthalpy[is];
+				watercolumns[vertexdown]+=dt*meltingrate_enthalpy[is]; 
 			}
 		}
-	}
-	else{
-		_error_("Size of field " << EnumToStringx(ThermalSpctemperatureEnum) << " not supported");
-	}
-
-	/*Free ressources:*/
-	iomodel->DeleteData(spcvector,ThermalSpctemperatureEnum);
-	xDelete<IssmDouble>(times);
-	xDelete<IssmDouble>(values);
-}/*}}}*/
-void EnthalpyAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
-	/*No loads */
-}/*}}}*/
-
-/*Finite Element Analysis*/
-void EnthalpyAnalysis::Core(FemModel* femmodel){/*{{{*/
-	_error_("not implemented");
+		else{
+			basalmeltingrates[vertexdown]=meltingrate_enthalpy[is];
+			if(watercolumns[vertexdown]+meltingrate_enthalpy[is]<0.)
+				watercolumns[vertexdown]=0.;
+			else
+				watercolumns[vertexdown]+=meltingrate_enthalpy[is];
+		}	
+		basalmeltingrates[vertexdown]*=rho_water/rho_ice; // convert meltingrate from water to ice equivalent
+		_assert_(watercolumns[vertexdown]>=0.);
+	}/*}}}*/
+
+	/*feed updated variables back into model*/
+	if(dt!=0.){
+		element->AddInput(enthalpy_enum,enthalpies,P1Enum); //TODO: distinguis for steadystate and transient run
+		element->AddInput(WatercolumnEnum,watercolumns,P1Enum);
+	}
+	element->AddInput(BasalforcingsGroundediceMeltingRateEnum,basalmeltingrates,P1Enum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<int>(pairindices);
+	xDelete<IssmDouble>(enthalpies);
+	xDelete<IssmDouble>(pressures);
+	xDelete<IssmDouble>(watercolumns);
+	xDelete<IssmDouble>(basalmeltingrates);
+	xDelete<IssmDouble>(meltingrate_enthalpy);
+	xDelete<IssmDouble>(heating);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_base);
+}/*}}}*/
+void           EnthalpyAnalysis::Core(FemModel* femmodel){/*{{{*/
+	if(VerboseSolution()) _printf0_("   computing enthalpy\n");
+	femmodel->SetCurrentConfiguration(EnthalpyAnalysisEnum);
+	solutionsequence_thermal_nonlinear(femmodel);
+
+	/*transfer enthalpy to enthalpy picard for the next step: */
+	InputDuplicatex(femmodel,EnthalpyEnum,EnthalpyPicardEnum);
+
+	IssmDouble dt;
+	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	if(dt==0.) ComputeBasalMeltingrate(femmodel);
+	else PostProcessing(femmodel);
+
 }/*}}}*/
 ElementVector* EnthalpyAnalysis::CreateDVector(Element* element){/*{{{*/
@@ -316,7 +573,7 @@
 			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)*vx*vx;  K[0][1]=h/(2.*vel)*vx*vy; K[0][2]=h/(2.*vel)*vx*vz;
-			K[1][0]=h/(2.*vel)*vy*vx;  K[1][1]=h/(2.*vel)*vy*vy; K[1][2]=h/(2.*vel)*vy*vz;
-			K[2][0]=h/(2.*vel)*vz*vx;  K[2][1]=h/(2.*vel)*vz*vy; K[2][2]=h/(2.*vel)*vz*vz;
+			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];
 
@@ -549,6 +806,10 @@
 	if(!element->IsOnBase() || element->IsFloating()) return NULL;
 
-	IssmDouble  dt,Jdet,enthalpy,pressure,watercolumn,geothermalflux,vx,vy,vz;
-	IssmDouble  enthalpyup,pressureup,alpha2,scalar,basalfriction,heatflux;
+	bool isdynamicbasalspc;
+	int i, state;
+	IssmDouble  dt,Jdet,scalar;
+	IssmDouble	enthalpy, enthalpyup, pressure, pressureup, watercolumn, meltingrate;
+	IssmDouble	vx,vy,vz;
+	IssmDouble  alpha2,basalfriction,geothermalflux,heatflux;
 	IssmDouble *xyz_list_base = NULL;
 
@@ -563,13 +824,14 @@
 	element->GetVerticesCoordinatesBase(&xyz_list_base);
 	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	element->FindParam(&isdynamicbasalspc,ThermalIsdynamicbasalspcEnum);
 	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* enthalpy_input       = element->GetInput(EnthalpyPicardEnum);              _assert_(enthalpy_input);
-	Input* pressure_input       = element->GetInput(PressureEnum);                    _assert_(pressure_input);
+	Input* enthalpy_input		 = element->GetInput(EnthalpyPicardEnum);					 _assert_(enthalpy_input);
+	Input* pressure_input		 = element->GetInput(PressureEnum);							 _assert_(pressure_input);
+	Input* watercolumn_input	 = element->GetInput(WatercolumnEnum);							 _assert_(watercolumn_input);
+	Input* meltingrate_input	 = element->GetInput(BasalforcingsGroundediceMeltingRateEnum);							 _assert_(meltingrate_input);
 	Input* geothermalflux_input = element->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
-	Input* watercolumn_input    = element->GetInput(WatercolumnEnum);                 _assert_(watercolumn_input);
-	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
-	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble  rho_ice			 = element->GetMaterialParameter(MaterialsRhoIceEnum);
 
 	/*Build friction element, needed later: */
@@ -577,46 +839,56 @@
 
 	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss   = element->NewGaussBase(2);
-	Gauss* gaussup = element->NewGaussTop(2);
+	Gauss* gauss=element->NewGaussBase(2);
+	Gauss* gaussup=element->NewGaussTop(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 		gauss->GaussPoint(ig);
+		gaussup->GaussPoint(ig);
 
 		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
 		element->NodalFunctions(basis,gauss);
 
-		enthalpy_input->GetInputValue(&enthalpy,gauss);
-		pressure_input->GetInputValue(&pressure,gauss);
-		watercolumn_input->GetInputValue(&watercolumn,gauss);
-
-		if((watercolumn<=0.) && (enthalpy<PureIceEnthalpy(element,pressure))){
-			/* the above check is equivalent to 
-			 NOT [(watercolumn>0.) AND (enthalpy<PIE)] AND (enthalpy<PIE)*/
-			geothermalflux_input->GetInputValue(&geothermalflux,gauss);
-
-			friction->GetAlpha2(&alpha2,gauss);
-			vx_input->GetInputValue(&vx,gauss);
-			vy_input->GetInputValue(&vy,gauss);
-			vz_input->GetInputValue(&vz,gauss);
-			basalfriction = alpha2*(vx*vx + vy*vy + vz*vz);
-			heatflux      = (basalfriction+geothermalflux)/(rho_ice);
-
-			scalar = gauss->weight*Jdet*heatflux;
-			if(dt!=0.) scalar=dt*scalar;
-
-			for(int i=0;i<numnodes;i++) pe->values[i]+=scalar*basis[i];
-		}
-		else if(enthalpy >= PureIceEnthalpy(element,pressure)){
-			/* check positive thickness of temperate basal ice layer */
+		if(isdynamicbasalspc){
+			enthalpy_input->GetInputValue(&enthalpy,gauss);
 			enthalpy_input->GetInputValue(&enthalpyup,gaussup);
+			pressure_input->GetInputValue(&pressure,gauss);
 			pressure_input->GetInputValue(&pressureup,gaussup);
-			if(enthalpyup >= PureIceEnthalpy(element,pressureup)){
-				// do nothing, set grad enthalpy*n=0.
-			}
-			else{
-				// only base temperate, set Dirichlet BCs in Penta::UpdateBasalConstraintsEnthalpy()
-			}
-		}
-		else{
-			// base cold, but watercolumn positive. Set base to pressure melting point enthalpy
+			watercolumn_input->GetInputValue(&watercolumn,gauss);
+			meltingrate_input->GetInputValue(&meltingrate,gauss);
+			state=GetThermalBasalCondition(element, enthalpy, enthalpyup, pressure, pressureup, watercolumn, meltingrate);
+		}
+		else
+			state=0;
+
+		switch (state) {
+			case 0:
+				// cold, dry base: apply basal surface forcing
+				geothermalflux_input->GetInputValue(&geothermalflux,gauss);
+				friction->GetAlpha2(&alpha2,gauss);
+				vx_input->GetInputValue(&vx,gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				vz_input->GetInputValue(&vz,gauss);
+				basalfriction=alpha2*(vx*vx+vy*vy+vz*vz);
+				heatflux=(basalfriction+geothermalflux)/(rho_ice);
+				scalar=gauss->weight*Jdet*heatflux;
+				if(dt!=0.) scalar=dt*scalar;
+				for(i=0;i<numnodes;i++) 
+					pe->values[i]+=scalar*basis[i];
+				break;
+			case 1:
+				// cold, wet base: keep at pressure melting point 
+				break;
+			case 2:
+				// temperate, thin refreezing base: release spc
+				break;
+			case 3:
+				// temperate, thin melting base: set spc
+				break;
+			case 4:
+				// temperate, thick melting base: set grad H*n=0
+				for(i=0;i<numnodes;i++) 
+					pe->values[i]+=0.;
+				break;
+			default:
+				_printf0_("	unknown thermal basal state found!");
 		}
 	}
@@ -639,5 +911,5 @@
 	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
 
-	IssmDouble  h_pmp,dt,Jdet,scalar_ocean,pressure;
+	IssmDouble  Hpmp,dt,Jdet,scalar_ocean,pressure;
 	IssmDouble *xyz_list_base = NULL;
 
@@ -669,7 +941,7 @@
 
 		pressure_input->GetInputValue(&pressure,gauss);
-		h_pmp=element->PureIceEnthalpy(pressure);
-
-		scalar_ocean=gauss->weight*Jdet*rho_water*mixed_layer_capacity*thermal_exchange_vel*h_pmp/(heatcapacity*rho_ice);
+		Hpmp=element->PureIceEnthalpy(pressure);
+
+		scalar_ocean=gauss->weight*Jdet*rho_water*mixed_layer_capacity*thermal_exchange_vel*Hpmp/(heatcapacity*rho_ice);
 		if(reCast<bool,IssmDouble>(dt)) scalar_ocean=dt*scalar_ocean;
 
@@ -683,416 +955,12 @@
 	return pe;
 }/*}}}*/
-void EnthalpyAnalysis::GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
-	 * For node i, Bi' can be expressed in the actual coordinate system
-	 * by: 
-	 *       Bi_conduct=[ dh/dx ]
-	 *                  [ dh/dy ]
-	 *                  [ dh/dz ]
-	 * where h is the interpolation function for node i.
-	 *
-	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
-	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-	/*Build B: */
-	for(int i=0;i<numnodes;i++){
-		B[numnodes*0+i] = dbasis[0*numnodes+i];
-		B[numnodes*1+i] = dbasis[1*numnodes+i];
-		B[numnodes*2+i] = dbasis[2*numnodes+i];
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(dbasis);
-}/*}}}*/
-void EnthalpyAnalysis::GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
-	 * For node i, Bi' can be expressed in the actual coordinate system
-	 * by: 
-	 *       Bi_advec =[ h ]
-	 *                 [ h ]
-	 *                 [ h ]
-	 * where h is the interpolation function for node i.
-	 *
-	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions*/
-	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	element->NodalFunctions(basis,gauss);
-
-	/*Build B: */
-	for(int i=0;i<numnodes;i++){
-		B[numnodes*0+i] = basis[i];
-		B[numnodes*1+i] = basis[i];
-		B[numnodes*2+i] = basis[i];
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(basis);
-}/*}}}*/
-void EnthalpyAnalysis::GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
-	 * For node i, Bi' can be expressed in the actual coordinate system
-	 * by: 
-	 *       Biprime_advec=[ dh/dx ]
-	 *                     [ dh/dy ]
-	 *                     [ dh/dz ]
-	 * where h is the interpolation function for node i.
-	 *
-	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
-	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-	/*Build B: */
-	for(int i=0;i<numnodes;i++){
-		B[numnodes*0+i] = dbasis[0*numnodes+i];
-		B[numnodes*1+i] = dbasis[1*numnodes+i];
-		B[numnodes*2+i] = dbasis[2*numnodes+i];
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(dbasis);
-}/*}}}*/
-void EnthalpyAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
-	element->GetSolutionFromInputsOneDof(solution,EnthalpyEnum);
-}/*}}}*/
-void EnthalpyAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
-	_error_("Not implemented yet");
-}/*}}}*/
-void EnthalpyAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
-
-	bool        converged;
-	int         i,rheology_law;
-	IssmDouble  B_average,s_average,T_average=0.,P_average=0.;
-	int        *doflist   = NULL;
-	IssmDouble *xyz_list  = NULL;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes    = element->GetNumberOfNodes();
-
-	/*Fetch dof list and allocate solution vector*/
-	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	IssmDouble* values        = xNew<IssmDouble>(numnodes);
-	IssmDouble* pressure      = xNew<IssmDouble>(numnodes);
-	IssmDouble* surface       = xNew<IssmDouble>(numnodes);
-	IssmDouble* B             = xNew<IssmDouble>(numnodes);
-	IssmDouble* temperature   = xNew<IssmDouble>(numnodes);
-	IssmDouble* waterfraction = xNew<IssmDouble>(numnodes);
-
-	/*Use the dof list to index into the solution vector: */
-	for(i=0;i<numnodes;i++){
-		values[i]=solution[doflist[i]];
-
-		/*Check solution*/
-		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
-	}
-
-	/*Get all inputs and parameters*/
-	element->GetInputValue(&converged,ConvergedEnum);
-	element->GetInputListOnNodes(&pressure[0],PressureEnum);
-	if(converged){
-		for(i=0;i<numnodes;i++){
-			element->EnthalpyToThermal(&temperature[i],&waterfraction[i],values[i],pressure[i]);
-			if(waterfraction[i]<0.) _error_("Negative water fraction found in solution vector");
-			//if(waterfraction[i]>1.) _error_("Water fraction >1 found in solution vector");
-		}
-		element->AddInput(EnthalpyEnum,values,element->GetElementType());
-		element->AddInput(WaterfractionEnum,waterfraction,element->GetElementType());
-		element->AddInput(TemperatureEnum,temperature,element->GetElementType());
-
-		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
-		 * otherwise the rheology could be negative*/
-		element->FindParam(&rheology_law,MaterialsRheologyLawEnum);
-		element->GetInputListOnNodes(&surface[0],SurfaceEnum);
-		switch(rheology_law){
-			case NoneEnum:
-				/*Do nothing: B is not temperature dependent*/
-				break;
-			case CuffeyEnum:
-				for(i=0;i<numnodes;i++) B[i]=Cuffey(temperature[i]);
-				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
-				break;
-			case PatersonEnum:
-				for(i=0;i<numnodes;i++) B[i]=Paterson(temperature[i]);
-				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
-				break;
-			case ArrheniusEnum:
-				element->GetVerticesCoordinates(&xyz_list);
-				for(i=0;i<numnodes;i++) B[i]=Arrhenius(temperature[i],surface[i]-xyz_list[i*3+2],element->GetMaterialParameter(MaterialsRheologyNEnum));
-				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
-				break;
-			case LliboutryDuvalEnum:
-				for(i=0;i<numnodes;i++) B[i]=LliboutryDuval(values[i],pressure[i],element->GetMaterialParameter(MaterialsRheologyNEnum),element->GetMaterialParameter(MaterialsBetaEnum),element->GetMaterialParameter(ConstantsReferencetemperatureEnum),element->GetMaterialParameter(MaterialsHeatcapacityEnum),element->GetMaterialParameter(MaterialsLatentheatEnum)); 
-				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType()); 
-				break; 
-			default: _error_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
-		}
-	}
-	else{
-		element->AddInput(EnthalpyPicardEnum,values,element->GetElementType());
-	}
-
-	/*Free ressources:*/
-	xDelete<IssmDouble>(values);
-	xDelete<IssmDouble>(pressure);
-	xDelete<IssmDouble>(surface);
-	xDelete<IssmDouble>(B);
-	xDelete<IssmDouble>(temperature);
-	xDelete<IssmDouble>(waterfraction);
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<int>(doflist);
-}/*}}}*/
-void EnthalpyAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
-
-	bool islevelset;
-	femmodel->parameters->FindParam(&islevelset,TransientIslevelsetEnum);
-	if(islevelset){
-		SetActiveNodesLSMx(femmodel);
-	}
-	return;
-}/*}}}*/
-
-/*Modules*/
-void EnthalpyAnalysis::PostProcessing(FemModel* femmodel){/*{{{*/
-
-	/*Intermediaries*/
-	int solution_type, i;
-	bool computebasalmeltingrates=true;
-	bool isdrainage=true;
-	bool updatebasalconstraints=true;
-
-	if(isdrainage){
-		/*Drain excess water fraction in ice column: */
-		for(i=0;i<femmodel->elements->Size();i++){
-			Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-			DrainWaterfractionIcecolumn(element);
-		}
-	}
-
-	if(computebasalmeltingrates){
-		/*Compute basal melting rates: */
-		for(i=0;i<femmodel->elements->Size();i++){
-			Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-			ComputeBasalMeltingrate(element);
-		}
-	}
-
-	if(updatebasalconstraints){
-		/*Update basal dirichlet BCs for enthalpy in transient runs: */
-		femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-		if(solution_type==TransientSolutionEnum){
-			for(i=0;i<femmodel->elements->Size();i++){
-				Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-				UpdateBasalConstraints(element);
-			}
-		}
-	}
-}/*}}}*/
-void EnthalpyAnalysis::ComputeBasalMeltingrate(Element* element){/*{{{*/
-	/*Calculate the basal melt rates of the enthalpy model after Aschwanden 2012*/
-	/* melting rate is positive when melting, negative when refreezing*/
-
-	/* Check if ice in element */
-	if(!element->IsIceInElement()) return;
-
-	/* Only compute melt rates at the base of grounded ice*/
-	if(!element->IsOnBase() || element->IsFloating()) return;
-
-	/* Intermediaries */
-	const int   dim=3;
-	int         i,is,vertexdown,vertexup,numvertices,numsegments;
-	IssmDouble  heatflux;
-	IssmDouble  vec_heatflux[dim],normal_base[dim],d1enthalpy[dim];
-	IssmDouble  basalfriction,alpha2;
-	IssmDouble  dt,yts;
-	IssmDouble  melting_overshoot,lambda;
-	IssmDouble  geothermalflux;
-	IssmDouble  vx,vy,vz;
-	IssmDouble *xyz_list      = NULL;
-	IssmDouble *xyz_list_base = NULL;
-	int        *pairindices   = NULL;
-
-	/*Fetch parameters and inputs */
-	element->GetVerticesCoordinates(&xyz_list);
-	element->GetVerticesCoordinatesBase(&xyz_list_base);
-	IssmDouble latentheat = element->GetMaterialParameter(MaterialsLatentheatEnum);
-	IssmDouble rho_ice    = element->GetMaterialParameter(MaterialsRhoIceEnum);
-	IssmDouble rho_water  = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
-	Input* enthalpy_input         = element->GetInput(EnthalpyEnum);                    _assert_(enthalpy_input);
-	Input* geothermalflux_input   = element->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
-	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);
-	IssmDouble kappa=EnthalpyDiffusionParameterVolume(element,EnthalpyEnum);     _assert_(kappa>=0.);
-	element->NormalBase(&normal_base[0],xyz_list_base);
-	element->VerticalSegmentIndices(&pairindices,&numsegments);
-	IssmDouble* meltingrate_enthalpy = xNew<IssmDouble>(numsegments);
-	IssmDouble* heating = xNew<IssmDouble>(numsegments);	
-
-	/*Build friction element, needed later: */
-	Friction* friction=new Friction(element,dim);
-
-	/******** MELTING RATES  ************************************/
-	numvertices=element->GetNumberOfVertices();
-	IssmDouble* enthalpy = xNew<IssmDouble>(numvertices);
-	IssmDouble* pressure = xNew<IssmDouble>(numvertices);
-	IssmDouble* watercolumn = xNew<IssmDouble>(numvertices);
-	IssmDouble* basalmeltingrate = xNew<IssmDouble>(numvertices);
-	element->GetInputListOnVertices(enthalpy,EnthalpyEnum);
-	element->GetInputListOnVertices(pressure,PressureEnum);
-	element->GetInputListOnVertices(watercolumn,WatercolumnEnum);
-	element->GetInputListOnVertices(basalmeltingrate,BasalforcingsGroundediceMeltingRateEnum);
-
-	Gauss* gauss=element->NewGauss();
-	
-	for(int is=0;is<numsegments;is++){
-		vertexdown = pairindices[is*2+0];
-		vertexup   = pairindices[is*2+1];
-		gauss->GaussVertex(vertexdown);
-		
-		bool checkpositivethickness=true;
-		_assert_(watercolumn[vertexdown]>=0.);
-
-		/*Calculate basal meltingrate after Fig.5 of A.Aschwanden 2012*/
-		meltingrate_enthalpy[is]=0.;
-		heating[is]=0.;
-		if((watercolumn[vertexdown]>0.) && (enthalpy[vertexdown]<PureIceEnthalpy(element,pressure[vertexdown]))){
-			/*ensure that no ice is at T<Tm(p), if water layer present*/
-			enthalpy[vertexdown]=element->PureIceEnthalpy(pressure[vertexdown]); 
-		}
-		else if(enthalpy[vertexdown]<element->PureIceEnthalpy(pressure[vertexdown])){
-			/*cold base: set q*n=q_geo*n+frictionheating as Neumann BC in Penta::CreatePVectorEnthalpySheet*/
-			checkpositivethickness=false; // cold base, skip next test
-		}
-		else{/*we have a temperate base, go to next test*/}
-
-		if(checkpositivethickness){
-			/*From here on all basal ice is temperate. Check for positive thickness of layer of temperate ice. */
-			bool istemperatelayer=false;
-			if(enthalpy[vertexup]>=element->PureIceEnthalpy(pressure[vertexup])) istemperatelayer=true;
-			if(istemperatelayer) for(i=0;i<dim;i++) vec_heatflux[i]=0.; // TODO: add -k*nabla T_pmp
-			else{
-				enthalpy_input->GetInputDerivativeValue(&d1enthalpy[0],xyz_list,gauss);
-				for(i=0;i<3;i++) vec_heatflux[i]=-kappa*d1enthalpy[i];
-			}
-
-			/*heat flux along normal*/
-			heatflux=0.;
-			for(i=0;i<3;i++) heatflux+=(vec_heatflux[i])*normal_base[i];
-
-			/*basal friction*/
-			friction->GetAlpha2(&alpha2,gauss);
-			vx_input->GetInputValue(&vx,gauss);
-			vy_input->GetInputValue(&vy,gauss);
-			vz_input->GetInputValue(&vz,gauss);
-			basalfriction=alpha2*(vx*vx + vy*vy + vz*vz);
-
-			geothermalflux_input->GetInputValue(&geothermalflux,gauss);
-			/* -Mb= Fb-(q-q_geo)/((1-w)*L*rho), and (1-w)*rho=rho_ice, cf Aschwanden 2012, eqs.1, 2, 66*/
-			heating[is]=(heatflux+basalfriction+geothermalflux);
-			meltingrate_enthalpy[is]=heating[is]/(latentheat*rho_ice); // m/s water equivalent
-		}
-	}
-	/******** UPDATE MELTINGRATES AND WATERCOLUMN **************/
-	element->FindParam(&dt,TimesteppingTimeStepEnum);
-	for(is=0;is<numsegments;is++){
-		vertexdown = pairindices[is*2+0];
-		vertexup   = pairindices[is*2+1];
-		if(dt!=0.){
-			if(watercolumn[vertexdown]+meltingrate_enthalpy[is]*dt<0.){	// prevent too much freeze on			
-				lambda = -watercolumn[vertexdown]/(dt*meltingrate_enthalpy[is]); _assert_(lambda>=0.); _assert_(lambda<1.);
-				watercolumn[vertexdown]=0.;
-				basalmeltingrate[vertexdown]=lambda*meltingrate_enthalpy[is]; // restrict freeze on only to size of watercolumn
-				enthalpy[vertexdown]+=(1.-lambda)*meltingrate_enthalpy[is]*dt*latentheat; // use rest of energy to cool down base
-			}
-			else{
-				basalmeltingrate[vertexdown]=meltingrate_enthalpy[is];
-				watercolumn[vertexdown]+=dt*meltingrate_enthalpy[is]; 
-			}
-		}
-		else{
-			basalmeltingrate[vertexdown]=meltingrate_enthalpy[is];
-			watercolumn[vertexdown]+=meltingrate_enthalpy[is];
-		}	
-		basalmeltingrate[vertexdown]*=rho_water/rho_ice; // convert meltingrate from water to ice equivalent
-		_assert_(watercolumn[vertexdown]>=0.);
-	}
-
-	/*feed updated variables back into model*/
-	element->AddInput(EnthalpyEnum,enthalpy,P1Enum);
-	element->AddInput(WatercolumnEnum,watercolumn,P1Enum);
-	element->AddInput(BasalforcingsGroundediceMeltingRateEnum,basalmeltingrate,P1Enum);
-
-	/*Clean up and return*/
-	delete gauss;
-	delete friction;
-	xDelete<int>(pairindices);
-	xDelete<IssmDouble>(enthalpy);
-	xDelete<IssmDouble>(pressure);
-	xDelete<IssmDouble>(watercolumn);
-	xDelete<IssmDouble>(basalmeltingrate);
-	xDelete<IssmDouble>(meltingrate_enthalpy);
-	xDelete<IssmDouble>(heating);
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(xyz_list_base);
-}/*}}}*/
-void EnthalpyAnalysis::DrainWaterfractionIcecolumn(Element* element){/*{{{*/
-
-	/* Check if ice in element */
-	if(!element->IsIceInElement()) return;
-
-	/* Only drain waterfraction of ice column from element at base*/
-	if(!element->IsOnBase()) return; //FIXME: allow freeze on for floating elements
-
-	/* Intermediaries*/
-	int is, numvertices, numsegments;
-	int *pairindices   = NULL;
-
-	numvertices=element->GetNumberOfVertices();
-	element->VerticalSegmentIndices(&pairindices,&numsegments);
-
-	IssmDouble* watercolumn = xNew<IssmDouble>(numvertices);
-	IssmDouble* drainrate_column  = xNew<IssmDouble>(numsegments);
-	IssmDouble* drainrate_element = xNew<IssmDouble>(numsegments);
-
-	element->GetInputListOnVertices(watercolumn,WatercolumnEnum);
-
-	for(is=0;is<numsegments;is++)	drainrate_column[is]=0.;
-	Element* elementi = element;
-	for(;;){
-		for(is=0;is<numsegments;is++)	drainrate_element[is]=0.;
-		DrainWaterfraction(elementi,drainrate_element); // TODO: make sure every vertex is only drained once
-		for(is=0;is<numsegments;is++)	drainrate_column[is]+=drainrate_element[is];
-
-		if(elementi->IsOnSurface()) break;
-		elementi=elementi->GetUpperElement();			
-	}
-	/* add drained water to water column*/
-	for(is=0;is<numsegments;is++) watercolumn[is]+=drainrate_column[is];
-	/* Feed updated water column back into model */
-	element->AddInput(WatercolumnEnum,watercolumn,P1Enum);
-
-	xDelete<int>(pairindices);
-	xDelete<IssmDouble>(drainrate_column);
-	xDelete<IssmDouble>(drainrate_element);
-	xDelete<IssmDouble>(watercolumn);
-}/*}}}*/
-void EnthalpyAnalysis::DrainWaterfraction(Element* element, IssmDouble* pdrainrate_element){/*{{{*/
+void           EnthalpyAnalysis::DrainWaterfraction(FemModel* femmodel){/*{{{*/
+	/*Drain excess water fraction in ice column: */
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		DrainWaterfractionIcecolumn(element);
+	}
+}/*}}}*/
+void           EnthalpyAnalysis::DrainWaterfraction(Element* element, IssmDouble* pdrainrate_element){/*{{{*/
 
 	/* Check if ice in element */
@@ -1156,76 +1024,46 @@
 	xDelete<IssmDouble>(deltawaterfractions);
 }/*}}}*/
-void EnthalpyAnalysis::UpdateBasalConstraints(Element* element){/*{{{*/
+void           EnthalpyAnalysis::DrainWaterfractionIcecolumn(Element* element){/*{{{*/
 
 	/* Check if ice in element */
 	if(!element->IsIceInElement()) return;
 
-	/* Only update Constraints at the base of grounded ice*/
-	if(!(element->IsOnBase()) || element->IsFloating()) return;
-
-	/*Intermediary*/
-	bool        isdynamicbasalspc,setspc;
-	int         numindices, numindicesup;
-	IssmDouble  pressure, pressureup;
-	IssmDouble  h_pmp, enthalpy, enthalpyup;
-	IssmDouble  watercolumn;
-	int        *indices = NULL, *indicesup = NULL;
-	Node*       node = NULL;
-
-	/*Check wether dynamic basal boundary conditions are activated */
-	element->FindParam(&isdynamicbasalspc,ThermalIsdynamicbasalspcEnum);
-	if(!isdynamicbasalspc) return;
-
-	/*Fetch indices of basal & surface nodes for this finite element*/
-	Penta *penta =  (Penta *) element; // TODO: add Basal-/SurfaceNodeIndices to element.h, and change this to Element*
-	penta->BasalNodeIndices(&numindices,&indices,element->GetElementType());
-	penta->SurfaceNodeIndices(&numindicesup,&indicesup,element->GetElementType());
-	_assert_(numindices==numindicesup);
-
-	/*Get parameters and inputs: */
-	Input* pressure_input=element->GetInput(PressureEnum); _assert_(pressure_input);
-	Input* enthalpy_input=element->GetInput(EnthalpyEnum); _assert_(enthalpy_input);
-	Input* watercolumn_input=element->GetInput(WatercolumnEnum); _assert_(watercolumn_input);
-
-	/*if there is a temperate layer of zero thickness, set spc enthalpy=h_pmp at that node*/
-	GaussPenta* gauss=new GaussPenta();
-	GaussPenta* gaussup=new GaussPenta();
-	for(int i=0;i<numindices;i++){
-		gauss->GaussNode(element->GetElementType(),indices[i]);
-		gaussup->GaussNode(element->GetElementType(),indicesup[i]);
-
-		/*Check wether there is a temperate layer at the base or not */
-		/*check if node is temperate, else continue*/
-		enthalpy_input->GetInputValue(&enthalpy, gauss);
-		pressure_input->GetInputValue(&pressure, gauss);
-		watercolumn_input->GetInputValue(&watercolumn,gauss);
-		h_pmp=PureIceEnthalpy(element,pressure);
-		if (enthalpy>=h_pmp){
-			/*check if upper node is temperate, too.
-				if yes, then we have a temperate layer of positive thickness and reset the spc.
-				if not, apply dirichlet BC.*/
-			enthalpy_input->GetInputValue(&enthalpyup, gaussup);
-			pressure_input->GetInputValue(&pressureup, gaussup);
-			setspc=((enthalpyup<PureIceEnthalpy(element,pressureup)) && (watercolumn>=0.))?true:false;
-		}
-		else
-			setspc = false;
-
-		node=element->GetNode(indices[i]);
-		if(setspc) 
-			node->ApplyConstraint(0,h_pmp); /*apply spc*/ 
-		else			
-			node->DofInFSet(0); /*remove spc*/ 
-	}
-
-	/*Free ressources:*/
-	xDelete<int>(indices);
-	xDelete<int>(indicesup);
-	delete gauss;
-	delete gaussup;
-}/*}}}*/
-
-/*Intermediaries*/
-IssmDouble EnthalpyAnalysis::EnthalpyDiffusionParameter(Element* element,IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
+	/* Only drain waterfraction of ice column from element at base*/
+	if(!element->IsOnBase()) return; //FIXME: allow freeze on for floating elements
+
+	/* Intermediaries*/
+	int is, numvertices, numsegments;
+	int *pairindices   = NULL;
+
+	numvertices=element->GetNumberOfVertices();
+	element->VerticalSegmentIndices(&pairindices,&numsegments);
+
+	IssmDouble* watercolumn = xNew<IssmDouble>(numvertices);
+	IssmDouble* drainrate_column  = xNew<IssmDouble>(numsegments);
+	IssmDouble* drainrate_element = xNew<IssmDouble>(numsegments);
+
+	element->GetInputListOnVertices(watercolumn,WatercolumnEnum);
+
+	for(is=0;is<numsegments;is++)	drainrate_column[is]=0.;
+	Element* elementi = element;
+	for(;;){
+		for(is=0;is<numsegments;is++)	drainrate_element[is]=0.;
+		DrainWaterfraction(elementi,drainrate_element); // TODO: make sure every vertex is only drained once
+		for(is=0;is<numsegments;is++)	drainrate_column[is]+=drainrate_element[is];
+
+		if(elementi->IsOnSurface()) break;
+		elementi=elementi->GetUpperElement();			
+	}
+	/* add drained water to water column*/
+	for(is=0;is<numsegments;is++) watercolumn[is]+=drainrate_column[is];
+	/* Feed updated water column back into model */
+	element->AddInput(WatercolumnEnum,watercolumn,P1Enum);
+
+	xDelete<int>(pairindices);
+	xDelete<IssmDouble>(drainrate_column);
+	xDelete<IssmDouble>(drainrate_element);
+	xDelete<IssmDouble>(watercolumn);
+}/*}}}*/
+IssmDouble     EnthalpyAnalysis::EnthalpyDiffusionParameter(Element* element,IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
 
 	IssmDouble heatcapacity             = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
@@ -1240,5 +1078,5 @@
 	}
 }/*}}}*/
-IssmDouble EnthalpyAnalysis::EnthalpyDiffusionParameterVolume(Element* element,int enthalpy_enum){/*{{{*/
+IssmDouble     EnthalpyAnalysis::EnthalpyDiffusionParameterVolume(Element* element,int enthalpy_enum){/*{{{*/
 
 	int         iv;
@@ -1295,5 +1133,404 @@
 	return kappa;
 }/*}}}*/
-IssmDouble EnthalpyAnalysis::PureIceEnthalpy(Element* element,IssmDouble pressure){/*{{{*/
+void           EnthalpyAnalysis::GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_advec =[ h ]
+	 *                 [ h ]
+	 *                 [ h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
+		B[numnodes*2+i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void           EnthalpyAnalysis::GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Biprime_advec=[ dh/dx ]
+	 *                     [ dh/dy ]
+	 *                     [ dh/dz ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = dbasis[0*numnodes+i];
+		B[numnodes*1+i] = dbasis[1*numnodes+i];
+		B[numnodes*2+i] = dbasis[2*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void           EnthalpyAnalysis::GetBasalConstraints(Vector<IssmDouble>* vec_spc,Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return;
+
+	/* Only update Constraints at the base of grounded ice*/
+	if(!(element->IsOnBase()) || element->IsFloating()) return;
+
+	/*Intermediary*/
+	bool        isdynamicbasalspc;
+	IssmDouble	dt;
+
+	/*Check wether dynamic basal boundary conditions are activated */
+	element->FindParam(&isdynamicbasalspc,ThermalIsdynamicbasalspcEnum);
+	if(!isdynamicbasalspc) return;
+
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	if(dt==0.){
+		GetBasalConstraintsSteadystate(vec_spc,element);
+	}
+	else{
+		GetBasalConstraintsTransient(vec_spc,element);
+	}
+}/*}}}*/
+void           EnthalpyAnalysis::GetBasalConstraintsSteadystate(Vector<IssmDouble>* vec_spc,Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return;
+
+	/* Only update Constraints at the base of grounded ice*/
+	if(!(element->IsOnBase()) || element->IsFloating()) return;
+
+	/*Intermediary*/
+	int         numindices, numindicesup, state;
+	int        *indices = NULL, *indicesup = NULL;
+	IssmDouble	enthalpy, enthalpyup, pressure, pressureup, watercolumn, meltingrate;
+
+	/*Get parameters and inputs: */
+	Input* enthalpy_input		 = element->GetInput(EnthalpyPicardEnum);					 _assert_(enthalpy_input);
+	Input* pressure_input		 = element->GetInput(PressureEnum);							 _assert_(pressure_input);
+	Input* watercolumn_input	 = element->GetInput(WatercolumnEnum);							 _assert_(watercolumn_input);
+	Input* meltingrate_input	 = element->GetInput(BasalforcingsGroundediceMeltingRateEnum);							 _assert_(meltingrate_input);
+
+	/*Fetch indices of basal & surface nodes for this finite element*/
+	Penta *penta =  (Penta *) element; // TODO: add Basal-/SurfaceNodeIndices to element.h, and change this to Element*
+	penta->BasalNodeIndices(&numindices,&indices,element->GetElementType());
+	penta->SurfaceNodeIndices(&numindicesup,&indicesup,element->GetElementType());	_assert_(numindices==numindicesup);
+
+	GaussPenta* gauss=new GaussPenta();
+	GaussPenta* gaussup=new GaussPenta();
+	for(int i=0;i<numindices;i++){
+		gauss->GaussNode(element->GetElementType(),indices[i]);
+		gaussup->GaussNode(element->GetElementType(),indicesup[i]);
+
+		enthalpy_input->GetInputValue(&enthalpy,gauss);
+		enthalpy_input->GetInputValue(&enthalpyup,gaussup);
+		pressure_input->GetInputValue(&pressure,gauss);
+		pressure_input->GetInputValue(&pressureup,gaussup);
+		watercolumn_input->GetInputValue(&watercolumn,gauss);
+		meltingrate_input->GetInputValue(&meltingrate,gauss);
+
+		state=GetThermalBasalCondition(element, enthalpy, enthalpyup, pressure, pressureup, watercolumn, meltingrate);
+		switch (state) {
+			case 0:
+				// cold, dry base: apply basal surface forcing
+				vec_spc->SetValue(element->nodes[i]->Sid(),0.,INS_VAL);
+				break;
+			case 1:
+				// cold, wet base: keep at pressure melting point 
+				vec_spc->SetValue(element->nodes[i]->Sid(),1.,INS_VAL);
+				break;
+			case 2:
+				// temperate, thin refreezing base: release spc
+				vec_spc->SetValue(element->nodes[i]->Sid(),0.,INS_VAL);
+				break;
+			case 3:
+				// temperate, thin melting base: set spc
+				vec_spc->SetValue(element->nodes[i]->Sid(),1.,INS_VAL);
+				break;
+			case 4:
+				// temperate, thick melting base: s
+				vec_spc->SetValue(element->nodes[i]->Sid(),1.,INS_VAL);
+				break;
+			default:
+				_printf0_("	unknown thermal basal state found!");
+		}
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(indices);
+	xDelete<int>(indicesup);
+	delete gauss;
+	delete gaussup;
+}/*}}}*/
+void           EnthalpyAnalysis::GetBasalConstraintsTransient(Vector<IssmDouble>* vec_spc,Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return;
+
+	/* Only update Constraints at the base of grounded ice*/
+	if(!(element->IsOnBase()) || element->IsFloating()) return;
+
+	/*Intermediary*/
+	int         numindices, numindicesup, state;
+	int        *indices = NULL, *indicesup = NULL;
+	IssmDouble	enthalpy, enthalpyup, pressure, pressureup, watercolumn, meltingrate;
+
+	/*Get parameters and inputs: */
+	Input* enthalpy_input       = element->GetInput(EnthalpyEnum);                    _assert_(enthalpy_input); //TODO: check EnthalpyPicard?
+	Input* pressure_input		 = element->GetInput(PressureEnum);							 _assert_(pressure_input);
+	Input* watercolumn_input	 = element->GetInput(WatercolumnEnum);							 _assert_(watercolumn_input);
+	Input* meltingrate_input	 = element->GetInput(BasalforcingsGroundediceMeltingRateEnum);							 _assert_(meltingrate_input);
+
+	/*Fetch indices of basal & surface nodes for this finite element*/
+	Penta *penta =  (Penta *) element; // TODO: add Basal-/SurfaceNodeIndices to element.h, and change this to Element*
+	penta->BasalNodeIndices(&numindices,&indices,element->GetElementType());
+	penta->SurfaceNodeIndices(&numindicesup,&indicesup,element->GetElementType());	_assert_(numindices==numindicesup);
+
+	GaussPenta* gauss=new GaussPenta();
+	GaussPenta* gaussup=new GaussPenta();
+
+	for(int i=0;i<numindices;i++){
+		gauss->GaussNode(element->GetElementType(),indices[i]);
+		gaussup->GaussNode(element->GetElementType(),indicesup[i]);
+		
+		enthalpy_input->GetInputValue(&enthalpy,gauss);
+		enthalpy_input->GetInputValue(&enthalpyup,gaussup);
+		pressure_input->GetInputValue(&pressure,gauss);
+		pressure_input->GetInputValue(&pressureup,gaussup);
+		watercolumn_input->GetInputValue(&watercolumn,gauss);
+		meltingrate_input->GetInputValue(&meltingrate,gauss);
+
+		state=GetThermalBasalCondition(element, enthalpy, enthalpyup, pressure, pressureup, watercolumn, meltingrate);
+
+		switch (state) {
+			case 0:
+				// cold, dry base: apply basal surface forcing
+				vec_spc->SetValue(element->nodes[i]->Sid(),0.,INS_VAL);
+				break;
+			case 1:
+				// cold, wet base: keep at pressure melting point 
+				vec_spc->SetValue(element->nodes[i]->Sid(),1.,INS_VAL);
+				break;
+			case 2:
+				// temperate, thin refreezing base: release spc
+				vec_spc->SetValue(element->nodes[i]->Sid(),0.,INS_VAL);
+				break;
+			case 3:
+				// temperate, thin melting base: set spc
+				vec_spc->SetValue(element->nodes[i]->Sid(),1.,INS_VAL);
+				break;
+			case 4:
+				// temperate, thick melting base: set grad H*n=0
+				vec_spc->SetValue(element->nodes[i]->Sid(),0.,INS_VAL);
+				break;
+			default:
+				_printf0_("	unknown thermal basal state found!");
+		}
+
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(indices);
+	xDelete<int>(indicesup);
+	delete gauss;
+	delete gaussup;
+}/*}}}*/
+void           EnthalpyAnalysis::GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_conduct=[ dh/dx ]
+	 *                  [ dh/dy ]
+	 *                  [ dh/dz ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = dbasis[0*numnodes+i];
+		B[numnodes*1+i] = dbasis[1*numnodes+i];
+		B[numnodes*2+i] = dbasis[2*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void           EnthalpyAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	element->GetSolutionFromInputsOneDof(solution,EnthalpyEnum);
+}/*}}}*/
+int            EnthalpyAnalysis::GetThermalBasalCondition(Element* element, IssmDouble enthalpy, IssmDouble enthalpyup, IssmDouble pressure, IssmDouble pressureup, IssmDouble watercolumn, IssmDouble meltingrate){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return -1;
+
+	/* Only update Constraints at the base of grounded ice*/
+	if(!(element->IsOnBase())) return -1;
+
+	/*Intermediary*/
+	int state=-1;
+	IssmDouble	dt;
+
+	/*Get parameters and inputs: */
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+
+	if(enthalpy<PureIceEnthalpy(element,pressure)){
+		if(watercolumn<=0.) state=0; // cold, dry base
+		else state=1; // cold, wet base (refreezing)
+	}
+	else{
+		if(enthalpyup<PureIceEnthalpy(element,pressureup)){
+			if((dt==0.) && (meltingrate<0.)) state=2;	// refreezing temperate base (non-physical, only for steadystate solver)
+			else	state=3; // temperate base, but no temperate layer
+		}
+		else state=4; // temperate layer with positive thickness
+	}
+
+	_assert_(state>=0);
+	return state;
+}/*}}}*/
+IssmDouble     EnthalpyAnalysis::GetWetIceConductivity(Element* element, IssmDouble enthalpy, IssmDouble pressure){/*{{{*/
+
+	IssmDouble temperature, waterfraction;
+	IssmDouble kappa_w = 0.6; // thermal conductivity of water (in W/m/K)
+	IssmDouble kappa_i = element->GetMaterialParameter(MaterialsThermalconductivityEnum);
+	element->EnthalpyToThermal(&temperature, &waterfraction, enthalpy, pressure);
+
+	return (1.-waterfraction)*kappa_i + waterfraction*kappa_w;
+}/*}}}*/
+void           EnthalpyAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void           EnthalpyAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+
+	bool        converged;
+	int         i,rheology_law;
+	IssmDouble  B_average,s_average,T_average=0.,P_average=0.;
+	int        *doflist   = NULL;
+	IssmDouble *xyz_list  = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes    = element->GetNumberOfNodes();
+
+	/*Fetch dof list and allocate solution vector*/
+	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values        = xNew<IssmDouble>(numnodes);
+	IssmDouble* pressure      = xNew<IssmDouble>(numnodes);
+	IssmDouble* surface       = xNew<IssmDouble>(numnodes);
+	IssmDouble* B             = xNew<IssmDouble>(numnodes);
+	IssmDouble* temperature   = xNew<IssmDouble>(numnodes);
+	IssmDouble* waterfraction = xNew<IssmDouble>(numnodes);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numnodes;i++){
+		values[i]=solution[doflist[i]];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get all inputs and parameters*/
+	element->GetInputValue(&converged,ConvergedEnum);
+	element->GetInputListOnNodes(&pressure[0],PressureEnum);
+	if(converged){
+		for(i=0;i<numnodes;i++){
+			element->EnthalpyToThermal(&temperature[i],&waterfraction[i],values[i],pressure[i]);
+			if(waterfraction[i]<0.) _error_("Negative water fraction found in solution vector");
+			//if(waterfraction[i]>1.) _error_("Water fraction >1 found in solution vector");
+		}
+		element->AddInput(EnthalpyEnum,values,element->GetElementType());
+		element->AddInput(WaterfractionEnum,waterfraction,element->GetElementType());
+		element->AddInput(TemperatureEnum,temperature,element->GetElementType());
+
+		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
+		 * otherwise the rheology could be negative*/
+		element->FindParam(&rheology_law,MaterialsRheologyLawEnum);
+		element->GetInputListOnNodes(&surface[0],SurfaceEnum);
+		switch(rheology_law){
+			case NoneEnum:
+				/*Do nothing: B is not temperature dependent*/
+				break;
+			case CuffeyEnum:
+				for(i=0;i<numnodes;i++) B[i]=Cuffey(temperature[i]);
+				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
+				break;
+			case PatersonEnum:
+				for(i=0;i<numnodes;i++) B[i]=Paterson(temperature[i]);
+				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
+				break;
+			case ArrheniusEnum:
+				element->GetVerticesCoordinates(&xyz_list);
+				for(i=0;i<numnodes;i++) B[i]=Arrhenius(temperature[i],surface[i]-xyz_list[i*3+2],element->GetMaterialParameter(MaterialsRheologyNEnum));
+				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType());
+				break;
+			case LliboutryDuvalEnum:
+				for(i=0;i<numnodes;i++) B[i]=LliboutryDuval(values[i],pressure[i],element->GetMaterialParameter(MaterialsRheologyNEnum),element->GetMaterialParameter(MaterialsBetaEnum),element->GetMaterialParameter(ConstantsReferencetemperatureEnum),element->GetMaterialParameter(MaterialsHeatcapacityEnum),element->GetMaterialParameter(MaterialsLatentheatEnum)); 
+				element->AddInput(MaterialsRheologyBEnum,&B[0],element->GetElementType()); 
+				break; 
+			default: _error_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
+		}
+	}
+	else{
+		element->AddInput(EnthalpyPicardEnum,values,element->GetElementType());
+	}
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(surface);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(temperature);
+	xDelete<IssmDouble>(waterfraction);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<int>(doflist);
+}/*}}}*/
+void           EnthalpyAnalysis::PostProcessing(FemModel* femmodel){/*{{{*/
+
+	/*Intermediaries*/
+	bool computebasalmeltingrates=true;
+	bool drainicecolumn=true;
+	bool isdynamicbasalspc;
+	IssmDouble dt;
+
+	femmodel->parameters->FindParam(&isdynamicbasalspc,ThermalIsdynamicbasalspcEnum);
+	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+
+	//TODO: use dt to decide what to do
+	if(drainicecolumn)	DrainWaterfraction(femmodel);
+	if(computebasalmeltingrates)	ComputeBasalMeltingrate(femmodel);
+	if(isdynamicbasalspc)	UpdateBasalConstraints(femmodel);
+
+}/*}}}*/
+IssmDouble     EnthalpyAnalysis::PureIceEnthalpy(Element* element,IssmDouble pressure){/*{{{*/
 
 	IssmDouble heatcapacity         = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
@@ -1302,5 +1539,5 @@
 	return heatcapacity*(TMeltingPoint(element,pressure)-referencetemperature);
 }/*}}}*/
-IssmDouble EnthalpyAnalysis::TMeltingPoint(Element* element,IssmDouble pressure){/*{{{*/
+IssmDouble     EnthalpyAnalysis::TMeltingPoint(Element* element,IssmDouble pressure){/*{{{*/
 
 	IssmDouble meltingpoint = element->GetMaterialParameter(MaterialsMeltingpointEnum);
@@ -1309,2 +1546,40 @@
 	return meltingpoint-beta*pressure;
 }/*}}}*/
+void           EnthalpyAnalysis::UpdateBasalConstraints(FemModel* femmodel){/*{{{*/
+
+	/*Update basal dirichlet BCs for enthalpy: */
+	Vector<IssmDouble>* spc           = NULL;
+	IssmDouble*         serial_spc    = NULL;
+
+	spc=new Vector<IssmDouble>(femmodel->nodes->NumberOfNodes(EnthalpyAnalysisEnum));
+	/*First create a vector to figure out what elements should be constrained*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		GetBasalConstraints(spc,element);
+	}
+
+	/*Assemble and serialize*/
+	spc->Assemble();
+	serial_spc=spc->ToMPISerial();
+	delete spc;
+
+	/*Then update basal constraints nodes accordingly*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		ApplyBasalConstraints(serial_spc,element);
+	}
+
+	femmodel->UpdateConstraintsx();
+
+	/*Delete*/
+	xDelete<IssmDouble>(serial_spc);
+}/*}}}*/
+void           EnthalpyAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+
+	bool islevelset;
+	femmodel->parameters->FindParam(&islevelset,TransientIslevelsetEnum);
+	if(islevelset){
+		SetActiveNodesLSMx(femmodel);
+	}
+	return;
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/EnthalpyAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/EnthalpyAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/EnthalpyAnalysis.h	(revision 19105)
@@ -8,4 +8,5 @@
 /*Headers*/
 #include "./Analysis.h"
+#include "../classes/classes.h"
 
 class EnthalpyAnalysis: public Analysis{
@@ -13,42 +14,46 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,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);
-		ElementVector* CreateDVector(Element* element);
-		ElementMatrix* CreateJacobianMatrix(Element* element);
-		ElementMatrix* CreateKMatrix(Element* element);
-		ElementMatrix* CreateKMatrixVolume(Element* element);
-		ElementMatrix* CreateKMatrixShelf(Element* element);
-		ElementVector* CreatePVector(Element* element);
-		ElementVector* CreatePVectorVolume(Element* element);
-		ElementVector* CreatePVectorSheet(Element* element);
-		ElementVector* CreatePVectorShelf(Element* element);
-		void GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
-
-		/*Modules*/
-		static void PostProcessing(FemModel* femmodel);
-		static void ComputeBasalMeltingrate(Element* element);
-		static void DrainWaterfractionIcecolumn(Element* element);
-		static void DrainWaterfraction(Element* element, IssmDouble* pdrainrate_element);
-		static void UpdateBasalConstraints(Element* element);
-
-		/*Intermediaries*/
+		static void       ApplyBasalConstraints(IssmDouble* serial_spc,Element* element);
+		static void       ComputeBasalMeltingrate(FemModel* femmodel);
+		static void       ComputeBasalMeltingrate(Element* element);
+		void              Core(FemModel* femmodel);
+		ElementVector*    CreateDVector(Element* element);
+		ElementMatrix*    CreateJacobianMatrix(Element* element);
+		ElementMatrix*    CreateKMatrix(Element* element);
+		ElementMatrix*    CreateKMatrixVolume(Element* element);
+		ElementMatrix*    CreateKMatrixShelf(Element* element);
+		ElementVector*    CreatePVector(Element* element);
+		ElementVector*    CreatePVectorVolume(Element* element);
+		ElementVector*    CreatePVectorSheet(Element* element);
+		ElementVector*    CreatePVectorShelf(Element* element);
+		static void       DrainWaterfraction(FemModel* femmodel);
+		static void       DrainWaterfraction(Element* element, IssmDouble* pdrainrate_element);
+		static void       DrainWaterfractionIcecolumn(Element* element);
 		static IssmDouble EnthalpyDiffusionParameter(Element* element,IssmDouble enthalpy,IssmDouble pressure);
 		static IssmDouble EnthalpyDiffusionParameterVolume(Element* element,int enthalpy_enum);
+		void              GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void              GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		static void       GetBasalConstraints(Vector<IssmDouble>* vec_spc,Element* element);
+		static void       GetBasalConstraintsSteadystate(Vector<IssmDouble>* vec_spc,Element* element);
+		static void       GetBasalConstraintsTransient(Vector<IssmDouble>* vec_spc,Element* element);
+		void              GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void              GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		static int        GetThermalBasalCondition(Element* element, IssmDouble enthalpy, IssmDouble enthalpy_up, IssmDouble pressure, IssmDouble pressure_up, IssmDouble watercolumn, IssmDouble meltingrate);
+		static IssmDouble GetWetIceConductivity(Element* element, IssmDouble enthalpy, IssmDouble pressure);
+		void              GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void              InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		static void       PostProcessing(FemModel* femmodel);
 		static IssmDouble PureIceEnthalpy(Element* element,IssmDouble pressure);
 		static IssmDouble TMeltingPoint(Element* element,IssmDouble pressure);
+		static void       UpdateBasalConstraints(FemModel* femmodel);
+		void              UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/EnumToAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnumToAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/EnumToAnalysis.cpp	(revision 19105)
@@ -86,9 +86,6 @@
 		case DepthAverageAnalysisEnum : return new DepthAverageAnalysis();
 		#endif
-		#ifdef _HAVE_SMOOTHEDSURFACESLOPEX_
-		case SmoothedSurfaceSlopeXAnalysisEnum : return new SmoothedSurfaceSlopeXAnalysis();
-		#endif
-		#ifdef _HAVE_SMOOTHEDSURFACESLOPEY_
-		case SmoothedSurfaceSlopeYAnalysisEnum : return new SmoothedSurfaceSlopeYAnalysis();
+		#ifdef _HAVE_SMOOTH_
+		case SmoothAnalysisEnum : return new SmoothAnalysis();
 		#endif
 		#ifdef _HAVE_THERMAL_
Index: /issm/trunk/src/c/analyses/ExtrapolationAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ExtrapolationAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/ExtrapolationAnalysis.cpp	(revision 19105)
@@ -6,11 +6,22 @@
 #include "../solutionsequences/solutionsequences.h"
 
-int ExtrapolationAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+void ExtrapolationAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	// do nothing for now
+	return;
+}
+/*}}}*/
+void ExtrapolationAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	//	do nothing for now
+	return;
+}/*}}}*/
+void ExtrapolationAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	int finiteelement=P1Enum;
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,ExtrapolationAnalysisEnum,finiteelement);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}
+/*}}}*/
+int  ExtrapolationAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}
-/*}}}*/
-void ExtrapolationAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-	//do nothing for now
-	return;
 }
 /*}}}*/
@@ -36,23 +47,12 @@
 }
 /*}}}*/
-void ExtrapolationAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-	int finiteelement=P1Enum;
-	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	::CreateNodes(nodes,iomodel,ExtrapolationAnalysisEnum,finiteelement);
-	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-}
-/*}}}*/
-void ExtrapolationAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-	// do nothing for now
+void ExtrapolationAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+	//do nothing for now
 	return;
 }
 /*}}}*/
-void ExtrapolationAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-	//	do nothing for now
-	return;
-}/*}}}*/
 
 /*Finite element Analysis*/
-void ExtrapolationAnalysis::Core(FemModel* femmodel){/*{{{*/
+void           ExtrapolationAnalysis::Core(FemModel* femmodel){/*{{{*/
 
 	/* Intermediaries */
@@ -237,11 +237,66 @@
 	return pe;
 }/*}}}*/
-void ExtrapolationAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           ExtrapolationAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void           ExtrapolationAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		Bprime[numnodes*0+i] = dbasis[0*numnodes+i];
+		Bprime[numnodes*1+i] = dbasis[1*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+void           ExtrapolationAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	_error_("not implemented yet");
 }/*}}}*/
-void ExtrapolationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           ExtrapolationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void ExtrapolationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           ExtrapolationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int domaintype, extrapolationvariable;
@@ -258,60 +313,5 @@
 	}
 }/*}}}*/
-void ExtrapolationAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
-	 * For node i, Bi can be expressed in the actual coordinate system
-	 * by: 
-	 *       Bi=[ N ]
-	 *          [ N ]
-	 * where N is the finiteelement function for node i.
-	 *
-	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions*/
-	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	element->NodalFunctions(basis,gauss);
-
-	/*Build B: */
-	for(int i=0;i<numnodes;i++){
-		B[numnodes*0+i] = basis[i];
-		B[numnodes*1+i] = basis[i];
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(basis);
-}/*}}}*/
-void ExtrapolationAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
-	 * For node i, Bi' can be expressed in the actual coordinate system
-	 * by: 
-	 *       Bi_prime=[ dN/dx ]
-	 *                [ dN/dy ]
-	 * where N is the finiteelement function for node i.
-	 *
-	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
-	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-	/*Build B': */
-	for(int i=0;i<numnodes;i++){
-		Bprime[numnodes*0+i] = dbasis[0*numnodes+i];
-		Bprime[numnodes*1+i] = dbasis[1*numnodes+i];
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(dbasis);
-
-}/*}}}*/
-void ExtrapolationAnalysis::SetConstraintsOnIce(Element* element){/*{{{*/
+void           ExtrapolationAnalysis::SetConstraintsOnIce(Element* element){/*{{{*/
 
 	int numnodes=element->GetNumberOfNodes();	
@@ -347,8 +347,8 @@
 	delete gauss;
 }/*}}}*/
-void ExtrapolationAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           ExtrapolationAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		this->SetConstraintsOnIce(element);
 	}
Index: /issm/trunk/src/c/analyses/ExtrapolationAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/ExtrapolationAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/ExtrapolationAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
  public:
 	/*Model processing*/
-	int  DofsPerNode(int** doflist,int domaintype,int approximation);
-	void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-	void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-	void CreateNodes(Nodes* nodes,IoModel* iomodel);
 	void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 	void CreateLoads(Loads* loads, IoModel* iomodel);
+	void CreateNodes(Nodes* nodes,IoModel* iomodel);
+	int  DofsPerNode(int** doflist,int domaintype,int approximation);
+	void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+	void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 	/*Finite element Analysis*/
@@ -26,11 +26,11 @@
 	ElementMatrix* CreateKMatrix(Element* element);
 	ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-	void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-	void UpdateConstraints(FemModel* femmodel);
-	void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-	void GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-	void SetConstraintsOnIce(Element* element);
+	void           GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+	void           GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+	void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+	void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+	void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+	void           SetConstraintsOnIce(Element* element);
+	void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.cpp	(revision 19105)
@@ -6,8 +6,15 @@
 
 /*Model processing*/
+void ExtrudeFromBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void ExtrudeFromBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	::CreateNodes(nodes,iomodel,ExtrudeFromBaseAnalysisEnum,P1Enum);
+
+}/*}}}*/
 int  ExtrudeFromBaseAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void ExtrudeFromBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 void ExtrudeFromBaseAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -26,12 +33,5 @@
 	}
 }/*}}}*/
-void ExtrudeFromBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	::CreateNodes(nodes,iomodel,ExtrudeFromBaseAnalysisEnum,P1Enum);
-
-}/*}}}*/
-void ExtrudeFromBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-}/*}}}*/
-void ExtrudeFromBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+void ExtrudeFromBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 
@@ -61,4 +61,94 @@
 	return Ke;
 }/*}}}*/
+ElementMatrix* ExtrudeFromBaseAnalysis::CreateKMatrixBed(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+
+	/*Intermediaries */
+	int         dim;
+	IssmDouble  Jdet,D,normal[3];
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Get dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*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);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->NormalBase(&normal[0],xyz_list_base);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+		D = - gauss->weight*Jdet*normal[dim-1]; 
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* ExtrudeFromBaseAnalysis::CreateKMatrixSurface(Element* element){/*{{{*/
+
+	if(!element->IsOnSurface()) return NULL;
+
+	/*Intermediaries */
+	int         dim;
+	IssmDouble  Jdet,D,normal[3];
+	IssmDouble *xyz_list_top = NULL;
+
+	/*Get dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*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);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesTop(&xyz_list_top);
+	element->NormalTop(&normal[0],xyz_list_top);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussTop(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantTop(&Jdet,xyz_list_top,gauss);
+		element->NodalFunctions(basis,gauss);
+		D = - gauss->weight*Jdet*normal[dim-1]; 
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list_top);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
 ElementMatrix* ExtrudeFromBaseAnalysis::CreateKMatrixVolume(Element* element){/*{{{*/
 
@@ -106,98 +196,8 @@
 }
 /*}}}*/
-ElementMatrix* ExtrudeFromBaseAnalysis::CreateKMatrixSurface(Element* element){/*{{{*/
-
-	if(!element->IsOnSurface()) return NULL;
-
-	/*Intermediaries */
-	int         dim;
-	IssmDouble  Jdet,D,normal[3];
-	IssmDouble *xyz_list_top = NULL;
-
-	/*Get dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
-
-	/*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);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinatesTop(&xyz_list_top);
-	element->NormalTop(&normal[0],xyz_list_top);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGaussTop(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminantTop(&Jdet,xyz_list_top,gauss);
-		element->NodalFunctions(basis,gauss);
-		D = - gauss->weight*Jdet*normal[dim-1]; 
-
-		TripleMultiply(basis,1,numnodes,1,
-					&D,1,1,0,
-					basis,1,numnodes,0,
-					&Ke->values[0],1);
-	}
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list_top);
-	xDelete<IssmDouble>(basis);
-	delete gauss;
-	return Ke;
-}
-/*}}}*/
-ElementMatrix* ExtrudeFromBaseAnalysis::CreateKMatrixBed(Element* element){/*{{{*/
-
-	if(!element->IsOnBase()) return NULL;
-
-	/*Intermediaries */
-	int         dim;
-	IssmDouble  Jdet,D,normal[3];
-	IssmDouble *xyz_list_base = NULL;
-
-	/*Get dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
-
-	/*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);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinatesBase(&xyz_list_base);
-	element->NormalBase(&normal[0],xyz_list_base);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGaussBase(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-		element->NodalFunctions(basis,gauss);
-		D = - gauss->weight*Jdet*normal[dim-1]; 
-
-		TripleMultiply(basis,1,numnodes,1,
-					&D,1,1,0,
-					basis,1,numnodes,0,
-					&Ke->values[0],1);
-	}
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list_base);
-	xDelete<IssmDouble>(basis);
-	delete gauss;
-	return Ke;
-}
-/*}}}*/
 ElementVector* ExtrudeFromBaseAnalysis::CreatePVector(Element* element){/*{{{*/
 	return NULL;
 }/*}}}*/
-void ExtrudeFromBaseAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           ExtrudeFromBaseAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
 		where hi is the interpolation function for node i.*/
@@ -219,11 +219,11 @@
 }
 /*}}}*/
-void ExtrudeFromBaseAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           ExtrudeFromBaseAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void ExtrudeFromBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           ExtrudeFromBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void ExtrudeFromBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           ExtrudeFromBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int inputenum;
@@ -231,5 +231,5 @@
 	element->InputUpdateFromSolutionOneDof(solution,inputenum);
 }/*}}}*/
-void ExtrudeFromBaseAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           ExtrudeFromBaseAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/ExtrudeFromBaseAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -25,13 +25,13 @@
 		ElementMatrix* CreateJacobianMatrix(Element* element);
 		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixBed(Element* element);
+		ElementMatrix* CreateKMatrixSurface(Element* element);
 		ElementMatrix* CreateKMatrixVolume(Element* element);
-		ElementMatrix* CreateKMatrixSurface(Element* element);
-		ElementMatrix* CreateKMatrixBed(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.cpp	(revision 19105)
@@ -6,8 +6,15 @@
 
 /*Model processing*/
+void ExtrudeFromTopAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void ExtrudeFromTopAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void ExtrudeFromTopAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	::CreateNodes(nodes,iomodel,ExtrudeFromTopAnalysisEnum,P1Enum);
+
+}/*}}}*/
 int  ExtrudeFromTopAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void ExtrudeFromTopAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 void ExtrudeFromTopAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -26,12 +33,5 @@
 	}
 }/*}}}*/
-void ExtrudeFromTopAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	::CreateNodes(nodes,iomodel,ExtrudeFromTopAnalysisEnum,P1Enum);
-
-}/*}}}*/
-void ExtrudeFromTopAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-}/*}}}*/
-void ExtrudeFromTopAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+void ExtrudeFromTopAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 
@@ -199,5 +199,5 @@
 	return NULL;
 }/*}}}*/
-void ExtrudeFromTopAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           ExtrudeFromTopAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
 		where hi is the interpolation function for node i.*/
@@ -219,11 +219,11 @@
 }
 /*}}}*/
-void ExtrudeFromTopAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           ExtrudeFromTopAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void ExtrudeFromTopAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           ExtrudeFromTopAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void ExtrudeFromTopAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           ExtrudeFromTopAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int inputenum;
@@ -231,5 +231,5 @@
 	element->InputUpdateFromSolutionOneDof(solution,inputenum);
 }/*}}}*/
-void ExtrudeFromTopAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           ExtrudeFromTopAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/ExtrudeFromTopAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -25,13 +25,13 @@
 		ElementMatrix* CreateJacobianMatrix(Element* element);
 		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixBed(Element* element);
+		ElementMatrix* CreateKMatrixSurface(Element* element);
 		ElementMatrix* CreateKMatrixVolume(Element* element);
-		ElementMatrix* CreateKMatrixSurface(Element* element);
-		ElementMatrix* CreateKMatrixBed(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp	(revision 19105)
@@ -6,8 +6,55 @@
 
 /*Model processing*/
+void FreeSurfaceBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	int penpair_ids[2];
+	int count=0;
+	int numvertex_pairing;
+
+	/*Create Penpair for vertex_pairing: */
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonbase=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
+	for(int i=0;i<numvertex_pairing;i++){
+
+		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
+
+			/*Skip if one of the two is not on the bed*/
+			if(iomodel->domaintype!=Domain2DhorizontalEnum){
+				if(!(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
+			}
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(
+							iomodel->loadcounter+count+1,
+							&penpair_ids[0],
+							FreeSurfaceBaseAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
+	iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
+}/*}}}*/
+void FreeSurfaceBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,FreeSurfaceBaseAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
 int  FreeSurfaceBaseAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void FreeSurfaceBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 void FreeSurfaceBaseAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -43,52 +90,5 @@
 	}
 }/*}}}*/
-void FreeSurfaceBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	::CreateNodes(nodes,iomodel,FreeSurfaceBaseAnalysisEnum,P1Enum);
-	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-}/*}}}*/
-void FreeSurfaceBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-}/*}}}*/
-void FreeSurfaceBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
-	/*Intermediaries*/
-	int penpair_ids[2];
-	int count=0;
-	int numvertex_pairing;
-
-	/*Create Penpair for vertex_pairing: */
-	IssmDouble *vertex_pairing=NULL;
-	IssmDouble *nodeonbase=NULL;
-	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
-	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
-	for(int i=0;i<numvertex_pairing;i++){
-
-		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
-
-			/*In debugging mode, check that the second node is in the same cpu*/
-			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
-
-			/*Skip if one of the two is not on the bed*/
-			if(iomodel->domaintype!=Domain2DhorizontalEnum){
-				if(!(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
-			}
-
-			/*Get node ids*/
-			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
-			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
-
-			/*Create Load*/
-			loads->AddObject(new Penpair(
-							iomodel->loadcounter+count+1,
-							&penpair_ids[0],
-							FreeSurfaceBaseAnalysisEnum));
-			count++;
-		}
-	}
-
-	/*free ressources: */
-	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
-	iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
+void FreeSurfaceBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 
@@ -304,5 +304,5 @@
 
 }/*}}}*/
-void FreeSurfaceBaseAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           FreeSurfaceBaseAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
 	 * For node i, Bi can be expressed in the actual coordinate system
@@ -332,5 +332,5 @@
 	xDelete<IssmDouble>(basis);
 }/*}}}*/
-void FreeSurfaceBaseAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           FreeSurfaceBaseAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
 	 * For node i, Bi' can be expressed in the actual coordinate system
@@ -361,14 +361,14 @@
 
 }/*}}}*/
-void FreeSurfaceBaseAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           FreeSurfaceBaseAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void FreeSurfaceBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           FreeSurfaceBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void FreeSurfaceBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           FreeSurfaceBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	element->InputUpdateFromSolutionOneDof(solution,BaseEnum);
 }/*}}}*/
-void FreeSurfaceBaseAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           FreeSurfaceBaseAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 
 	/*Intermediary*/
@@ -377,5 +377,5 @@
 	for(int i=0;i<femmodel->elements->Size();i++){
 
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		if(!element->IsOnBase()) continue;
 
Index: /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,10 +26,10 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp	(revision 19105)
@@ -6,8 +6,55 @@
 
 /*Model processing*/
+void FreeSurfaceTopAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void FreeSurfaceTopAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	int penpair_ids[2];
+	int count=0;
+	int numvertex_pairing;
+
+	/*Create Penpair for vertex_pairing: */
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonsurface=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(&nodeonsurface,NULL,NULL,MeshVertexonsurfaceEnum);
+	for(int i=0;i<numvertex_pairing;i++){
+
+		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
+
+			/*Skip if one of the two is not on the bed*/
+			if(iomodel->domaintype!=Domain2DhorizontalEnum){
+				if(!(reCast<bool>(nodeonsurface[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonsurface[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
+			}
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(
+							iomodel->loadcounter+count+1,
+							&penpair_ids[0],
+							FreeSurfaceTopAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
+	iomodel->DeleteData(nodeonsurface,MeshVertexonsurfaceEnum);
+}/*}}}*/
+void FreeSurfaceTopAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,FreeSurfaceTopAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
 int  FreeSurfaceTopAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void FreeSurfaceTopAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 void FreeSurfaceTopAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -51,52 +98,5 @@
 	}
 }/*}}}*/
-void FreeSurfaceTopAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	::CreateNodes(nodes,iomodel,FreeSurfaceTopAnalysisEnum,P1Enum);
-	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-}/*}}}*/
-void FreeSurfaceTopAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-}/*}}}*/
-void FreeSurfaceTopAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
-	/*Intermediaries*/
-	int penpair_ids[2];
-	int count=0;
-	int numvertex_pairing;
-
-	/*Create Penpair for vertex_pairing: */
-	IssmDouble *vertex_pairing=NULL;
-	IssmDouble *nodeonsurface=NULL;
-	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
-	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(&nodeonsurface,NULL,NULL,MeshVertexonsurfaceEnum);
-	for(int i=0;i<numvertex_pairing;i++){
-
-		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
-
-			/*In debugging mode, check that the second node is in the same cpu*/
-			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
-
-			/*Skip if one of the two is not on the bed*/
-			if(iomodel->domaintype!=Domain2DhorizontalEnum){
-				if(!(reCast<bool>(nodeonsurface[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonsurface[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
-			}
-
-			/*Get node ids*/
-			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
-			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
-
-			/*Create Load*/
-			loads->AddObject(new Penpair(
-							iomodel->loadcounter+count+1,
-							&penpair_ids[0],
-							FreeSurfaceTopAnalysisEnum));
-			count++;
-		}
-	}
-
-	/*free ressources: */
-	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
-	iomodel->DeleteData(nodeonsurface,MeshVertexonsurfaceEnum);
+void FreeSurfaceTopAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 
@@ -307,5 +307,5 @@
 
 }/*}}}*/
-void FreeSurfaceTopAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           FreeSurfaceTopAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
 	 * For node i, Bi can be expressed in the actual coordinate system
@@ -335,5 +335,5 @@
 	xDelete<IssmDouble>(basis);
 }/*}}}*/
-void FreeSurfaceTopAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           FreeSurfaceTopAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
 	 * For node i, Bi' can be expressed in the actual coordinate system
@@ -364,15 +364,15 @@
 
 }/*}}}*/
-void FreeSurfaceTopAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           FreeSurfaceTopAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void FreeSurfaceTopAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           FreeSurfaceTopAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void FreeSurfaceTopAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           FreeSurfaceTopAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	element->InputUpdateFromSolutionOneDof(solution,SurfaceEnum);
 }/*}}}*/
-void FreeSurfaceTopAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           FreeSurfaceTopAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,10 +26,10 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/GiaAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/GiaAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/GiaAnalysis.cpp	(revision 19105)
@@ -6,8 +6,15 @@
 
 /*Model processing*/
+void GiaAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	/*No constraints*/
+}/*}}}*/
+void GiaAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	/*No loads*/
+}/*}}}*/
+void GiaAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	::CreateNodes(nodes,iomodel,GiaAnalysisEnum,P1Enum);
+}/*}}}*/
 int  GiaAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void GiaAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 void GiaAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -27,12 +34,5 @@
 	iomodel->FetchDataToInput(elements,GiaLithosphereThicknessEnum);
 }/*}}}*/
-void GiaAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-	::CreateNodes(nodes,iomodel,GiaAnalysisEnum,P1Enum);
-}/*}}}*/
-void GiaAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-	/*No constraints*/
-}/*}}}*/
-void GiaAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-	/*No loads*/
+void GiaAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 
@@ -54,14 +54,14 @@
 _error_("not implemented yet");
 }/*}}}*/
-void GiaAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           GiaAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void GiaAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           GiaAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void GiaAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           GiaAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	_error_("not implemented yet");
 }/*}}}*/
-void GiaAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           GiaAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/GiaAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/GiaAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/GiaAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,8 +26,8 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.cpp	(revision 19105)
@@ -12,6 +12,7 @@
 
 	int         hydrology_model;
+	int         eplflip_lock;
+	int         eplthickcomp;
 	bool        isefficientlayer;
-
 	/*retrieve some parameters: */
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
@@ -22,7 +23,16 @@
 	/*Do we want an efficient layer*/
 	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+
+	/*If not return*/
 	if(!isefficientlayer) return;
 
-	/*Nothing for now*/
+	/*If yes, initialize a flip flop counter*/
+	iomodel->FetchData(&eplflip_lock,HydrologydcEplflipLockEnum);
+	parameters->AddObject(new IntParam(HydrologydcEplflipLockEnum,eplflip_lock));
+
+	iomodel->FetchData(&eplthickcomp,HydrologydcEplThickCompEnum);
+	parameters->AddObject(new IntParam(HydrologydcEplThickCompEnum,eplthickcomp));
+
+	
 }/*}}}*/
 void HydrologyDCEfficientAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -55,12 +65,11 @@
 	iomodel->FetchDataToInput(elements,HydrologydcEplInitialThicknessEnum);
 	iomodel->FetchDataToInput(elements,HydrologydcEplMaxThicknessEnum);
-	iomodel->FetchDataToInput(elements,HydrologydcSedimentTransmitivityEnum);
 	iomodel->FetchDataToInput(elements,HydrologydcEplThicknessEnum);
-	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		if(iomodel->domaintype!=Domain2DhorizontalEnum){
 		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
 		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
 	}
-
-}/*}}}*/
+}/*}}}*/
+
 void HydrologyDCEfficientAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
 
@@ -79,4 +88,5 @@
 	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
 }/*}}}*/
+
 void HydrologyDCEfficientAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
 
@@ -92,8 +102,30 @@
 
 	IoModelToConstraintsx(constraints,iomodel,HydrologydcSpceplHeadEnum,HydrologyDCEfficientAnalysisEnum,P1Enum);
-
-}/*}}}*/
+}/*}}}*/
+
 void HydrologyDCEfficientAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
 	/*Nothing for now*/
+}/*}}}*/
+
+void HydrologyDCEfficientAnalysis::InitZigZagCounter(FemModel* femmodel){/*{{{*/
+	int*   eplzigzag_counter =NULL;
+	
+	eplzigzag_counter=xNewZeroInit<int>(femmodel->nodes->Size());
+	femmodel->parameters->AddObject(new IntVecParam(EplZigZagCounterEnum,eplzigzag_counter,femmodel->nodes->Size()));
+	xDelete<int>(eplzigzag_counter);
+}/*}}}*/
+
+void HydrologyDCEfficientAnalysis::ResetCounter(FemModel* femmodel){/*{{{*/
+
+	int*     eplzigzag_counter=NULL;
+	Element* element=NULL;
+
+	femmodel->parameters->FindParam(&eplzigzag_counter,NULL,EplZigZagCounterEnum);
+	for(int i=0;i<femmodel->nodes->Size();i++){
+
+		eplzigzag_counter[i]=0;
+	}
+	femmodel->parameters->SetParam(eplzigzag_counter,femmodel->nodes->Size(),EplZigZagCounterEnum);
+	xDelete<int>(eplzigzag_counter);
 }/*}}}*/
 
@@ -102,11 +134,14 @@
 	_error_("not implemented");
 }/*}}}*/
+
 ElementVector* HydrologyDCEfficientAnalysis::CreateDVector(Element* element){/*{{{*/
 	/*Default, return NULL*/
 	return NULL;
 }/*}}}*/
+
 ElementMatrix* HydrologyDCEfficientAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
 _error_("Not implemented");
 }/*}}}*/
+
 ElementMatrix* HydrologyDCEfficientAnalysis::CreateKMatrix(Element* element){/*{{{*/
 
@@ -140,4 +175,5 @@
 		return NULL;
 	}
+
 	/* Intermediaries */
 	IssmDouble  D_scalar,Jdet,dt;
@@ -158,9 +194,10 @@
 	basalelement->GetVerticesCoordinates(&xyz_list);
 	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
-	Input* thickness_input = basalelement->GetInput(HydrologydcEplThicknessEnum);          _assert_(thickness_input);
+
+	Input* epl_thick_input = basalelement->GetInput(HydrologydcEplThicknessEnum); _assert_(epl_thick_input);
 	Input* sed_head_input  = basalelement->GetInput(SedimentHeadEnum);
 	Input* epl_head_input  = basalelement->GetInput(EplHeadEnum);
-	Input* sed_trans_input = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum);
-	Input* residual_input  = basalelement->GetInput(SedimentHeadResidualEnum);
+	Input* thick_input     = basalelement->GetInput(ThicknessEnum);
+	Input* base_input      = basalelement->GetInput(BaseEnum);
 
 	IssmDouble epl_specificstoring   = EplSpecificStoring(basalelement);
@@ -172,5 +209,5 @@
 		gauss           ->GaussPoint(ig);
 		basalelement    ->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		thickness_input ->GetInputValue(&epl_thickness,gauss);
+		epl_thick_input ->GetInputValue(&epl_thickness,gauss);
 
 		/*Diffusivity*/
@@ -194,7 +231,8 @@
 						&Ke->values[0],1);
 			
+			
 			/*Transfer EPL part*/
-			transfer=GetHydrologyKMatrixTransfer(basalelement,gauss,thickness_input,sed_head_input,epl_head_input,sed_trans_input,residual_input);
-			D_scalar=transfer*gauss->weight*Jdet*dt;
+			transfer=GetHydrologyKMatrixTransfer(basalelement,gauss,sed_head_input,epl_head_input,thick_input,base_input);
+			D_scalar=dt*transfer*gauss->weight*Jdet;
 			TripleMultiply(basis,numnodes,1,0,
 										 &D_scalar,1,1,0,
@@ -211,6 +249,6 @@
 	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
 	return Ke;
-
-}/*}}}*/
+}/*}}}*/
+
 ElementVector* HydrologyDCEfficientAnalysis::CreatePVector(Element* element){/*{{{*/
 
@@ -266,9 +304,10 @@
 	basalelement->FindParam(&dt,TimesteppingTimeStepEnum);	
 
-	Input* thickness_input = basalelement->GetInput(HydrologydcEplThicknessEnum); _assert_(thickness_input);
-	Input* sed_head_input  = basalelement->GetInput(SedimentHeadEnum);
-	Input* epl_head_input  = basalelement->GetInput(EplHeadEnum);
-	Input* sed_trans_input = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum);
-	Input* residual_input  = basalelement->GetInput(SedimentHeadResidualEnum);    _assert_(residual_input);
+	Input* epl_thick_input   = basalelement->GetInput(HydrologydcEplThicknessEnum); _assert_(epl_thick_input);
+	Input* sed_head_input    = basalelement->GetInput(SedimentHeadEnum);
+	Input* epl_head_input    = basalelement->GetInput(EplHeadEnum);
+	Input* thick_input       = basalelement->GetInput(ThicknessEnum);
+	Input* base_input        = basalelement->GetInput(BaseEnum);
+	Input* residual_input    = basalelement->GetInput(SedimentHeadResidualEnum);    _assert_(residual_input);
 	if(dt!= 0.){old_wh_input = basalelement->GetInput(EplHeadOldEnum);            _assert_(old_wh_input);}
 
@@ -286,9 +325,9 @@
 		if(dt!=0.){
 			old_wh_input    ->GetInputValue(&water_head,gauss);
-			thickness_input ->GetInputValue(&epl_thickness,gauss);
+			epl_thick_input ->GetInputValue(&epl_thickness,gauss);
 			
 			/*Dealing with the epl part of the transfer term*/
-			transfer=GetHydrologyPVectorTransfer(basalelement,gauss,thickness_input,sed_head_input,epl_head_input,sed_trans_input,residual_input);
-			scalar = Jdet*gauss->weight*((water_head*epl_specificstoring*epl_thickness)+(transfer*dt));
+			transfer=GetHydrologyPVectorTransfer(basalelement,gauss,sed_head_input,epl_head_input,thick_input,base_input);
+			scalar = Jdet*gauss->weight*((water_head*epl_specificstoring*epl_thickness)+(dt*transfer));
 			for(int i=0;i<numnodes;i++)pe->values[i]+=scalar*basis[i];
 		}
@@ -314,12 +353,16 @@
 	return pe;
 }/*}}}*/
+
 void HydrologyDCEfficientAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	element->GetSolutionFromInputsOneDof(solution,EplHeadEnum);
 }/*}}}*/
+
 void HydrologyDCEfficientAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
+
 void HydrologyDCEfficientAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
+	bool active_element;
 	int domaintype,i;
 	Element*   basalelement=NULL;
@@ -342,6 +385,12 @@
 
 	/*Fetch dof list and allocate solution vector*/
+	IssmDouble* sedhead     = xNew<IssmDouble>(numnodes);
+	IssmDouble* eplHeads    = xNew<IssmDouble>(numnodes);
+
 	basalelement->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	IssmDouble* eplHeads    = xNew<IssmDouble>(numnodes);
+	basalelement->GetInputListOnVertices(&sedhead[0],SedimentHeadEnum);
+
+	Input* active_element_input=basalelement->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);
+	active_element_input->GetInputValue(&active_element);
 
 	/*Use the dof list to index into the solution vector: */
@@ -355,7 +404,9 @@
 	/*Free ressources:*/
 	xDelete<IssmDouble>(eplHeads);
+	xDelete<IssmDouble>(sedhead);
 	xDelete<int>(doflist);
 	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
 } /*}}}*/
+
 void HydrologyDCEfficientAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
@@ -372,4 +423,5 @@
 	return rho_freshwater*g*epl_porosity*(water_compressibility+(epl_compressibility/epl_porosity));		 
 }/*}}}*/
+
 IssmDouble HydrologyDCEfficientAnalysis::SedimentStoring(Element* element){/*{{{*/
 	IssmDouble rho_freshwater           = element->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
@@ -381,17 +433,16 @@
 	return rho_freshwater*g*sediment_porosity*sediment_thickness*(water_compressibility+(sediment_compressibility/sediment_porosity));		 
 }/*}}}*/
-IssmDouble HydrologyDCEfficientAnalysis::GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* residual_input){/*{{{*/
-	
+
+IssmDouble HydrologyDCEfficientAnalysis::GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* sed_head_input, Input* epl_head_input, Input* thick_input, Input* base_input){/*{{{*/
+
 	int transfermethod;
-	IssmDouble epl_thickness;
-	IssmDouble epl_head,sed_head;
-	IssmDouble sediment_transmitivity;
-	IssmDouble leakage,residual,transfer;
-
-	IssmDouble sediment_thickness  = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
-	IssmDouble sediment_storing    = SedimentStoring(element);
- 	IssmDouble epl_specificstoring = EplSpecificStoring(element);		
+	IssmDouble hmax;
+	IssmDouble epl_head,sediment_head;
+	IssmDouble leakage,transfer;
+	IssmDouble continuum, factor;
+	HydrologyDCInefficientAnalysis* inefanalysis = NULL;
 
 	element->FindParam(&transfermethod,HydrologydcTransferFlagEnum);
+
 	/*Switch between the different transfer methods cases*/
 	switch(transfermethod){
@@ -401,50 +452,39 @@
 		break;
 	case 1:
-		_assert_(epl_thick_input); 
-		_assert_(sed_head_input); 
-		_assert_(epl_head_input); 
-		_assert_(sed_trans_input); 
-		_assert_(residual_input); 
-		/* get input */
-		epl_thick_input->GetInputValue(&epl_thickness,gauss);
-		sed_head_input->GetInputValue(&sed_head,gauss);
+		_assert_(sed_head_input);
+		_assert_(epl_head_input);
+		
+		inefanalysis = new HydrologyDCInefficientAnalysis();
+		hmax = inefanalysis->GetHydrologyDCInefficientHmax(element,gauss,thick_input,base_input);
+		delete inefanalysis;
+
+		sed_head_input->GetInputValue(&sediment_head,gauss);
 		epl_head_input->GetInputValue(&epl_head,gauss);
-		sed_trans_input->GetInputValue(&sediment_transmitivity,gauss);
-		residual_input->GetInputValue(&residual,gauss);
 		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
-		transfer=(sediment_transmitivity)/(sediment_thickness*leakage); 
-		/* if(epl_head>sed_head){ */
-		/* 	if(residual>0.0){	 */
-		/* 		transfer=0.0; */
-		/* 	} */
-		/* 	else{ */
-		/* 		transfer=(sediment_transmitivity)/(sediment_thickness*leakage); */
-		/* 		//transfer=(epl_specificstoring*epl_thickness*sediment_transmitivity)/(sediment_thickness*leakage); */
-		/* 	} */
-		/* } */
-		/* else{ */
-		/* 	transfer=(sediment_transmitivity)/(sediment_thickness*leakage); */
-		/* 	//transfer=(sediment_storing*sediment_transmitivity)/(sediment_thickness*leakage); */
-		/* } */
+		
+		//Computing continuum function to apply to transfer term, transfer is null only if
+		// epl_head>sediment_head AND sediment_head>h_max
+		continuum=((1.0/(1.0+exp(-20.0*(sediment_head-epl_head)))))+(1.0/(1.0+exp(-20.0*(hmax-sediment_head))));
+		factor=min(continuum,1.0);
+		transfer=leakage*factor;
 		break;
 	default:
 		_error_("no case higher than 1 for the Transfer method");
 	}
-	
 	return transfer;
 }/*}}}*/
-IssmDouble HydrologyDCEfficientAnalysis::GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* residual_input){/*{{{*/
+
+IssmDouble HydrologyDCEfficientAnalysis::GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* sed_head_input, Input* epl_head_input, Input* thick_input, Input* base_input){/*{{{*/
 
 	int transfermethod;
-	IssmDouble epl_thickness;
+	IssmDouble hmax;
 	IssmDouble epl_head,sediment_head;
-	IssmDouble sediment_transmitivity;
-	IssmDouble leakage,residual,transfer;
-
-	IssmDouble sediment_thickness = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
-	IssmDouble sediment_storing   = SedimentStoring(element);
- 	IssmDouble epl_specificstoring = EplSpecificStoring(element);		
+	IssmDouble leakage,transfer;
+	IssmDouble continuum, factor;
+
+	HydrologyDCInefficientAnalysis* inefanalysis = NULL;
 
 	element->FindParam(&transfermethod,HydrologydcTransferFlagEnum);
+
 	/*Switch between the different transfer methods cases*/
 	switch(transfermethod){
@@ -454,34 +494,26 @@
 		break;
 	case 1:
-		_assert_(epl_thick_input); 
-		_assert_(sed_head_input); 
-		_assert_(epl_head_input); 
-		_assert_(sed_trans_input); 
-		_assert_(residual_input); 
-		/* get input */
-		epl_thick_input->GetInputValue(&epl_thickness,gauss);
+		_assert_(sed_head_input);
+		_assert_(epl_head_input);
+
+		inefanalysis = new HydrologyDCInefficientAnalysis();
+		hmax = inefanalysis->GetHydrologyDCInefficientHmax(element,gauss,thick_input,base_input);
+		delete inefanalysis;
+		
 		sed_head_input->GetInputValue(&sediment_head,gauss);
 		epl_head_input->GetInputValue(&epl_head,gauss);
-		sed_trans_input->GetInputValue(&sediment_transmitivity,gauss);
-		residual_input->GetInputValue(&residual,gauss);
 		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
-		transfer=(sediment_transmitivity*sediment_head)/(sediment_thickness*leakage);
-		/* if(epl_head>sediment_head){ */
-		/* 	if(residual>0.0){	 */
-		/* 		transfer=0.0; */
-		/* 	} */
-		/* 	else{ */
-		/* 		transfer=(sediment_transmitivity*sediment_head)/(sediment_thickness*leakage); */
-		/* 		//transfer=(epl_specificstoring*epl_thickness*sediment_transmitivity*sediment_head)/(sediment_thickness*leakage); */
-		/* 	} */
-		/* } */
-		/* else{ */
-		/* 	transfer=(sediment_transmitivity*sediment_head)/(sediment_thickness*leakage); */
-		/* 	//transfer=(sediment_storing*sediment_transmitivity*sediment_head)/(sediment_thickness*leakage); */
-		/* } */
+
+		//Computing continuum function to apply to transfer term, transfer is null only if
+		// epl_head>sediment_head AND sediment_head>h_max
+		continuum=((1.0/(1.0+exp(-20.0*(sediment_head-epl_head)))))+(1.0/(1.0+exp(-20.0*(hmax-sediment_head))));
+		factor=min(continuum,1.0);
+		transfer=sediment_head*leakage*factor;
+
 		break;
 	default:
 		_error_("no case higher than 1 for the Transfer method");
 	}
+
 	return transfer;
 }/*}}}*/
@@ -490,4 +522,5 @@
 
 	bool        active_element;
+	int         iseplthickcomp;
 	int         domaintype;
 	IssmDouble  dt,A,B;
@@ -495,4 +528,5 @@
 	IssmDouble  EPL_N;
 
+	
 	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
 
@@ -500,8 +534,10 @@
 		
 		Element* element=(Element*)femmodel->elements->GetObjectByOffset(j);
+		element->parameters->FindParam(&iseplthickcomp,HydrologydcEplThickCompEnum);
+		if(iseplthickcomp==0) return;
 		
 		switch(domaintype){
 		case Domain2DhorizontalEnum:
-			if(!element->IsOnBase()) return;			
+			if(!element->IsOnBase()) return;	
 			B = element->GetMaterialParameter(MaterialsRheologyBbarEnum);
 			break;
@@ -512,5 +548,5 @@
 		_error_("not Implemented Yet");
 		}
-			
+		
 		int         numnodes      = element->GetNumberOfNodes();
 		IssmDouble* thickness     = xNew<IssmDouble>(numnodes);
@@ -544,5 +580,5 @@
 		element->GetInputListOnVertices(&ice_thickness[0],ThicknessEnum);
 		element->GetInputListOnVertices(&bed[0],BaseEnum);
-			
+		
 		if(!active_element){
 			
@@ -556,11 +592,12 @@
 				
 				/*Compute first the effective pressure in the EPL*/
-				EPL_N=gravity*((rho_ice*ice_thickness[i])-(rho_water*(eplhead[i]-bed[i])));
+				EPL_N=gravity*((rho_ice*ice_thickness[i])-(rho_water*max(0.0,(eplhead[i]-bed[i]))));
 				if(EPL_N<0.0)EPL_N=0.0;
 				/*Get then the square of the gradient of EPL heads*/
-				EPLgrad2 = (epl_slopeX[i]+epl_slopeY[i])*(epl_slopeX[i]+epl_slopeY[i]);
+				EPLgrad2 = (epl_slopeX[i]*epl_slopeX[i])+(epl_slopeY[i]*epl_slopeY[i]);
 				
 				/*And proceed to the real thing*/
-				thickness[i] = old_thickness[i]*(1+((rho_water*gravity*dt)/(rho_ice*latentheat))*epl_conductivity*EPLgrad2-2.0*(A*dt/(pow(n,n)))*(pow(EPL_N,n)));
+				thickness[i] = old_thickness[i]*(1.0+((rho_water*gravity*dt)/(rho_ice*latentheat))*epl_conductivity*EPLgrad2-
+																				 (2.0*(A*dt/(pow(n,n)))*(pow(EPL_N,n))));
 				
 				/*Take care of otherthikening*/
@@ -579,6 +616,6 @@
 		xDelete<IssmDouble>(bed);
 	}
-}
-/*}}}*/
+}/*}}}*/
+
 void HydrologyDCEfficientAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
@@ -608,5 +645,6 @@
 	xDelete<IssmDouble>(dbasis);
 }/*}}}*/
-void  HydrologyDCEfficientAnalysis::HydrologyEPLGetMask(Vector<IssmDouble>* vec_mask,Element* element){
+
+void  HydrologyDCEfficientAnalysis::HydrologyEPLGetMask(Vector<IssmDouble>* vec_mask, Vector<IssmDouble>* recurence, int* eplzigzag_counter, Element* element){
 
 	bool        active_element;
@@ -615,5 +653,5 @@
 	IssmDouble  h_max;
 	IssmDouble  sedheadmin;
-	Element*   basalelement=NULL;
+	Element*    basalelement=NULL;
 
 	/*Get basal element*/
@@ -629,7 +667,5 @@
 		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
 	}
-
 	/*Intermediaries*/
-
 	int         numnodes      =basalelement->GetNumberOfNodes();
 	IssmDouble* epl_thickness =xNew<IssmDouble>(numnodes);
@@ -638,6 +674,7 @@
 	IssmDouble* eplhead       =xNew<IssmDouble>(numnodes);
 	IssmDouble* residual      =xNew<IssmDouble>(numnodes);
-
-	IssmDouble init_thick =	basalelement->GetMaterialParameter(HydrologydcEplInitialThicknessEnum);
+	
+	IssmDouble init_thick    =basalelement->GetMaterialParameter(HydrologydcEplInitialThicknessEnum);
+	IssmDouble colapse_thick =basalelement->GetMaterialParameter(HydrologydcEplColapseThicknessEnum);
 
 	Input* active_element_input=basalelement->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);
@@ -653,18 +690,22 @@
 	sedheadmin=sedhead[0];
 	for(i=1;i<numnodes;i++) if(sedhead[i]<=sedheadmin)sedheadmin=sedhead[i];
-
 	for(i=0;i<numnodes;i++){
-		/*Activate EPL if residual is >0 */
+		/*If node is now closed bring its thickness back to initial*/
+		if (old_active[i]==0.){
+			epl_thickness[i]=init_thick;
+		}
+
+		/*Now starting to look at the activations*/
 		if(residual[i]>0.){
 			vec_mask->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
-		}
-
-		/*If mask was already one, keep one*/
+			if(old_active[i]==0.)	recurence->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
+		}
+		/*If mask was already one, keep one or colapse*/
 		else if(old_active[i]>0.){
 			vec_mask->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
-			/*If epl thickness gets under 10-3 initial thickness, close the layer*/
-			if(epl_thickness[i]<0.001*init_thick){
+			/*If epl thickness gets under colapse thickness, close the layer*/
+			if(epl_thickness[i]<colapse_thick){
 				vec_mask->SetValue(basalelement->nodes[i]->Sid(),0.,INS_VAL);
-				epl_thickness[i]=init_thick;
+				recurence->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
 			}
 		}
@@ -673,14 +714,14 @@
 		if(eplhead[i]>=h_max && active_element){
 			for(j=0;j<numnodes;j++){
-				if(old_active[j]>0.){
-					vec_mask->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
-				}
 				/*Increase of the domain is on the downstream node in term of sediment head*/
 				if(sedhead[j] == sedheadmin){
 					vec_mask->SetValue(basalelement->nodes[j]->Sid(),1.,INS_VAL);
+					if(old_active[i]==0.)	recurence->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
 				}
 			}
 		}
 	}
+	basalelement->AddInput(HydrologydcEplThicknessEnum,epl_thickness,basalelement->GetElementType());
+
 	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
 	xDelete<IssmDouble>(epl_thickness);
@@ -691,7 +732,7 @@
 }
 /*}}}*/
+
 void HydrologyDCEfficientAnalysis::HydrologyEPLGetActive(Vector<IssmDouble>* active_vec, Element* element){
 	/*Constants*/
-
 	int      domaintype;
 	Element*   basalelement=NULL;
@@ -713,13 +754,24 @@
 	IssmDouble  flag     = 0.;
 	IssmDouble* active   = xNew<IssmDouble>(numnodes);
-		
+
+	/*Pass the activity mask from elements to nodes*/
 	basalelement->GetInputListOnVertices(&active[0],HydrologydcMaskEplactiveNodeEnum);
+	bool active_element;
+	Input* 	active_element_input=basalelement->GetInput(HydrologydcMaskEplactiveEltEnum); _assert_(active_element_input);		
+	active_element_input->GetInputValue(&active_element);
 	
 	for(int i=0;i<numnodes;i++) flag+=active[i];
 
+	/*If any node is active all the node in the element are active*/
 	if(flag>0.){
 		for(int i=0;i<numnodes;i++){
 			active_vec->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
 		}
+	}
+	/*If the element is active all its nodes are active*/
+	else if(active_element){
+		for(int i=0;i<numnodes;i++){
+			active_vec->SetValue(basalelement->nodes[i]->Sid(),1.,INS_VAL);
+		}		
 	}
 	else{
Index: /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/HydrologyDCEfficientAnalysis.h	(revision 19105)
@@ -20,5 +20,7 @@
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
-
+		void InitZigZagCounter(FemModel* femmodel);
+		void ResetCounter(FemModel* femmodel);
+			
 		/*Finite element Analysis*/
 		void           Core(FemModel* femmodel);
@@ -36,7 +38,7 @@
 		IssmDouble EplSpecificStoring(Element* element);
 		IssmDouble SedimentStoring(Element* element);
-		IssmDouble GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* residual_input);
-		IssmDouble GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* residual_input);
-		void HydrologyEPLGetMask(Vector<IssmDouble>* vec_mask,Element* element);
+		IssmDouble GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* sed_head_input, Input* epl_head_input, Input* thick_input, Input* base_input);
+		IssmDouble GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* sed_head_input, Input* epl_head_input, Input* thick_input, Input* base_input);
+		void HydrologyEPLGetMask(Vector<IssmDouble>* vec_mask, Vector<IssmDouble>* recurence, int* eplzigzag_counter, Element* element);
 		void HydrologyEPLGetActive(Vector<IssmDouble>* active_vec, Element* element);
 		void GetHydrologyDCInefficientHmax(IssmDouble* ph_max,Element* element, Node* innode);
Index: /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.cpp	(revision 19105)
@@ -10,4 +10,5 @@
 	return 1;
 }/*}}}*/
+
 void HydrologyDCInefficientAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 
@@ -55,11 +56,12 @@
 	parameters->AddObject(new IntParam(HydrologydcPenaltyLockEnum,penalty_lock));
 	parameters->AddObject(new IntParam(HydrologydcMaxIterEnum,hydro_maxiter));
-
-}/*}}}*/
+}/*}}}*/
+
 void HydrologyDCInefficientAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
 
 	bool   isefficientlayer;
+	bool   element_active;
 	int    hydrology_model;
-
+	
 	/*Fetch data needed: */
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
@@ -93,6 +95,9 @@
 	}
 
-	if(isefficientlayer)iomodel->FetchDataToInput(elements,HydrologydcMaskEplactiveNodeEnum);
-}/*}}}*/
+	if(isefficientlayer){
+		iomodel->FetchDataToInput(elements,HydrologydcMaskEplactiveNodeEnum);
+	}
+}/*}}}*/
+
 void HydrologyDCInefficientAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
 
@@ -108,4 +113,5 @@
 	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
 }/*}}}*/
+
 void HydrologyDCInefficientAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
 
@@ -117,4 +123,5 @@
 	IoModelToConstraintsx(constraints,iomodel,HydrologydcSpcsedimentHeadEnum,HydrologyDCInefficientAnalysisEnum,P1Enum);
 }/*}}}*/
+
 void HydrologyDCInefficientAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
 
@@ -148,11 +155,14 @@
 	_error_("not implemented");
 }/*}}}*/
+
 ElementVector* HydrologyDCInefficientAnalysis::CreateDVector(Element* element){/*{{{*/
 	/*Default, return NULL*/
 	return NULL;
 }/*}}}*/
+
 ElementMatrix* HydrologyDCInefficientAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
 _error_("Not implemented");
 }/*}}}*/
+
 ElementMatrix* HydrologyDCInefficientAnalysis::CreateKMatrix(Element* element){/*{{{*/
 
@@ -197,11 +207,10 @@
 	basalelement ->FindParam(&dt,TimesteppingTimeStepEnum);
 	basalelement ->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
-
-	Input* epl_thick_input   = basalelement->GetInput(HydrologydcEplThicknessEnum);
-	Input* sed_head_input    = basalelement->GetInput(SedimentHeadEnum);
-	Input* epl_head_input    = basalelement->GetInput(EplHeadEnum);
-	Input* thickness_input   = basalelement->GetInput(ThicknessEnum);
-	Input* base_input         = basalelement->GetInput(BaseEnum);
-	Input* SedTrans_input    = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum); _assert_(SedTrans_input);
+	Input* SedTrans_input = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum); _assert_(SedTrans_input);
+	Input* sed_head_input = basalelement->GetInput(SedimentHeadEnum);
+	Input* epl_head_input = basalelement->GetInput(EplHeadEnum);
+	Input* thick_input    = basalelement->GetInput(ThicknessEnum);
+	Input* base_input     = basalelement->GetInput(BaseEnum);
+
 	IssmDouble sediment_storing = SedimentStoring(basalelement);
 	/*Transfer related Inputs*/
@@ -240,7 +249,7 @@
 				active_element_input->GetInputValue(&active_element);
 				if(active_element){
-					transfer=GetHydrologyKMatrixTransfer(basalelement,gauss,epl_thick_input,sed_head_input,epl_head_input,SedTrans_input,thickness_input,base_input);
+					transfer=GetHydrologyKMatrixTransfer(basalelement,gauss,sed_head_input,epl_head_input,thick_input,base_input);
 					basalelement->NodalFunctions(&basis[0],gauss);
-					D_scalar=transfer*gauss->weight*Jdet*dt;
+					D_scalar=dt*transfer*gauss->weight*Jdet;
 					TripleMultiply(basis,numnodes,1,0,
 												 &D_scalar,1,1,0,
@@ -259,4 +268,5 @@
 	return Ke;
 }/*}}}*/
+
 ElementVector* HydrologyDCInefficientAnalysis::CreatePVector(Element* element){/*{{{*/
 
@@ -301,11 +311,9 @@
 	basalelement->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
 
-	Input* epl_thick_input   = basalelement->GetInput(HydrologydcEplThicknessEnum);
-	Input* sed_head_input    = basalelement->GetInput(SedimentHeadEnum);
-	Input* epl_head_input    = basalelement->GetInput(EplHeadEnum);
-	Input* sed_trans_input   = basalelement->GetInput(HydrologydcSedimentTransmitivityEnum);
-	Input* thickness_input   = basalelement->GetInput(ThicknessEnum);
-	Input* base_input        = basalelement->GetInput(BaseEnum);
-	Input* water_input       = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(water_input);
+	Input* sed_head_input = basalelement->GetInput(SedimentHeadEnum);
+	Input* epl_head_input = basalelement->GetInput(EplHeadEnum);
+	Input* water_input    = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum); _assert_(water_input);
+	Input* thick_input    = basalelement->GetInput(ThicknessEnum);
+	Input* base_input     = basalelement->GetInput(BaseEnum);
 	if(dt!= 0.){old_wh_input = basalelement->GetInput(SedimentHeadOldEnum);                     _assert_(old_wh_input);}
 
@@ -327,7 +335,5 @@
 		/*Loading term*/
 		water_input->GetInputValue(&water_load,gauss);
-
 		scalar = Jdet*gauss->weight*(water_load);
-
 		if(dt!=0.) scalar = scalar*dt;
 		for(int i=0;i<numnodes;i++){
@@ -342,5 +348,5 @@
 				active_element_input->GetInputValue(&active_element);
 				if(active_element){
-					transfer=GetHydrologyPVectorTransfer(basalelement,gauss,epl_thick_input,sed_head_input,epl_head_input,sed_trans_input,thickness_input,base_input);
+					transfer=GetHydrologyPVectorTransfer(basalelement,gauss,sed_head_input,epl_head_input,thick_input,base_input);
 				}
 				else{
@@ -363,4 +369,5 @@
 	return pe;
 }/*}}}*/
+
 void HydrologyDCInefficientAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
@@ -390,10 +397,13 @@
 	xDelete<IssmDouble>(dbasis);
 }/*}}}*/
+
 void HydrologyDCInefficientAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	element->GetSolutionFromInputsOneDof(solution,SedimentHeadEnum);
 }/*}}}*/
+
 void HydrologyDCInefficientAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
+
 void HydrologyDCInefficientAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
@@ -456,5 +466,6 @@
 				residual[i] = 0.;
 			}
-			pressure[i]=(rho_ice*g*thickness[i])-(rho_freshwater*g*(min(h_max,values[i])-base[i]));
+			//adding base in min to take into account heads under bed wich don't change N
+			pressure[i]=(rho_ice*g*thickness[i])-(rho_freshwater*g*(max((min(h_max,values[i])-base[i]),0.0)));
 		}
 		xDelete<IssmDouble>(thickness);
@@ -474,4 +485,5 @@
 	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
 }/*}}}*/
+
 void HydrologyDCInefficientAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
@@ -536,4 +548,5 @@
 	return h_max;
 }/*}}}*/
+
 void  HydrologyDCInefficientAnalysis::GetHydrologyDCInefficientHmax(IssmDouble* ph_max,Element* element, Node* innode){/*{{{*/
 	
@@ -571,17 +584,15 @@
 }
 /*}}}*/
-IssmDouble HydrologyDCInefficientAnalysis::GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* thickness_input, Input* base_input){/*{{{*/
+
+IssmDouble HydrologyDCInefficientAnalysis::GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* sed_head_input, Input* epl_head_input, Input* thick_input, Input* base_input){/*{{{*/
 
 	int transfermethod;
-	IssmDouble epl_thickness;
-	IssmDouble epl_head,sed_head;
-	IssmDouble sediment_transmitivity;
-	IssmDouble leakage,h_max,transfer;
-
-	IssmDouble sediment_thickness  = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
-	IssmDouble sediment_storing    = SedimentStoring(element);
- 	IssmDouble epl_specificstoring = EplSpecificStoring(element);		
-
+	IssmDouble hmax;
+	IssmDouble epl_head,sediment_head;
+	IssmDouble leakage,transfer;
+	IssmDouble continuum, factor;
+	
 	element->FindParam(&transfermethod,HydrologydcTransferFlagEnum);
+
 	/*Switch between the different transfer methods cases*/
 	switch(transfermethod){
@@ -591,56 +602,36 @@
 		break;
 	case 1:
-		
-		_assert_(epl_thick_input);
 		_assert_(sed_head_input);
 		_assert_(epl_head_input);
-		_assert_(sed_trans_input);
-		_assert_(thickness_input);
-		_assert_(base_input);
-
-		epl_thick_input->GetInputValue(&epl_thickness,gauss);
-		sed_head_input->GetInputValue(&sed_head,gauss);
+		
+		sed_head_input->GetInputValue(&sediment_head,gauss);
 		epl_head_input->GetInputValue(&epl_head,gauss);
-		sed_trans_input->GetInputValue(&sediment_transmitivity,gauss);
 		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
-		
-		transfer=(sediment_transmitivity)/(sediment_thickness*leakage);
-		
-		/* if(epl_head>sed_head){ */
-		/* 	h_max=GetHydrologyDCInefficientHmax(element,gauss,thickness_input,base_input); */
-		/* 	if(sed_head>=h_max){ */
-		/* 		transfer=0.0; */
-		/* 	} */
-		/* 	else{ */
-		/* 		transfer=(sediment_transmitivity)/(sediment_thickness*leakage); */
-		/* 		//transfer=(epl_specificstoring*epl_thickness*sediment_transmitivity)/(sediment_thickness*leakage); */
-		/* 	} */
-		/* } */
-		/* else{ */
-		/* 	transfer=(sediment_transmitivity)/(sediment_thickness*leakage); */
-		/* 	//transfer=(sediment_storing*sediment_transmitivity)/(sediment_thickness*leakage); */
-		/* } */
-		
+
+		hmax=GetHydrologyDCInefficientHmax(element, gauss, thick_input, base_input);
+	
+		//Computing continuum function to apply to transfer term, transfer is null only if
+		//epl_head>sediment_head AND sediment_head>h_max
+		continuum=((1.0/(1.0+exp(-20.0*(sediment_head-epl_head)))))+(1.0/(1.0+exp(-20.0*(hmax-sediment_head))));
+		factor=min(continuum,1.0);
+		transfer=leakage*factor;
+
 		break;
 	default:
 		_error_("no case higher than 1 for the Transfer method");
 	}
-	
 	return transfer;
 }/*}}}*/
 
-IssmDouble HydrologyDCInefficientAnalysis::GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* thickness_input, Input* base_input){/*{{{*/
+IssmDouble HydrologyDCInefficientAnalysis::GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* sed_head_input, Input* epl_head_input, Input* thick_input, Input* base_input){/*{{{*/
 
 	int transfermethod;
-	IssmDouble epl_thickness;
+	IssmDouble hmax;
 	IssmDouble epl_head,sediment_head;
-	IssmDouble sediment_transmitivity;
-	IssmDouble leakage,h_max,transfer;
-
-	IssmDouble sediment_thickness = element->GetMaterialParameter(HydrologydcSedimentThicknessEnum);
-	IssmDouble sediment_storing   = SedimentStoring(element);
- 	IssmDouble epl_specificstoring = EplSpecificStoring(element);		
-
+	IssmDouble leakage,transfer;
+	IssmDouble continuum, factor;
+	
 	element->FindParam(&transfermethod,HydrologydcTransferFlagEnum);
+
 	/*Switch between the different transfer methods cases*/
 	switch(transfermethod){
@@ -650,33 +641,18 @@
 		break;
 	case 1:
-		
-		_assert_(epl_thick_input);
 		_assert_(sed_head_input);
 		_assert_(epl_head_input);
-		_assert_(sed_trans_input);
-		_assert_(thickness_input);
-		_assert_(base_input);
-
-		epl_thick_input->GetInputValue(&epl_thickness,gauss);
+		
 		sed_head_input->GetInputValue(&sediment_head,gauss);
 		epl_head_input->GetInputValue(&epl_head,gauss);
-		sed_trans_input->GetInputValue(&sediment_transmitivity,gauss);
-
 		element->FindParam(&leakage,HydrologydcLeakageFactorEnum);
- 		transfer=(sediment_transmitivity*epl_head)/(sediment_thickness*leakage);
-		/* if(epl_head>sediment_head){ */
-		/* 	h_max=GetHydrologyDCInefficientHmax(element,gauss,thickness_input,base_input); */
- 		/* 	if(sediment_head>=h_max){ */
-		/* 		transfer=0.0; */
-		/* 	} */
-		/* 	else{ */
-		/* 		transfer=(sediment_transmitivity*epl_head)/(sediment_thickness*leakage); */
-		/* 		//transfer=(epl_specificstoring*epl_thickness*sediment_transmitivity*epl_head)/(sediment_thickness*leakage); */
-		/* 	} */
-		/* } */
-		/* else{ */
-		/* 	transfer=(sediment_transmitivity*epl_head)/(sediment_thickness*leakage); */
-		/* 	//transfer=(sediment_storing*sediment_transmitivity*epl_head)/(sediment_thickness*leakage); */
-		/* } */
+
+		hmax=GetHydrologyDCInefficientHmax(element, gauss, thick_input, base_input);
+		
+		//Computing continuum function to apply to transfer term, transfer is null only if
+		//epl_head>sediment_head AND sediment_head>h_max
+		continuum=((1.0/(1.0+exp(-20.0*(sediment_head-epl_head)))))+(1.0/(1.0+exp(-20.0*(hmax-sediment_head))));
+		factor=min(continuum,1.0);
+		transfer=epl_head*leakage*factor;
 		break;
 	default:
@@ -692,9 +668,8 @@
 
 	for(int i=0;i<femmodel->elements->Size();i++){
-		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-
-		int numvertices = element->GetNumberOfVertices();
-		Input* node_mask_input = element->GetInput(HydrologydcMaskEplactiveNodeEnum);
-		if(node_mask_input->Max()>0.) {
+		element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			Input* node_mask_input = element->GetInput(HydrologydcMaskEplactiveNodeEnum); _assert_(node_mask_input);
+		
+		if(node_mask_input->Max()>0.){
 			element_active = true;
 		}
@@ -705,3 +680,2 @@
 	}
 }/*}}}*/
-
Index: /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/HydrologyDCInefficientAnalysis.h	(revision 19105)
@@ -38,6 +38,6 @@
 		IssmDouble GetHydrologyDCInefficientHmax(Element* element, Gauss* gauss, Input* thickness_input, Input* base_input);
 		void GetHydrologyDCInefficientHmax(IssmDouble* ph_max,Element* element, Node* innode);
-		IssmDouble GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* thickness_input, Input* base_input);
-		IssmDouble GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* epl_thick_input, Input* sed_head_input, Input* epl_head_input, Input* sed_trans_input, Input* thickness_input, Input* base_input);
+		IssmDouble GetHydrologyKMatrixTransfer(Element* element, Gauss* gauss, Input* sed_head_input, Input* epl_head_input, Input* thick_input, Input* base_input);
+		IssmDouble GetHydrologyPVectorTransfer(Element* element, Gauss* gauss, Input* sed_head_input, Input* epl_head_input, Input* thick_input, Input* base_input);
 		void ElementizeEplMask(FemModel* femmodel);
 };
Index: /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.cpp	(revision 19105)
@@ -6,19 +6,33 @@
 
 /*Model processing*/
+void HydrologyShreveAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*retrieve some parameters: */
+	int          hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	if(hydrology_model!=HydrologyshreveEnum) return;
+
+	IoModelToConstraintsx(constraints,iomodel,HydrologyshreveSpcwatercolumnEnum,HydrologyShreveAnalysisEnum,P1Enum);
+
+}/*}}}*/
+void HydrologyShreveAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	/*No loads*/
+}/*}}}*/
+void HydrologyShreveAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+
+	/*Now, do we really want Shreve?*/
+	if(hydrology_model!=HydrologyshreveEnum) return;
+
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,HydrologyShreveAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
 int  HydrologyShreveAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void HydrologyShreveAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-
-	/*retrieve some parameters: */
-	int  hydrology_model;
-	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
-
-	/*Now, do we really want Shreve?*/
-	if(hydrology_model!=HydrologyshreveEnum) return;
-
-	parameters->AddObject(new IntParam(HydrologyModelEnum,hydrology_model));
-	parameters->AddObject(iomodel->CopyConstantObject(HydrologyshreveStabilizationEnum));
-
 }/*}}}*/
 void HydrologyShreveAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -55,7 +69,7 @@
 	elements->InputDuplicate(WatercolumnEnum,WaterColumnOldEnum);
 }/*}}}*/
-void HydrologyShreveAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	/*Fetch parameters: */
+void HydrologyShreveAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*retrieve some parameters: */
 	int  hydrology_model;
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
@@ -64,21 +78,7 @@
 	if(hydrology_model!=HydrologyshreveEnum) return;
 
-	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	::CreateNodes(nodes,iomodel,HydrologyShreveAnalysisEnum,P1Enum);
-	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-}/*}}}*/
-void HydrologyShreveAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-
-	/*retrieve some parameters: */
-	int          hydrology_model;
-	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
-
-	if(hydrology_model!=HydrologyshreveEnum) return;
-
-	IoModelToConstraintsx(constraints,iomodel,HydrologyshreveSpcwatercolumnEnum,HydrologyShreveAnalysisEnum,P1Enum);
-
-}/*}}}*/
-void HydrologyShreveAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-	/*No loads*/
+	parameters->AddObject(new IntParam(HydrologyModelEnum,hydrology_model));
+	parameters->AddObject(iomodel->CopyConstantObject(HydrologyshreveStabilizationEnum));
+
 }/*}}}*/
 
@@ -90,4 +90,48 @@
 	/*Default, return NULL*/
 	return NULL;
+}/*}}}*/
+void           HydrologyShreveAnalysis::CreateHydrologyWaterVelocityInput(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dsdx,dsdy,dbdx,dbdy,w;
+
+	/*Retrieve all inputs and parameters*/
+	IssmDouble  rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  rho_water = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  g         = element->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble  mu_water  = element->GetMaterialParameter(MaterialsMuWaterEnum);
+	Input* surfaceslopex_input = element->GetInput(SurfaceSlopeXEnum); _assert_(surfaceslopex_input);
+	Input* surfaceslopey_input = element->GetInput(SurfaceSlopeYEnum); _assert_(surfaceslopey_input);
+	Input* bedslopex_input     = element->GetInput(BedSlopeXEnum);     _assert_(bedslopex_input);
+	Input* bedslopey_input     = element->GetInput(BedSlopeYEnum);     _assert_(bedslopey_input);
+	Input* watercolumn_input   = element->GetInput(WatercolumnEnum);   _assert_(watercolumn_input);
+
+	/*Fetch number of vertices and allocate output*/
+	int numvertices = element->GetNumberOfVertices();
+	IssmDouble* vx  = xNew<IssmDouble>(numvertices);
+	IssmDouble* vy  = xNew<IssmDouble>(numvertices);
+
+	Gauss* gauss=element->NewGauss();
+	for(int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+		surfaceslopex_input->GetInputValue(&dsdx,gauss);
+		surfaceslopey_input->GetInputValue(&dsdy,gauss);
+		bedslopex_input->GetInputValue(&dbdx,gauss);
+		bedslopey_input->GetInputValue(&dbdy,gauss);
+		watercolumn_input->GetInputValue(&w,gauss);
+
+		/* Water velocity x and y components */
+		vx[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
+		vy[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
+	}
+
+	/*clean-up*/
+	delete gauss;
+
+	/*Add to inputs*/
+	element->AddInput(HydrologyWaterVxEnum,vx,P1Enum);
+	element->AddInput(HydrologyWaterVyEnum,vy,P1Enum);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(vy);
 }/*}}}*/
 ElementMatrix* HydrologyShreveAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
@@ -234,5 +278,5 @@
 	return pe;
 }/*}}}*/
-void HydrologyShreveAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           HydrologyShreveAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
 	 * For node i, Bi can be expressed in the actual coordinate system
@@ -261,5 +305,5 @@
 	xDelete<IssmDouble>(basis);
 }/*}}}*/
-void HydrologyShreveAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           HydrologyShreveAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
 	 * For node i, Bi' can be expressed in the actual coordinate system
@@ -289,11 +333,11 @@
 
 }/*}}}*/
-void HydrologyShreveAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           HydrologyShreveAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	element->GetSolutionFromInputsOneDof(solution,WatercolumnEnum);
 }/*}}}*/
-void HydrologyShreveAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           HydrologyShreveAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void HydrologyShreveAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           HydrologyShreveAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	/*Intermediary*/
@@ -321,55 +365,8 @@
 	xDelete<int>(doflist);
 }/*}}}*/
-void HydrologyShreveAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           HydrologyShreveAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
 }/*}}}*/
-
-/*Intermediaries*/
-void HydrologyShreveAnalysis::CreateHydrologyWaterVelocityInput(Element* element){/*{{{*/
-
-	/*Intermediaries*/
-	IssmDouble dsdx,dsdy,dbdx,dbdy,w;
-
-	/*Retrieve all inputs and parameters*/
-	IssmDouble  rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
-	IssmDouble  rho_water = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
-	IssmDouble  g         = element->GetMaterialParameter(ConstantsGEnum);
-	IssmDouble  mu_water  = element->GetMaterialParameter(MaterialsMuWaterEnum);
-	Input* surfaceslopex_input = element->GetInput(SurfaceSlopeXEnum); _assert_(surfaceslopex_input);
-	Input* surfaceslopey_input = element->GetInput(SurfaceSlopeYEnum); _assert_(surfaceslopey_input);
-	Input* bedslopex_input     = element->GetInput(BedSlopeXEnum);     _assert_(bedslopex_input);
-	Input* bedslopey_input     = element->GetInput(BedSlopeYEnum);     _assert_(bedslopey_input);
-	Input* watercolumn_input   = element->GetInput(WatercolumnEnum);   _assert_(watercolumn_input);
-
-	/*Fetch number of vertices and allocate output*/
-	int numvertices = element->GetNumberOfVertices();
-	IssmDouble* vx  = xNew<IssmDouble>(numvertices);
-	IssmDouble* vy  = xNew<IssmDouble>(numvertices);
-
-	Gauss* gauss=element->NewGauss();
-	for(int iv=0;iv<numvertices;iv++){
-		gauss->GaussVertex(iv);
-		surfaceslopex_input->GetInputValue(&dsdx,gauss);
-		surfaceslopey_input->GetInputValue(&dsdy,gauss);
-		bedslopex_input->GetInputValue(&dbdx,gauss);
-		bedslopey_input->GetInputValue(&dbdy,gauss);
-		watercolumn_input->GetInputValue(&w,gauss);
-
-		/* Water velocity x and y components */
-		vx[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdx+(rho_water-rho_ice)*g*dbdx);
-		vy[iv]= - w*w/(12 * mu_water)*(rho_ice*g*dsdy+(rho_water-rho_ice)*g*dbdy);
-	}
-
-	/*clean-up*/
-	delete gauss;
-
-	/*Add to inputs*/
-	element->AddInput(HydrologyWaterVxEnum,vx,P1Enum);
-	element->AddInput(HydrologyWaterVyEnum,vy,P1Enum);
-	xDelete<IssmDouble>(vx);
-	xDelete<IssmDouble>(vy);
-}/*}}}*/
-
 
 
Index: /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/HydrologyShreveAnalysis.h	(revision 19105)
@@ -13,26 +13,24 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,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);
 		ElementVector* CreateDVector(Element* element);
+		void           CreateHydrologyWaterVelocityInput(Element* element);
 		ElementMatrix* CreateJacobianMatrix(Element* element);
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
-
-		/*Intermediaries*/
-		void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void CreateHydrologyWaterVelocityInput(Element* element);
+		void           GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.cpp	(revision 19105)
@@ -6,8 +6,25 @@
 
 /*Model processing*/
+void L2ProjectionBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*No constraints*/
+}/*}}}*/
+void L2ProjectionBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+}/*}}}*/
+void L2ProjectionBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype==Domain3DEnum){
+		iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	}
+	else if(iomodel->domaintype==Domain2DverticalEnum){
+		iomodel->FetchData(1,MeshVertexonbaseEnum);
+	}
+	::CreateNodes(nodes,iomodel,L2ProjectionBaseAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
 int  L2ProjectionBaseAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void L2ProjectionBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 void L2ProjectionBaseAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -31,22 +48,5 @@
 	}
 }/*}}}*/
-void L2ProjectionBaseAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	if(iomodel->domaintype==Domain3DEnum){
-		iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	}
-	else if(iomodel->domaintype==Domain2DverticalEnum){
-		iomodel->FetchData(1,MeshVertexonbaseEnum);
-	}
-	::CreateNodes(nodes,iomodel,L2ProjectionBaseAnalysisEnum,P1Enum);
-	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-}/*}}}*/
-void L2ProjectionBaseAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-
-	/*No constraints*/
-}/*}}}*/
-void L2ProjectionBaseAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
-	/*No loads*/
+void L2ProjectionBaseAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 
@@ -93,5 +93,5 @@
 
 	/*Initialize Element vector*/
-	ElementMatrix* Ke    = basalelement->NewElementMatrix(NoneApproximationEnum);
+	ElementMatrix* Ke    = basalelement->NewElementMatrix();
 	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
 
@@ -196,11 +196,11 @@
 	return pe;
 }/*}}}*/
-void L2ProjectionBaseAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           L2ProjectionBaseAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void L2ProjectionBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           L2ProjectionBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void L2ProjectionBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           L2ProjectionBaseAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int inputenum,domaintype,elementtype;
@@ -225,5 +225,5 @@
 	}
 }/*}}}*/
-void L2ProjectionBaseAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           L2ProjectionBaseAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/L2ProjectionBaseAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,8 +26,8 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.cpp	(revision 19105)
@@ -6,8 +6,34 @@
 
 /*Model processing*/
+void L2ProjectionEPLAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*No constraints*/
+}/*}}}*/
+void L2ProjectionEPLAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*No loads*/
+}/*}}}*/
+void L2ProjectionEPLAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	/*Now, do we really want DC?*/
+	int  hydrology_model;
+	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
+
+	/*Do we want an efficient layer*/
+	bool isefficientlayer;
+	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+	if(!isefficientlayer) return;
+
+	if(iomodel->domaintype==Domain3DEnum){
+		iomodel->FetchData(1,MeshVertexonbaseEnum);
+	}
+	else if(iomodel->domaintype==Domain2DverticalEnum){
+		iomodel->FetchData(1,MeshVertexonbaseEnum);
+	}
+	::CreateNodes(nodes,iomodel,L2ProjectionEPLAnalysisEnum,P1Enum);
+	iomodel->DeleteData(1,MeshVertexonbaseEnum);
+}/*}}}*/
 int  L2ProjectionEPLAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void L2ProjectionEPLAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 void L2ProjectionEPLAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -41,31 +67,5 @@
 	}
 }/*}}}*/
-void L2ProjectionEPLAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-	/*Now, do we really want DC?*/
-	int  hydrology_model;
-	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
-	if(hydrology_model!=HydrologydcEnum) return;
-
-	/*Do we want an efficient layer*/
-	bool isefficientlayer;
-	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
-	if(!isefficientlayer) return;
-
-	if(iomodel->domaintype==Domain3DEnum){
-		iomodel->FetchData(1,MeshVertexonbaseEnum);
-	}
-	else if(iomodel->domaintype==Domain2DverticalEnum){
-		iomodel->FetchData(1,MeshVertexonbaseEnum);
-	}
-	::CreateNodes(nodes,iomodel,L2ProjectionEPLAnalysisEnum,P1Enum);
-	iomodel->DeleteData(1,MeshVertexonbaseEnum);
-}/*}}}*/
-void L2ProjectionEPLAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-
-	/*No constraints*/
-}/*}}}*/
-void L2ProjectionEPLAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
-	/*No loads*/
+void L2ProjectionEPLAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 
@@ -226,11 +226,11 @@
 	return pe;
 }/*}}}*/
-void L2ProjectionEPLAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           L2ProjectionEPLAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void L2ProjectionEPLAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           L2ProjectionEPLAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void L2ProjectionEPLAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           L2ProjectionEPLAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	int inputenum,domaintype;
 
@@ -250,5 +250,5 @@
 	}
 }/*}}}*/
-void L2ProjectionEPLAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           L2ProjectionEPLAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/L2ProjectionEPLAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,8 +26,8 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/LevelsetAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/LevelsetAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/LevelsetAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,13 +26,13 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
-		void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void SetDistanceOnIntersectedElements(FemModel* femmodel);
-		void SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_signed_dist, Element* element);
-		IssmDouble GetDistanceToStraight(IssmDouble* q, IssmDouble* s0, IssmDouble* s1);
+		void           GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		IssmDouble     GetDistanceToStraight(IssmDouble* q, IssmDouble* s0, IssmDouble* s1);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           SetDistanceOnIntersectedElements(FemModel* femmodel);
+		void           SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_signed_dist, Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/LsfReinitializationAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/LsfReinitializationAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/LsfReinitializationAnalysis.cpp	(revision 19105)
@@ -10,9 +10,18 @@
 
 /*Model processing*/
+void LsfReinitializationAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	/* Do nothing for now */
+}/*}}}*/
+void LsfReinitializationAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	/* Do nothing for now */
+}/*}}}*/
+void LsfReinitializationAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+	int finiteelement=P1Enum;
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,LsfReinitializationAnalysisEnum,finiteelement);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
 int  LsfReinitializationAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void LsfReinitializationAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-	/* Do nothing for now */
 }/*}}}*/
 void LsfReinitializationAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -34,19 +43,10 @@
 	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
 }/*}}}*/
-void LsfReinitializationAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-	int finiteelement=P1Enum;
-	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	::CreateNodes(nodes,iomodel,LsfReinitializationAnalysisEnum,finiteelement);
-	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-}/*}}}*/
-void LsfReinitializationAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+void LsfReinitializationAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 	/* Do nothing for now */
 }/*}}}*/
-void LsfReinitializationAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-	/* Do nothing for now */
-}/*}}}*/
 
 /*Finite element Analysis*/
-void  LsfReinitializationAnalysis::Core(FemModel* femmodel){/*{{{*/
+void           LsfReinitializationAnalysis::Core(FemModel* femmodel){/*{{{*/
 
 	/*parameters: */
@@ -249,5 +249,84 @@
 	return pe;
 	}/*}}}*/
-void LsfReinitializationAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           LsfReinitializationAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi=[ N ]
+	 *          [ N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void           LsfReinitializationAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_prime=[ dN/dx ]
+	 *                [ dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B': */
+	for(int i=0;i<numnodes;i++){
+		Bprime[numnodes*0+i] = dbasis[0*numnodes+i];
+		Bprime[numnodes*1+i] = dbasis[1*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+
+}/*}}}*/
+IssmDouble     LsfReinitializationAnalysis::GetDistanceToStraight(IssmDouble* q, IssmDouble* s0, IssmDouble* s1){/*{{{*/
+	// returns distance d of point q to straight going through points s0, s1
+	// d=|a x b|/|b|
+	// with a=q-s0, b=s1-s0
+	
+	/* Intermediaries */
+	const int dim=2;
+	int i;
+	IssmDouble a[dim], b[dim];
+	IssmDouble norm_b;
+
+	for(i=0;i<dim;i++){
+		a[i]=q[i]-s0[i];
+		b[i]=s1[i]-s0[i];
+	}
+	
+	norm_b=0.;
+	for(i=0;i<dim;i++)
+		norm_b+=b[i]*b[i];
+	norm_b=sqrt(norm_b);
+	_assert_(norm_b>0.);
+
+	return fabs(a[0]*b[1]-a[1]*b[0])/norm_b;
+}/*}}}*/
+void           LsfReinitializationAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 
 	IssmDouble   lsf;
@@ -284,8 +363,8 @@
 
 }/*}}}*/
-void LsfReinitializationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           LsfReinitializationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void LsfReinitializationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           LsfReinitializationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int domaintype;
@@ -301,65 +380,142 @@
 	}
 }/*}}}*/
-void LsfReinitializationAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
-	/* Do nothing for now */
-}/*}}}*/
-void LsfReinitializationAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
-	 * For node i, Bi can be expressed in the actual coordinate system
-	 * by: 
-	 *       Bi=[ N ]
-	 *          [ N ]
-	 * where N is the finiteelement function for node i.
-	 *
-	 * We assume B_prog has been allocated already, of size: 2x(NDOF1*numnodes)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions*/
-	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	element->NodalFunctions(basis,gauss);
-
-	/*Build B: */
-	for(int i=0;i<numnodes;i++){
-		B[numnodes*0+i] = basis[i];
-		B[numnodes*1+i] = basis[i];
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(basis);
-}/*}}}*/
-void LsfReinitializationAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
-	 * For node i, Bi' can be expressed in the actual coordinate system
-	 * by: 
-	 *       Bi_prime=[ dN/dx ]
-	 *                [ dN/dy ]
-	 * where N is the finiteelement function for node i.
-	 *
-	 * We assume B' has been allocated already, of size: 3x(NDOF2*numnodes)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
-	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-	/*Build B': */
-	for(int i=0;i<numnodes;i++){
-		Bprime[numnodes*0+i] = dbasis[0*numnodes+i];
-		Bprime[numnodes*1+i] = dbasis[1*numnodes+i];
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(dbasis);
-
-}/*}}}*/
-
-/* Other */
-void LsfReinitializationAnalysis::SetReinitSPCs(FemModel* femmodel){/*{{{*/
+bool           LsfReinitializationAnalysis::ReinitConvergence(Vector<IssmDouble>* lsfg,Vector<IssmDouble>* lsfg_old,IssmDouble reltol){/*{{{*/
+
+	/*Output*/
+	bool converged = true;
+
+	/*Intermediary*/
+	Vector<IssmDouble>* dlsfg    = NULL;
+	IssmDouble          norm_dlsf,norm_lsf;
+
+	/*compute norm(du)/norm(u)*/
+	dlsfg=lsfg_old->Duplicate(); lsfg_old->Copy(dlsfg); dlsfg->AYPX(lsfg,-1.0);
+	norm_dlsf=dlsfg->Norm(NORM_TWO); norm_lsf=lsfg_old->Norm(NORM_TWO);
+	if (xIsNan<IssmDouble>(norm_dlsf) || xIsNan<IssmDouble>(norm_lsf)) _error_("convergence criterion is NaN!");
+	if((norm_dlsf/norm_lsf)<reltol){
+		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<norm_dlsf/norm_lsf*100<<" < "<<reltol*100<<" %\n");
+	}
+	else{ 
+		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<norm_dlsf/norm_lsf*100<<" > "<<reltol*100<<" %\n");
+		converged=false;
+	}
+
+	/*Cleanup*/
+	delete dlsfg;
+
+	return converged;
+}/*}}}*/
+void           LsfReinitializationAnalysis::SetDistanceOnIntersectedElements(FemModel* femmodel){/*{{{*/
+
+	/* Intermediaries */
+	int i;
+	IssmDouble dmaxp,dmaxm,val;
+	Element* element;
+
+	/*Initialize vector with number of vertices*/
+	int numvertices=femmodel->vertices->NumberOfVertices();
+
+	Vector<IssmDouble>* vec_dist_zerolevelset = NULL;
+	GetVectorFromInputsx(&vec_dist_zerolevelset, femmodel, MaskIceLevelsetEnum, VertexPIdEnum);
+	
+	/* set distance on elements intersected by zero levelset */
+	for(i=0;i<femmodel->elements->Size();i++){
+		element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		if(element->IsZeroLevelset(MaskIceLevelsetEnum)){
+			SetDistanceToZeroLevelsetElement(vec_dist_zerolevelset, element);
+		}
+	}
+	vec_dist_zerolevelset->Assemble();
+
+	/* Get maximum distance to interface along vertices */
+	dmaxp=0.; dmaxm=0.;
+	for(i=0;i<numvertices;i++){
+		vec_dist_zerolevelset->GetValue(&val,i); 
+		if((val>0.) && (val>dmaxp))
+			 dmaxp=val;
+		else if((val<0.) && (val<dmaxm))
+			 dmaxm=val;
+	}
+	//wait until all values are computed
+
+	/* set all none intersected vertices to max/min distance */
+	for(i=0;i<numvertices;i++){
+		vec_dist_zerolevelset->GetValue(&val,i);
+		if(val==1.) //FIXME: improve check
+			vec_dist_zerolevelset->SetValue(i,3.*dmaxp,INS_VAL);
+		else if(val==-1.)
+			vec_dist_zerolevelset->SetValue(i,3.*dmaxm,INS_VAL);
+	}
+
+	/*Assemble vector and serialize */
+	vec_dist_zerolevelset->Assemble();
+	IssmDouble* dist_zerolevelset=vec_dist_zerolevelset->ToMPISerial();
+	InputUpdateFromVectorx(femmodel,dist_zerolevelset,MaskIceLevelsetEnum,VertexSIdEnum);
+
+	/*Clean up and return*/
+	delete vec_dist_zerolevelset;
+	delete dist_zerolevelset;
+
+}/*}}}*/
+void           LsfReinitializationAnalysis::SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_signed_dist, Element* element){/*{{{*/
+
+	if(!element->IsZeroLevelset(MaskIceLevelsetEnum))
+		return;
+
+	/* Intermediaries */
+	int dim=3;
+	int i,d;
+	IssmDouble dist,lsf_old;
+
+	int numvertices=element->GetNumberOfVertices();
+
+	IssmDouble* lsf = xNew<IssmDouble>(numvertices);
+	IssmDouble* sign_lsf = xNew<IssmDouble>(numvertices);
+	IssmDouble* signed_dist = xNew<IssmDouble>(numvertices);
+	IssmDouble* s0 = xNew<IssmDouble>(dim);
+	IssmDouble* s1 = xNew<IssmDouble>(dim);
+	IssmDouble* v = xNew<IssmDouble>(dim);
+	IssmDouble* xyz_list = NULL;
+	IssmDouble* xyz_list_zero = NULL;
+
+	/* retrieve inputs and parameters */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetInputListOnVertices(lsf,MaskIceLevelsetEnum);
+
+	/* get sign of levelset function */
+	for(i=0;i<numvertices;i++)
+		sign_lsf[i]=(lsf[i]>=0.?1.:-1.);
+
+	element->ZeroLevelsetCoordinates(&xyz_list_zero, xyz_list, MaskIceLevelsetEnum);
+	for(i=0;i<dim;i++){
+		s0[i]=xyz_list_zero[0+i];
+		s1[i]=xyz_list_zero[3+i];
+	}
+
+	/* get signed_distance of vertices to zero levelset straight */
+	for(i=0;i<numvertices;i++){
+		for(d=0;d<dim;d++)
+			v[d]=xyz_list[dim*i+d];
+		dist=GetDistanceToStraight(&v[0],&s0[0],&s1[0]);
+		signed_dist[i]=sign_lsf[i]*dist;
+	}
+	
+	/* insert signed_distance into vec_signed_dist, if computed distance is smaller */
+	for(i=0;i<numvertices;i++){
+		vec_signed_dist->GetValue(&lsf_old, element->vertices[i]->Sid());
+		/* initial lsf values are +-1. Update those fields or if distance to interface smaller.*/
+		if(fabs(lsf_old)==1. || fabs(signed_dist[i])<fabs(lsf_old))
+			vec_signed_dist->SetValue(element->vertices[i]->Sid(),signed_dist[i],INS_VAL);
+	}
+
+	xDelete<IssmDouble>(lsf);
+	xDelete<IssmDouble>(sign_lsf);
+	xDelete<IssmDouble>(signed_dist);
+	xDelete<IssmDouble>(s0);
+	xDelete<IssmDouble>(s1);
+	xDelete<IssmDouble>(v);
+
+}/*}}}*/
+void           LsfReinitializationAnalysis::SetReinitSPCs(FemModel* femmodel){/*{{{*/
 
 	int i,k, numnodes;
@@ -369,5 +525,5 @@
 	/* deactivate all spcs */
 	for(i=0;i<femmodel->elements->Size();i++){
-		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		for(k=0;k<element->GetNumberOfNodes();k++){
 			node=element->GetNode(k);
@@ -382,5 +538,5 @@
 	/* reactivate spcs on elements intersected by zero levelset */
 	for(i=0;i<femmodel->elements->Size();i++){
-		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		if(element->IsZeroLevelset(MaskIceLevelsetEnum)){
 			/*iterate over nodes and set spc */
@@ -399,163 +555,5 @@
 
 }/*}}}*/
-void LsfReinitializationAnalysis::SetDistanceOnIntersectedElements(FemModel* femmodel){/*{{{*/
-
-	/* Intermediaries */
-	int i;
-	IssmDouble dmaxp,dmaxm,val;
-	Element* element;
-
-	/*Initialize vector with number of vertices*/
-	int numvertices=femmodel->vertices->NumberOfVertices();
-
-	Vector<IssmDouble>* vec_dist_zerolevelset = NULL;
-	GetVectorFromInputsx(&vec_dist_zerolevelset, femmodel, MaskIceLevelsetEnum, VertexEnum);
-	
-	/* set distance on elements intersected by zero levelset */
-	for(i=0;i<femmodel->elements->Size();i++){
-		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-		if(element->IsZeroLevelset(MaskIceLevelsetEnum)){
-			SetDistanceToZeroLevelsetElement(vec_dist_zerolevelset, element);
-		}
-	}
-	vec_dist_zerolevelset->Assemble();
-
-	/* Get maximum distance to interface along vertices */
-	dmaxp=0.; dmaxm=0.;
-	for(i=0;i<numvertices;i++){
-		vec_dist_zerolevelset->GetValue(&val,i); 
-		if((val>0.) && (val>dmaxp))
-			 dmaxp=val;
-		else if((val<0.) && (val<dmaxm))
-			 dmaxm=val;
-	}
-	//wait until all values are computed
-
-	/* set all none intersected vertices to max/min distance */
-	for(i=0;i<numvertices;i++){
-		vec_dist_zerolevelset->GetValue(&val,i);
-		if(val==1.) //FIXME: improve check
-			vec_dist_zerolevelset->SetValue(i,3.*dmaxp,INS_VAL);
-		else if(val==-1.)
-			vec_dist_zerolevelset->SetValue(i,3.*dmaxm,INS_VAL);
-	}
-
-	/*Assemble vector and serialize */
-	vec_dist_zerolevelset->Assemble();
-	IssmDouble* dist_zerolevelset=vec_dist_zerolevelset->ToMPISerial();
-	InputUpdateFromVectorx(femmodel,dist_zerolevelset,MaskIceLevelsetEnum,VertexSIdEnum);
-
-	/*Clean up and return*/
-	delete vec_dist_zerolevelset;
-	delete dist_zerolevelset;
-
-}/*}}}*/
-void LsfReinitializationAnalysis::SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_signed_dist, Element* element){/*{{{*/
-
-	if(!element->IsZeroLevelset(MaskIceLevelsetEnum))
-		return;
-
-	/* Intermediaries */
-	int dim=3;
-	int i,d;
-	IssmDouble dist,lsf_old;
-
-	int numvertices=element->GetNumberOfVertices();
-
-	IssmDouble* lsf = xNew<IssmDouble>(numvertices);
-	IssmDouble* sign_lsf = xNew<IssmDouble>(numvertices);
-	IssmDouble* signed_dist = xNew<IssmDouble>(numvertices);
-	IssmDouble* s0 = xNew<IssmDouble>(dim);
-	IssmDouble* s1 = xNew<IssmDouble>(dim);
-	IssmDouble* v = xNew<IssmDouble>(dim);
-	IssmDouble* xyz_list = NULL;
-	IssmDouble* xyz_list_zero = NULL;
-
-	/* retrieve inputs and parameters */
-	element->GetVerticesCoordinates(&xyz_list);
-	element->GetInputListOnVertices(lsf,MaskIceLevelsetEnum);
-
-	/* get sign of levelset function */
-	for(i=0;i<numvertices;i++)
-		sign_lsf[i]=(lsf[i]>=0.?1.:-1.);
-
-	element->ZeroLevelsetCoordinates(&xyz_list_zero, xyz_list, MaskIceLevelsetEnum);
-	for(i=0;i<dim;i++){
-		s0[i]=xyz_list_zero[0+i];
-		s1[i]=xyz_list_zero[3+i];
-	}
-
-	/* get signed_distance of vertices to zero levelset straight */
-	for(i=0;i<numvertices;i++){
-		for(d=0;d<dim;d++)
-			v[d]=xyz_list[dim*i+d];
-		dist=GetDistanceToStraight(&v[0],&s0[0],&s1[0]);
-		signed_dist[i]=sign_lsf[i]*dist;
-	}
-	
-	/* insert signed_distance into vec_signed_dist, if computed distance is smaller */
-	for(i=0;i<numvertices;i++){
-		vec_signed_dist->GetValue(&lsf_old, element->vertices[i]->Sid());
-		/* initial lsf values are +-1. Update those fields or if distance to interface smaller.*/
-		if(fabs(lsf_old)==1. || fabs(signed_dist[i])<fabs(lsf_old))
-			vec_signed_dist->SetValue(element->vertices[i]->Sid(),signed_dist[i],INS_VAL);
-	}
-
-	xDelete<IssmDouble>(lsf);
-	xDelete<IssmDouble>(sign_lsf);
-	xDelete<IssmDouble>(signed_dist);
-	xDelete<IssmDouble>(s0);
-	xDelete<IssmDouble>(s1);
-	xDelete<IssmDouble>(v);
-
-}/*}}}*/
-IssmDouble LsfReinitializationAnalysis::GetDistanceToStraight(IssmDouble* q, IssmDouble* s0, IssmDouble* s1){/*{{{*/
-	// returns distance d of point q to straight going through points s0, s1
-	// d=|a x b|/|b|
-	// with a=q-s0, b=s1-s0
-	
-	/* Intermediaries */
-	const int dim=2;
-	int i;
-	IssmDouble a[dim], b[dim];
-	IssmDouble norm_b;
-
-	for(i=0;i<dim;i++){
-		a[i]=q[i]-s0[i];
-		b[i]=s1[i]-s0[i];
-	}
-	
-	norm_b=0.;
-	for(i=0;i<dim;i++)
-		norm_b+=b[i]*b[i];
-	norm_b=sqrt(norm_b);
-	_assert_(norm_b>0.);
-
-	return fabs(a[0]*b[1]-a[1]*b[0])/norm_b;
-}/*}}}*/
-bool LsfReinitializationAnalysis::ReinitConvergence(Vector<IssmDouble>* lsfg,Vector<IssmDouble>* lsfg_old,IssmDouble reltol){/*{{{*/
-
-	/*Output*/
-	bool converged = true;
-
-	/*Intermediary*/
-	Vector<IssmDouble>* dlsfg    = NULL;
-	IssmDouble          norm_dlsf,norm_lsf;
-
-	/*compute norm(du)/norm(u)*/
-	dlsfg=lsfg_old->Duplicate(); lsfg_old->Copy(dlsfg); dlsfg->AYPX(lsfg,-1.0);
-	norm_dlsf=dlsfg->Norm(NORM_TWO); norm_lsf=lsfg_old->Norm(NORM_TWO);
-	if (xIsNan<IssmDouble>(norm_dlsf) || xIsNan<IssmDouble>(norm_lsf)) _error_("convergence criterion is NaN!");
-	if((norm_dlsf/norm_lsf)<reltol){
-		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<norm_dlsf/norm_lsf*100<<" < "<<reltol*100<<" %\n");
-	}
-	else{ 
-		if(VerboseConvergence()) _printf0_("\n"<<setw(50)<<left<<"   Velocity convergence: norm(du)/norm(u)"<<norm_dlsf/norm_lsf*100<<" > "<<reltol*100<<" %\n");
-		converged=false;
-	}
-
-	/*Cleanup*/
-	delete dlsfg;
-
-	return converged;
-}/*}}}*/
+void           LsfReinitializationAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/* Do nothing for now */
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/LsfReinitializationAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/LsfReinitializationAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/LsfReinitializationAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 public:
 	/*Model processing*/
-	int  DofsPerNode(int** doflist,int domaintype,int approximation);
-	void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-	void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-	void CreateNodes(Nodes* nodes,IoModel* iomodel);
 	void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 	void CreateLoads(Loads* loads, IoModel* iomodel);
+	void CreateNodes(Nodes* nodes,IoModel* iomodel);
+	int  DofsPerNode(int** doflist,int domaintype,int approximation);
+	void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+	void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 	/*Finite element Analysis*/
@@ -26,17 +26,15 @@
 	ElementMatrix* CreateKMatrix(Element* element);
 	ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-	void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-	void UpdateConstraints(FemModel* femmodel);
-	void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-	void GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-	
-	/* Other */
-	void SetReinitSPCs(FemModel* femmodel);
-	void SetDistanceOnIntersectedElements(FemModel* femmodel);
-	void SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_dist, Element* element);
-	IssmDouble GetDistanceToStraight(IssmDouble* q, IssmDouble* s0, IssmDouble* s1);
-	bool ReinitConvergence(Vector<IssmDouble>* lsfg,Vector<IssmDouble>* lsfg_old,IssmDouble reltol);
+	void           GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+	void           GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+	IssmDouble     GetDistanceToStraight(IssmDouble* q, IssmDouble* s0, IssmDouble* s1);
+	void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+	void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+	void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+	bool           ReinitConvergence(Vector<IssmDouble>* lsfg,Vector<IssmDouble>* lsfg_old,IssmDouble reltol);
+	void           SetDistanceOnIntersectedElements(FemModel* femmodel);
+	void           SetDistanceToZeroLevelsetElement(Vector<IssmDouble>* vec_dist, Element* element);
+	void           SetReinitSPCs(FemModel* femmodel);
+	void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/MasstransportAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/MasstransportAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/MasstransportAnalysis.cpp	(revision 19105)
@@ -6,31 +6,119 @@
 
 /*Model processing*/
+void MasstransportAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int stabilization;
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Do not add constraints in DG,  they are weakly imposed*/
+	if(stabilization!=3){
+		IoModelToConstraintsx(constraints,iomodel,MasstransportSpcthicknessEnum,MasstransportAnalysisEnum,P1Enum);
+	}
+
+	/*FCT, constraints are imposed using penalties*/
+	if(stabilization==4){
+		constraints->ActivatePenaltyMethod(MasstransportAnalysisEnum);
+	}
+}/*}}}*/
+void MasstransportAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	int element;
+	int penpair_ids[2];
+	int count=0;
+	int stabilization;
+	int numvertex_pairing;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Loads only in DG*/
+	if (stabilization==3){
+
+		/*Get faces and elements*/
+		CreateFaces(iomodel);
+		iomodel->FetchData(1,ThicknessEnum);
+
+		/*First load data:*/
+		for(int i=0;i<iomodel->numberoffaces;i++){
+
+			/*Get left and right elements*/
+			element=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
+
+			/*Now, if this element is not in the partition, pass: */
+			if(!iomodel->my_elements[element]) continue;
+
+			/* Add load */
+			loads->AddObject(new Numericalflux(iomodel->loadcounter+i+1,i,i,iomodel,MasstransportAnalysisEnum));
+		}
+
+		/*Free data: */
+		iomodel->DeleteData(1,ThicknessEnum);
+	}
+
+	/*Create Penpair for vertex_pairing: */
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonbase=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
+
+	for(int i=0;i<numvertex_pairing;i++){
+
+		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
+
+			/*Skip if one of the two is not on the bed*/
+			if(iomodel->domaintype!=Domain2DhorizontalEnum){
+				if(!(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
+			}
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(
+							iomodel->loadcounter+count+1,
+							&penpair_ids[0],
+							MasstransportAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
+	iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
+
+}/*}}}*/
+void MasstransportAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Fetch parameters: */
+	int  stabilization;
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Check in 3d*/
+	if(stabilization==3 && iomodel->domaintype==Domain3DEnum) _error_("DG 3d not implemented yet");
+
+	/*Create Nodes either DG or CG depending on stabilization*/
+	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	if(stabilization!=3){
+		::CreateNodes(nodes,iomodel,MasstransportAnalysisEnum,P1Enum);
+	}
+	else{
+		::CreateNodes(nodes,iomodel,MasstransportAnalysisEnum,P1DGEnum);
+	}
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
 int  MasstransportAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
 }/*}}}*/
-void MasstransportAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-
-	int     numoutputs;
-	char**  requestedoutputs = NULL;
-
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
-
-	parameters->AddObject(iomodel->CopyConstantObject(MasstransportIsfreesurfaceEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(MasstransportHydrostaticAdjustmentEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(MasstransportStabilizationEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(MasstransportMinThicknessEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(MasstransportPenaltyFactorEnum));
-
-	iomodel->FetchData(&requestedoutputs,&numoutputs,MasstransportRequestedOutputsEnum);
-	parameters->AddObject(new IntParam(MasstransportNumRequestedOutputsEnum,numoutputs));
-	if(numoutputs)parameters->AddObject(new StringArrayParam(MasstransportRequestedOutputsEnum,requestedoutputs,numoutputs));
-	iomodel->DeleteData(&requestedoutputs,numoutputs,MasstransportRequestedOutputsEnum);
-
-}/*}}}*/
 void MasstransportAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
 
 	int    stabilization,finiteelement,smb_model;
 	bool   dakota_analysis;
-	bool   isdelta18o;
+	bool   isdelta18o,ismungsm;
 	bool   isgroundingline;
 	bool   islevelset;
@@ -72,4 +160,7 @@
 		iomodel->FetchDataToInput(elements,MasstransportSpcthicknessEnum); //for DG, we need the spc in the element
 	}
+	if(stabilization==4){
+		iomodel->FetchDataToInput(elements,MasstransportSpcthicknessEnum); //for FCT, we need the spc in the element (penlaties)
+	}
 
 	if(iomodel->domaintype!=Domain2DhorizontalEnum){
@@ -88,14 +179,17 @@
 		case SMBpddEnum:
 			iomodel->Constant(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+			iomodel->Constant(&ismungsm,SurfaceforcingsIsmungsmEnum);
 			iomodel->FetchDataToInput(elements,ThermalSpctemperatureEnum);
-			if(isdelta18o){
+			if(isdelta18o || ismungsm){
 				iomodel->FetchDataToInput(elements,SurfaceforcingsTemperaturesLgmEnum);
 				iomodel->FetchDataToInput(elements,SurfaceforcingsTemperaturesPresentdayEnum);
 				iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationsPresentdayEnum);
+				iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationsLgmEnum);
 			}
 			else{
-				iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationEnum);
+			        iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationEnum);
 				iomodel->FetchDataToInput(elements,SurfaceforcingsMonthlytemperaturesEnum);
 			}
+
 			break;
 		case SMBgradientsEnum:
@@ -124,104 +218,20 @@
 
 }/*}}}*/
-void MasstransportAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	/*Fetch parameters: */
-	int  stabilization;
-	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
-
-	/*Check in 3d*/
-	if(stabilization==3 && iomodel->domaintype==Domain3DEnum) _error_("DG 3d not implemented yet");
-
-	/*Create Nodes either DG or CG depending on stabilization*/
-	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	if(stabilization!=3){
-		::CreateNodes(nodes,iomodel,MasstransportAnalysisEnum,P1Enum);
-	}
-	else{
-		::CreateNodes(nodes,iomodel,MasstransportAnalysisEnum,P1DGEnum);
-	}
-	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-}/*}}}*/
-void MasstransportAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-
-	/*Fetch parameters: */
-	int stabilization;
-	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
-
-	/*Do not add constraints in DG, they are weakly imposed*/
-	if(stabilization!=3){
-		IoModelToConstraintsx(constraints,iomodel,MasstransportSpcthicknessEnum,MasstransportAnalysisEnum,P1Enum);
-	}
-}/*}}}*/
-void MasstransportAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
-	/*Intermediaries*/
-	int element;
-	int penpair_ids[2];
-	int count=0;
-	int stabilization;
-	int numvertex_pairing;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
-
-	/*Loads only in DG*/
-	if (stabilization==3){
-
-		/*Get faces and elements*/
-		CreateFaces(iomodel);
-		iomodel->FetchData(1,ThicknessEnum);
-
-		/*First load data:*/
-		for(int i=0;i<iomodel->numberoffaces;i++){
-
-			/*Get left and right elements*/
-			element=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
-
-			/*Now, if this element is not in the partition, pass: */
-			if(!iomodel->my_elements[element]) continue;
-
-			/* Add load */
-			loads->AddObject(new Numericalflux(iomodel->loadcounter+i+1,i,i,iomodel,MasstransportAnalysisEnum));
-		}
-
-		/*Free data: */
-		iomodel->DeleteData(1,ThicknessEnum);
-	}
-
-	/*Create Penpair for vertex_pairing: */
-	IssmDouble *vertex_pairing=NULL;
-	IssmDouble *nodeonbase=NULL;
-	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
-	if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
-
-	for(int i=0;i<numvertex_pairing;i++){
-
-		if(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+0])-1]){
-
-			/*In debugging mode, check that the second node is in the same cpu*/
-			_assert_(iomodel->my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]);
-
-			/*Skip if one of the two is not on the bed*/
-			if(iomodel->domaintype!=Domain2DhorizontalEnum){
-				if(!(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonbase[reCast<int>(vertex_pairing[2*i+1])-1]))) continue;
-			}
-
-			/*Get node ids*/
-			penpair_ids[0]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+0]);
-			penpair_ids[1]=iomodel->nodecounter+reCast<int>(vertex_pairing[2*i+1]);
-
-			/*Create Load*/
-			loads->AddObject(new Penpair(
-							iomodel->loadcounter+count+1,
-							&penpair_ids[0],
-							MasstransportAnalysisEnum));
-			count++;
-		}
-	}
-
-	/*free ressources: */
-	iomodel->DeleteData(vertex_pairing,MasstransportVertexPairingEnum);
-	iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
+void MasstransportAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	int     numoutputs;
+	char**  requestedoutputs = NULL;
+
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MasstransportIsfreesurfaceEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MasstransportHydrostaticAdjustmentEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MasstransportStabilizationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MasstransportMinThicknessEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(MasstransportPenaltyFactorEnum));
+
+	iomodel->FetchData(&requestedoutputs,&numoutputs,MasstransportRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(MasstransportNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(MasstransportRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,MasstransportRequestedOutputsEnum);
 
 }/*}}}*/
@@ -362,24 +372,31 @@
 					&Ke->values[0],1);
 
-		if(stabilization==2){
-			if(dim==1){
-				vel=fabs(vx)+1.e-8;
-				D[0]=h/(2*vel)*vx*vx;
-			}
-			else{
-				/*Streamline upwinding*/
-				vel=sqrt(vx*vx+vy*vy)+1.e-8;
-				D[0*dim+0]=h/(2*vel)*vx*vx;
-				D[1*dim+0]=h/(2*vel)*vy*vx;
-				D[0*dim+1]=h/(2*vel)*vx*vy;
-				D[1*dim+1]=h/(2*vel)*vy*vy;
-			}
-		}
-		else if(stabilization==1){
-			/*SSA*/
-			vxaverage_input->GetInputAverage(&vx);
-			if(dim==2) vyaverage_input->GetInputAverage(&vy);
-			D[0*dim+0]=h/2.0*fabs(vx);
-			if(dim==2) D[1*dim+1]=h/2.0*fabs(vy);
+		switch(stabilization){
+			case 0:
+				/*Nothing to be onde*/
+				break;
+			case 1:
+				/*SSA*/
+				vxaverage_input->GetInputAverage(&vx);
+				if(dim==2) vyaverage_input->GetInputAverage(&vy);
+				D[0*dim+0]=h/2.0*fabs(vx);
+				if(dim==2) D[1*dim+1]=h/2.0*fabs(vy);
+				break;
+			case 2:
+				if(dim==1){
+					vel=fabs(vx)+1.e-8;
+					D[0]=h/(2*vel)*vx*vx;
+				}
+				else{
+					/*Streamline upwinding*/
+					vel=sqrt(vx*vx+vy*vy)+1.e-8;
+					D[0*dim+0]=h/(2*vel)*vx*vx;
+					D[1*dim+0]=h/(2*vel)*vy*vx;
+					D[0*dim+1]=h/(2*vel)*vx*vy;
+					D[1*dim+1]=h/(2*vel)*vy*vy;
+				}
+				break;
+			default:
+				_error_("Stabilization "<<stabilization<<" not supported yet");
 		}
 		if(stabilization==1 || stabilization==2){
@@ -611,5 +628,5 @@
 	return pe;
 }/*}}}*/
-void MasstransportAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           MasstransportAnalysis::GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
 	 * For node i, Bi can be expressed in the actual coordinate system
@@ -639,5 +656,5 @@
 	xDelete<IssmDouble>(basis);
 }/*}}}*/
-void MasstransportAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           MasstransportAnalysis::GetBprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
 	 * For node i, Bi' can be expressed in the actual coordinate system
@@ -668,11 +685,11 @@
 
 }/*}}}*/
-void MasstransportAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void MasstransportAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           MasstransportAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	element->GetSolutionFromInputsOneDof(solution,ThicknessEnum);
+}/*}}}*/
+void           MasstransportAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void MasstransportAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           MasstransportAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int        i,hydroadjustment,domaintype;
@@ -758,5 +775,5 @@
 	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
 }/*}}}*/
-void MasstransportAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           MasstransportAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 
 	bool islevelset;
@@ -767,2 +784,172 @@
 	return;
 }/*}}}*/
+
+/*Flux Correction Transport*/
+ElementMatrix* MasstransportAnalysis::CreateFctKMatrix(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries */
+	IssmDouble Jdet;
+	IssmDouble vx,vy;
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int dim      = 2;
+
+	/*Initialize Element vector and other vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    B      = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(dim*numnodes);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(dim*dim);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* vxaverage_input=element->GetInput(VxEnum); _assert_(vxaverage_input);
+	Input* vyaverage_input=element->GetInput(VyEnum); _assert_(vyaverage_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		GetB(B,element,dim,xyz_list,gauss);
+		GetBprime(Bprime,element,dim,xyz_list,gauss);
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+
+		D[0*dim+0] = -gauss->weight*vx*Jdet;
+		D[1*dim+1] = -gauss->weight*vy*Jdet;
+
+		TripleMultiply(B,dim,numnodes,1,
+					D,dim,dim,0,
+					Bprime,dim,numnodes,0,
+					&Ke->values[0],1);
+
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(D);
+	delete gauss;
+	return Ke;
+}/*}}}*/
+ElementMatrix* MasstransportAnalysis::CreateMassMatrix(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Intermediaries*/
+	IssmDouble  D,Jdet;
+	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* Me     = element->NewElementMatrix();
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		D=gauss->weight*Jdet;
+		TripleMultiply(basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Me->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return Me;
+}/*}}}*/
+void           MasstransportAnalysis::FctKMatrix(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,FemModel* femmodel){/*{{{*/
+
+	/*Output*/
+	Matrix<IssmDouble>* Kff = NULL;
+	Matrix<IssmDouble>* Kfs = NULL;
+
+	/*Initialize Jacobian Matrix*/
+	AllocateSystemMatricesx(&Kff,&Kfs,NULL,NULL,femmodel);
+
+	/*Create and assemble matrix*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element*       element = xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		ElementMatrix* Ke     = this->CreateFctKMatrix(element);
+		if(Ke) Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+	Kff->Assemble();
+	Kfs->Assemble();
+
+	/*Assign output pointer*/
+	*pKff=Kff;
+	if(pKfs){
+		*pKfs=Kfs;
+	}
+	else{
+		delete Kfs;
+	}
+}/*}}}*/
+void           MasstransportAnalysis::LumpedMassMatrix(Vector<IssmDouble>** pMlff,FemModel* femmodel){/*{{{*/
+
+	/*Intermediaries*/
+	int  configuration_type;
+
+	/*Initialize Lumped mass matrix (actually we just save its diagonal)*/
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	int fsize      = femmodel->nodes->NumberOfDofs(configuration_type,FsetEnum);
+	int flocalsize = femmodel->nodes->NumberOfDofsLocal(configuration_type,FsetEnum);
+	Vector<IssmDouble>* Mlff = new Vector<IssmDouble>(flocalsize,fsize);
+
+	/*Create and assemble matrix*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element*       element = xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		ElementMatrix* MLe     = this->CreateMassMatrix(element);
+		if(MLe){
+			MLe->Lump();
+			MLe->AddDiagonalToGlobal(Mlff);
+		}
+		delete MLe;
+	}
+	Mlff->Assemble();
+
+	/*Assign output pointer*/
+	*pMlff=Mlff;
+}/*}}}*/
+void           MasstransportAnalysis::MassMatrix(Matrix<IssmDouble>** pMff,FemModel* femmodel){/*{{{*/
+
+	/*Initialize Mass matrix*/
+	Matrix<IssmDouble> *Mff = NULL;
+	AllocateSystemMatricesx(&Mff,NULL,NULL,NULL,femmodel);
+
+	/*Create and assemble matrix*/
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element*       element = xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		ElementMatrix* MLe     = this->CreateMassMatrix(element);
+		if(MLe){
+			MLe->AddToGlobal(Mff);
+		}
+		delete MLe;
+	}
+	Mff->Assemble();
+
+	/*Assign output pointer*/
+	*pMff=Mff;
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/MasstransportAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/MasstransportAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/MasstransportAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -30,10 +30,17 @@
 		ElementVector* CreatePVectorCG(Element* element);
 		ElementVector* CreatePVectorDG(Element* element);
-		void GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetB(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
+
+		/*FCT*/
+		ElementMatrix* CreateFctKMatrix(Element* element);
+		ElementMatrix* CreateMassMatrix(Element* element);
+		void           FctKMatrix(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,FemModel* femmodel);
+		void           LumpedMassMatrix(Vector<IssmDouble>** pMLff,FemModel* femmodel);
+		void           MassMatrix(Matrix<IssmDouble>** pMff,FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/MeltingAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/MeltingAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/MeltingAnalysis.cpp	(revision 19105)
@@ -6,65 +6,4 @@
 
 /*Model processing*/
-int  MeltingAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
-	return 1;
-}/*}}}*/
-void MeltingAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-	parameters->AddObject(iomodel->CopyConstantObject(FrictionLawEnum));
-}/*}}}*/
-void MeltingAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-
-	int frictionlaw;
-
-	/*Now, is the model 3d? otherwise, do nothing: */
-	if(iomodel->domaintype==Domain2DhorizontalEnum)return;
-
-	/*Update elements: */
-	int counter=0;
-	for(int i=0;i<iomodel->numberofelements;i++){
-		if(iomodel->my_elements[i]){
-			Element* element=(Element*)elements->GetObjectByOffset(counter);
-			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
-			counter++;
-		}
-	}
-
-	iomodel->Constant(&frictionlaw,FrictionLawEnum);
-
-	/*Create inputs: */
-	iomodel->FetchDataToInput(elements,ThicknessEnum);
-	iomodel->FetchDataToInput(elements,SurfaceEnum);
-	iomodel->FetchDataToInput(elements,BaseEnum);
-	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
-	if(iomodel->domaintype!=Domain2DhorizontalEnum){
-		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
-		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
-	}
-	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
-	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
-	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
-	iomodel->FetchDataToInput(elements,PressureEnum);
-	
-	/*Friction law variables*/
-	switch(frictionlaw){
-		case 1:
-			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
-			iomodel->FetchDataToInput(elements,FrictionPEnum);
-			iomodel->FetchDataToInput(elements,FrictionQEnum);
-			break;
-		case 2:
-			iomodel->FetchDataToInput(elements,FrictionCEnum);
-			iomodel->FetchDataToInput(elements,FrictionMEnum);
-			break;
-		default:
-			_error_("not supported");
-	}
-}/*}}}*/
-void MeltingAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	::CreateNodes(nodes,iomodel,MeltingAnalysisEnum,P1Enum);
-	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-}/*}}}*/
 void MeltingAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
 	/*No Constraints*/
@@ -88,4 +27,43 @@
 	iomodel->DeleteData(1,MeshVertexonbaseEnum);
 
+}/*}}}*/
+void MeltingAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,MeltingAnalysisEnum,P1Enum);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
+int  MeltingAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void MeltingAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	int frictionlaw;
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if(iomodel->domaintype==Domain2DhorizontalEnum)return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	/*Create inputs: */
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+	iomodel->FetchDataToInput(elements,PressureEnum);
+}/*}}}*/
+void MeltingAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 }/*}}}*/
 
@@ -148,14 +126,14 @@
 	return NULL;
 }/*}}}*/
-void MeltingAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           MeltingAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void MeltingAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           MeltingAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void MeltingAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           MeltingAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	element->InputUpdateFromSolutionOneDof(solution,BasalforcingsGroundediceMeltingRateEnum);
 }/*}}}*/
-void MeltingAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           MeltingAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/MeltingAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/MeltingAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/MeltingAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,8 +26,8 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/MeshdeformationAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/MeshdeformationAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/MeshdeformationAnalysis.cpp	(revision 19105)
@@ -6,11 +6,8 @@
 
 /*Model processing*/
-int  MeshdeformationAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
-	_error_("not implemented");
-}/*}}}*/
-void MeshdeformationAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+void MeshdeformationAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void MeshdeformationAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+void MeshdeformationAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
@@ -18,8 +15,11 @@
 	   _error_("not implemented yet");
 }/*}}}*/
-void MeshdeformationAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+int  MeshdeformationAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+void MeshdeformationAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void MeshdeformationAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+void MeshdeformationAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
@@ -42,14 +42,14 @@
 _error_("not implemented yet");
 }/*}}}*/
-void MeshdeformationAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           MeshdeformationAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	   _error_("not implemented yet");
 }/*}}}*/
-void MeshdeformationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           MeshdeformationAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void MeshdeformationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           MeshdeformationAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 	_error_("not implemented yet");
 }/*}}}*/
-void MeshdeformationAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           MeshdeformationAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/MeshdeformationAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/MeshdeformationAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/MeshdeformationAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,8 +26,8 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/SmoothAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/SmoothAnalysis.cpp	(revision 19105)
+++ /issm/trunk/src/c/analyses/SmoothAnalysis.cpp	(revision 19105)
@@ -0,0 +1,228 @@
+#include "./SmoothAnalysis.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+/*Model processing*/
+void SmoothAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void SmoothAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+}/*}}}*/
+void SmoothAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	::CreateNodes(nodes,iomodel,SmoothAnalysisEnum,P1Enum);
+
+}/*}}}*/
+int  SmoothAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void SmoothAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+}/*}}}*/
+void SmoothAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+}/*}}}*/
+
+/*Finite Element Analysis*/
+void           SmoothAnalysis::Core(FemModel* femmodel){/*{{{*/
+	_error_("not implemented");
+}/*}}}*/
+ElementVector* SmoothAnalysis::CreateDVector(Element* element){/*{{{*/
+	/*Default, return NULL*/
+	return NULL;
+}/*}}}*/
+ElementMatrix* SmoothAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
+_error_("Not implemented");
+}/*}}}*/
+ElementMatrix* SmoothAnalysis::CreateKMatrix(Element* element){/*{{{*/
+
+	/* Intermediaries */
+	int         domaintype;
+	IssmDouble  Jdet,thickness,l;
+	IssmDouble *xyz_list = NULL;
+
+	/*Check dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix();
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->FindParam(&l,SmoothThicknessMultiplierEnum); _assert_(l>0.);
+	element->GetVerticesCoordinates(&xyz_list);
+	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+		if(thickness<50.) thickness=50.;
+
+		element->NodalFunctions(basis,gauss);
+		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+		for(int i=0;i<numnodes;i++){
+			for(int j=0;j<numnodes;j++){
+				Ke->values[i*numnodes+j] += gauss->weight*Jdet*(
+							basis[i]*basis[j]
+							+(l*thickness)*(l*thickness)*(dbasis[0*numnodes+i]*dbasis[0*numnodes+j] + dbasis[1*numnodes+i]*dbasis[1*numnodes+j])
+							);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list);
+	return Ke;
+}/*}}}*/
+ElementVector* SmoothAnalysis::CreatePVector(Element* element){/*{{{*/
+
+	/*Get basal element*/
+	int domaintype;
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+
+	/*Intermediaries */
+	int         input_enum;
+	IssmDouble  Jdet,value;
+	IssmDouble *xyz_list  = NULL;
+	Input      *input = NULL;
+
+	/*SPECIFICS: Driving stress for balance velocities*/
+	Input*      H_input = NULL, *surface_input = NULL, *vx_input = NULL, *vy_input = NULL;
+	IssmDouble  taud_x,norms,normv,vx,vy;
+	IssmDouble  rho_ice,gravity,slope[2],thickness;
+
+	/*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);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&input_enum,InputToSmoothEnum);
+
+	switch(input_enum){
+		case DrivingStressXEnum:
+		case DrivingStressYEnum:{
+			rho_ice       = element->GetMaterialParameter(MaterialsRhoIceEnum);
+			gravity       = element->GetMaterialParameter(ConstantsGEnum);
+			H_input       = element->GetInput(ThicknessEnum); _assert_(H_input);
+			surface_input = element->GetInput(SurfaceEnum);   _assert_(surface_input);
+			vx_input      = element->GetInput(VxEnum);
+			vy_input      = element->GetInput(VyEnum);
+			}
+			break;
+		case SurfaceSlopeXEnum:
+		case SurfaceSlopeYEnum:{
+			surface_input = element->GetInput(SurfaceEnum);   _assert_(surface_input);
+			}
+			break;
+		default: input = element->GetInput(input_enum);
+	}
+
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+
+		switch(input_enum){
+			case DrivingStressXEnum: 
+			case DrivingStressYEnum:{
+				H_input->GetInputValue(&thickness,gauss);
+				surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+				if(vx_input && vy_input){
+					vx_input->GetInputValue(&vx,gauss);
+					vy_input->GetInputValue(&vy,gauss);
+					norms = sqrt(slope[0]*slope[0]+slope[1]*slope[1]+1.e-10);
+					normv = sqrt(vx*vx + vy*vy);
+					if(normv>15./(365.*24.*3600.)){
+						slope[0] = -vx/normv*norms;
+						slope[1] = -vy/normv*norms;
+					}
+				}
+				if(input_enum==DrivingStressXEnum)
+				 value = rho_ice*gravity*thickness*slope[0];
+				else
+				 value = rho_ice*gravity*thickness*slope[1];
+			}
+			break;
+			case SurfaceSlopeXEnum: 
+				surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+				value = slope[0];
+				break;
+			case SurfaceSlopeYEnum:
+				surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+				value = slope[1];
+				break;
+			default:
+				input->GetInputValue(&value,gauss);
+		}
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*value*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}/*}}}*/
+void           SmoothAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	   _error_("not implemented yet");
+}/*}}}*/
+void           SmoothAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+	_error_("Not implemented yet");
+}/*}}}*/
+void           SmoothAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+	int inputenum,domaintype,elementtype;
+
+	element->FindParam(&inputenum,InputToSmoothEnum);
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DhorizontalEnum:
+			element->InputUpdateFromSolutionOneDof(solution,inputenum);
+			break;
+		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
+	}
+}/*}}}*/
+void           SmoothAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+	/*Default, do nothing*/
+	return;
+}/*}}}*/
Index: /issm/trunk/src/c/analyses/SmoothAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/SmoothAnalysis.h	(revision 19105)
+++ /issm/trunk/src/c/analyses/SmoothAnalysis.h	(revision 19105)
@@ -0,0 +1,33 @@
+/*! \file SmoothAnalysis.h 
+ *  \brief: header file for generic external result object
+ */
+
+#ifndef _SmoothAnalysis_
+#define _SmoothAnalysis_
+
+/*Headers*/
+#include "./Analysis.h"
+
+class SmoothAnalysis: public Analysis{
+
+	public:
+		/*Model processing*/
+		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
+		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,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);
+		ElementVector* CreateDVector(Element* element);
+		ElementMatrix* CreateJacobianMatrix(Element* element);
+		ElementMatrix* CreateKMatrix(Element* element);
+		ElementVector* CreatePVector(Element* element);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
+};
+#endif
Index: sm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.cpp	(revision 19104)
+++ 	(revision )
@@ -1,183 +1,0 @@
-#include "./SmoothedSurfaceSlopeXAnalysis.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-
-/*Model processing*/
-int  SmoothedSurfaceSlopeXAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
-	return 1;
-}/*}}}*/
-void SmoothedSurfaceSlopeXAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-}/*}}}*/
-void SmoothedSurfaceSlopeXAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-
-	/*Update elements: */
-	int counter=0;
-	for(int i=0;i<iomodel->numberofelements;i++){
-		if(iomodel->my_elements[i]){
-			Element* element=(Element*)elements->GetObjectByOffset(counter);
-			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
-			counter++;
-		}
-	}
-
-	iomodel->FetchDataToInput(elements,SurfaceEnum);
-	iomodel->FetchDataToInput(elements,BaseEnum);
-	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
-	if(iomodel->domaintype!=Domain2DhorizontalEnum){
-		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
-		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
-	}
-}/*}}}*/
-void SmoothedSurfaceSlopeXAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(1,MeshVertexonbaseEnum);
-	::CreateNodes(nodes,iomodel,SmoothedSurfaceSlopeXAnalysisEnum,P1Enum);
-	if(iomodel->domaintype==Domain3DEnum) iomodel->DeleteData(1,MeshVertexonbaseEnum);
-}/*}}}*/
-void SmoothedSurfaceSlopeXAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-}/*}}}*/
-void SmoothedSurfaceSlopeXAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-}/*}}}*/
-
-/*Finite Element Analysis*/
-void           SmoothedSurfaceSlopeXAnalysis::Core(FemModel* femmodel){/*{{{*/
-	_error_("not implemented");
-}/*}}}*/
-ElementVector* SmoothedSurfaceSlopeXAnalysis::CreateDVector(Element* element){/*{{{*/
-	/*Default, return NULL*/
-	return NULL;
-}/*}}}*/
-ElementMatrix* SmoothedSurfaceSlopeXAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
-_error_("Not implemented");
-}/*}}}*/
-ElementMatrix* SmoothedSurfaceSlopeXAnalysis::CreateKMatrix(Element* element){/*{{{*/
-
-	/* Intermediaries */
-	IssmDouble  Jdet,thickness,l=8.;
-	IssmDouble *xyz_list = NULL;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Initialize Element matrix and vectors*/
-	ElementMatrix* Ke     = element->NewElementMatrix();
-	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
-	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
-
-	/* Start looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		thickness_input->GetInputValue(&thickness,gauss);
-		if(thickness<50.) thickness=50.;
-
-		element->NodalFunctions(basis,gauss);
-		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-		for(int i=0;i<numnodes;i++){
-			for(int j=0;j<numnodes;j++){
-				Ke->values[i*numnodes+j] += gauss->weight*Jdet*(
-							basis[i]*basis[j]
-							+(l*thickness)*(l*thickness)*(dbasis[0*numnodes+i]*dbasis[0*numnodes+j] + dbasis[1*numnodes+i]*dbasis[1*numnodes+j])
-							);
-			}
-		}
-	}
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<IssmDouble>(dbasis);
-	xDelete<IssmDouble>(basis);
-	xDelete<IssmDouble>(xyz_list);
-	return Ke;
-}/*}}}*/
-ElementVector* SmoothedSurfaceSlopeXAnalysis::CreatePVector(Element* element){/*{{{*/
-
-	/*Intermediaries*/
-	int      domaintype;
-	Element* basalelement;
-
-	/*Get basal element*/
-	element->FindParam(&domaintype,DomainTypeEnum);
-	switch(domaintype){
-		case Domain2DhorizontalEnum:
-			basalelement = element;
-			break;
-		case Domain3DEnum:
-			if(!element->IsOnBase()) return NULL;
-			basalelement = element->SpawnBasalElement();
-			break;
-		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
-	}
-
-	/*Intermediaries */
-	int         input_enum;
-	IssmDouble  Jdet,thickness,slope[2];
-	IssmDouble  taud_x,norms,normv,vx,vy;
-	IssmDouble *xyz_list  = NULL;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = basalelement->GetNumberOfNodes();
-
-	/*Initialize Element vector*/
-	ElementVector* pe    = basalelement->NewElementVector();
-	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
-
-	/*Retrieve all inputs and parameters*/
-	basalelement->GetVerticesCoordinates(&xyz_list);
-	IssmDouble rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
-	IssmDouble gravity   = element->GetMaterialParameter(ConstantsGEnum);
-	Input* H_input       = basalelement->GetInput(ThicknessEnum); _assert_(H_input);
-	Input* surface_input = basalelement->GetInput(SurfaceEnum);   _assert_(surface_input);
-	Input* vx_input      = basalelement->GetInput(VxEnum);
-	Input* vy_input      = basalelement->GetInput(VyEnum);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=basalelement->NewGauss(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		basalelement->NodalFunctions(basis,gauss);
-
-		H_input->GetInputValue(&thickness,gauss);
-		surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
-		if(vx_input && vy_input){
-			vx_input->GetInputValue(&vx,gauss);
-			vy_input->GetInputValue(&vy,gauss);
-			norms = sqrt(slope[0]*slope[0]+slope[1]*slope[1]+1.e-10);
-			normv = sqrt(vx*vx + vy*vy);
-			if(normv>15./(365.*24.*3600.)) slope[0] = -vx/normv*norms;
-		}
-		taud_x = rho_ice*gravity*thickness*slope[0];
-
-		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*taud_x*basis[i];
-	}
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(basis);
-	delete gauss;
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
-	return pe;
-}/*}}}*/
-void SmoothedSurfaceSlopeXAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void SmoothedSurfaceSlopeXAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
-	_error_("Not implemented yet");
-}/*}}}*/
-void SmoothedSurfaceSlopeXAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
-	element->InputUpdateFromSolutionOneDof(solution,SurfaceSlopeXEnum);
-}/*}}}*/
-void SmoothedSurfaceSlopeXAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
-	/*Default, do nothing*/
-	return;
-}/*}}}*/
Index: sm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeXAnalysis.h	(revision 19104)
+++ 	(revision )
@@ -1,33 +1,0 @@
-/*! \file SmoothedSurfaceSlopeXAnalysis.h 
- *  \brief: header file for generic external result object
- */
-
-#ifndef _SmoothedSurfaceSlopeXAnalysis_
-#define _SmoothedSurfaceSlopeXAnalysis_
-
-/*Headers*/
-#include "./Analysis.h"
-
-class SmoothedSurfaceSlopeXAnalysis: public Analysis{
-
-	public:
-		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
-		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
-		void CreateLoads(Loads* loads, IoModel* iomodel);
-
-		/*Finite element Analysis*/
-		void           Core(FemModel* femmodel);
-		ElementVector* CreateDVector(Element* element);
-		ElementMatrix* CreateJacobianMatrix(Element* element);
-		ElementMatrix* CreateKMatrix(Element* element);
-		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
-};
-#endif
Index: sm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.cpp	(revision 19104)
+++ 	(revision )
@@ -1,182 +1,0 @@
-#include "./SmoothedSurfaceSlopeYAnalysis.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-
-/*Model processing*/
-int  SmoothedSurfaceSlopeYAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
-	return 1;
-}/*}}}*/
-void SmoothedSurfaceSlopeYAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-}/*}}}*/
-void SmoothedSurfaceSlopeYAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-
-	/*Update elements: */
-	int counter=0;
-	for(int i=0;i<iomodel->numberofelements;i++){
-		if(iomodel->my_elements[i]){
-			Element* element=(Element*)elements->GetObjectByOffset(counter);
-			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
-			counter++;
-		}
-	}
-
-	iomodel->FetchDataToInput(elements,SurfaceEnum);
-	iomodel->FetchDataToInput(elements,BaseEnum);
-	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
-	if(iomodel->domaintype!=Domain2DhorizontalEnum){
-		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
-		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
-	}
-}/*}}}*/
-void SmoothedSurfaceSlopeYAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(1,MeshVertexonbaseEnum);
-	::CreateNodes(nodes,iomodel,SmoothedSurfaceSlopeYAnalysisEnum,P1Enum);
-	if(iomodel->domaintype==Domain3DEnum) iomodel->DeleteData(1,MeshVertexonbaseEnum);
-}/*}}}*/
-void SmoothedSurfaceSlopeYAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-}/*}}}*/
-void SmoothedSurfaceSlopeYAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-}/*}}}*/
-
-/*Finite Element Analysis*/
-void           SmoothedSurfaceSlopeYAnalysis::Core(FemModel* femmodel){/*{{{*/
-	_error_("not implemented");
-}/*}}}*/
-ElementVector* SmoothedSurfaceSlopeYAnalysis::CreateDVector(Element* element){/*{{{*/
-	/*Default, return NULL*/
-	return NULL;
-}/*}}}*/
-ElementMatrix* SmoothedSurfaceSlopeYAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
-_error_("Not implemented");
-}/*}}}*/
-ElementMatrix* SmoothedSurfaceSlopeYAnalysis::CreateKMatrix(Element* element){/*{{{*/
-
-	/* Intermediaries */
-	IssmDouble  Jdet,thickness,l=8.;
-	IssmDouble *xyz_list = NULL;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Initialize Element matrix and vectors*/
-	ElementMatrix* Ke     = element->NewElementMatrix();
-	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
-	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	Input* thickness_input = element->GetInput(ThicknessEnum); _assert_(thickness_input);
-
-	/* Start looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		thickness_input->GetInputValue(&thickness,gauss);
-		if(thickness<50.) thickness=50.;
-
-		element->NodalFunctions(basis,gauss);
-		element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-		for(int i=0;i<numnodes;i++){
-			for(int j=0;j<numnodes;j++){
-				Ke->values[i*numnodes+j] += gauss->weight*Jdet*(
-							basis[i]*basis[j]
-							+(l*thickness)*(l*thickness)*(dbasis[0*numnodes+i]*dbasis[0*numnodes+j] + dbasis[1*numnodes+i]*dbasis[1*numnodes+j])
-							);
-			}
-		}
-	}
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<IssmDouble>(dbasis);
-	xDelete<IssmDouble>(basis);
-	xDelete<IssmDouble>(xyz_list);
-	return Ke;
-}/*}}}*/
-ElementVector* SmoothedSurfaceSlopeYAnalysis::CreatePVector(Element* element){/*{{{*/
-
-	/*Intermediaries*/
-	int      domaintype;
-	Element* basalelement;
-
-	/*Get basal element*/
-	element->FindParam(&domaintype,DomainTypeEnum);
-	switch(domaintype){
-		case Domain2DhorizontalEnum:
-			basalelement = element;
-			break;
-		case Domain3DEnum:
-			if(!element->IsOnBase()) return NULL;
-			basalelement = element->SpawnBasalElement();
-			break;
-		default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
-	}
-
-	/*Intermediaries */
-	IssmDouble  Jdet,thickness,slope[2];
-	IssmDouble  taud_y,norms,normv,vx,vy;
-	IssmDouble *xyz_list  = NULL;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = basalelement->GetNumberOfNodes();
-
-	/*Initialize Element vector*/
-	ElementVector* pe    = basalelement->NewElementVector();
-	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
-
-	/*Retrieve all inputs and parameters*/
-	basalelement->GetVerticesCoordinates(&xyz_list);
-	IssmDouble rho_ice   = element->GetMaterialParameter(MaterialsRhoIceEnum);
-	IssmDouble gravity   = element->GetMaterialParameter(ConstantsGEnum);
-	Input* H_input       = basalelement->GetInput(ThicknessEnum); _assert_(H_input);
-	Input* surface_input = basalelement->GetInput(SurfaceEnum);   _assert_(surface_input);
-	Input* vx_input      = basalelement->GetInput(VxEnum);
-	Input* vy_input      = basalelement->GetInput(VyEnum);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=basalelement->NewGauss(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		basalelement->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		basalelement->NodalFunctions(basis,gauss);
-
-		H_input->GetInputValue(&thickness,gauss);
-		surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
-		if(vx_input && vy_input){
-			vx_input->GetInputValue(&vx,gauss);
-			vy_input->GetInputValue(&vy,gauss);
-			norms = sqrt(slope[0]*slope[0]+slope[1]*slope[1]+1.e-10);
-			normv = sqrt(vx*vx + vy*vy);
-			if(normv>15./(365.*24.*3600.)) slope[1] = -vy/normv*norms;
-		}
-		taud_y = rho_ice*gravity*thickness*slope[1];
-
-		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*taud_y*basis[i];
-	}
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(basis);
-	delete gauss;
-	if(domaintype!=Domain2DhorizontalEnum){basalelement->DeleteMaterials(); delete basalelement;};
-	return pe;
-}/*}}}*/
-void SmoothedSurfaceSlopeYAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
-	   _error_("not implemented yet");
-}/*}}}*/
-void SmoothedSurfaceSlopeYAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
-	_error_("Not implemented yet");
-}/*}}}*/
-void SmoothedSurfaceSlopeYAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
-	element->InputUpdateFromSolutionOneDof(solution,SurfaceSlopeYEnum);
-}/*}}}*/
-void SmoothedSurfaceSlopeYAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
-	/*Default, do nothing*/
-	return;
-}/*}}}*/
Index: sm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/SmoothedSurfaceSlopeYAnalysis.h	(revision 19104)
+++ 	(revision )
@@ -1,33 +1,0 @@
-/*! \file SmoothedSurfaceSlopeYAnalysis.h 
- *  \brief: header file for generic external result object
- */
-
-#ifndef _SmoothedSurfaceSlopeYAnalysis_
-#define _SmoothedSurfaceSlopeYAnalysis_
-
-/*Headers*/
-#include "./Analysis.h"
-
-class SmoothedSurfaceSlopeYAnalysis: public Analysis{
-
-	public:
-		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
-		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
-		void CreateLoads(Loads* loads, IoModel* iomodel);
-
-		/*Finite element Analysis*/
-		void           Core(FemModel* femmodel);
-		ElementVector* CreateDVector(Element* element);
-		ElementMatrix* CreateJacobianMatrix(Element* element);
-		ElementMatrix* CreateKMatrix(Element* element);
-		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
-};
-#endif
Index: /issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp	(revision 19105)
@@ -11,4 +11,588 @@
 
 /*Model processing*/
+void StressbalanceAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	int        i,j;
+	int        count,finiteelement;
+	IssmDouble g;
+	IssmDouble rho_ice;
+	IssmDouble FSreconditioning;
+	bool       isSIA,isSSA,isL1L2,isHO,isFS,iscoupling;
+	bool       spcpresent = false;
+	int        Mx,Nx;
+	int        My,Ny;
+	int        Mz,Nz;
+	IssmDouble *spcvx          = NULL;
+	IssmDouble *spcvy          = NULL;
+	IssmDouble *spcvz          = NULL;
+	IssmDouble *nodeonSSA = NULL;
+	IssmDouble *nodeonHO   = NULL;
+	IssmDouble *nodeonFS   = NULL;
+	IssmDouble *nodeonbase      = NULL;
+	IssmDouble *groundedice_ls = NULL;
+	IssmDouble *vertices_type  = NULL;
+	IssmDouble *surface        = NULL;
+	IssmDouble *z              = NULL;
+	IssmDouble *timesx=NULL;
+	IssmDouble *timesy=NULL;
+	IssmDouble *timesz=NULL;
+   IssmDouble* values=NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&g,ConstantsGEnum);
+	iomodel->Constant(&rho_ice,MaterialsRhoIceEnum);
+	iomodel->Constant(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+
+	/*Now, is the flag macayaealHO on? otherwise, do nothing: */
+	if(!isSSA && !isHO && !isFS && !isL1L2) return;
+
+	/*Do we have coupling*/
+	if((isSIA?1.:0.) + (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
+	 iscoupling = true;
+	else
+	 iscoupling = false;
+
+	/*If no coupling, call Regular IoModelToConstraintsx, else, use P1 elements only*/
+	if(!iscoupling){
+
+		/*Get finite element type*/
+		if(isSSA)       iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
+		else if(isL1L2) finiteelement = P1Enum;
+		else if(isHO)   iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
+		else if(isFS){  iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
+			/*Deduce velocity interpolation from finite element*/
+			switch(finiteelement){
+				case P1P1Enum              : finiteelement = P1Enum;       break;
+				case P1P1GLSEnum           : finiteelement = P1Enum;       break;
+				case MINIcondensedEnum     : finiteelement = P1bubbleEnum; break;
+				case MINIEnum              : finiteelement = P1bubbleEnum; break;
+				case TaylorHoodEnum        : finiteelement = P2Enum;       break;
+				case XTaylorHoodEnum       : finiteelement = P2Enum;       break;
+				case LATaylorHoodEnum      : finiteelement = P2Enum;       break;
+				case LACrouzeixRaviartEnum : finiteelement = P2bubbleEnum; break;
+				case OneLayerP4zEnum       : finiteelement = P2xP4Enum;    break;
+				case CrouzeixRaviartEnum   : finiteelement = P2bubbleEnum; break;
+				default: _error_("finite element "<<EnumToStringx(finiteelement)<<" not supported");
+			}
+		}
+		else{
+			_error_("model not supported yet");
+		}
+
+		if(isFS){
+
+			/*Constraint at the bedrock interface (v.n = vz = 0) (Coordinates will be updated according to the bed slope)*/
+			iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
+			iomodel->FetchData(&nodeonFS,NULL,NULL,FlowequationBorderFSEnum);
+			iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
+			iomodel->FetchData(&groundedice_ls,NULL,NULL,MaskGroundediceLevelsetEnum);
+			if(iomodel->domaintype==Domain3DEnum){
+				iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvzEnum);
+			}
+			else if (iomodel->domaintype==Domain2DverticalEnum){
+				iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvyEnum);
+			}
+			else{
+				_error_("not supported yet");
+			}
+			if(iomodel->domaintype==Domain3DEnum){
+				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,0);
+				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvyEnum,StressbalanceAnalysisEnum,finiteelement,1);
+				IoModelToConstraintsx(constraints,iomodel,spcvz,Mz,Nz,StressbalanceAnalysisEnum,finiteelement,2);
+				iomodel->DeleteData(spcvz,StressbalanceSpcvzEnum);
+			}
+			else if (iomodel->domaintype==Domain2DverticalEnum){
+				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,0);
+				IoModelToConstraintsx(constraints,iomodel,spcvz,Mz,Nz,StressbalanceAnalysisEnum,finiteelement,1);
+				iomodel->DeleteData(spcvz,StressbalanceSpcvyEnum);
+			}
+			else{
+				_error_("not supported yet");
+			}
+			iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+			iomodel->DeleteData(nodeonFS,FlowequationBorderFSEnum);
+			iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
+			iomodel->DeleteData(groundedice_ls,MaskGroundediceLevelsetEnum);
+
+			/*Pressure spc*/
+			count = constraints->Size();
+			iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
+			iomodel->FetchData(&surface,NULL,NULL,SurfaceEnum);
+			iomodel->FetchData(&z,NULL,NULL,MeshZEnum);
+			switch(finiteelement){
+				case P1Enum:
+					for(i=0;i<iomodel->numberofvertices;i++){
+						if(iomodel->my_vertices[i]){
+							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				case P1bubbleEnum:
+					for(i=0;i<iomodel->numberofvertices;i++){
+						if(iomodel->my_vertices[i]){
+							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				case P2Enum:
+					for(i=0;i<iomodel->numberofvertices;i++){
+						if(iomodel->my_vertices[i]){
+							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				case P2bubbleEnum:
+					for(i=0;i<iomodel->numberofvertices;i++){
+						if(iomodel->my_vertices[i]){
+							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberofelements+iomodel->numberoffaces+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				case P2xP4Enum:
+					//Nothing yet
+					break;
+				default:
+					_error_("not implemented yet");
+			}
+			iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+			iomodel->DeleteData(surface,SurfaceEnum);
+			iomodel->DeleteData(z,MeshZEnum);
+		}
+		else{
+			IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,0);
+			if(iomodel->domaintype!=Domain2DverticalEnum){
+				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvyEnum,StressbalanceAnalysisEnum,finiteelement,1);
+			}
+		}
+
+		return;
+	}
+
+	/*Constraints: fetch data: */
+	iomodel->FetchData(&spcvx,&Mx,&Nx,StressbalanceSpcvxEnum);
+	iomodel->FetchData(&spcvy,&My,&Ny,StressbalanceSpcvyEnum);
+	iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvzEnum);
+	iomodel->FetchData(&nodeonSSA,NULL,NULL,FlowequationBorderSSAEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&nodeonHO,NULL,NULL,FlowequationBorderHOEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&nodeonFS,NULL,NULL,FlowequationBorderFSEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&groundedice_ls,NULL,NULL,MaskGroundediceLevelsetEnum);
+	iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
+	iomodel->FetchData(&surface,NULL,NULL,SurfaceEnum);
+	iomodel->FetchData(&z,NULL,NULL,MeshZEnum);
+
+	/*Initialize counter: */
+	count=0;
+
+	/*figure out times: */
+	timesx=xNew<IssmDouble>(Nx);
+	for(j=0;j<Nx;j++){
+		timesx[j]=spcvx[(Mx-1)*Nx+j];
+	}
+	/*figure out times: */
+	timesy=xNew<IssmDouble>(Ny);
+	for(j=0;j<Ny;j++){
+		timesy[j]=spcvy[(My-1)*Ny+j];
+	}
+	/*figure out times: */
+	timesz=xNew<IssmDouble>(Nz);
+	for(j=0;j<Nz;j++){
+		timesz[j]=spcvz[(Mz-1)*Nz+j];
+	}
+
+	/*Create spcs from x,y,z, as well as the spc values on those spcs: */
+	for(i=0;i<iomodel->numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+
+			/*Start with adding spcs of coupling: zero at the border SSA/HO for the appropriate dofs*/
+			if(reCast<int,IssmDouble>(vertices_type[i]==SSAHOApproximationEnum)){
+				/*If grionSSA, spc HO dofs: 3 & 4*/
+					if (reCast<int,IssmDouble>(nodeonHO[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if (reCast<int,IssmDouble>(nodeonSSA[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else _error_("if vertices_type is SSAHO, you shoud have nodeonHO or nodeonSSA");
+			}
+			/*Also add spcs of coupling: zero at the border HO/FS for the appropriate dofs*/
+			else if (reCast<int,IssmDouble>(vertices_type[i])==HOFSApproximationEnum){
+				/*If grion,HO spc FS dofs: 3 4 & 5*/
+					if (reCast<int,IssmDouble>(nodeonHO[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if (reCast<int,IssmDouble>(nodeonFS[i])){ //spc HO nodes: 1 & 2
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvz[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+					}
+					else _error_("if vertices_type is HOFS, you shoud have nodeonHO or nodeonFS");
+			}
+			/*Also add spcs of coupling: zero at the border HO/FS for the appropriate dofs*/
+			else if (reCast<int,IssmDouble>(vertices_type[i])==SSAFSApproximationEnum){
+				/*If grion,HO spc FS dofs: 3 4 & 5*/
+					if (reCast<int,IssmDouble>(nodeonSSA[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+
+					}
+					else if (reCast<int,IssmDouble>(nodeonFS[i])){ //spc SSA nodes: 1 & 2
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+						count++;
+						if (!xIsNan<IssmDouble>(spcvx[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvy[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+						if (!xIsNan<IssmDouble>(spcvz[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+							count++;
+						}
+					}
+					else _error_("if vertices_type is SSAFS, you shoud have nodeonSSA or nodeonFS");
+			}
+			/*Now add the regular spcs*/
+			else{
+				if (Mx==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvx[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+					count++;
+
+				}
+				else if (Mx==iomodel->numberofvertices+1) {
+					/*figure out times and values: */
+					values=xNew<IssmDouble>(Nx);
+					spcpresent=false;
+					for(j=0;j<Nx;j++){
+						values[j]=spcvx[i*Nx+j];
+						if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+					}
+
+					if(spcpresent){
+						constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,Nx,timesx,values,StressbalanceAnalysisEnum));
+						count++;
+					}
+					xDelete<IssmDouble>(values);
+				}
+				else if (vertices_type[i]==SIAApproximationEnum){
+					constraints->AddObject(new SpcDynamic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,StressbalanceAnalysisEnum));
+					count++;
+				}
+
+				if (My==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvy[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vy.
+					count++;
+				}
+				else if (My==iomodel->numberofvertices+1){
+					/*figure out times and values: */
+					values=xNew<IssmDouble>(Ny);
+					spcpresent=false;
+					for(j=0;j<Ny;j++){
+						values[j]=spcvy[i*Ny+j];
+						if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+					}
+					if(spcpresent){
+						constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,Ny,timesy,values,StressbalanceAnalysisEnum));
+						count++;
+					}
+					xDelete<IssmDouble>(values);
+				}
+				else if (vertices_type[i]==SIAApproximationEnum){
+					constraints->AddObject(new SpcDynamic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,StressbalanceAnalysisEnum));
+					count++;
+				}
+
+				if (reCast<int,IssmDouble>(vertices_type[i])==FSApproximationEnum ||  (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum)){
+					if (Mz==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvz[i])){
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+						count++;
+					}
+					else if (Mz==iomodel->numberofvertices+1){
+						/*figure out times and values: */
+						values=xNew<IssmDouble>(Nz);
+						spcpresent=false;
+						for(j=0;j<Nz;j++){
+							values[j]=spcvz[i*Nz+j];
+							if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
+						}
+						if(spcpresent){
+							constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,Nz,timesz,values,StressbalanceAnalysisEnum));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+
+				}
+				if (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+					count++;
+				}
+			}
+		}
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(spcvx,StressbalanceSpcvxEnum);
+	iomodel->DeleteData(spcvy,StressbalanceSpcvyEnum);
+	iomodel->DeleteData(spcvz,StressbalanceSpcvzEnum);
+	iomodel->DeleteData(nodeonSSA,FlowequationBorderSSAEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(nodeonHO,FlowequationBorderHOEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(nodeonFS,FlowequationBorderFSEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
+	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(groundedice_ls,MaskGroundediceLevelsetEnum);
+	iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+	iomodel->DeleteData(surface,SurfaceEnum);
+	iomodel->DeleteData(z,MeshZEnum);
+
+	/*Free resources:*/
+	xDelete<IssmDouble>(timesx);
+	xDelete<IssmDouble>(timesy);
+	xDelete<IssmDouble>(timesz);
+	xDelete<IssmDouble>(values);
+
+}/*}}}*/
+void StressbalanceAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	const int   RIFTINFOSIZE = 12;
+	int         i;
+	int         count;
+	int         penpair_ids[2];
+	bool        isSSA,isL1L2,isHO,isFS;
+	int         numpenalties,numrifts,numriftsegments;
+	IssmDouble *riftinfo       = NULL;
+	IssmDouble *penalties      = NULL;
+	int         assert_int;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&numrifts,RiftsNumriftsEnum);
+
+	/*Now, is the flag macayaealHO on? otherwise, do nothing: */
+	if(!isSSA && !isHO && !isFS && !isL1L2) return;
+
+	/*Initialize counter: */
+	count=0;
+
+	/*Create Penpair for penalties: */
+	iomodel->FetchData(&penalties,&numpenalties,NULL,StressbalanceVertexPairingEnum);
+
+	for(i=0;i<numpenalties;i++){
+
+		if(iomodel->my_vertices[reCast<int,IssmDouble>(penalties[2*i+0]-1)]){
+
+			/*In debugging mode, check that the second node is in the same cpu*/
+			assert_int=iomodel->my_vertices[reCast<int,IssmDouble>(penalties[2*i+1]-1)]; _assert_(assert_int);
+
+			/*Get node ids*/
+			penpair_ids[0]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+0]);
+			penpair_ids[1]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+1]);
+
+			/*Create Load*/
+			loads->AddObject(new Penpair(iomodel->loadcounter+count+1,&penpair_ids[0],StressbalanceAnalysisEnum));
+			count++;
+		}
+	}
+
+	/*free ressources: */
+	iomodel->DeleteData(penalties,StressbalanceVertexPairingEnum);
+
+	/*Create Riffront loads for rifts: */
+	if(numrifts){
+		iomodel->FetchData(&riftinfo,&numriftsegments,NULL,RiftsRiftstructEnum);
+		iomodel->FetchData(5,RiftsRiftstructEnum,ThicknessEnum,BaseEnum,SurfaceEnum,MaskGroundediceLevelsetEnum);
+		for(i=0;i<numriftsegments;i++){
+			if(iomodel->my_elements[reCast<int,IssmDouble>(*(riftinfo+RIFTINFOSIZE*i+2))-1]){
+				loads->AddObject(new Riftfront(iomodel->loadcounter+count+1,i,iomodel,StressbalanceAnalysisEnum));
+				count++;
+			}
+		}
+		iomodel->DeleteData(5,RiftsRiftstructEnum,ThicknessEnum,BaseEnum,SurfaceEnum,MaskGroundediceLevelsetEnum);
+		xDelete<IssmDouble>(riftinfo);
+	}
+}/*}}}*/
+void StressbalanceAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Intermediary*/
+	bool isSSA,isL1L2,isHO,isFS,iscoupling;
+	int  finiteelement=-1,approximation=-1;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+
+	/*Now, check that we have non SIA elements */
+	if(!isSSA & !isL1L2 & !isHO & !isFS) return;
+
+	/*Do we have coupling*/
+	if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
+	 iscoupling = true;
+	else
+	 iscoupling = false;
+
+	/*If no coupling, call Regular CreateNodes, else, use P1 elements only*/
+	if(!iscoupling){
+
+		/*Get finite element type*/
+		if(isSSA){
+			approximation=SSAApproximationEnum;
+			iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
+		}
+		else if(isL1L2){
+			approximation = L1L2ApproximationEnum;
+			finiteelement = P1Enum;
+		}
+		else if(isHO){
+			approximation = HOApproximationEnum;
+			iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
+		}
+		else if(isFS){
+			approximation = FSApproximationEnum;
+			iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
+		}
+		iomodel->FetchData(3,FlowequationBorderSSAEnum,FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+		if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(3,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderFSEnum);
+		::CreateNodes(nodes,iomodel,StressbalanceAnalysisEnum,finiteelement,approximation);
+		iomodel->DeleteData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+	}
+	else{
+		/*Coupling: we are going to create P1 Elements only*/
+
+		Node*  node  = NULL;
+		int    lid=0;
+		if(!nodes) nodes = new Nodes();
+
+		iomodel->FetchData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+		if(isFS){
+			/*P1+ velocity*/
+			for(int i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					approximation=reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]);
+					if(approximation==FSApproximationEnum)  approximation=FSvelocityEnum;
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceAnalysisEnum,approximation));
+				}
+			}
+			for(int i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					node = new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,StressbalanceAnalysisEnum,FSvelocityEnum);
+					node->Deactivate();
+					nodes->AddObject(node);
+				}
+			}
+			/*P1 pressure*/
+			for(int i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					approximation=reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]);
+					node = new Node(iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,iomodel->numberofvertices+iomodel->numberofelements+i,lid++,i,iomodel,StressbalanceAnalysisEnum,FSpressureEnum);
+					if(approximation==HOApproximationEnum || approximation==SSAApproximationEnum){
+						node->Deactivate();
+					}
+					nodes->AddObject(node);
+				}
+			}
+		}
+		else{
+			for(int i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceAnalysisEnum,reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i])));
+				}
+			}
+		}
+		iomodel->DeleteData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+	}
+}/*}}}*/
 int  StressbalanceAnalysis::DofsPerNode(int** pdoftype,int domaintype,int approximation){/*{{{*/
 
@@ -84,4 +668,172 @@
 	return numdofs;
 }/*}}}*/
+void StressbalanceAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Intermediaries*/
+	int    materials_type,finiteelement,fe_FS;
+	int    approximation,frictionlaw;
+	int*   finiteelement_list=NULL;
+	bool   isSSA,isL1L2,isHO,isFS,iscoupling;
+	bool   control_analysis;
+	bool   dakota_analysis;
+	bool   islevelset;
+	bool   isdamage;
+
+	/*Fetch constants needed: */
+	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
+	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
+	iomodel->Constant(&isHO,FlowequationIsHOEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
+	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&materials_type,MaterialsEnum);
+	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
+	iomodel->Constant(&frictionlaw,FrictionLawEnum);
+
+	/*return if no processing required*/
+	if(!isSSA & !isL1L2 & !isHO & !isFS) return;
+
+	/*Fetch data needed and allocate vectors: */
+	iomodel->FetchData(1,FlowequationElementEquationEnum);
+	finiteelement_list=xNewZeroInit<int>(iomodel->numberofelements);
+
+	/*Do we have coupling*/
+	if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
+	 iscoupling = true;
+	else
+	 iscoupling = false;
+
+	/*is damage mechanics being used?*/
+	if(materials_type==MaticeEnum) isdamage = false;
+	else if(materials_type==MatdamageiceEnum) isdamage = true;
+	else _error_("Material type not recognized");
+
+	/*Get finite element type*/
+	if(!iscoupling){
+		if(isSSA)       iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
+		else if(isL1L2) finiteelement = P1Enum;
+		else if(isHO)   iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
+		else if(isFS)   iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
+		for(int i=0;i<iomodel->numberofelements;i++){
+			finiteelement_list[i]=finiteelement;
+		}
+	}
+	else{
+		if(isFS){
+			for(int i=0;i<iomodel->numberofelements;i++){
+				approximation=reCast<int>(iomodel->Data(FlowequationElementEquationEnum)[i]);
+				if(approximation==FSApproximationEnum || approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+					finiteelement_list[i]=MINIcondensedEnum;
+				}
+				else{
+					finiteelement_list[i]=P1Enum;
+				}
+			}
+		}
+		else{
+			finiteelement = P1Enum;
+			for(int i=0;i<iomodel->numberofelements;i++){
+				finiteelement_list[i]=finiteelement;
+			}
+		}
+	}
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement_list[i]);
+			counter++;
+		}
+	}
+
+	/*Create inputs: */
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,VxEnum,0.);
+	iomodel->FetchDataToInput(elements,VyEnum,0.);
+	iomodel->FetchDataToInput(elements,LoadingforceXEnum);
+	iomodel->FetchDataToInput(elements,LoadingforceYEnum);
+	#ifdef LATERALFRICTION
+	iomodel->FetchDataToInput(elements,MeshVertexonboundaryEnum);
+	#endif
+	if(isdamage)iomodel->FetchDataToInput(elements,DamageDEnum);
+
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+	if(iomodel->domaintype==Domain3DEnum){
+		iomodel->FetchDataToInput(elements,FlowequationBorderFSEnum);
+		iomodel->FetchDataToInput(elements,LoadingforceZEnum);
+		iomodel->FetchDataToInput(elements,VzEnum,0.);
+	}
+	if(isFS){
+		iomodel->FetchDataToInput(elements,PressureEnum,0.);
+		iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum,0.);
+	}
+	if(islevelset){
+		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
+	}
+	/*LATH parameters*/
+	iomodel->Constant(&fe_FS,FlowequationFeFSEnum);
+	if(fe_FS==LATaylorHoodEnum || fe_FS==LACrouzeixRaviartEnum){
+		InputUpdateFromConstantx(elements,0.,SigmaNNEnum);
+	}
+
+	/*Friction law variables*/
+	switch(frictionlaw){
+		case 1:
+			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,FrictionPEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			break;
+		case 2:
+			iomodel->FetchDataToInput(elements,FrictionCEnum);
+			iomodel->FetchDataToInput(elements,FrictionMEnum);
+			break;
+		case 3:
+			iomodel->FetchDataToInput(elements,FrictionCEnum);
+			iomodel->FetchDataToInput(elements,FrictionAsEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			iomodel->FetchDataToInput(elements,FrictionEffectivePressureEnum);
+			break;
+		case 4:
+			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,FrictionPEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			iomodel->FetchDataToInput(elements,PressureEnum);
+			iomodel->FetchDataToInput(elements,TemperatureEnum);
+			break;
+		case 5:
+			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,FrictionPEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			iomodel->FetchDataToInput(elements,FrictionWaterLayerEnum);
+			break;
+		case 6:
+			iomodel->FetchDataToInput(elements,FrictionCEnum);
+			iomodel->FetchDataToInput(elements,FrictionMEnum);
+			iomodel->FetchDataToInput(elements,PressureEnum);
+			iomodel->FetchDataToInput(elements,TemperatureEnum);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+#ifdef _HAVE_ANDROID_
+	elements->InputDuplicate(FrictionCoefficientEnum,AndroidFrictionCoefficientEnum);
+#endif
+
+	/*Free data: */
+	iomodel->DeleteData(1,FlowequationElementEquationEnum);
+	xDelete<int>(finiteelement_list);
+}/*}}}*/
 void StressbalanceAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
 
@@ -112,5 +864,5 @@
 	/*XTH LATH parameters*/
 	iomodel->Constant(&fe_FS,FlowequationFeFSEnum);
-	if(fe_FS==XTaylorHoodEnum || fe_FS==LATaylorHoodEnum){
+	if(fe_FS==XTaylorHoodEnum || fe_FS==LATaylorHoodEnum || fe_FS==LACrouzeixRaviartEnum){
 		parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianREnum));
 		parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianRlambdaEnum));
@@ -130,731 +882,9 @@
 	iomodel->DeleteData(&requestedoutputs,numoutputs,StressbalanceRequestedOutputsEnum);
 
-}/*}}}*/
-void StressbalanceAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-
-	/*Intermediaries*/
-	int    materials_type,finiteelement,fe_FS;
-	int    approximation,frictionlaw;
-	int*   finiteelement_list=NULL;
-	bool   isSSA,isL1L2,isHO,isFS,iscoupling;
-	bool   control_analysis;
-	bool   dakota_analysis;
-	bool   islevelset;
-	bool   isdamage;
-
-	/*Fetch constants needed: */
-	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
-	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
-	iomodel->Constant(&isHO,FlowequationIsHOEnum);
-	iomodel->Constant(&isFS,FlowequationIsFSEnum);
-	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
-	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
-	iomodel->Constant(&materials_type,MaterialsEnum);
-	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
+	/*Deal with friction parameters*/
+	int frictionlaw;
 	iomodel->Constant(&frictionlaw,FrictionLawEnum);
-
-	/*return if no processing required*/
-	if(!isSSA & !isL1L2 & !isHO & !isFS) return;
-
-	/*Fetch data needed and allocate vectors: */
-	iomodel->FetchData(1,FlowequationElementEquationEnum);
-	finiteelement_list=xNewZeroInit<int>(iomodel->numberofelements);
-
-	/*Do we have coupling*/
-	if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
-	 iscoupling = true;
-	else
-	 iscoupling = false;
-
-	/*is damage mechanics being used?*/
-	if(materials_type==MaticeEnum) isdamage = false;
-	else if(materials_type==MatdamageiceEnum) isdamage = true;
-	else _error_("Material type not recognized");
-
-	/*Get finite element type*/
-	if(!iscoupling){
-		if(isSSA)       iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
-		else if(isL1L2) finiteelement = P1Enum;
-		else if(isHO)   iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
-		else if(isFS)   iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
-		for(int i=0;i<iomodel->numberofelements;i++){
-			finiteelement_list[i]=finiteelement;
-		}
-	}
-	else{
-		if(isFS){
-			for(int i=0;i<iomodel->numberofelements;i++){
-				approximation=reCast<int>(iomodel->Data(FlowequationElementEquationEnum)[i]);
-				if(approximation==FSApproximationEnum || approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
-					finiteelement_list[i]=MINIcondensedEnum;
-				}
-				else{
-					finiteelement_list[i]=P1Enum;
-				}
-			}
-		}
-		else{
-			finiteelement = P1Enum;
-			for(int i=0;i<iomodel->numberofelements;i++){
-				finiteelement_list[i]=finiteelement;
-			}
-		}
-	}
-
-	/*Update elements: */
-	int counter=0;
-	for(int i=0;i<iomodel->numberofelements;i++){
-		if(iomodel->my_elements[i]){
-			Element* element=(Element*)elements->GetObjectByOffset(counter);
-			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement_list[i]);
-			counter++;
-		}
-	}
-
-	/*Create inputs: */
-	iomodel->FetchDataToInput(elements,ThicknessEnum);
-	iomodel->FetchDataToInput(elements,SurfaceEnum);
-	iomodel->FetchDataToInput(elements,BaseEnum);
-	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
-	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
-	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
-	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
-	iomodel->FetchDataToInput(elements,VxEnum,0.);
-	iomodel->FetchDataToInput(elements,VyEnum,0.);
-	iomodel->FetchDataToInput(elements,LoadingforceXEnum);
-	iomodel->FetchDataToInput(elements,LoadingforceYEnum);
-	#ifdef LATERALFRICTION
-	iomodel->FetchDataToInput(elements,MeshVertexonboundaryEnum);
-	#endif
-	if(isdamage)iomodel->FetchDataToInput(elements,DamageDEnum);
-
-	if(iomodel->domaintype!=Domain2DhorizontalEnum){
-		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
-		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
-	}
-	if(iomodel->domaintype==Domain3DEnum){
-		iomodel->FetchDataToInput(elements,FlowequationBorderFSEnum);
-		iomodel->FetchDataToInput(elements,LoadingforceZEnum);
-		iomodel->FetchDataToInput(elements,VzEnum,0.);
-	}
-	if(isFS){
-		iomodel->FetchDataToInput(elements,PressureEnum,0.);
-		iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum,0.);
-	}
-	if(islevelset){
-		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
-	}
-	/*LATH parameters*/
-	iomodel->Constant(&fe_FS,FlowequationFeFSEnum);
-	if(fe_FS==LATaylorHoodEnum){
-		iomodel->FetchDataToInput(elements,PressureEnum,0.);
-		InputUpdateFromConstantx(elements,0.,SigmaNNEnum);
-	}
-
-	/*Friction law variables*/
-	switch(frictionlaw){
-		case 1:
-			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
-			iomodel->FetchDataToInput(elements,FrictionPEnum);
-			iomodel->FetchDataToInput(elements,FrictionQEnum);
-			break;
-		case 2:
-			iomodel->FetchDataToInput(elements,FrictionCEnum);
-			iomodel->FetchDataToInput(elements,FrictionMEnum);
-			break;
-		default:
-			_error_("not supported");
-	}
-
-#ifdef _HAVE_ANDROID_
-	elements->InputDuplicate(FrictionCoefficientEnum,AndroidFrictionCoefficientEnum);
-#endif
-
-	/*Free data: */
-	iomodel->DeleteData(1,FlowequationElementEquationEnum);
-	xDelete<int>(finiteelement_list);
-}/*}}}*/
-void StressbalanceAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	/*Intermediary*/
-	bool isSSA,isL1L2,isHO,isFS,iscoupling;
-	int  finiteelement=-1,approximation=-1;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
-	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
-	iomodel->Constant(&isHO,FlowequationIsHOEnum);
-	iomodel->Constant(&isFS,FlowequationIsFSEnum);
-
-	/*Now, check that we have non SIA elements */
-	if(!isSSA & !isL1L2 & !isHO & !isFS) return;
-
-	/*Do we have coupling*/
-	if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
-	 iscoupling = true;
-	else
-	 iscoupling = false;
-
-	/*If no coupling, call Regular CreateNodes, else, use P1 elements only*/
-	if(!iscoupling){
-
-		/*Get finite element type*/
-		if(isSSA){
-			approximation=SSAApproximationEnum;
-			iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
-		}
-		else if(isL1L2){
-			approximation = L1L2ApproximationEnum;
-			finiteelement = P1Enum;
-		}
-		else if(isHO){
-			approximation = HOApproximationEnum;
-			iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
-		}
-		else if(isFS){
-			approximation = FSApproximationEnum;
-			iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
-		}
-		iomodel->FetchData(3,FlowequationBorderSSAEnum,FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
-		if(iomodel->domaintype!=Domain2DhorizontalEnum) iomodel->FetchData(3,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderFSEnum);
-		::CreateNodes(nodes,iomodel,StressbalanceAnalysisEnum,finiteelement,approximation);
-		iomodel->DeleteData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
-					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
-	}
-	else{
-		/*Coupling: we are going to create P1 Elements only*/
-
-		Node*  node  = NULL;
-		int    lid=0;
-		if(!nodes) nodes = new Nodes();
-
-		iomodel->FetchData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
-					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
-		if(isFS){
-			/*P1+ velocity*/
-			for(int i=0;i<iomodel->numberofvertices;i++){
-				if(iomodel->my_vertices[i]){
-					approximation=reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]);
-					if(approximation==FSApproximationEnum)  approximation=FSvelocityEnum;
-					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceAnalysisEnum,approximation));
-				}
-			}
-			for(int i=0;i<iomodel->numberofelements;i++){
-				if(iomodel->my_elements[i]){
-					node = new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,StressbalanceAnalysisEnum,FSvelocityEnum);
-					node->Deactivate();
-					nodes->AddObject(node);
-				}
-			}
-			/*P1 pressure*/
-			for(int i=0;i<iomodel->numberofvertices;i++){
-				if(iomodel->my_vertices[i]){
-					approximation=reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]);
-					node = new Node(iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,iomodel->numberofvertices+iomodel->numberofelements+i,lid++,i,iomodel,StressbalanceAnalysisEnum,FSpressureEnum);
-					if(approximation==HOApproximationEnum || approximation==SSAApproximationEnum){
-						node->Deactivate();
-					}
-					nodes->AddObject(node);
-				}
-			}
-		}
-		else{
-			for(int i=0;i<iomodel->numberofvertices;i++){
-				if(iomodel->my_vertices[i]){
-					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceAnalysisEnum,reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i])));
-				}
-			}
-		}
-		iomodel->DeleteData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
-					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
-	}
-}/*}}}*/
-void StressbalanceAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-
-	/*Intermediary*/
-	int        i,j;
-	int        count,finiteelement;
-	IssmDouble g;
-	IssmDouble rho_ice;
-	IssmDouble FSreconditioning;
-	bool       isSIA,isSSA,isL1L2,isHO,isFS,iscoupling;
-	bool       spcpresent = false;
-	int        Mx,Nx;
-	int        My,Ny;
-	int        Mz,Nz;
-	IssmDouble *spcvx          = NULL;
-	IssmDouble *spcvy          = NULL;
-	IssmDouble *spcvz          = NULL;
-	IssmDouble *nodeonSSA = NULL;
-	IssmDouble *nodeonHO   = NULL;
-	IssmDouble *nodeonFS   = NULL;
-	IssmDouble *nodeonbase      = NULL;
-	IssmDouble *groundedice_ls = NULL;
-	IssmDouble *vertices_type  = NULL;
-	IssmDouble *surface        = NULL;
-	IssmDouble *z              = NULL;
-	IssmDouble *timesx=NULL;
-	IssmDouble *timesy=NULL;
-	IssmDouble *timesz=NULL;
-   IssmDouble* values=NULL;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&g,ConstantsGEnum);
-	iomodel->Constant(&rho_ice,MaterialsRhoIceEnum);
-	iomodel->Constant(&FSreconditioning,StressbalanceFSreconditioningEnum);
-	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
-	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
-	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
-	iomodel->Constant(&isHO,FlowequationIsHOEnum);
-	iomodel->Constant(&isFS,FlowequationIsFSEnum);
-
-	/*Now, is the flag macayaealHO on? otherwise, do nothing: */
-	if(!isSSA && !isHO && !isFS && !isL1L2) return;
-
-	/*Do we have coupling*/
-	if((isSIA?1.:0.) + (isSSA?1.:0.) + (isL1L2?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
-	 iscoupling = true;
-	else
-	 iscoupling = false;
-
-	/*If no coupling, call Regular IoModelToConstraintsx, else, use P1 elements only*/
-	if(!iscoupling){
-
-		/*Get finite element type*/
-		if(isSSA)       iomodel->Constant(&finiteelement,FlowequationFeSSAEnum);
-		else if(isL1L2) finiteelement = P1Enum;
-		else if(isHO)   iomodel->Constant(&finiteelement,FlowequationFeHOEnum);
-		else if(isFS){  iomodel->Constant(&finiteelement,FlowequationFeFSEnum);
-			/*Deduce velocity interpolation from finite element*/
-			switch(finiteelement){
-				case P1P1Enum            : finiteelement = P1Enum;       break;
-				case P1P1GLSEnum         : finiteelement = P1Enum;       break;
-				case MINIcondensedEnum   : finiteelement = P1bubbleEnum; break;
-				case MINIEnum            : finiteelement = P1bubbleEnum; break;
-				case TaylorHoodEnum      : finiteelement = P2Enum;       break;
-				case XTaylorHoodEnum     : finiteelement = P2Enum;       break;
-				case LATaylorHoodEnum    : finiteelement = P2Enum;       break;
-				case OneLayerP4zEnum     : finiteelement = P2xP4Enum;    break;
-				case CrouzeixRaviartEnum : finiteelement = P2bubbleEnum; break;
-				default: _error_("finite element "<<EnumToStringx(finiteelement)<<" not supported");
-			}
-		}
-		else{
-			_error_("model not supported yet");
-		}
-
-		if(isFS){
-
-			/*Constraint at the bedrock interface (v.n = vz = 0) (Coordinates will be updated according to the bed slope)*/
-			iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
-			iomodel->FetchData(&nodeonFS,NULL,NULL,FlowequationBorderFSEnum);
-			iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
-			iomodel->FetchData(&groundedice_ls,NULL,NULL,MaskGroundediceLevelsetEnum);
-			if(iomodel->domaintype==Domain3DEnum){
-				iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvzEnum);
-			}
-			else if (iomodel->domaintype==Domain2DverticalEnum){
-				iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvyEnum);
-			}
-			else{
-				_error_("not supported yet");
-			}
-			if(iomodel->domaintype==Domain3DEnum){
-				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,0);
-				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvyEnum,StressbalanceAnalysisEnum,finiteelement,1);
-				IoModelToConstraintsx(constraints,iomodel,spcvz,Mz,Nz,StressbalanceAnalysisEnum,finiteelement,2);
-				iomodel->DeleteData(spcvz,StressbalanceSpcvzEnum);
-			}
-			else if (iomodel->domaintype==Domain2DverticalEnum){
-				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,0);
-				IoModelToConstraintsx(constraints,iomodel,spcvz,Mz,Nz,StressbalanceAnalysisEnum,finiteelement,1);
-				iomodel->DeleteData(spcvz,StressbalanceSpcvyEnum);
-			}
-			else{
-				_error_("not supported yet");
-			}
-			iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
-			iomodel->DeleteData(nodeonFS,FlowequationBorderFSEnum);
-			iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
-			iomodel->DeleteData(groundedice_ls,MaskGroundediceLevelsetEnum);
-
-			/*Pressure spc*/
-			count = constraints->Size();
-			iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
-			iomodel->FetchData(&surface,NULL,NULL,SurfaceEnum);
-			iomodel->FetchData(&z,NULL,NULL,MeshZEnum);
-			switch(finiteelement){
-				case P1Enum:
-					for(i=0;i<iomodel->numberofvertices;i++){
-						if(iomodel->my_vertices[i]){
-							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
-								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
-								count++;
-							}
-						}
-					}
-					break;
-				case P1bubbleEnum:
-					for(i=0;i<iomodel->numberofvertices;i++){
-						if(iomodel->my_vertices[i]){
-							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
-								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
-								count++;
-							}
-						}
-					}
-					break;
-				case P2Enum:
-					for(i=0;i<iomodel->numberofvertices;i++){
-						if(iomodel->my_vertices[i]){
-							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
-								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
-								count++;
-							}
-						}
-					}
-					break;
-				case P2bubbleEnum:
-					for(i=0;i<iomodel->numberofvertices;i++){
-						if(iomodel->my_vertices[i]){
-							if(reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
-								constraints->AddObject(new SpcStatic(count+1,iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberofelements+iomodel->numberoffaces+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
-								count++;
-							}
-						}
-					}
-					break;
-				case P2xP4Enum:
-					//Nothing yet
-					break;
-				default:
-					_error_("not implemented yet");
-			}
-			iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
-			iomodel->DeleteData(surface,SurfaceEnum);
-			iomodel->DeleteData(z,MeshZEnum);
-		}
-		else{
-			IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,0);
-			if(iomodel->domaintype!=Domain2DverticalEnum){
-				IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvyEnum,StressbalanceAnalysisEnum,finiteelement,1);
-			}
-		}
-
-		return;
-	}
-
-	/*Constraints: fetch data: */
-	iomodel->FetchData(&spcvx,&Mx,&Nx,StressbalanceSpcvxEnum);
-	iomodel->FetchData(&spcvy,&My,&Ny,StressbalanceSpcvyEnum);
-	iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvzEnum);
-	iomodel->FetchData(&nodeonSSA,NULL,NULL,FlowequationBorderSSAEnum);
-	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&nodeonHO,NULL,NULL,FlowequationBorderHOEnum);
-	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&nodeonFS,NULL,NULL,FlowequationBorderFSEnum);
-	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&nodeonbase,NULL,NULL,MeshVertexonbaseEnum);
-	if(iomodel->domaintype==Domain3DEnum)iomodel->FetchData(&groundedice_ls,NULL,NULL,MaskGroundediceLevelsetEnum);
-	iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
-	iomodel->FetchData(&surface,NULL,NULL,SurfaceEnum);
-	iomodel->FetchData(&z,NULL,NULL,MeshZEnum);
-
-	/*Initialize counter: */
-	count=0;
-
-	/*figure out times: */
-	timesx=xNew<IssmDouble>(Nx);
-	for(j=0;j<Nx;j++){
-		timesx[j]=spcvx[(Mx-1)*Nx+j];
-	}
-	/*figure out times: */
-	timesy=xNew<IssmDouble>(Ny);
-	for(j=0;j<Ny;j++){
-		timesy[j]=spcvy[(My-1)*Ny+j];
-	}
-	/*figure out times: */
-	timesz=xNew<IssmDouble>(Nz);
-	for(j=0;j<Nz;j++){
-		timesz[j]=spcvz[(Mz-1)*Nz+j];
-	}
-
-	/*Create spcs from x,y,z, as well as the spc values on those spcs: */
-	for(i=0;i<iomodel->numberofvertices;i++){
-		if(iomodel->my_vertices[i]){
-
-			/*Start with adding spcs of coupling: zero at the border SSA/HO for the appropriate dofs*/
-			if(reCast<int,IssmDouble>(vertices_type[i]==SSAHOApproximationEnum)){
-				/*If grionSSA, spc HO dofs: 3 & 4*/
-					if (reCast<int,IssmDouble>(nodeonHO[i])){
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						if (!xIsNan<IssmDouble>(spcvx[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-						if (!xIsNan<IssmDouble>(spcvy[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-
-					}
-					else if (reCast<int,IssmDouble>(nodeonSSA[i])){
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						if (!xIsNan<IssmDouble>(spcvx[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-						if (!xIsNan<IssmDouble>(spcvy[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-
-					}
-					else _error_("if vertices_type is SSAHO, you shoud have nodeonHO or nodeonSSA");
-			}
-			/*Also add spcs of coupling: zero at the border HO/FS for the appropriate dofs*/
-			else if (reCast<int,IssmDouble>(vertices_type[i])==HOFSApproximationEnum){
-				/*If grion,HO spc FS dofs: 3 4 & 5*/
-					if (reCast<int,IssmDouble>(nodeonHO[i])){
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						if (!xIsNan<IssmDouble>(spcvx[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-						if (!xIsNan<IssmDouble>(spcvy[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-
-					}
-					else if (reCast<int,IssmDouble>(nodeonFS[i])){ //spc HO nodes: 1 & 2
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						if (!xIsNan<IssmDouble>(spcvx[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-						if (!xIsNan<IssmDouble>(spcvy[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-						if (!xIsNan<IssmDouble>(spcvz[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-					}
-					else _error_("if vertices_type is HOFS, you shoud have nodeonHO or nodeonFS");
-			}
-			/*Also add spcs of coupling: zero at the border HO/FS for the appropriate dofs*/
-			else if (reCast<int,IssmDouble>(vertices_type[i])==SSAFSApproximationEnum){
-				/*If grion,HO spc FS dofs: 3 4 & 5*/
-					if (reCast<int,IssmDouble>(nodeonSSA[i])){
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						if (!xIsNan<IssmDouble>(spcvx[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-						if (!xIsNan<IssmDouble>(spcvy[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-
-					}
-					else if (reCast<int,IssmDouble>(nodeonFS[i])){ //spc SSA nodes: 1 & 2
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-						count++;
-						if (!xIsNan<IssmDouble>(spcvx[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-						if (!xIsNan<IssmDouble>(spcvy[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-						if (!xIsNan<IssmDouble>(spcvz[i])){
-							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,4,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-							count++;
-						}
-					}
-					else _error_("if vertices_type is SSAFS, you shoud have nodeonSSA or nodeonFS");
-			}
-			/*Now add the regular spcs*/
-			else{
-				if (Mx==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvx[i])){
-					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,spcvx[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
-					count++;
-
-				}
-				else if (Mx==iomodel->numberofvertices+1) {
-					/*figure out times and values: */
-					values=xNew<IssmDouble>(Nx);
-					spcpresent=false;
-					for(j=0;j<Nx;j++){
-						values[j]=spcvx[i*Nx+j];
-						if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
-					}
-
-					if(spcpresent){
-						constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,Nx,timesx,values,StressbalanceAnalysisEnum));
-						count++;
-					}
-					xDelete<IssmDouble>(values);
-				}
-				else if (vertices_type[i]==SIAApproximationEnum){
-					constraints->AddObject(new SpcDynamic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,0,StressbalanceAnalysisEnum));
-					count++;
-				}
-
-				if (My==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvy[i])){
-					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,spcvy[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vy.
-					count++;
-				}
-				else if (My==iomodel->numberofvertices+1){
-					/*figure out times and values: */
-					values=xNew<IssmDouble>(Ny);
-					spcpresent=false;
-					for(j=0;j<Ny;j++){
-						values[j]=spcvy[i*Ny+j];
-						if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
-					}
-					if(spcpresent){
-						constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,Ny,timesy,values,StressbalanceAnalysisEnum));
-						count++;
-					}
-					xDelete<IssmDouble>(values);
-				}
-				else if (vertices_type[i]==SIAApproximationEnum){
-					constraints->AddObject(new SpcDynamic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,StressbalanceAnalysisEnum));
-					count++;
-				}
-
-				if (reCast<int,IssmDouble>(vertices_type[i])==FSApproximationEnum ||  (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum)){
-					if (Mz==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvz[i])){
-						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,spcvz[i],StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
-						count++;
-					}
-					else if (Mz==iomodel->numberofvertices+1){
-						/*figure out times and values: */
-						values=xNew<IssmDouble>(Nz);
-						spcpresent=false;
-						for(j=0;j<Nz;j++){
-							values[j]=spcvz[i*Nz+j];
-							if(!xIsNan<IssmDouble>(values[j]))spcpresent=true; //NaN means no spc by default
-						}
-						if(spcpresent){
-							constraints->AddObject(new SpcTransient(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,Nz,timesz,values,StressbalanceAnalysisEnum));
-							count++;
-						}
-						xDelete<IssmDouble>(values);
-					}
-
-				}
-				if (reCast<int,IssmDouble>(vertices_type[i])==NoneApproximationEnum){
-					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,0,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
-					count++;
-				}
-			}
-		}
-	}
-
-	/*Free data: */
-	iomodel->DeleteData(spcvx,StressbalanceSpcvxEnum);
-	iomodel->DeleteData(spcvy,StressbalanceSpcvyEnum);
-	iomodel->DeleteData(spcvz,StressbalanceSpcvzEnum);
-	iomodel->DeleteData(nodeonSSA,FlowequationBorderSSAEnum);
-	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(nodeonHO,FlowequationBorderHOEnum);
-	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(nodeonFS,FlowequationBorderFSEnum);
-	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(nodeonbase,MeshVertexonbaseEnum);
-	if(iomodel->domaintype==Domain3DEnum)iomodel->DeleteData(groundedice_ls,MaskGroundediceLevelsetEnum);
-	iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
-	iomodel->DeleteData(surface,SurfaceEnum);
-	iomodel->DeleteData(z,MeshZEnum);
-
-	/*Free resources:*/
-	xDelete<IssmDouble>(timesx);
-	xDelete<IssmDouble>(timesy);
-	xDelete<IssmDouble>(timesz);
-	xDelete<IssmDouble>(values);
-
-}/*}}}*/
-void StressbalanceAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
-	/*Intermediary*/
-	const int   RIFTINFOSIZE = 12;
-	int         i;
-	int         count;
-	int         penpair_ids[2];
-	bool        isSSA,isL1L2,isHO,isFS;
-	int         numpenalties,numrifts,numriftsegments;
-	IssmDouble *riftinfo       = NULL;
-	IssmDouble *penalties      = NULL;
-	int         assert_int;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&isL1L2,FlowequationIsL1L2Enum);
-	iomodel->Constant(&isFS,FlowequationIsFSEnum);
-	iomodel->Constant(&isSSA,FlowequationIsSSAEnum);
-	iomodel->Constant(&isHO,FlowequationIsHOEnum);
-	iomodel->Constant(&numrifts,RiftsNumriftsEnum);
-
-	/*Now, is the flag macayaealHO on? otherwise, do nothing: */
-	if(!isSSA && !isHO && !isFS && !isL1L2) return;
-
-	/*Initialize counter: */
-	count=0;
-
-	/*Create Penpair for penalties: */
-	iomodel->FetchData(&penalties,&numpenalties,NULL,StressbalanceVertexPairingEnum);
-
-	for(i=0;i<numpenalties;i++){
-
-		if(iomodel->my_vertices[reCast<int,IssmDouble>(penalties[2*i+0]-1)]){
-
-			/*In debugging mode, check that the second node is in the same cpu*/
-			assert_int=iomodel->my_vertices[reCast<int,IssmDouble>(penalties[2*i+1]-1)]; _assert_(assert_int);
-
-			/*Get node ids*/
-			penpair_ids[0]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+0]);
-			penpair_ids[1]=iomodel->nodecounter+reCast<int,IssmDouble>(penalties[2*i+1]);
-
-			/*Create Load*/
-			loads->AddObject(new Penpair(iomodel->loadcounter+count+1,&penpair_ids[0],StressbalanceAnalysisEnum));
-			count++;
-		}
-	}
-
-	/*free ressources: */
-	iomodel->DeleteData(penalties,StressbalanceVertexPairingEnum);
-
-	/*Create Riffront loads for rifts: */
-	if(numrifts){
-		iomodel->FetchData(&riftinfo,&numriftsegments,NULL,RiftsRiftstructEnum);
-		iomodel->FetchData(5,RiftsRiftstructEnum,ThicknessEnum,BaseEnum,SurfaceEnum,MaskGroundediceLevelsetEnum);
-		for(i=0;i<numriftsegments;i++){
-			if(iomodel->my_elements[reCast<int,IssmDouble>(*(riftinfo+RIFTINFOSIZE*i+2))-1]){
-				loads->AddObject(new Riftfront(iomodel->loadcounter+count+1,i,iomodel,StressbalanceAnalysisEnum));
-				count++;
-			}
-		}
-		iomodel->DeleteData(5,RiftsRiftstructEnum,ThicknessEnum,BaseEnum,SurfaceEnum,MaskGroundediceLevelsetEnum);
-		xDelete<IssmDouble>(riftinfo);
-	}
+	if(frictionlaw==4 || frictionlaw==6) parameters->AddObject(iomodel->CopyConstantObject(FrictionGammaEnum));
+
 }/*}}}*/
 
@@ -882,5 +912,5 @@
 		if (fe_FS==XTaylorHoodEnum)
 		 solutionsequence_la_theta(femmodel);
-		else if (fe_FS==LATaylorHoodEnum)
+		else if (fe_FS==LATaylorHoodEnum || fe_FS==LACrouzeixRaviartEnum)
 		 solutionsequence_la(femmodel);
 		else if(newton>0)
@@ -997,5 +1027,5 @@
 	}
 }/*}}}*/
-void StressbalanceAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           StressbalanceAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 
 	int approximation;
@@ -1018,5 +1048,5 @@
 	}
 }/*}}}*/
-void StressbalanceAnalysis::GetSolutionFromInputsHoriz(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           StressbalanceAnalysis::GetSolutionFromInputsHoriz(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 
 	IssmDouble   vx,vy;
@@ -1068,8 +1098,8 @@
 	xDelete<int>(doflist);
 }/*}}}*/
-void StressbalanceAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           StressbalanceAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void StressbalanceAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           StressbalanceAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int approximation;
@@ -1103,5 +1133,5 @@
 	}
 }/*}}}*/
-void StressbalanceAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           StressbalanceAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	bool islevelset;
@@ -1451,7 +1481,4 @@
 					Bprime,bsize,numdof,0,
 					&Ke->values[0],1);
-
-		for(int i=0;i<bsize*numdof;i++) if(B[i]==1.) _error_("STREAM");
-		for(int i=0;i<bsize*numdof;i++) if(Bprime[i]==1.) _error_("STREAM");
 	}
 
@@ -1541,5 +1568,5 @@
 		element->NodalFunctions(basis, gauss);
 
-		thickness_input->GetInputValue(&thickness,gauss);
+		thickness_input->GetInputValue(&thickness,gauss); _assert_(thickness>0);
 		surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
 
@@ -1598,5 +1625,4 @@
 	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
 	element->GetVerticesCoordinates(&xyz_list);
-	//element->ZeroLevelsetCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
 	element->GetIcefrontCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
 	element->NormalSection(&normal[0],xyz_list_front);
@@ -1634,5 +1660,5 @@
 	return pe;
 }/*}}}*/
-void StressbalanceAnalysis::GetBSSA(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetBSSA(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
 	 * For node i, Bi can be expressed in the actual coordinate system
@@ -1674,5 +1700,5 @@
 	xDelete<IssmDouble>(dbasis);
 }/*}}}*/
-void StressbalanceAnalysis::GetBSSAFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetBSSAFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is square and of size 2. 
 	 * For node i, Bi can be expressed in the actual coordinate system
@@ -1711,5 +1737,5 @@
 	xDelete<IssmDouble>(basis);
 }/*}}}*/
-void StressbalanceAnalysis::GetBSSAprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetBSSAprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
 	 * For node i, Bi' can be expressed in the actual coordinate system
@@ -1751,5 +1777,5 @@
 	xDelete<IssmDouble>(dbasis);
 }/*}}}*/
-void StressbalanceAnalysis::InputUpdateFromSolutionSSA(IssmDouble* solution,Element* element){/*{{{*/
+void           StressbalanceAnalysis::InputUpdateFromSolutionSSA(IssmDouble* solution,Element* element){/*{{{*/
 
 	int         i,dim,domaintype;
@@ -2050,5 +2076,5 @@
 	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
 	element->GetVerticesCoordinates(&xyz_list);
-	element->ZeroLevelsetCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
+	element->GetIcefrontCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
 	element->NormalSection(&normal[0],xyz_list_front);
 
@@ -2085,5 +2111,5 @@
 	return pe;
 }/*}}}*/
-void StressbalanceAnalysis::InputUpdateFromSolutionL1L2(IssmDouble* solution,Element* element){/*{{{*/
+void           StressbalanceAnalysis::InputUpdateFromSolutionL1L2(IssmDouble* solution,Element* element){/*{{{*/
 
 	int         i,dim,domaintype;
@@ -2260,4 +2286,84 @@
 	return Ke;
 }/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixHOFriction(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	if(element->IsFloating() || !element->IsOnBase()) return NULL;
+
+	/*Intermediaries*/
+	int         dim;
+	bool        mainlyfloating;
+	int         migration_style,point1;
+	IssmDouble  alpha2,Jdet,fraction1,fraction2;
+	IssmDouble  gllevelset,phi=1.;
+	IssmDouble *xyz_list_base = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+	int numdof   = numnodes*(dim-1);
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke = element->NewElementMatrix(HOApproximationEnum);
+	IssmDouble*    B  = xNew<IssmDouble>((dim-1)*numdof);
+	IssmDouble*    D  = xNewZeroInit<IssmDouble>((dim-1)*(dim-1));
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->FindParam(&migration_style,GroundinglineMigrationEnum);
+	Input* gllevelset_input = NULL;
+
+	/*build friction object, used later on: */
+	Friction* friction=new Friction(element,2);
+
+	/*Recover portion of element that is grounded*/
+	if(migration_style==SubelementMigrationEnum) phi=element->GetGroundedPortion(xyz_list_base);
+	if(migration_style==SubelementMigration2Enum){
+		gllevelset_input=element->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
+		element->GetGroundedPart(&point1,&fraction1,&fraction2,&mainlyfloating);
+		//gauss = element->NewGauss(point1,fraction1,fraction2,mainlyfloating,2);
+		gauss=element->NewGaussBase(2);
+	}
+	else{
+		gauss=element->NewGaussBase(2);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		friction->GetAlpha2(&alpha2,gauss);
+		if(migration_style==SubelementMigrationEnum) alpha2=phi*alpha2;
+		if(migration_style==SubelementMigration2Enum){
+			gllevelset_input->GetInputValue(&gllevelset, gauss);
+			if(gllevelset<0.) alpha2=0.;
+		}
+
+		this->GetBHOFriction(B,element,dim,xyz_list_base,gauss);
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		for(int i=0;i<dim-1;i++) D[i*(dim-1)+i]=alpha2*gauss->weight*Jdet;
+
+		TripleMultiply(B,dim-1,numdof,1,
+					D,dim-1,dim-1,0,
+					B,dim-1,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	if(dim==3) element->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(D);
+	return Ke;
+}/*}}}*/
 ElementMatrix* StressbalanceAnalysis::CreateKMatrixHOViscous(Element* element){/*{{{*/
 
@@ -2332,84 +2438,4 @@
 	return Ke;
 }/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixHOFriction(Element* element){/*{{{*/
-
-	/* Check if ice in element */
-	if(!element->IsIceInElement()) return NULL;
-
-	if(element->IsFloating() || !element->IsOnBase()) return NULL;
-
-	/*Intermediaries*/
-	int         dim;
-	bool        mainlyfloating;
-	int         migration_style,point1;
-	IssmDouble  alpha2,Jdet,fraction1,fraction2;
-	IssmDouble  gllevelset,phi=1.;
-	IssmDouble *xyz_list_base = NULL;
-	Gauss*      gauss         = NULL;
-
-	/*Get problem dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-	int numdof   = numnodes*(dim-1);
-
-	/*Initialize Element matrix and vectors*/
-	ElementMatrix* Ke = element->NewElementMatrix(HOApproximationEnum);
-	IssmDouble*    B  = xNew<IssmDouble>((dim-1)*numdof);
-	IssmDouble*    D  = xNewZeroInit<IssmDouble>((dim-1)*(dim-1));
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinatesBase(&xyz_list_base);
-	element->FindParam(&migration_style,GroundinglineMigrationEnum);
-	Input* gllevelset_input = NULL;
-
-	/*build friction object, used later on: */
-	Friction* friction=new Friction(element,2);
-
-	/*Recover portion of element that is grounded*/
-	if(migration_style==SubelementMigrationEnum) phi=element->GetGroundedPortion(xyz_list_base);
-	if(migration_style==SubelementMigration2Enum){
-		gllevelset_input=element->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
-		element->GetGroundedPart(&point1,&fraction1,&fraction2,&mainlyfloating);
-		//gauss = element->NewGauss(point1,fraction1,fraction2,mainlyfloating,2);
-		gauss=element->NewGaussBase(2);
-	}
-	else{
-		gauss=element->NewGaussBase(2);
-	}
-
-	/* Start  looping on the number of gaussian points: */
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		friction->GetAlpha2(&alpha2,gauss);
-		if(migration_style==SubelementMigrationEnum) alpha2=phi*alpha2;
-		if(migration_style==SubelementMigration2Enum){
-			gllevelset_input->GetInputValue(&gllevelset, gauss);
-			if(gllevelset<0.) alpha2=0.;
-		}
-
-		this->GetBHOFriction(B,element,dim,xyz_list_base,gauss);
-		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-		for(int i=0;i<dim-1;i++) D[i*(dim-1)+i]=alpha2*gauss->weight*Jdet;
-
-		TripleMultiply(B,dim-1,numdof,1,
-					D,dim-1,dim-1,0,
-					B,dim-1,numdof,0,
-					&Ke->values[0],1);
-	}
-
-	/*Transform Coordinate System*/
-	if(dim==3) element->TransformStiffnessMatrixCoord(Ke,XYEnum);
-
-	/*Clean up and return*/
-	delete gauss;
-	delete friction;
-	xDelete<IssmDouble>(xyz_list_base);
-	xDelete<IssmDouble>(B);
-	xDelete<IssmDouble>(D);
-	return Ke;
-}/*}}}*/
 #ifdef FSANALYTICAL
 ElementVector* StressbalanceAnalysis::CreatePVectorHO(Element* element){/*{{{*/
@@ -2568,5 +2594,5 @@
 	IssmDouble gravity   = element->GetMaterialParameter(ConstantsGEnum);
 	element->GetVerticesCoordinates(&xyz_list);
-	element->ZeroLevelsetCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
+	element->GetIcefrontCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
 	element->NormalSection(&normal[0],xyz_list_front);
 
@@ -2607,5 +2633,5 @@
 	return pe;
 }/*}}}*/
-void StressbalanceAnalysis::GetBHO(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetBHO(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF2. 
 	 * For node i, Bi can be expressed in the actual coordinate system
@@ -2656,5 +2682,42 @@
 	xDelete<IssmDouble>(dbasis);
 }/*}}}*/
-void StressbalanceAnalysis::GetBHOprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetBHOFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3] where Bi is square and of size 2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 
+	 *                       3D           2D
+	 *                 Bi=[ N   0 ]    Bi=N
+	 *                    [ 0   N ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 2 x (numdof*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build L: */
+	if(dim==3){
+		for(int i=0;i<numnodes;i++){
+			B[2*numnodes*0+2*i+0] = basis[i];
+			B[2*numnodes*0+2*i+1] = 0.;
+			B[2*numnodes*1+2*i+0] = 0.;
+			B[2*numnodes*1+2*i+1] = basis[i];
+		}
+	}
+	else{
+		for(int i=0;i<numnodes;i++){
+			B[i] = basis[i];
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void           StressbalanceAnalysis::GetBHOprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
 	 * For node i, Bi' can be expressed in the actual coordinate system
@@ -2701,42 +2764,5 @@
 	xDelete<IssmDouble>(dbasis);
 }/*}}}*/
-void StressbalanceAnalysis::GetBHOFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B  matrix. B=[B1 B2 B3] where Bi is square and of size 2. 
-	 * For node i, Bi can be expressed in the actual coordinate system
-	 * by: 
-	 *                       3D           2D
-	 *                 Bi=[ N   0 ]    Bi=N
-	 *                    [ 0   N ]
-	 * where N is the finiteelement function for node i.
-	 *
-	 * We assume B has been allocated already, of size: 2 x (numdof*numnodes)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	element->NodalFunctions(basis,gauss);
-
-	/*Build L: */
-	if(dim==3){
-		for(int i=0;i<numnodes;i++){
-			B[2*numnodes*0+2*i+0] = basis[i];
-			B[2*numnodes*0+2*i+1] = 0.;
-			B[2*numnodes*1+2*i+0] = 0.;
-			B[2*numnodes*1+2*i+1] = basis[i];
-		}
-	}
-	else{
-		for(int i=0;i<numnodes;i++){
-			B[i] = basis[i];
-		}
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(basis);
-}/*}}}*/
-void StressbalanceAnalysis::InputUpdateFromSolutionHO(IssmDouble* solution,Element* element){/*{{{*/
+void           StressbalanceAnalysis::InputUpdateFromSolutionHO(IssmDouble* solution,Element* element){/*{{{*/
 
 	int         i,dim;
@@ -2941,6 +2967,6 @@
 	if(fe_FS==XTaylorHoodEnum)
 	 Ke1=CreateKMatrixFSViscousXTH(element);
-	else if(fe_FS==LATaylorHoodEnum)
-	 Ke1=CreateKMatrixFSViscousLATH(element);
+	else if(fe_FS==LATaylorHoodEnum || fe_FS==LACrouzeixRaviartEnum)
+	 Ke1=CreateKMatrixFSViscousLA(element);
 	else
 	 Ke1=CreateKMatrixFSViscous(element);
@@ -2956,5 +2982,142 @@
 	return Ke;
 }/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSViscousLATH(Element* element){/*{{{*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSShelf(Element* element){/*{{{*/
+
+	if(!element->IsFloating() || !element->IsOnBase()) return NULL;
+
+	/*If on not water or not FS, skip stiffness: */
+	int approximation,shelf_dampening;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum && approximation!=HOFSApproximationEnum) return NULL;
+	element->FindParam(&shelf_dampening,StressbalanceShelfDampeningEnum);
+	if(shelf_dampening==0) return NULL;
+
+	/*Intermediaries*/
+	bool        mainlyfloating;
+	int         j,i,dim;
+	IssmDouble  Jdet,slope2,scalar,dt;
+	IssmDouble  slope[3];
+	IssmDouble *xyz_list_base = NULL;
+	IssmDouble *xyz_list      = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numdof    = vnumnodes*dim + pnumnodes;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke = element->NewElementMatrix(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&dt,TimesteppingTimeStepEnum);
+	if(dt==0)   dt=1.e+5;
+	IssmDouble  rho_water     = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  gravity       = element->GetMaterialParameter(ConstantsGEnum);
+	Input*      surface_input = element->GetInput(SurfaceEnum); _assert_(surface_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=element->NewGaussBase(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		if(dim==2) slope2=slope[0]*slope[0];
+		else if(dim==3) slope2=slope[0]*slope[0]+slope[1]*slope[1];
+		scalar  = rho_water*gravity*sqrt(1+slope2)*gauss->weight*Jdet*dt; 
+		for(i=0;i<vnumnodes;i++){
+			for(j=0;j<vnumnodes;j++){
+				Ke->values[numdof*((i+1)*dim-1)+(j+1)*dim-1] += scalar*vbasis[i]*vbasis[j];
+			}
+		}
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(vbasis);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSViscous(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         i,dim,epssize;
+	IssmDouble  viscosity,FSreconditioning,Jdet;
+	IssmDouble *xyz_list = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+	if(dim==2) epssize = 3;
+	else       epssize = 6;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numdof    = vnumnodes*dim + pnumnodes;
+	int bsize     = epssize + 2;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = element->NewElementMatrix(FSvelocityEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(bsize*numdof);
+	IssmDouble*    Bprime = xNew<IssmDouble>(bsize*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(bsize*bsize);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	Input* vx_input=element->GetInput(VxEnum);     _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum);     _assert_(vy_input);
+	Input* vz_input;
+	if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		this->GetBFS(B,element,dim,xyz_list,gauss);
+		this->GetBFSprime(Bprime,element,dim,xyz_list,gauss);
+
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		for(i=0;i<epssize;i++)     D[i*bsize+i] = + 2.*viscosity*gauss->weight*Jdet;
+		for(i=epssize;i<bsize;i++) D[i*bsize+i] = - FSreconditioning*gauss->weight*Jdet;
+
+		TripleMultiply(B,bsize,numdof,1,
+					D,bsize,bsize,0,
+					Bprime,bsize,numdof,0,
+					&Ke->values[0],1);
+	}
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(B);
+	xDelete<int>(cs_list);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSViscousLA(Element* element){/*{{{*/
 
 	/*Intermediaries*/
@@ -3028,5 +3191,10 @@
 	}
 
-	if(element->IsOnBase()){ 
+	/*The pressure augmentation should not be transformed*/
+	MatrixMultiply(BtBUzawa,pnumdof,numdof,1,
+				BtBUzawa,pnumdof,numdof,0,
+				&Ke->values[0],1);
+
+	if(element->IsOnBase() && 0){ 
 		element->FindParam(&rl,AugmentedLagrangianRlambdaEnum);
 		element->GetVerticesCoordinatesBase(&xyz_list_base);
@@ -3068,9 +3236,4 @@
 	/*Transform Coordinate System*/
 	element->TransformStiffnessMatrixCoord(Ke,cs_list);
-
-	/*The pressure augmentation should not be transformed*/
-	MatrixMultiply(BtBUzawa,pnumdof,numdof,1,
-				BtBUzawa,pnumdof,numdof,0,
-				&Ke->values[0],1);
 
 	/*Clean up and return*/
@@ -3155,141 +3318,4 @@
 	return Ke;
 }/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSViscous(Element* element){/*{{{*/
-
-	/*Intermediaries*/
-	int         i,dim,epssize;
-	IssmDouble  viscosity,FSreconditioning,Jdet;
-	IssmDouble *xyz_list = NULL;
-
-	/*Get problem dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
-	if(dim==2) epssize = 3;
-	else       epssize = 6;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int vnumnodes = element->NumberofNodesVelocity();
-	int pnumnodes = element->NumberofNodesPressure();
-	int numdof    = vnumnodes*dim + pnumnodes;
-	int bsize     = epssize + 2;
-
-	/*Prepare coordinate system list*/
-	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
-	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
-	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
-	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
-
-	/*Initialize Element matrix and vectors*/
-	ElementMatrix* Ke     = element->NewElementMatrix(FSvelocityEnum);
-	IssmDouble*    B      = xNew<IssmDouble>(bsize*numdof);
-	IssmDouble*    Bprime = xNew<IssmDouble>(bsize*numdof);
-	IssmDouble*    D      = xNewZeroInit<IssmDouble>(bsize*bsize);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
-	Input* vx_input=element->GetInput(VxEnum);     _assert_(vx_input);
-	Input* vy_input=element->GetInput(VyEnum);     _assert_(vy_input);
-	Input* vz_input;
-	if(dim==3){vz_input=element->GetInput(VzEnum); _assert_(vz_input);}
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss = element->NewGauss(5);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		this->GetBFS(B,element,dim,xyz_list,gauss);
-		this->GetBFSprime(Bprime,element,dim,xyz_list,gauss);
-
-		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
-		for(i=0;i<epssize;i++)     D[i*bsize+i] = + 2.*viscosity*gauss->weight*Jdet;
-		for(i=epssize;i<bsize;i++) D[i*bsize+i] = - FSreconditioning*gauss->weight*Jdet;
-
-		TripleMultiply(B,bsize,numdof,1,
-					D,bsize,bsize,0,
-					Bprime,bsize,numdof,0,
-					&Ke->values[0],1);
-	}
-
-	/*Transform Coordinate System*/
-	element->TransformStiffnessMatrixCoord(Ke,cs_list);
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(D);
-	xDelete<IssmDouble>(Bprime);
-	xDelete<IssmDouble>(B);
-	xDelete<int>(cs_list);
-	return Ke;
-}/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSShelf(Element* element){/*{{{*/
-
-	if(!element->IsFloating() || !element->IsOnBase()) return NULL;
-
-	/*If on not water or not FS, skip stiffness: */
-	int approximation,shelf_dampening;
-	element->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum && approximation!=HOFSApproximationEnum) return NULL;
-	element->FindParam(&shelf_dampening,StressbalanceShelfDampeningEnum);
-	if(shelf_dampening==0) return NULL;
-
-	/*Intermediaries*/
-	bool        mainlyfloating;
-	int         j,i,dim;
-	IssmDouble  Jdet,slope2,scalar,dt;
-	IssmDouble  slope[3];
-	IssmDouble *xyz_list_base = NULL;
-	IssmDouble *xyz_list      = NULL;
-	Gauss*      gauss         = NULL;
-
-	/*Get problem dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int vnumnodes = element->NumberofNodesVelocity();
-	int pnumnodes = element->NumberofNodesPressure();
-	int numdof    = vnumnodes*dim + pnumnodes;
-
-	/*Initialize Element matrix and vectors*/
-	ElementMatrix* Ke = element->NewElementMatrix(FSvelocityEnum);
-	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinatesBase(&xyz_list_base);
-	element->GetVerticesCoordinates(&xyz_list);
-	element->FindParam(&dt,TimesteppingTimeStepEnum);
-	if(dt==0)   dt=1.e+5;
-	IssmDouble  rho_water     = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
-	IssmDouble  gravity       = element->GetMaterialParameter(ConstantsGEnum);
-	Input*      surface_input = element->GetInput(SurfaceEnum); _assert_(surface_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=element->NewGaussBase(3);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
-		element->NodalFunctionsVelocity(vbasis,gauss);
-		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-		if(dim==2) slope2=slope[0]*slope[0];
-		else if(dim==3) slope2=slope[0]*slope[0]+slope[1]*slope[1];
-		scalar  = rho_water*gravity*sqrt(1+slope2)*gauss->weight*Jdet*dt; 
-		for(i=0;i<vnumnodes;i++){
-			for(j=0;j<vnumnodes;j++){
-				Ke->values[numdof*((i+1)*dim-1)+(j+1)*dim-1] += scalar*vbasis[i]*vbasis[j];
-			}
-		}
-	}
-
-	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<IssmDouble>(xyz_list_base);
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(vbasis);
-	return Ke;
-}/*}}}*/
 #ifdef FSANALYTICAL
 ElementMatrix* StressbalanceAnalysis::CreateKMatrixFSFriction(Element* element){/*{{{*/
@@ -3376,4 +3402,114 @@
 
 	/*clean-up and return*/
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSFriction(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+
+	/*Intermediaries*/
+	int         dim;
+	IssmDouble  alpha2,Jdet;
+	IssmDouble  bed_normal[3];
+	IssmDouble *xyz_list_base = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Initialize Element matrix and vectors*/
+	ElementVector* pe = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	Input*  alpha2_input=element->GetInput(FrictionCoefficientEnum); _assert_(alpha2_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=element->NewGaussBase(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		alpha2_input->GetInputValue(&alpha2, gauss);
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+		element->NormalBase(&bed_normal[0],xyz_list_base);
+
+		for(int i=0;i<vnumnodes;i++){
+			pe->values[i*dim+0] += - alpha2*gauss->weight*Jdet*vbasis[i]*bed_normal[1];
+			pe->values[i*dim+1] += alpha2*gauss->weight*Jdet*vbasis[i]*bed_normal[0];
+			if(dim==3){
+				pe->values[i*dim+2]+= alpha2*gauss->weight*Jdet*vbasis[i];
+			}
+		}
+
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(vbasis);
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSStress(Element* element){/*{{{*/
+
+	if(!element->IsOnBase()) return NULL;
+
+	/*Intermediaries*/
+	int         dim;
+	IssmDouble  sigmann,sigmant,Jdet,bedslope,beta;
+	IssmDouble *xyz_list_base = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Initialize Element matrix and vectors*/
+	ElementVector* pe = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	Input*  sigmann_input=element->GetInput(VzEnum); _assert_(sigmann_input);
+	Input*  sigmant_input=element->GetInput(TemperatureEnum); _assert_(sigmant_input);
+	Input*  bedslope_input=element->GetInput(BedSlopeXEnum);     _assert_(bedslope_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=element->NewGaussBase(3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		sigmann_input->GetInputValue(&sigmann, gauss);
+		sigmant_input->GetInputValue(&sigmant, gauss);
+		bedslope_input->GetInputValue(&bedslope, gauss);
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+
+		beta=sqrt(1+bedslope*bedslope);
+		for(int i=0;i<vnumnodes;i++){
+			pe->values[i*dim+0] += - (1./beta)*(-bedslope*sigmann + sigmant)*gauss->weight*Jdet*vbasis[i];
+			pe->values[i*dim+1] += - (1./beta)*(sigmann + bedslope*sigmant)*gauss->weight*Jdet*vbasis[i];
+			if(dim==3){
+				//pe->values[i*dim+2]+= alpha2*gauss->weight*Jdet*vbasis[i];
+				_error_("3d not supported yet");
+			}
+		}
+
+	}
+
+	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list_base);
+	xDelete<IssmDouble>(vbasis);
 	return pe;
 }/*}}}*/
@@ -3444,6 +3580,6 @@
 		return pe3;
 	}
-	else if(fe_FS==LATaylorHoodEnum){
-		ElementVector* pe2=CreatePVectorFSViscousLATH(element);
+	else if(fe_FS==LATaylorHoodEnum || fe_FS==LACrouzeixRaviartEnum){
+		ElementVector* pe2=CreatePVectorFSViscousLA(element);
 		ElementVector* pe3 = new ElementVector(pe,pe2);
 		delete pe;
@@ -3451,114 +3587,4 @@
 		return pe3;
 	}
-	return pe;
-}/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorFSFriction(Element* element){/*{{{*/
-
-	if(!element->IsOnBase()) return NULL;
-
-	/*Intermediaries*/
-	int         dim;
-	IssmDouble  alpha2,Jdet;
-	IssmDouble  bed_normal[3];
-	IssmDouble *xyz_list_base = NULL;
-	Gauss*      gauss         = NULL;
-
-	/*Get problem dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int vnumnodes = element->NumberofNodesVelocity();
-
-	/*Initialize Element matrix and vectors*/
-	ElementVector* pe = element->NewElementVector(FSvelocityEnum);
-	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinatesBase(&xyz_list_base);
-	Input*  alpha2_input=element->GetInput(FrictionCoefficientEnum); _assert_(alpha2_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=element->NewGaussBase(3);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		alpha2_input->GetInputValue(&alpha2, gauss);
-		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-		element->NodalFunctionsVelocity(vbasis,gauss);
-		element->NormalBase(&bed_normal[0],xyz_list_base);
-
-		for(int i=0;i<vnumnodes;i++){
-			pe->values[i*dim+0] += - alpha2*gauss->weight*Jdet*vbasis[i]*bed_normal[1];
-			pe->values[i*dim+1] += alpha2*gauss->weight*Jdet*vbasis[i]*bed_normal[0];
-			if(dim==3){
-				pe->values[i*dim+2]+= alpha2*gauss->weight*Jdet*vbasis[i];
-			}
-		}
-
-	}
-
-	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<IssmDouble>(xyz_list_base);
-	xDelete<IssmDouble>(vbasis);
-	return pe;
-}/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorFSStress(Element* element){/*{{{*/
-
-	if(!element->IsOnBase()) return NULL;
-
-	/*Intermediaries*/
-	int         dim;
-	IssmDouble  sigmann,sigmant,Jdet,bedslope,beta;
-	IssmDouble *xyz_list_base = NULL;
-	Gauss*      gauss         = NULL;
-
-	/*Get problem dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int vnumnodes = element->NumberofNodesVelocity();
-
-	/*Initialize Element matrix and vectors*/
-	ElementVector* pe = element->NewElementVector(FSvelocityEnum);
-	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinatesBase(&xyz_list_base);
-	Input*  sigmann_input=element->GetInput(VzEnum); _assert_(sigmann_input);
-	Input*  sigmant_input=element->GetInput(TemperatureEnum); _assert_(sigmant_input);
-	Input*  bedslope_input=element->GetInput(BedSlopeXEnum);     _assert_(bedslope_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=element->NewGaussBase(3);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		sigmann_input->GetInputValue(&sigmann, gauss);
-		sigmant_input->GetInputValue(&sigmant, gauss);
-		bedslope_input->GetInputValue(&bedslope, gauss);
-		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-		element->NodalFunctionsVelocity(vbasis,gauss);
-
-		beta=sqrt(1+bedslope*bedslope);
-		for(int i=0;i<vnumnodes;i++){
-			pe->values[i*dim+0] += - (1./beta)*(-bedslope*sigmann + sigmant)*gauss->weight*Jdet*vbasis[i];
-			pe->values[i*dim+1] += - (1./beta)*(sigmann + bedslope*sigmant)*gauss->weight*Jdet*vbasis[i];
-			if(dim==3){
-				//pe->values[i*dim+2]+= alpha2*gauss->weight*Jdet*vbasis[i];
-				_error_("3d not supported yet");
-			}
-		}
-
-	}
-
-	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<IssmDouble>(xyz_list_base);
-	xDelete<IssmDouble>(vbasis);
 	return pe;
 }/*}}}*/
@@ -3668,10 +3694,10 @@
 		delete pe4;
 	}
-	else if(fe_FS==LATaylorHoodEnum){
+	else if(fe_FS==LATaylorHoodEnum || fe_FS==LACrouzeixRaviartEnum){
 		ElementVector* pe1=CreatePVectorFSViscous(element);
 		ElementVector* pe2=CreatePVectorFSShelf(element);
 		ElementVector* pe3=CreatePVectorFSFront(element);
 		ElementVector* petemp =new ElementVector(pe1,pe2,pe3);
-		ElementVector* pe4=CreatePVectorFSViscousLATH(element);
+		ElementVector* pe4=CreatePVectorFSViscousLA(element);
 		pe = new ElementVector(petemp,pe4);
 		delete pe1;
@@ -3764,4 +3790,249 @@
 }/*}}}*/
 #endif
+ElementVector* StressbalanceAnalysis::CreatePVectorFSFront(Element* element){/*{{{*/
+
+	/*If no front, return NULL*/
+	if(!element->IsIcefront()) return NULL;
+
+	/*Intermediaries*/
+	int         i,dim;
+	IssmDouble  Jdet,pressure,surface,z;
+	IssmDouble	normal[3];
+	IssmDouble *xyz_list       = NULL;
+	IssmDouble *xyz_list_front = NULL;
+	Gauss      *gauss          = NULL;
+
+	/*Make sure current element is floating*/
+	if(!element->IsFloating()) return NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes   = element->NumberofNodesVelocity();
+	int pnumnodes   = element->NumberofNodesPressure();
+	int numvertices = element->GetNumberOfVertices();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize vectors*/
+	ElementVector* pe     = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetIcefrontCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
+	element->NormalSection(&normal[0],xyz_list_front);
+	Input* surface_input  = element->GetInput(SurfaceEnum); _assert_(surface_input);
+	IssmDouble  rho_water = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  gravity   = element->GetMaterialParameter(ConstantsGEnum);
+
+	/*Initialize gauss points*/
+	IssmDouble zmax=xyz_list[0*3+(dim-1)]; for(int i=1;i<numvertices;i++) if(xyz_list[i*3+(dim-1)]>zmax) zmax=xyz_list[i*3+(dim-1)];
+	IssmDouble zmin=xyz_list[0*3+(dim-1)]; for(int i=1;i<numvertices;i++) if(xyz_list[i*3+(dim-1)]<zmin) zmin=xyz_list[i*3+(dim-1)];
+	if(zmax>0. && zmin<0.) gauss=element->NewGauss(xyz_list,xyz_list_front,3,30);//refined in vertical because of the sea level discontinuity
+	else                   gauss=element->NewGauss(xyz_list,xyz_list_front,3,3);
+
+	/* Start  looping on the number of gaussian points: */
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantSurface(&Jdet,xyz_list_front,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+		surface_input->GetInputValue(&surface,gauss);
+		if(dim==3) z=element->GetZcoord(xyz_list,gauss);
+		else       z=element->GetYcoord(xyz_list,gauss);
+		pressure = rho_water*gravity*min(0.,z);//0 if the gaussian point is above water level
+
+		for (int i=0;i<vnumnodes;i++){
+			pe->values[dim*i+0]+= pressure*Jdet*gauss->weight*normal[0]*vbasis[i];
+			pe->values[dim*i+1]+= pressure*Jdet*gauss->weight*normal[1]*vbasis[i];
+			if(dim==3) pe->values[dim*i+2]+= pressure*Jdet*gauss->weight*normal[2]*vbasis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_front);
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSShelf(Element* element){/*{{{*/
+
+	int         i,dim;
+	IssmDouble  Jdet,water_pressure,bed;
+	IssmDouble	normal[3];
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize vectors*/
+	ElementVector* pe     = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesBase(&xyz_list_base);
+	Input*      base_input=element->GetInput(BaseEnum); _assert_(base_input);
+	IssmDouble  rho_water=element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  gravity  =element->GetMaterialParameter(ConstantsGEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctionsVelocity(vbasis,gauss);
+
+		element->NormalBase(&normal[0],xyz_list_base);
+		_assert_(normal[dim-1]<0.);
+		base_input->GetInputValue(&bed, gauss);
+		water_pressure=gravity*rho_water*bed;
+
+		for(i=0;i<vnumnodes;i++){
+			pe->values[i*dim+0] += water_pressure*gauss->weight*Jdet*vbasis[i]*normal[0];
+			pe->values[i*dim+1] += water_pressure*gauss->weight*Jdet*vbasis[i]*normal[1];
+			if(dim==3){
+				pe->values[i*dim+2]+=water_pressure*gauss->weight*Jdet*vbasis[i]*normal[2];
+			}
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,cs_list);
+
+	/* shelf dampening*/
+	int shelf_dampening;
+	element->FindParam(&shelf_dampening,StressbalanceShelfDampeningEnum);
+	if(shelf_dampening) {
+		Input*      mb_input=element->GetInput(BasalforcingsFloatingiceMeltingRateEnum); _assert_(mb_input);
+		IssmDouble dt,mb,normal_b;
+		element->FindParam(&dt,TimesteppingTimeStepEnum);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+			element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+			element->NodalFunctionsVelocity(vbasis,gauss);
+			element->NormalBase(&normal[0],xyz_list_base);
+			if (dim==2) normal_b=normal[1];
+			else if (dim==3) normal_b=sqrt(normal[0]*normal[0]+normal[1]*normal[1]);
+			mb_input->GetInputValue(&mb, gauss);
+			for(i=0;i<vnumnodes;i++){
+				pe->values[i*dim+1] += dt*rho_water*gravity*mb*gauss->weight*Jdet*vbasis[i]*normal_b;
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
+	xDelete<IssmDouble>(xyz_list_base);
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorFSViscousLA(Element* element){/*{{{*/
+
+	int         i,dim;
+	IssmDouble  Jdet,pressure;
+	IssmDouble  bed_normal[3];
+	IssmDouble *xyz_list      = NULL;
+	IssmDouble *xyz_list_base = NULL;
+	Gauss*      gauss         = NULL;
+
+	/*Get problem dimension*/
+	element->FindParam(&dim,DomainDimensionEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(numnodes);
+	if(dim==2) for(i=0;i<numnodes;i++) cs_list[i] = XYEnum;
+	else       for(i=0;i<numnodes;i++) cs_list[i] = XYZEnum;
+
+	/*Initialize vectors*/
+	ElementVector* pe      = element->NewElementVector(FSvelocityEnum);
+	IssmDouble*    dbasis  = xNew<IssmDouble>(3*numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/*Get pressure and sigmann*/
+	Input* pressure_input=element->GetInput(PressureEnum); _assert_(pressure_input);
+	Input* sigmann_input =element->GetInput(SigmaNNEnum);  _assert_(sigmann_input);
+
+	gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		
+		pressure_input->GetInputValue(&pressure, gauss);
+		element->NodalFunctionsDerivativesVelocity(dbasis,xyz_list,gauss);
+
+		for(i=0;i<numnodes;i++){
+			pe->values[i*dim+0] += pressure*gauss->weight*Jdet*dbasis[0*numnodes+i];
+			pe->values[i*dim+1] += pressure*gauss->weight*Jdet*dbasis[1*numnodes+i];
+			if(dim==3) pe->values[i*dim+2]+= pressure*gauss->weight*Jdet*dbasis[2*numnodes+i];
+		}
+	}
+
+	if(element->IsOnBase() && 0){ 
+		IssmDouble   sigmann;
+		IssmDouble*  vbasis = xNew<IssmDouble>(numnodes);
+
+		element->GetVerticesCoordinatesBase(&xyz_list_base);
+		element->NormalBase(&bed_normal[0],xyz_list_base);
+
+		delete gauss;
+		gauss=element->NewGaussBase(5);
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
+			gauss->GaussPoint(ig);
+
+			element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+			element->NodalFunctionsVelocity(vbasis,gauss);
+			sigmann_input->GetInputValue(&sigmann, gauss);
+
+			for(i=0;i<numnodes;i++){
+				pe->values[i*dim+0] += + sigmann*bed_normal[0]*gauss->weight*Jdet*vbasis[i];
+				pe->values[i*dim+1] += + sigmann*bed_normal[1]*gauss->weight*Jdet*vbasis[i];
+				if(dim==3) pe->values[i*dim+2] += + sigmann*bed_normal[2]*gauss->weight*Jdet*vbasis[i];
+			}
+		}
+		xDelete<IssmDouble>(xyz_list_base);
+		xDelete<IssmDouble>(vbasis);
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(dbasis);
+	return pe;
+}/*}}}*/
 ElementVector* StressbalanceAnalysis::CreatePVectorFSViscousXTH(Element* element){/*{{{*/
 
@@ -3936,251 +4207,5 @@
 	return pe;
 }/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorFSViscousLATH(Element* element){/*{{{*/
-
-	int         i,dim;
-	IssmDouble  Jdet,r,pressure;
-	IssmDouble  bed_normal[3];
-	IssmDouble *xyz_list      = NULL;
-	IssmDouble *xyz_list_base = NULL;
-	Gauss*      gauss         = NULL;
-
-	/*Get problem dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Prepare coordinate system list*/
-	int* cs_list = xNew<int>(numnodes);
-	if(dim==2) for(i=0;i<numnodes;i++) cs_list[i] = XYEnum;
-	else       for(i=0;i<numnodes;i++) cs_list[i] = XYZEnum;
-
-	/*Initialize vectors*/
-	ElementVector* pe      = element->NewElementVector(FSvelocityEnum);
-	IssmDouble*    dbasis  = xNew<IssmDouble>(3*numnodes);
-
-	/*Retrieve all inputs and parameters*/
-	element->FindParam(&r,AugmentedLagrangianREnum);
-	element->GetVerticesCoordinates(&xyz_list);
-
-	/*Get pressure and sigmann*/
-	Input* pressure_input=element->GetInput(PressureEnum); _assert_(pressure_input);
-	Input* sigmann_input =element->GetInput(SigmaNNEnum);  _assert_(sigmann_input);
-
-	gauss=element->NewGauss(5);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		
-		pressure_input->GetInputValue(&pressure, gauss);
-		element->NodalFunctionsDerivativesVelocity(dbasis,xyz_list,gauss);
-
-		for(i=0;i<numnodes;i++){
-			pe->values[i*dim+0] += pressure*gauss->weight*Jdet*dbasis[0*numnodes+i];
-			pe->values[i*dim+1] += pressure*gauss->weight*Jdet*dbasis[1*numnodes+i];
-			if(dim==3) pe->values[i*dim+2]+= pressure*gauss->weight*Jdet*dbasis[2*numnodes+i];
-		}
-	}
-
-	if(element->IsOnBase()){ 
-		IssmDouble   sigmann;
-		IssmDouble*  vbasis = xNew<IssmDouble>(numnodes);
-
-		element->GetVerticesCoordinatesBase(&xyz_list_base);
-		element->NormalBase(&bed_normal[0],xyz_list_base);
-
-		delete gauss;
-		gauss=element->NewGaussBase(5);
-		for(int ig=gauss->begin();ig<gauss->end();ig++){
-			gauss->GaussPoint(ig);
-
-			element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-			element->NodalFunctionsVelocity(vbasis,gauss);
-			sigmann_input->GetInputValue(&sigmann, gauss);
-
-			for(i=0;i<numnodes;i++){
-				pe->values[i*dim+0] += + sigmann*bed_normal[0]*gauss->weight*Jdet*vbasis[i];
-				pe->values[i*dim+1] += + sigmann*bed_normal[1]*gauss->weight*Jdet*vbasis[i];
-				if(dim==3) pe->values[i*dim+2] += + sigmann*bed_normal[2]*gauss->weight*Jdet*vbasis[i];
-			}
-		}
-		xDelete<IssmDouble>(xyz_list_base);
-		xDelete<IssmDouble>(vbasis);
-	}
-
-	/*Transform coordinate system*/
-	//element->TransformLoadVectorCoord(pe,cs_list); Do not transform augmentation
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<int>(cs_list);
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(dbasis);
-	return pe;
-}/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorFSShelf(Element* element){/*{{{*/
-
-	int         i,dim;
-	IssmDouble  Jdet,water_pressure,bed;
-	IssmDouble	normal[3];
-	IssmDouble *xyz_list_base = NULL;
-
-	/*Get basal element*/
-	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
-
-	/*Get problem dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int vnumnodes = element->NumberofNodesVelocity();
-	int pnumnodes = element->NumberofNodesPressure();
-
-	/*Prepare coordinate system list*/
-	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
-	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
-	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
-	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
-
-	/*Initialize vectors*/
-	ElementVector* pe     = element->NewElementVector(FSvelocityEnum);
-	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinatesBase(&xyz_list_base);
-	Input*      base_input=element->GetInput(BaseEnum); _assert_(base_input);
-	IssmDouble  rho_water=element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
-	IssmDouble  gravity  =element->GetMaterialParameter(ConstantsGEnum);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGaussBase(5);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-		element->NodalFunctionsVelocity(vbasis,gauss);
-
-		element->NormalBase(&normal[0],xyz_list_base);
-		_assert_(normal[dim-1]<0.);
-		base_input->GetInputValue(&bed, gauss);
-		water_pressure=gravity*rho_water*bed;
-
-		for(i=0;i<vnumnodes;i++){
-			pe->values[i*dim+0] += water_pressure*gauss->weight*Jdet*vbasis[i]*normal[0];
-			pe->values[i*dim+1] += water_pressure*gauss->weight*Jdet*vbasis[i]*normal[1];
-			if(dim==3){
-				pe->values[i*dim+2]+=water_pressure*gauss->weight*Jdet*vbasis[i]*normal[2];
-			}
-		}
-	}
-
-	/*Transform coordinate system*/
-	element->TransformLoadVectorCoord(pe,cs_list);
-
-	/* shelf dampening*/
-	int shelf_dampening;
-	element->FindParam(&shelf_dampening,StressbalanceShelfDampeningEnum);
-	if(shelf_dampening) {
-		Input*      mb_input=element->GetInput(BasalforcingsFloatingiceMeltingRateEnum); _assert_(mb_input);
-		IssmDouble dt,mb,normal_b;
-		element->FindParam(&dt,TimesteppingTimeStepEnum);
-		for(int ig=gauss->begin();ig<gauss->end();ig++){
-			gauss->GaussPoint(ig);
-			element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
-			element->NodalFunctionsVelocity(vbasis,gauss);
-			element->NormalBase(&normal[0],xyz_list_base);
-			if (dim==2) normal_b=normal[1];
-			else if (dim==3) normal_b=sqrt(normal[0]*normal[0]+normal[1]*normal[1]);
-			mb_input->GetInputValue(&mb, gauss);
-			for(i=0;i<vnumnodes;i++){
-				pe->values[i*dim+1] += dt*rho_water*gravity*mb*gauss->weight*Jdet*vbasis[i]*normal_b;
-			}
-		}
-	}
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<int>(cs_list);
-	xDelete<IssmDouble>(vbasis);
-	xDelete<IssmDouble>(xyz_list_base);
-	return pe;
-}/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorFSFront(Element* element){/*{{{*/
-
-	/*If no front, return NULL*/
-	if(!element->IsIcefront()) return NULL;
-
-	/*Intermediaries*/
-	int         i,dim;
-	IssmDouble  Jdet,pressure,surface,z;
-	IssmDouble	normal[3];
-	IssmDouble *xyz_list       = NULL;
-	IssmDouble *xyz_list_front = NULL;
-	Gauss      *gauss          = NULL;
-
-	/*Make sure current element is floating*/
-	if(!element->IsFloating()) return NULL;
-
-	/*Get problem dimension*/
-	element->FindParam(&dim,DomainDimensionEnum);
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int vnumnodes   = element->NumberofNodesVelocity();
-	int pnumnodes   = element->NumberofNodesPressure();
-	int numvertices = element->GetNumberOfVertices();
-
-	/*Prepare coordinate system list*/
-	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
-	if(dim==2) for(i=0;i<vnumnodes;i++) cs_list[i] = XYEnum;
-	else       for(i=0;i<vnumnodes;i++) cs_list[i] = XYZEnum;
-	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
-
-	/*Initialize vectors*/
-	ElementVector* pe     = element->NewElementVector(FSvelocityEnum);
-	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	element->ZeroLevelsetCoordinates(&xyz_list_front,xyz_list,MaskIceLevelsetEnum);
-	element->NormalSection(&normal[0],xyz_list_front);
-	Input* surface_input  = element->GetInput(SurfaceEnum); _assert_(surface_input);
-	IssmDouble  rho_water = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
-	IssmDouble  gravity   = element->GetMaterialParameter(ConstantsGEnum);
-
-	/*Initialize gauss points*/
-	IssmDouble zmax=xyz_list[0*3+(dim-1)]; for(int i=1;i<numvertices;i++) if(xyz_list[i*3+(dim-1)]>zmax) zmax=xyz_list[i*3+(dim-1)];
-	IssmDouble zmin=xyz_list[0*3+(dim-1)]; for(int i=1;i<numvertices;i++) if(xyz_list[i*3+(dim-1)]<zmin) zmin=xyz_list[i*3+(dim-1)];
-	if(zmax>0. && zmin<0.) gauss=element->NewGauss(xyz_list,xyz_list_front,3,30);//refined in vertical because of the sea level discontinuity
-	else                   gauss=element->NewGauss(xyz_list,xyz_list_front,3,3);
-
-	/* Start  looping on the number of gaussian points: */
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminantSurface(&Jdet,xyz_list_front,gauss);
-		element->NodalFunctionsVelocity(vbasis,gauss);
-		surface_input->GetInputValue(&surface,gauss);
-		if(dim==3) z=element->GetZcoord(xyz_list,gauss);
-		else       z=element->GetYcoord(xyz_list,gauss);
-		pressure = rho_water*gravity*min(0.,z);//0 if the gaussian point is above water level
-
-		for (int i=0;i<vnumnodes;i++){
-			pe->values[dim*i+0]+= pressure*Jdet*gauss->weight*normal[0]*vbasis[i];
-			pe->values[dim*i+1]+= pressure*Jdet*gauss->weight*normal[1]*vbasis[i];
-			if(dim==3) pe->values[dim*i+2]+= pressure*Jdet*gauss->weight*normal[2]*vbasis[i];
-		}
-	}
-
-	/*Transform coordinate system*/
-	element->TransformLoadVectorCoord(pe,cs_list);
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<int>(cs_list);
-	xDelete<IssmDouble>(vbasis);
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(xyz_list_front);
-	return pe;
-}/*}}}*/
-void StressbalanceAnalysis::GetBFS(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetBFS(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[Bv1 Bv2 ... Bp1 Bp2 ...] where Bvi is of size 3*NDOF3. 
 	 * For node i, Bvi can be expressed in the actual coordinate system
@@ -4294,5 +4319,65 @@
 	xDelete<IssmDouble>(pbasis);
 }/*}}}*/
-void StressbalanceAnalysis::GetBFSprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetBFSFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/* Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+	 * For node i, Li can be expressed in the actual coordinate system
+	 * by in 3d 
+	 *       Li=[ h 0 0 0 ]
+	 *	 	      [ 0 h 0 0 ]
+	 *	in 2d:
+	 *       Li=[ h 0 0 ]
+	 * where h is the interpolation function for node i.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes = element->NumberofNodesPressure();
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumdof   = pnumnodes;
+	int vnumdof   = vnumnodes*dim;
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vbasis=xNew<IssmDouble>(vnumnodes);
+	element->NodalFunctionsVelocity(vbasis,gauss);
+
+	/*Build B: */
+	if(dim==3){
+		for(int i=0;i<vnumnodes;i++){
+			B[(vnumdof+pnumdof)*0+3*i+0] = vbasis[i];
+			B[(vnumdof+pnumdof)*0+3*i+1] = 0.;
+			B[(vnumdof+pnumdof)*0+3*i+2] = 0.;
+
+			B[(vnumdof+pnumdof)*1+3*i+0] = 0.;
+			B[(vnumdof+pnumdof)*1+3*i+1] = vbasis[i];
+			B[(vnumdof+pnumdof)*1+3*i+2] = 0.;
+
+			B[(vnumdof+pnumdof)*2+3*i+0] = 0.;
+			B[(vnumdof+pnumdof)*2+3*i+1] = 0.;
+			B[(vnumdof+pnumdof)*2+3*i+2] = vbasis[i];
+		}
+		for(int i=0;i<pnumnodes;i++){
+			B[(vnumdof+pnumdof)*0+i+vnumdof+0] = 0.;
+			B[(vnumdof+pnumdof)*1+i+vnumdof+0] = 0.;
+			B[(vnumdof+pnumdof)*2+i+vnumdof+0] = 0.;
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			B[(vnumdof+pnumdof)*0+2*i+0] = vbasis[i];
+			B[(vnumdof+pnumdof)*0+2*i+1] = 0.;
+
+			B[(vnumdof+pnumdof)*1+2*i+0] = 0.;
+			B[(vnumdof+pnumdof)*1+2*i+1] = vbasis[i];
+		}
+
+		for(int i=0;i<pnumnodes;i++){
+			B[(vnumdof+pnumdof)*0+i+vnumdof+0] = 0.;
+			B[(vnumdof+pnumdof)*1+i+vnumdof+0] = 0.;
+		}
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(vbasis);
+}/*}}}*/
+void           StressbalanceAnalysis::GetBFSprime(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6' Bb'] where Bi' is of size 3*NDOF2. 
 	 *	For node i, Bi' can be expressed in the actual coordinate system
@@ -4407,5 +4492,126 @@
 	xDelete<IssmDouble>(pbasis);
 }/*}}}*/
-void StressbalanceAnalysis::GetBFSvel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetBFSprimeUzawa(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6'] where Bi' is of size 3*NDOF2. 
+	 *	For node i, Bi' can be expressed in the actual coordinate system
+	 *	by: 
+	 *			Bvi' = [  dphi/dx   dphi/dy ]
+	 *
+	 *	In 3d
+	 *     	   Bvi=[ dh/dx   dh/dy    dh/dz  ]
+	 *	where phi is the finiteelement function for node i.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
+	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+
+	/*Build B_prime: */
+	if(dim==2){
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[dim*i+1] = vdbasis[1*vnumnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[dim*i+2] = vdbasis[2*vnumnodes+i];
+		}
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+}/*}}}*/
+void           StressbalanceAnalysis::GetBFSprimevel(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6' Bb'] where Bi' is of size 3*NDOF2. 
+	 *	For node i, Bi' can be expressed in the actual coordinate system
+	 *	by: 
+	 *			Bvi' = [  dphi/dx     0     ]
+	 *					 [     0      dphi/dy ]
+	 *					 [  dphi/dy   dphi/dx ]
+	 *
+	 *	In 3d
+	 *     	   Bvi=[ dh/dx     0        0    ]
+	 *					[   0      dh/dy      0    ]
+	 *					[   0        0      dh/dz  ]
+	 *					[ dh/dy    dh/dx      0    ]
+	 *					[ dh/dz      0      dh/dx  ]
+	 *					[   0      dh/dz    dh/dy  ]
+	 *	where phi is the finiteelement function for node i.
+	 *	In 3d:
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int vnumnodes = element->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
+	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+
+	/*Build B_prime: */
+	if(dim==2){
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*0+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*2+dim*i+0] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*2+dim*i+1] = vdbasis[0*vnumnodes+i];
+		}
+	}
+	else{
+		for(int i=0;i<vnumnodes;i++){
+			Bprime[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*0+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*0+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*1+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes)*2+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*2+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*2+dim*i+2] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*3+dim*i+0] = vdbasis[1*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*3+dim*i+1] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*3+dim*i+2] = 0.;
+			Bprime[(dim*vnumnodes)*4+dim*i+0] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*4+dim*i+1] = 0.;
+			Bprime[(dim*vnumnodes)*4+dim*i+2] = vdbasis[0*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*5+dim*i+0] = 0.;
+			Bprime[(dim*vnumnodes)*5+dim*i+1] = vdbasis[2*vnumnodes+i];
+			Bprime[(dim*vnumnodes)*5+dim*i+2] = vdbasis[1*vnumnodes+i];
+		}
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+}/*}}}*/
+void           StressbalanceAnalysis::GetBFSUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[Bp1 Bp2 ...] where Bpi=phi_pi. 
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes;
+	if(dim==2) pnumnodes=3;
+	else pnumnodes=6;
+	//int pnumnodes = element->NumberofNodes(P1Enum);
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* basis =xNew<IssmDouble>(pnumnodes);
+	element->NodalFunctionsP1(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<pnumnodes;i++){
+		B[i] = basis[i];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(basis);
+}/*}}}*/
+void           StressbalanceAnalysis::GetBFSvel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[Bv1 Bv2 ... Bp1 Bp2 ...] where Bvi is of size 3*NDOF3. 
 	 * For node i, Bvi can be expressed in the actual coordinate system
@@ -4471,186 +4677,5 @@
 	xDelete<IssmDouble>(vdbasis);
 }/*}}}*/
-void StressbalanceAnalysis::GetBFSprimevel(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6' Bb'] where Bi' is of size 3*NDOF2. 
-	 *	For node i, Bi' can be expressed in the actual coordinate system
-	 *	by: 
-	 *			Bvi' = [  dphi/dx     0     ]
-	 *					 [     0      dphi/dy ]
-	 *					 [  dphi/dy   dphi/dx ]
-	 *
-	 *	In 3d
-	 *     	   Bvi=[ dh/dx     0        0    ]
-	 *					[   0      dh/dy      0    ]
-	 *					[   0        0      dh/dz  ]
-	 *					[ dh/dy    dh/dx      0    ]
-	 *					[ dh/dz      0      dh/dx  ]
-	 *					[   0      dh/dz    dh/dy  ]
-	 *	where phi is the finiteelement function for node i.
-	 *	In 3d:
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int vnumnodes = element->NumberofNodesVelocity();
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
-	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
-
-	/*Build B_prime: */
-	if(dim==2){
-		for(int i=0;i<vnumnodes;i++){
-			Bprime[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
-			Bprime[(dim*vnumnodes)*0+dim*i+1] = 0.;
-			Bprime[(dim*vnumnodes)*1+dim*i+0] = 0.;
-			Bprime[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
-			Bprime[(dim*vnumnodes)*2+dim*i+0] = vdbasis[1*vnumnodes+i];
-			Bprime[(dim*vnumnodes)*2+dim*i+1] = vdbasis[0*vnumnodes+i];
-		}
-	}
-	else{
-		for(int i=0;i<vnumnodes;i++){
-			Bprime[(dim*vnumnodes)*0+dim*i+0] = vdbasis[0*vnumnodes+i];
-			Bprime[(dim*vnumnodes)*0+dim*i+1] = 0.;
-			Bprime[(dim*vnumnodes)*0+dim*i+2] = 0.;
-			Bprime[(dim*vnumnodes)*1+dim*i+0] = 0.;
-			Bprime[(dim*vnumnodes)*1+dim*i+1] = vdbasis[1*vnumnodes+i];
-			Bprime[(dim*vnumnodes)*1+dim*i+2] = 0.;
-			Bprime[(dim*vnumnodes)*2+dim*i+0] = 0.;
-			Bprime[(dim*vnumnodes)*2+dim*i+1] = 0.;
-			Bprime[(dim*vnumnodes)*2+dim*i+2] = vdbasis[2*vnumnodes+i];
-			Bprime[(dim*vnumnodes)*3+dim*i+0] = vdbasis[1*vnumnodes+i];
-			Bprime[(dim*vnumnodes)*3+dim*i+1] = vdbasis[0*vnumnodes+i];
-			Bprime[(dim*vnumnodes)*3+dim*i+2] = 0.;
-			Bprime[(dim*vnumnodes)*4+dim*i+0] = vdbasis[2*vnumnodes+i];
-			Bprime[(dim*vnumnodes)*4+dim*i+1] = 0.;
-			Bprime[(dim*vnumnodes)*4+dim*i+2] = vdbasis[0*vnumnodes+i];
-			Bprime[(dim*vnumnodes)*5+dim*i+0] = 0.;
-			Bprime[(dim*vnumnodes)*5+dim*i+1] = vdbasis[2*vnumnodes+i];
-			Bprime[(dim*vnumnodes)*5+dim*i+2] = vdbasis[1*vnumnodes+i];
-		}
-	}
-
-	/*Clean up*/
-	xDelete<IssmDouble>(vdbasis);
-}/*}}}*/
-void StressbalanceAnalysis::GetBFSUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B  matrix. B=[Bp1 Bp2 ...] where Bpi=phi_pi. 
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int pnumnodes;
-	if(dim==2) pnumnodes=3;
-	else pnumnodes=6;
-	//int pnumnodes = element->NumberofNodes(P1Enum);
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* basis =xNew<IssmDouble>(pnumnodes);
-	element->NodalFunctionsP1(basis,gauss);
-
-	/*Build B: */
-	for(int i=0;i<pnumnodes;i++){
-		B[i] = basis[i];
-	}
-
-	/*Clean up*/
-	xDelete<IssmDouble>(basis);
-}/*}}}*/
-void StressbalanceAnalysis::GetBFSprimeUzawa(IssmDouble* Bprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*	Compute B'  matrix. B'=[B1' B2' B3' B4' B5' B6'] where Bi' is of size 3*NDOF2. 
-	 *	For node i, Bi' can be expressed in the actual coordinate system
-	 *	by: 
-	 *			Bvi' = [  dphi/dx   dphi/dy ]
-	 *
-	 *	In 3d
-	 *     	   Bvi=[ dh/dx   dh/dy    dh/dz  ]
-	 *	where phi is the finiteelement function for node i.
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int vnumnodes = element->NumberofNodesVelocity();
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* vdbasis=xNew<IssmDouble>(dim*vnumnodes);
-	element->NodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
-
-	/*Build B_prime: */
-	if(dim==2){
-		for(int i=0;i<vnumnodes;i++){
-			Bprime[dim*i+0] = vdbasis[0*vnumnodes+i];
-			Bprime[dim*i+1] = vdbasis[1*vnumnodes+i];
-		}
-	}
-	else{
-		for(int i=0;i<vnumnodes;i++){
-			Bprime[dim*i+0] = vdbasis[0*vnumnodes+i];
-			Bprime[dim*i+1] = vdbasis[1*vnumnodes+i];
-			Bprime[dim*i+2] = vdbasis[2*vnumnodes+i];
-		}
-	}
-
-	/*Clean up*/
-	xDelete<IssmDouble>(vdbasis);
-}/*}}}*/
-void StressbalanceAnalysis::GetBFSFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/* Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
-	 * For node i, Li can be expressed in the actual coordinate system
-	 * by in 3d 
-	 *       Li=[ h 0 0 0 ]
-	 *	 	      [ 0 h 0 0 ]
-	 *	in 2d:
-	 *       Li=[ h 0 0 ]
-	 * where h is the interpolation function for node i.
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int pnumnodes = element->NumberofNodesPressure();
-	int vnumnodes = element->NumberofNodesVelocity();
-	int pnumdof   = pnumnodes;
-	int vnumdof   = vnumnodes*dim;
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* vbasis=xNew<IssmDouble>(vnumnodes);
-	element->NodalFunctionsVelocity(vbasis,gauss);
-
-	/*Build B: */
-	if(dim==3){
-		for(int i=0;i<vnumnodes;i++){
-			B[(vnumdof+pnumdof)*0+3*i+0] = vbasis[i];
-			B[(vnumdof+pnumdof)*0+3*i+1] = 0.;
-			B[(vnumdof+pnumdof)*0+3*i+2] = 0.;
-
-			B[(vnumdof+pnumdof)*1+3*i+0] = 0.;
-			B[(vnumdof+pnumdof)*1+3*i+1] = vbasis[i];
-			B[(vnumdof+pnumdof)*1+3*i+2] = 0.;
-
-			B[(vnumdof+pnumdof)*2+3*i+0] = 0.;
-			B[(vnumdof+pnumdof)*2+3*i+1] = 0.;
-			B[(vnumdof+pnumdof)*2+3*i+2] = vbasis[i];
-		}
-		for(int i=0;i<pnumnodes;i++){
-			B[(vnumdof+pnumdof)*0+i+vnumdof+0] = 0.;
-			B[(vnumdof+pnumdof)*1+i+vnumdof+0] = 0.;
-			B[(vnumdof+pnumdof)*2+i+vnumdof+0] = 0.;
-		}
-	}
-	else{
-		for(int i=0;i<vnumnodes;i++){
-			B[(vnumdof+pnumdof)*0+2*i+0] = vbasis[i];
-			B[(vnumdof+pnumdof)*0+2*i+1] = 0.;
-
-			B[(vnumdof+pnumdof)*1+2*i+0] = 0.;
-			B[(vnumdof+pnumdof)*1+2*i+1] = vbasis[i];
-		}
-
-		for(int i=0;i<pnumnodes;i++){
-			B[(vnumdof+pnumdof)*0+i+vnumdof+0] = 0.;
-			B[(vnumdof+pnumdof)*1+i+vnumdof+0] = 0.;
-		}
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(vbasis);
-}/*}}}*/
-void StressbalanceAnalysis::GetCFS(IssmDouble* C,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetCFS(IssmDouble* C,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute C  matrix. C=[Cp1 Cp2 ...] where:
 	 *     Cpi=[phi phi]. 
@@ -4673,5 +4698,5 @@
 	xDelete<IssmDouble>(basis);
 }/*}}}*/
-void StressbalanceAnalysis::GetCFSprime(IssmDouble* Cprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetCFSprime(IssmDouble* Cprime,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*	Compute C'  matrix. C'=[C1' C2' ...] 
 	 *			Ci' = [  phi  0  ]
@@ -4721,5 +4746,5 @@
 	xDelete<IssmDouble>(vbasis);
 }/*}}}*/
-void StressbalanceAnalysis::GetSolutionFromInputsFS(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           StressbalanceAnalysis::GetSolutionFromInputsFS(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 
 	int*         vdoflist=NULL;
@@ -4784,5 +4809,5 @@
 	xDelete<IssmDouble>(vvalues);
 }/*}}}*/
-void StressbalanceAnalysis::InitializeXTH(Elements* elements,Parameters* parameters){/*{{{*/
+void           StressbalanceAnalysis::InitializeXTH(Elements* elements,Parameters* parameters){/*{{{*/
 
 	/*Intermediaries*/
@@ -4796,5 +4821,5 @@
 
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 
 		/*Get inputs and parameters*/
@@ -4863,5 +4888,5 @@
 
 }/*}}}*/
-void StressbalanceAnalysis::InputUpdateFromSolutionFS(IssmDouble* solution,Element* element){/*{{{*/
+void           StressbalanceAnalysis::InputUpdateFromSolutionFS(IssmDouble* solution,Element* element){/*{{{*/
 
 	bool         results_on_nodes;
@@ -4953,5 +4978,5 @@
 	xDelete<int>(cs_list);
 }/*}}}*/
-void StressbalanceAnalysis::InputUpdateFromSolutionFSXTH_d(Elements* elements,Parameters* parameters){/*{{{*/
+void           StressbalanceAnalysis::InputUpdateFromSolutionFSXTH_d(Elements* elements,Parameters* parameters){/*{{{*/
 
 	/*Intermediaries*/
@@ -4970,5 +4995,5 @@
 
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 
 		/*Get inputs and parameters*/
@@ -5166,5 +5191,5 @@
 	}
 }/*}}}*/
-void StressbalanceAnalysis::InputUpdateFromSolutionFSXTH_tau(Elements* elements,Parameters* parameters){/*{{{*/
+void           StressbalanceAnalysis::InputUpdateFromSolutionFSXTH_tau(Elements* elements,Parameters* parameters){/*{{{*/
 
 	/*Intermediaries*/
@@ -5183,5 +5208,5 @@
 
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 
 		/*Get inputs and parameters*/
@@ -5302,163 +5327,4 @@
 
 /*Coupling (Tiling)*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA3d(Element* element){/*{{{*/
-
-	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixSSA3dViscous(element);
-	ElementMatrix* Ke2=CreateKMatrixSSA3dFriction(element);
-	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
-
-	/*clean-up and return*/
-	delete Ke1;
-	delete Ke2;
-	return Ke;
-}/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA3dFriction(Element* element){/*{{{*/
-
-	/*Initialize Element matrix and return if necessary*/
-	if(element->IsFloating() || !element->IsOnBase()) return NULL;
-
-	/*Build a tria element using the 3 nodes of the base of the penta. Then use 
-	 * the tria functionality to build a friction stiffness matrix on these 3
-	 * nodes: */
-	Element* basalelement = element->SpawnBasalElement();
-	ElementMatrix* Ke=CreateKMatrixSSAFriction(basalelement);
-	basalelement->DeleteMaterials(); delete basalelement;
-
-	/*clean-up and return*/
-	return Ke;
-}/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA3dViscous(Element* element){/*{{{*/
-
-	/*Constants*/
-	const int    numdof2d=2*3;
-
-	/*Intermediaries */
-	int         i,j,approximation;
-	int         dim=3;
-	IssmDouble  Jdet,viscosity,oldviscosity,newviscosity,viscosity_overshoot;
-	IssmDouble  epsilon[5],oldepsilon[5];       /* epsilon=[exx,eyy,exy,exz,eyz];*/
-	IssmDouble  epsilons[6];                    //6 for FS
-	IssmDouble  B[3][numdof2d];
-	IssmDouble  Bprime[3][numdof2d];
-	IssmDouble  D[3][3]= {0.0};                 // material matrix, simple scalar matrix.
-	IssmDouble  D_scalar;
-	IssmDouble  Ke_gg[numdof2d][numdof2d]={0.0};
-	IssmDouble  *xyz_list  = NULL;
-
-	/*Find penta on bed as this is a SSA elements: */
-	Element* pentabase=element->GetBasalElement();
-	Element* basaltria=pentabase->SpawnBasalElement();
-
-	/*Initialize Element matrix*/
-	ElementMatrix* Ke=basaltria->NewElementMatrix(SSAApproximationEnum);
-	element->GetInputValue(&approximation,ApproximationEnum);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
-	Input* vx_input   =element->GetInput(VxEnum);       _assert_(vx_input);
-	Input* vy_input   =element->GetInput(VyEnum);       _assert_(vy_input);
-	Input* vxold_input=element->GetInput(VxPicardEnum); _assert_(vxold_input);
-	Input* vyold_input=element->GetInput(VyPicardEnum); _assert_(vyold_input);
-	Input* vz_input   =element->GetInput(VzEnum);       _assert_(vz_input);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(5);
-	Gauss* gauss_tria=new GaussTria();
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-		gauss->SynchronizeGaussBase(gauss_tria);
-
-		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
-		this->GetBSSA(&B[0][0],basaltria,2,xyz_list, gauss_tria);
-		this->GetBSSAprime(&Bprime[0][0],basaltria,2,xyz_list, gauss_tria);
-
-		if(approximation==SSAHOApproximationEnum){
-			element->ViscosityHO(&viscosity,dim,xyz_list,gauss,vx_input,vy_input);
-			element->ViscosityHO(&oldviscosity,dim,xyz_list,gauss,vxold_input,vyold_input);
-			newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
-		}
-		else if (approximation==SSAFSApproximationEnum){
-			element->ViscosityFS(&newviscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
-		}
-		else _error_("approximation " << approximation << " (" << EnumToStringx(approximation) << ") not supported yet");
-
-		D_scalar=2*newviscosity*gauss->weight*Jdet;
-		for (i=0;i<3;i++) D[i][i]=D_scalar;
-
-		TripleMultiply( &B[0][0],3,numdof2d,1,
-					&D[0][0],3,3,0,
-					&Bprime[0][0],3,numdof2d,0,
-					&Ke_gg[0][0],1);
-
-	}
-	for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof2d+j]+=Ke_gg[i][j];
-
-	/*Transform Coordinate System*/
-	basaltria->TransformStiffnessMatrixCoord(Ke,XYEnum);
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(xyz_list);
-	delete basaltria->material;
-	delete basaltria;
-	delete gauss_tria;
-	delete gauss;
-	return Ke;
-
-}/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixHOFS(Element* element){/*{{{*/
-
-	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixFS(element);
-	int indices[3]={18,19,20};
-	Ke1->StaticCondensation(3,&indices[0]);
-	int init = element->FiniteElement();
-	element->SetTemporaryElementType(P1Enum); // P1 needed for HO
-	ElementMatrix* Ke2=CreateKMatrixHO(element);
-	element->SetTemporaryElementType(init); // P1 needed for HO
-	ElementMatrix* Ke3=CreateKMatrixCouplingHOFS(element);
-	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
-
-	/*clean-up and return*/
-	delete Ke1;
-	delete Ke2;
-	delete Ke3;
-	return Ke;
-}/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSAHO(Element* element){/*{{{*/
-
-	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixSSA3d(element);
-	ElementMatrix* Ke2=CreateKMatrixHO(element);
-	ElementMatrix* Ke3=CreateKMatrixCouplingSSAHO(element);
-	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
-
-	/*clean-up and return*/
-	delete Ke1;
-	delete Ke2;
-	delete Ke3;
-	return Ke;
-}/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSAFS(Element* element){/*{{{*/
-
-	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixFS(element);
-	int indices[3]={18,19,20};
-	Ke1->StaticCondensation(3,&indices[0]);
-	int init = element->FiniteElement();
-	element->SetTemporaryElementType(P1Enum); 
-	ElementMatrix* Ke2=CreateKMatrixSSA3d(element);
-	element->SetTemporaryElementType(init); 
-	ElementMatrix* Ke3=CreateKMatrixCouplingSSAFS(element);
-	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
-
-	/*clean-up and return*/
-	delete Ke1;
-	delete Ke2;
-	delete Ke3;
-	return Ke;
-}/*}}}*/
 ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingHOFS(Element* element){/*{{{*/
 
@@ -5526,182 +5392,4 @@
 	delete Ke2;
 	return Ke;
-}/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAHO(Element* element){/*{{{*/
-
-	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixCouplingSSAHOViscous(element);
-	ElementMatrix* Ke2=CreateKMatrixCouplingSSAHOFriction(element);
-	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
-
-	/*clean-up and return*/
-	delete Ke1;
-	delete Ke2;
-	return Ke;
-}/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAHOFriction(Element* element){/*{{{*/
-
-	if(element->IsFloating() || !element->IsOnBase()) return NULL;
-
-	/*Constants*/
-	int numnodes    = element->GetNumberOfNodes();
-	int numdof      = 2*numnodes;
-	int numdoftotal = 4*numnodes;
-
-	/*Intermediaries */
-	int         i,j;
-	IssmDouble  Jdet2d,alpha2;
-	IssmDouble *xyz_list_tria = NULL;
-	IssmDouble* L             = xNewZeroInit<IssmDouble>(2*numdof);
-	IssmDouble  DL[2][2]      = {{ 0,0 },{0,0}}; //for basal drag
-	IssmDouble  DL_scalar;
-	IssmDouble* Ke_gg         = xNewZeroInit<IssmDouble>(numdof*numdof);
-	Node      **node_list     = xNew<Node*>(2*numnodes);
-	int*        cs_list       = xNew<int>(2*numnodes);
-
-	/*Initialize Element matrix and return if necessary*/
-	ElementMatrix* Ke1=element->NewElementMatrix(SSAApproximationEnum);
-	ElementMatrix* Ke2=element->NewElementMatrix(HOApproximationEnum);
-	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
-	delete Ke1; delete Ke2;
-
-	/*Prepare node list*/
-	for(i=0;i<numnodes;i++){
-		node_list[i+0*numnodes] = element->GetNode(i);
-		node_list[i+1*numnodes] = element->GetNode(i);
-		cs_list[i+0*numnodes] = XYEnum;
-		cs_list[i+1*numnodes] = XYEnum;
-	}
-
-	/*retrieve inputs :*/
-	element->GetVerticesCoordinatesBase(&xyz_list_tria);
-
-	/*build friction object, used later on: */
-	Friction* friction=new Friction(element,2);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGaussBase(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		/*Friction: */
-		friction->GetAlpha2(&alpha2,gauss);
-		element->JacobianDeterminantBase(&Jdet2d, xyz_list_tria,gauss);
-		this->GetBHOFriction(L,element,3,xyz_list_tria,gauss);
-
-		DL_scalar=alpha2*gauss->weight*Jdet2d;
-		for (i=0;i<2;i++) DL[i][i]=DL_scalar; 
-
-		/*  Do the triple producte tL*D*L: */
-		TripleMultiply( L,2,numdof,1,
-					&DL[0][0],2,2,0,
-					L,2,numdof,0,
-					Ke_gg,1);
-	}
-
-	for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdoftotal+(numdof+j)]+=Ke_gg[i*numdof+j];
-	for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[(i+numdof)*numdoftotal+j]+=Ke_gg[i*numdof+j];
-
-	/*Transform Coordinate System*/
-	element->TransformStiffnessMatrixCoord(Ke,node_list,2*numnodes,cs_list);
-
-	/*Clean up and return*/
-	delete gauss;
-	delete friction;
-	xDelete<int>(cs_list);
-	xDelete<Node*>(node_list);
-	xDelete<IssmDouble>(xyz_list_tria);
-	xDelete<IssmDouble>(Ke_gg);
-	xDelete<IssmDouble>(L);
-	return Ke;
-}/*}}}*/
-ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAHOViscous(Element* element){/*{{{*/
-
-	/*Constants*/
-	int numnodes    = element->GetNumberOfNodes();
-	int numdofm     = 1 *numnodes; //*2/2
-	int numdofp     = 2 *numnodes;
-	int numdoftotal = 2 *2 *numnodes;//2 dof per nodes and 2 sets of nodes for HO and SSA
-
-	/*Intermediaries */
-	int         i,j;
-	IssmDouble  Jdet,viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
-	IssmDouble  *xyz_list      = NULL;
-	IssmDouble* B              = xNew<IssmDouble>(3*numdofp);
-	IssmDouble* Bprime         = xNew<IssmDouble>(3*numdofm);
-	IssmDouble  D[3][3]={0.0}; // material matrix, simple scalar matrix.
-	IssmDouble  D_scalar;
-	IssmDouble* Ke_gg          = xNewZeroInit<IssmDouble>(numdofp*numdofm);
-	Node       **node_list     = xNew<Node*>(2*numnodes);
-	int*         cs_list= xNew<int>(2*numnodes);
-
-	/*Find penta on bed as HO must be coupled to the dofs on the bed: */
-	Element* pentabase=element->GetBasalElement();
-	Element* basaltria=pentabase->SpawnBasalElement();
-
-	/*prepare node list*/
-	for(i=0;i<numnodes;i++){
-		node_list[i+0*numnodes] = pentabase->GetNode(i);
-		node_list[i+1*numnodes] = element  ->GetNode(i);
-		cs_list[i+0*numnodes] = XYEnum;
-		cs_list[i+1*numnodes] = XYEnum;
-	}
-
-	/*Initialize Element matrix*/
-	ElementMatrix* Ke1= pentabase->NewElementMatrix(SSAApproximationEnum);
-	ElementMatrix* Ke2= element  ->NewElementMatrix(HOApproximationEnum);
-	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
-	delete Ke1; delete Ke2;
-
-	/* Get node coordinates and dof list: */
-	element->GetVerticesCoordinates(&xyz_list);
-	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
-	Input* vx_input   =element->GetInput(VxEnum);       _assert_(vx_input);
-	Input* vy_input   =element->GetInput(VyEnum);       _assert_(vy_input);
-	Input* vxold_input=element->GetInput(VxPicardEnum); _assert_(vxold_input);
-	Input* vyold_input=element->GetInput(VyPicardEnum); _assert_(vyold_input);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(5);
-	Gauss* gauss_tria=new GaussTria();
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-		gauss->SynchronizeGaussBase(gauss_tria);
-
-		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
-		this->GetBSSAHO(B, element,xyz_list, gauss);
-		this->GetBSSAprime(Bprime,basaltria,2,xyz_list, gauss_tria); 
-		element->ViscosityHO(&viscosity,3,xyz_list,gauss,vx_input,vy_input);
-		element->ViscosityHO(&oldviscosity,3,xyz_list,gauss,vxold_input,vyold_input);
-
-		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
-		D_scalar=2*newviscosity*gauss->weight*Jdet;
-		for (i=0;i<3;i++) D[i][i]=D_scalar;
-
-		TripleMultiply( B,3,numdofp,1,
-					&D[0][0],3,3,0,
-					Bprime,3,numdofm,0,
-					Ke_gg,1);
-	} 
-	for(i=0;i<numdofp;i++) for(j=0;j<numdofm;j++) Ke->values[(i+2*numdofm)*numdoftotal+j]+=Ke_gg[i*numdofm+j];
-	for(i=0;i<numdofm;i++) for(j=0;j<numdofp;j++) Ke->values[i*numdoftotal+(j+2*numdofm)]+=Ke_gg[j*numdofm+i];
-
-	/*Transform Coordinate System*/
-	element->TransformStiffnessMatrixCoord(Ke,node_list,2*numnodes,cs_list);
-
-	/*Clean-up and return*/
-	basaltria->DeleteMaterials(); delete basaltria;
-	
-	delete gauss;
-	delete gauss_tria;
-	xDelete<IssmDouble>(B);
-	xDelete<IssmDouble>(Bprime);
-	xDelete<IssmDouble>(Ke_gg);
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<Node*>(node_list);
-	xDelete<int>(cs_list);
-	return Ke;
-
 }/*}}}*/
 ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAFS(Element* element){/*{{{*/
@@ -5945,9 +5633,346 @@
 
 }/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorSSAHO(Element* element){/*{{{*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAHO(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixCouplingSSAHOViscous(element);
+	ElementMatrix* Ke2=CreateKMatrixCouplingSSAHOFriction(element);
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAHOFriction(Element* element){/*{{{*/
+
+	if(element->IsFloating() || !element->IsOnBase()) return NULL;
+
+	/*Constants*/
+	int numnodes    = element->GetNumberOfNodes();
+	int numdof      = 2*numnodes;
+	int numdoftotal = 4*numnodes;
+
+	/*Intermediaries */
+	int         i,j;
+	IssmDouble  Jdet2d,alpha2;
+	IssmDouble *xyz_list_tria = NULL;
+	IssmDouble* L             = xNewZeroInit<IssmDouble>(2*numdof);
+	IssmDouble  DL[2][2]      = {{ 0,0 },{0,0}}; //for basal drag
+	IssmDouble  DL_scalar;
+	IssmDouble* Ke_gg         = xNewZeroInit<IssmDouble>(numdof*numdof);
+	Node      **node_list     = xNew<Node*>(2*numnodes);
+	int*        cs_list       = xNew<int>(2*numnodes);
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke1=element->NewElementMatrix(SSAApproximationEnum);
+	ElementMatrix* Ke2=element->NewElementMatrix(HOApproximationEnum);
+	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/*Prepare node list*/
+	for(i=0;i<numnodes;i++){
+		node_list[i+0*numnodes] = element->GetNode(i);
+		node_list[i+1*numnodes] = element->GetNode(i);
+		cs_list[i+0*numnodes] = XYEnum;
+		cs_list[i+1*numnodes] = XYEnum;
+	}
+
+	/*retrieve inputs :*/
+	element->GetVerticesCoordinatesBase(&xyz_list_tria);
+
+	/*build friction object, used later on: */
+	Friction* friction=new Friction(element,2);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/*Friction: */
+		friction->GetAlpha2(&alpha2,gauss);
+		element->JacobianDeterminantBase(&Jdet2d, xyz_list_tria,gauss);
+		this->GetBHOFriction(L,element,3,xyz_list_tria,gauss);
+
+		DL_scalar=alpha2*gauss->weight*Jdet2d;
+		for (i=0;i<2;i++) DL[i][i]=DL_scalar; 
+
+		/*  Do the triple producte tL*D*L: */
+		TripleMultiply( L,2,numdof,1,
+					&DL[0][0],2,2,0,
+					L,2,numdof,0,
+					Ke_gg,1);
+	}
+
+	for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdoftotal+(numdof+j)]+=Ke_gg[i*numdof+j];
+	for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[(i+numdof)*numdoftotal+j]+=Ke_gg[i*numdof+j];
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,node_list,2*numnodes,cs_list);
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+	xDelete<int>(cs_list);
+	xDelete<Node*>(node_list);
+	xDelete<IssmDouble>(xyz_list_tria);
+	xDelete<IssmDouble>(Ke_gg);
+	xDelete<IssmDouble>(L);
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixCouplingSSAHOViscous(Element* element){/*{{{*/
+
+	/*Constants*/
+	int numnodes    = element->GetNumberOfNodes();
+	int numdofm     = 1 *numnodes; //*2/2
+	int numdofp     = 2 *numnodes;
+	int numdoftotal = 2 *2 *numnodes;//2 dof per nodes and 2 sets of nodes for HO and SSA
+
+	/*Intermediaries */
+	int         i,j;
+	IssmDouble  Jdet,viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
+	IssmDouble  *xyz_list      = NULL;
+	IssmDouble* B              = xNew<IssmDouble>(3*numdofp);
+	IssmDouble* Bprime         = xNew<IssmDouble>(3*numdofm);
+	IssmDouble  D[3][3]={0.0}; // material matrix, simple scalar matrix.
+	IssmDouble  D_scalar;
+	IssmDouble* Ke_gg          = xNewZeroInit<IssmDouble>(numdofp*numdofm);
+	Node       **node_list     = xNew<Node*>(2*numnodes);
+	int*         cs_list= xNew<int>(2*numnodes);
+
+	/*Find penta on bed as HO must be coupled to the dofs on the bed: */
+	Element* pentabase=element->GetBasalElement();
+	Element* basaltria=pentabase->SpawnBasalElement();
+
+	/*prepare node list*/
+	for(i=0;i<numnodes;i++){
+		node_list[i+0*numnodes] = pentabase->GetNode(i);
+		node_list[i+1*numnodes] = element  ->GetNode(i);
+		cs_list[i+0*numnodes] = XYEnum;
+		cs_list[i+1*numnodes] = XYEnum;
+	}
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke1= pentabase->NewElementMatrix(SSAApproximationEnum);
+	ElementMatrix* Ke2= element  ->NewElementMatrix(HOApproximationEnum);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+	delete Ke1; delete Ke2;
+
+	/* Get node coordinates and dof list: */
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
+	Input* vx_input   =element->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input   =element->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vxold_input=element->GetInput(VxPicardEnum); _assert_(vxold_input);
+	Input* vyold_input=element->GetInput(VyPicardEnum); _assert_(vyold_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	Gauss* gauss_tria=new GaussTria();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussBase(gauss_tria);
+
+		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
+		this->GetBSSAHO(B, element,xyz_list, gauss);
+		this->GetBSSAprime(Bprime,basaltria,2,xyz_list, gauss_tria); 
+		element->ViscosityHO(&viscosity,3,xyz_list,gauss,vx_input,vy_input);
+		element->ViscosityHO(&oldviscosity,3,xyz_list,gauss,vxold_input,vyold_input);
+
+		newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( B,3,numdofp,1,
+					&D[0][0],3,3,0,
+					Bprime,3,numdofm,0,
+					Ke_gg,1);
+	} 
+	for(i=0;i<numdofp;i++) for(j=0;j<numdofm;j++) Ke->values[(i+2*numdofm)*numdoftotal+j]+=Ke_gg[i*numdofm+j];
+	for(i=0;i<numdofm;i++) for(j=0;j<numdofp;j++) Ke->values[i*numdoftotal+(j+2*numdofm)]+=Ke_gg[j*numdofm+i];
+
+	/*Transform Coordinate System*/
+	element->TransformStiffnessMatrixCoord(Ke,node_list,2*numnodes,cs_list);
+
+	/*Clean-up and return*/
+	basaltria->DeleteMaterials(); delete basaltria;
+	
+	delete gauss;
+	delete gauss_tria;
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(Ke_gg);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<Node*>(node_list);
+	xDelete<int>(cs_list);
+	return Ke;
+
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixHOFS(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixFS(element);
+	int indices[3]={18,19,20};
+	Ke1->StaticCondensation(3,&indices[0]);
+	int init = element->FiniteElement();
+	element->SetTemporaryElementType(P1Enum); // P1 needed for HO
+	ElementMatrix* Ke2=CreateKMatrixHO(element);
+	element->SetTemporaryElementType(init); // P1 needed for HO
+	ElementMatrix* Ke3=CreateKMatrixCouplingHOFS(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSAFS(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixFS(element);
+	int indices[3]={18,19,20};
+	Ke1->StaticCondensation(3,&indices[0]);
+	int init = element->FiniteElement();
+	element->SetTemporaryElementType(P1Enum); 
+	ElementMatrix* Ke2=CreateKMatrixSSA3d(element);
+	element->SetTemporaryElementType(init); 
+	ElementMatrix* Ke3=CreateKMatrixCouplingSSAFS(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSAHO(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixSSA3d(element);
+	ElementMatrix* Ke2=CreateKMatrixHO(element);
+	ElementMatrix* Ke3=CreateKMatrixCouplingSSAHO(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	delete Ke3;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA3d(Element* element){/*{{{*/
+
+	/*compute all stiffness matrices for this element*/
+	ElementMatrix* Ke1=CreateKMatrixSSA3dViscous(element);
+	ElementMatrix* Ke2=CreateKMatrixSSA3dFriction(element);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+
+	/*clean-up and return*/
+	delete Ke1;
+	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA3dFriction(Element* element){/*{{{*/
+
+	/*Initialize Element matrix and return if necessary*/
+	if(element->IsFloating() || !element->IsOnBase()) return NULL;
+
+	/*Build a tria element using the 3 nodes of the base of the penta. Then use 
+	 * the tria functionality to build a friction stiffness matrix on these 3
+	 * nodes: */
+	Element* basalelement = element->SpawnBasalElement();
+	ElementMatrix* Ke=CreateKMatrixSSAFriction(basalelement);
+	basalelement->DeleteMaterials(); delete basalelement;
+
+	/*clean-up and return*/
+	return Ke;
+}/*}}}*/
+ElementMatrix* StressbalanceAnalysis::CreateKMatrixSSA3dViscous(Element* element){/*{{{*/
+
+	/*Constants*/
+	const int    numdof2d=2*3;
+
+	/*Intermediaries */
+	int         i,j,approximation;
+	int         dim=3;
+	IssmDouble  Jdet,viscosity,oldviscosity,newviscosity,viscosity_overshoot;
+	IssmDouble  epsilon[5],oldepsilon[5];       /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble  epsilons[6];                    //6 for FS
+	IssmDouble  B[3][numdof2d];
+	IssmDouble  Bprime[3][numdof2d];
+	IssmDouble  D[3][3]= {0.0};                 // material matrix, simple scalar matrix.
+	IssmDouble  D_scalar;
+	IssmDouble  Ke_gg[numdof2d][numdof2d]={0.0};
+	IssmDouble  *xyz_list  = NULL;
+
+	/*Find penta on bed as this is a SSA elements: */
+	Element* pentabase=element->GetBasalElement();
+	Element* basaltria=pentabase->SpawnBasalElement();
+
+	/*Initialize Element matrix*/
+	ElementMatrix* Ke=basaltria->NewElementMatrix(SSAApproximationEnum);
+	element->GetInputValue(&approximation,ApproximationEnum);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
+	Input* vx_input   =element->GetInput(VxEnum);       _assert_(vx_input);
+	Input* vy_input   =element->GetInput(VyEnum);       _assert_(vy_input);
+	Input* vxold_input=element->GetInput(VxPicardEnum); _assert_(vxold_input);
+	Input* vyold_input=element->GetInput(VyPicardEnum); _assert_(vyold_input);
+	Input* vz_input   =element->GetInput(VzEnum);       _assert_(vz_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	Gauss* gauss_tria=new GaussTria();
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		gauss->SynchronizeGaussBase(gauss_tria);
+
+		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
+		this->GetBSSA(&B[0][0],basaltria,2,xyz_list, gauss_tria);
+		this->GetBSSAprime(&Bprime[0][0],basaltria,2,xyz_list, gauss_tria);
+
+		if(approximation==SSAHOApproximationEnum){
+			element->ViscosityHO(&viscosity,dim,xyz_list,gauss,vx_input,vy_input);
+			element->ViscosityHO(&oldviscosity,dim,xyz_list,gauss,vxold_input,vyold_input);
+			newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
+		}
+		else if (approximation==SSAFSApproximationEnum){
+			element->ViscosityFS(&newviscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		}
+		else _error_("approximation " << approximation << " (" << EnumToStringx(approximation) << ") not supported yet");
+
+		D_scalar=2*newviscosity*gauss->weight*Jdet;
+		for (i=0;i<3;i++) D[i][i]=D_scalar;
+
+		TripleMultiply( &B[0][0],3,numdof2d,1,
+					&D[0][0],3,3,0,
+					&Bprime[0][0],3,numdof2d,0,
+					&Ke_gg[0][0],1);
+
+	}
+	for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof2d+j]+=Ke_gg[i][j];
+
+	/*Transform Coordinate System*/
+	basaltria->TransformStiffnessMatrixCoord(Ke,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(xyz_list);
+	delete basaltria->material;
+	delete basaltria;
+	delete gauss_tria;
+	delete gauss;
+	return Ke;
+
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingHOFS(Element* element){/*{{{*/
 
 	/*compute all load vectors for this element*/
-	ElementVector* pe1=CreatePVectorSSA(element);
-	ElementVector* pe2=CreatePVectorHO(element);
+	ElementVector* pe1=CreatePVectorCouplingHOFSViscous(element);
+	ElementVector* pe2=CreatePVectorCouplingHOFSFriction(element);
 	ElementVector* pe =new ElementVector(pe1,pe2);
 
@@ -5955,4 +5980,338 @@
 	delete pe1;
 	delete pe2;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingHOFSFriction(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         i,approximation;
+	int         dim=3;
+	IssmDouble  Jdet,Jdet2d,FSreconditioning;
+	IssmDouble	bed_normal[3];
+	IssmDouble  viscosity, w, alpha2_gauss;
+	IssmDouble  dw[3];
+	IssmDouble	*xyz_list_tria = NULL;
+	IssmDouble  *xyz_list      = NULL;
+	IssmDouble  basis[6]; //for the six nodes of the penta
+
+	/*Initialize Element vector and return if necessary*/
+	if(!element->IsOnBase() || element->IsFloating()) return NULL;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=HOFSApproximationEnum) return NULL;
+
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+	int numnodes  = vnumnodes+pnumnodes;
+
+	/*Prepare coordinate system list*/
+	int*   cs_list   = xNew<int>(vnumnodes+pnumnodes);
+	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++){
+		cs_list[i]           = XYZEnum;
+		node_list[i]           = element->GetNode(i);
+	}
+	for(i=0;i<pnumnodes;i++){
+		cs_list[vnumnodes+i] = PressureEnum;
+		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
+	}
+
+	ElementVector* pe=element->NewElementVector(FSvelocityEnum);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetVerticesCoordinatesBase(&xyz_list_tria);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	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* vzHO_input=element->GetInput(VzHOEnum); _assert_(vzHO_input);
+
+	/*build friction object, used later on: */
+	Friction* friction=new Friction(element,3);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet2d,xyz_list_tria,gauss);
+		element->NodalFunctionsP1(basis, gauss);
+
+		vzHO_input->GetInputValue(&w, gauss);
+		vzHO_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
+
+		element->NormalBase(&bed_normal[0],xyz_list_tria);
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		friction->GetAlpha2(&alpha2_gauss,gauss);
+
+		for(i=0;i<3;i++){
+			pe->values[i*3+0]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[0]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[0])*basis[i];
+			pe->values[i*3+1]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[1]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[1])*basis[i];
+			pe->values[i*3+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<Node*>(node_list);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_tria);
+	delete gauss;
+	delete friction;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingHOFSViscous(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int         i,approximation;
+	int         dim=3;
+	IssmDouble  viscosity,Jdet,FSreconditioning;
+	IssmDouble  dw[3];
+	IssmDouble  *xyz_list = NULL;
+	IssmDouble  basis[6]; //for the six nodes of the penta
+	IssmDouble  dbasis[3][6]; //for the six nodes of the penta
+
+	/*Initialize Element vector and return if necessary*/
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=HOFSApproximationEnum) return NULL;
+	int   vnumnodes = element->NumberofNodesVelocity();
+	int   pnumnodes = element->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int*   cs_list   = xNew<int>(vnumnodes+pnumnodes);
+	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++){
+		cs_list[i]             = XYZEnum;
+		node_list[i]           = element->GetNode(i);
+	}
+	for(i=0;i<pnumnodes;i++){
+		cs_list[vnumnodes+i]   = PressureEnum;
+		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
+	}
+	ElementVector* pe = element->NewElementVector(FSvelocityEnum);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	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* vzHO_input=element->GetInput(VzHOEnum);  _assert_(vzHO_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
+		element->NodalFunctionsP1(&basis[0],gauss);
+		element->NodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list,gauss);
+		
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		vzHO_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
+
+		for(i=0;i<6;i++){
+			pe->values[i*3+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
+			pe->values[i*3+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
+			pe->values[i*3+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
+			pe->values[3*vnumnodes+i]+=Jdet*gauss->weight*FSreconditioning*dw[2]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<Node*>(node_list);
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingSSAFS(Element* element){/*{{{*/
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorCouplingSSAFSViscous(element);
+	ElementVector* pe2=CreatePVectorCouplingSSAFSFriction(element);
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingSSAFSFriction(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         i,j,approximation;
+	int         dim=3;
+	IssmDouble  Jdet,Jdet2d,FSreconditioning;
+	IssmDouble	bed_normal[3];
+	IssmDouble  viscosity, w, alpha2_gauss;
+	IssmDouble  dw[3];
+	IssmDouble  basis[6]; //for the six nodes of the penta
+	IssmDouble	*xyz_list_tria = NULL;
+	IssmDouble  *xyz_list      = NULL;
+
+	/*Initialize Element vector and return if necessary*/
+	if(!element->IsOnBase() || element->IsFloating()) return NULL;
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=SSAFSApproximationEnum) return NULL;
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list     = xNew<int>(vnumnodes+pnumnodes);
+	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++){
+		cs_list[i]             = XYZEnum;
+		node_list[i]           = element->GetNode(i);
+	}
+	for(i=0;i<pnumnodes;i++){
+		cs_list[vnumnodes+i]   = PressureEnum;
+		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
+	}
+	ElementVector* pe=element->NewElementVector(FSvelocityEnum);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetVerticesCoordinatesBase(&xyz_list_tria);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	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* vzSSA_input=element->GetInput(VzSSAEnum); _assert_(vzSSA_input);
+
+	/*build friction object, used later on: */
+	Friction* friction=new Friction(element,3);
+
+	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet2d,xyz_list_tria,gauss);
+		element->NodalFunctionsP1(basis, gauss);
+
+		vzSSA_input->GetInputValue(&w, gauss);
+		vzSSA_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
+
+		element->NormalBase(&bed_normal[0],xyz_list_tria);
+		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
+		friction->GetAlpha2(&alpha2_gauss,gauss);
+
+		for(i=0;i<3;i++){
+			pe->values[i*3+0]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[0]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[0])*basis[i];
+			pe->values[i*3+1]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[1]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[1])*basis[i];
+			pe->values[i*3+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(xyz_list_tria);
+	xDelete<Node*>(node_list);
+	delete gauss;
+	delete friction;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorCouplingSSAFSViscous(Element* element){/*{{{*/
+
+	/*Intermediaries */
+	int         i,approximation;
+	IssmDouble  viscosity,Jdet,FSreconditioning;
+	IssmDouble  dw[3];
+	IssmDouble  *xyz_list = NULL;
+	IssmDouble  basis[6]; //for the six nodes of the penta
+	IssmDouble  dbasis[3][6]; //for the six nodes of the penta
+
+	/*Initialize Element vector and return if necessary*/
+	element->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=SSAFSApproximationEnum) return NULL;
+	int vnumnodes = element->NumberofNodesVelocity();
+	int pnumnodes = element->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++){
+		cs_list[i]             = XYZEnum;
+		node_list[i]           = element->GetNode(i);
+	}
+	for(i=0;i<pnumnodes;i++){
+		cs_list[vnumnodes+i]   = PressureEnum;
+		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
+	}
+	ElementVector* pe=element->NewElementVector(FSvelocityEnum);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	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* vzSSA_input=element->GetInput(VzSSAEnum);   _assert_(vzSSA_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctionsP1(&basis[0], gauss);
+		element->NodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list, gauss);
+
+		vzSSA_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
+		element->ViscosityFS(&viscosity,3,xyz_list,gauss,vx_input,vy_input,vz_input);
+
+		for(i=0;i<6;i++){
+			pe->values[i*3+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
+			pe->values[i*3+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
+			pe->values[i*3+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
+			pe->values[3*vnumnodes+i]+=Jdet*gauss->weight*FSreconditioning*dw[2]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<Node*>(node_list);
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return pe;
+}/*}}}*/
+ElementVector* StressbalanceAnalysis::CreatePVectorHOFS(Element* element){/*{{{*/
+
+	/*compute all load vectors for this element*/
+	int init = element->FiniteElement();
+	element->SetTemporaryElementType(P1Enum);
+	ElementVector* pe1=CreatePVectorHO(element);
+	element->SetTemporaryElementType(init);
+	ElementVector* pe2=CreatePVectorFS(element);
+	int indices[3]={18,19,20};
+	element->SetTemporaryElementType(MINIcondensedEnum);
+	ElementMatrix* Ke = CreateKMatrixFS(element);
+	element->SetTemporaryElementType(init);
+	pe2->StaticCondensation(Ke,3,&indices[0]);
+	delete Ke;
+	ElementVector* pe3=CreatePVectorCouplingHOFS(element);
+	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	delete pe3;
 	return pe;
 }/*}}}*/
@@ -5980,32 +6339,9 @@
 	return pe;
 }/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorHOFS(Element* element){/*{{{*/
+ElementVector* StressbalanceAnalysis::CreatePVectorSSAHO(Element* element){/*{{{*/
 
 	/*compute all load vectors for this element*/
-	int init = element->FiniteElement();
-	element->SetTemporaryElementType(P1Enum);
-	ElementVector* pe1=CreatePVectorHO(element);
-	element->SetTemporaryElementType(init);
-	ElementVector* pe2=CreatePVectorFS(element);
-	int indices[3]={18,19,20};
-	element->SetTemporaryElementType(MINIcondensedEnum);
-	ElementMatrix* Ke = CreateKMatrixFS(element);
-	element->SetTemporaryElementType(init);
-	pe2->StaticCondensation(Ke,3,&indices[0]);
-	delete Ke;
-	ElementVector* pe3=CreatePVectorCouplingHOFS(element);
-	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
-
-	/*clean-up and return*/
-	delete pe1;
-	delete pe2;
-	delete pe3;
-	return pe;
-}/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorCouplingHOFS(Element* element){/*{{{*/
-
-	/*compute all load vectors for this element*/
-	ElementVector* pe1=CreatePVectorCouplingHOFSViscous(element);
-	ElementVector* pe2=CreatePVectorCouplingHOFSFriction(element);
+	ElementVector* pe1=CreatePVectorSSA(element);
+	ElementVector* pe2=CreatePVectorHO(element);
 	ElementVector* pe =new ElementVector(pe1,pe2);
 
@@ -6015,341 +6351,83 @@
 	return pe;
 }/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorCouplingHOFSFriction(Element* element){/*{{{*/
-
-	/*Intermediaries*/
-	int         i,approximation;
-	int         dim=3;
-	IssmDouble  Jdet,Jdet2d,FSreconditioning;
-	IssmDouble	bed_normal[3];
-	IssmDouble  viscosity, w, alpha2_gauss;
-	IssmDouble  dw[3];
-	IssmDouble	*xyz_list_tria = NULL;
-	IssmDouble  *xyz_list      = NULL;
-	IssmDouble  basis[6]; //for the six nodes of the penta
-
-	/*Initialize Element vector and return if necessary*/
-	if(!element->IsOnBase() || element->IsFloating()) return NULL;
-	element->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=HOFSApproximationEnum) return NULL;
-
-	int vnumnodes = element->NumberofNodesVelocity();
-	int pnumnodes = element->NumberofNodesPressure();
-	int numnodes  = vnumnodes+pnumnodes;
-
-	/*Prepare coordinate system list*/
-	int*   cs_list   = xNew<int>(vnumnodes+pnumnodes);
-	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
-	for(i=0;i<vnumnodes;i++){
-		cs_list[i]           = XYZEnum;
-		node_list[i]           = element->GetNode(i);
-	}
-	for(i=0;i<pnumnodes;i++){
-		cs_list[vnumnodes+i] = PressureEnum;
-		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
-	}
-
-	ElementVector* pe=element->NewElementVector(FSvelocityEnum);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	element->GetVerticesCoordinatesBase(&xyz_list_tria);
-	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
-	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* vzHO_input=element->GetInput(VzHOEnum); _assert_(vzHO_input);
-
-	/*build friction object, used later on: */
-	Friction* friction=new Friction(element,3);
-
-	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
-	Gauss* gauss=element->NewGaussBase(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminantBase(&Jdet2d,xyz_list_tria,gauss);
-		element->NodalFunctionsP1(basis, gauss);
-
-		vzHO_input->GetInputValue(&w, gauss);
-		vzHO_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
-
-		element->NormalBase(&bed_normal[0],xyz_list_tria);
-		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
-		friction->GetAlpha2(&alpha2_gauss,gauss);
-
-		for(i=0;i<3;i++){
-			pe->values[i*3+0]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[0]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[0])*basis[i];
-			pe->values[i*3+1]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[1]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[1])*basis[i];
-			pe->values[i*3+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
-		}
-	}
-
-	/*Transform coordinate system*/
-	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
-
-	/*Clean up and return*/
-	xDelete<int>(cs_list);
-	xDelete<Node*>(node_list);
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(xyz_list_tria);
-	delete gauss;
-	delete friction;
-	return pe;
-}/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorCouplingHOFSViscous(Element* element){/*{{{*/
-
-	/*Intermediaries */
-	int         i,approximation;
-	int         dim=3;
-	IssmDouble  viscosity,Jdet,FSreconditioning;
-	IssmDouble  dw[3];
-	IssmDouble  *xyz_list = NULL;
-	IssmDouble  basis[6]; //for the six nodes of the penta
-	IssmDouble  dbasis[3][6]; //for the six nodes of the penta
-
-	/*Initialize Element vector and return if necessary*/
-	element->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=HOFSApproximationEnum) return NULL;
-	int   vnumnodes = element->NumberofNodesVelocity();
-	int   pnumnodes = element->NumberofNodesPressure();
-
-	/*Prepare coordinate system list*/
-	int*   cs_list   = xNew<int>(vnumnodes+pnumnodes);
-	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
-	for(i=0;i<vnumnodes;i++){
-		cs_list[i]             = XYZEnum;
-		node_list[i]           = element->GetNode(i);
-	}
-	for(i=0;i<pnumnodes;i++){
-		cs_list[vnumnodes+i]   = PressureEnum;
-		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
-	}
-	ElementVector* pe = element->NewElementVector(FSvelocityEnum);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
-	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* vzHO_input=element->GetInput(VzHOEnum);  _assert_(vzHO_input);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(5);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminant(&Jdet, xyz_list,gauss);
-		element->NodalFunctionsP1(&basis[0],gauss);
-		element->NodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list,gauss);
-		
-		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
-		vzHO_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
-
-		for(i=0;i<6;i++){
-			pe->values[i*3+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
-			pe->values[i*3+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
-			pe->values[i*3+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
-			pe->values[3*vnumnodes+i]+=Jdet*gauss->weight*FSreconditioning*dw[2]*basis[i];
-		}
-	}
-
-	/*Transform coordinate system*/
-	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
-
-	/*Clean up and return*/
-	xDelete<int>(cs_list);
-	xDelete<Node*>(node_list);
-	xDelete<IssmDouble>(xyz_list);
-	delete gauss;
-	return pe;
-}/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorCouplingSSAFS(Element* element){/*{{{*/
-
-	/*compute all load vectors for this element*/
-	ElementVector* pe1=CreatePVectorCouplingSSAFSViscous(element);
-	ElementVector* pe2=CreatePVectorCouplingSSAFSFriction(element);
-	ElementVector* pe =new ElementVector(pe1,pe2);
-
-	/*clean-up and return*/
-	delete pe1;
-	delete pe2;
-	return pe;
-}/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorCouplingSSAFSFriction(Element* element){/*{{{*/
-
-	/*Intermediaries*/
-	int         i,j,approximation;
-	int         dim=3;
-	IssmDouble  Jdet,Jdet2d,FSreconditioning;
-	IssmDouble	bed_normal[3];
-	IssmDouble  viscosity, w, alpha2_gauss;
-	IssmDouble  dw[3];
-	IssmDouble  basis[6]; //for the six nodes of the penta
-	IssmDouble	*xyz_list_tria = NULL;
-	IssmDouble  *xyz_list      = NULL;
-
-	/*Initialize Element vector and return if necessary*/
-	if(!element->IsOnBase() || element->IsFloating()) return NULL;
-	element->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=SSAFSApproximationEnum) return NULL;
-	int vnumnodes = element->NumberofNodesVelocity();
-	int pnumnodes = element->NumberofNodesPressure();
-
-	/*Prepare coordinate system list*/
-	int* cs_list     = xNew<int>(vnumnodes+pnumnodes);
-	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
-	for(i=0;i<vnumnodes;i++){
-		cs_list[i]             = XYZEnum;
-		node_list[i]           = element->GetNode(i);
-	}
-	for(i=0;i<pnumnodes;i++){
-		cs_list[vnumnodes+i]   = PressureEnum;
-		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
-	}
-	ElementVector* pe=element->NewElementVector(FSvelocityEnum);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	element->GetVerticesCoordinatesBase(&xyz_list_tria);
-	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
-	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* vzSSA_input=element->GetInput(VzSSAEnum); _assert_(vzSSA_input);
-
-	/*build friction object, used later on: */
-	Friction* friction=new Friction(element,3);
-
-	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
-	Gauss* gauss=element->NewGaussBase(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminantBase(&Jdet2d,xyz_list_tria,gauss);
-		element->NodalFunctionsP1(basis, gauss);
-
-		vzSSA_input->GetInputValue(&w, gauss);
-		vzSSA_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
-
-		element->NormalBase(&bed_normal[0],xyz_list_tria);
-		element->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,vz_input);
-		friction->GetAlpha2(&alpha2_gauss,gauss);
-
-		for(i=0;i<3;i++){
-			pe->values[i*3+0]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[0]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[0])*basis[i];
-			pe->values[i*3+1]+=Jdet2d*gauss->weight*(alpha2_gauss*w*bed_normal[1]*bed_normal[2]+2*viscosity*dw[2]*bed_normal[1])*basis[i];
-			pe->values[i*3+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
-		}
-	}
-
-	/*Transform coordinate system*/
-	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
-
-	/*Clean up and return*/
-	xDelete<int>(cs_list);
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(xyz_list_tria);
-	xDelete<Node*>(node_list);
-	delete gauss;
-	delete friction;
-	return pe;
-}/*}}}*/
-ElementVector* StressbalanceAnalysis::CreatePVectorCouplingSSAFSViscous(Element* element){/*{{{*/
-
-	/*Intermediaries */
-	int         i,approximation;
-	IssmDouble  viscosity,Jdet,FSreconditioning;
-	IssmDouble  dw[3];
-	IssmDouble  *xyz_list = NULL;
-	IssmDouble  basis[6]; //for the six nodes of the penta
-	IssmDouble  dbasis[3][6]; //for the six nodes of the penta
-
-	/*Initialize Element vector and return if necessary*/
-	element->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=SSAFSApproximationEnum) return NULL;
-	int vnumnodes = element->NumberofNodesVelocity();
-	int pnumnodes = element->NumberofNodesPressure();
-
-	/*Prepare coordinate system list*/
-	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
-	Node **node_list = xNew<Node*>(vnumnodes+pnumnodes);
-	for(i=0;i<vnumnodes;i++){
-		cs_list[i]             = XYZEnum;
-		node_list[i]           = element->GetNode(i);
-	}
-	for(i=0;i<pnumnodes;i++){
-		cs_list[vnumnodes+i]   = PressureEnum;
-		node_list[vnumnodes+i] = element->GetNode(vnumnodes+i);
-	}
-	ElementVector* pe=element->NewElementVector(FSvelocityEnum);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	element->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
-	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* vzSSA_input=element->GetInput(VzSSAEnum);   _assert_(vzSSA_input);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(5);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		element->NodalFunctionsP1(&basis[0], gauss);
-		element->NodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list, gauss);
-
-		vzSSA_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
-		element->ViscosityFS(&viscosity,3,xyz_list,gauss,vx_input,vy_input,vz_input);
-
-		for(i=0;i<6;i++){
-			pe->values[i*3+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
-			pe->values[i*3+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
-			pe->values[i*3+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
-			pe->values[3*vnumnodes+i]+=Jdet*gauss->weight*FSreconditioning*dw[2]*basis[i];
-		}
-	}
-
-	/*Transform coordinate system*/
-	element->TransformLoadVectorCoord(pe,node_list,vnumnodes+pnumnodes,cs_list);
-
-	/*Clean up and return*/
-	xDelete<int>(cs_list);
-	xDelete<Node*>(node_list);
-	xDelete<IssmDouble>(xyz_list);
-	delete gauss;
-	return pe;
-}/*}}}*/
-void StressbalanceAnalysis::GetBSSAHO(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 3*NDOF2. 
-	 * For node i, Bi can be expressed in the actual coordinate system
+void           StressbalanceAnalysis::GetBprimeSSAFS(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute Bprime  matrix. Bprime=[Bprime1 Bprime2 Bprime3 Bprime4 Bprime5 Bprime6] where Bprimei is of size 5*NDOF2. 
+	 * For node i, Bprimei can be expressed in the actual coordinate system
 	 * by: 
-	 *       Bi=[ dh/dx          0      ]
-	 *          [   0           dh/dy   ]
-	 *          [ 1/2*dh/dy  1/2*dh/dx  ]
+	 *       Bprimei=[ 2*dh/dx    dh/dy   0   0 ]
+	 *               [  dh/dx    2*dh/dy  0   0 ]
+	 *               [  dh/dy     dh/dx   0   0 ]
 	 * where h is the interpolation function for node i.
 	 *
-	 * We assume B has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
+	 * We assume Bprime has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
 	 */
 
+	int    i;
+	IssmDouble dbasismini[3][7];
+
+	/*Get dbasis in actual coordinate system: */
+	element->NodalFunctionsMINIDerivatives(&dbasismini[0][0],xyz_list, gauss);
+
+	/*Build Bprime: */
+	for(i=0;i<6;i++){
+		Bprime[(3*7+6)*0+3*i+0] = 2.*dbasismini[0][i];
+		Bprime[(3*7+6)*0+3*i+1] = dbasismini[1][i];
+		Bprime[(3*7+6)*0+3*i+2] = 0.;
+		Bprime[(3*7+6)*1+3*i+0] = dbasismini[0][i];
+		Bprime[(3*7+6)*1+3*i+1] = 2.*dbasismini[1][i];
+		Bprime[(3*7+6)*1+3*i+2] = 0.;
+		Bprime[(3*7+6)*2+3*i+0] = dbasismini[1][i];
+		Bprime[(3*7+6)*2+3*i+1] = dbasismini[0][i];
+		Bprime[(3*7+6)*2+3*i+2] = 0.;
+	}
+
+	for(i=0;i<1;i++){ //Add zeros for the bubble function
+		Bprime[(3*7+6)*0+3*(6+i)+0] = 0.;
+		Bprime[(3*7+6)*0+3*(6+i)+1] = 0.;
+		Bprime[(3*7+6)*0+3*(6+i)+2] = 0.;
+		Bprime[(3*7+6)*1+3*(6+i)+0] = 0.;
+		Bprime[(3*7+6)*1+3*(6+i)+1] = 0.;
+		Bprime[(3*7+6)*1+3*(6+i)+2] = 0.;
+		Bprime[(3*7+6)*2+3*(6+i)+0] = 0.;
+		Bprime[(3*7+6)*2+3*(6+i)+1] = 0.;
+		Bprime[(3*7+6)*2+3*(6+i)+2] = 0.;
+	}
+
+	for(i=0;i<6;i++){ //last column not for the bubble function
+		Bprime[(3*7+6)*0+7*3+i] = 0.;
+		Bprime[(3*7+6)*1+7*3+i] = 0.;
+		Bprime[(3*7+6)*2+7*3+i] = 0.;
+	}
+}/*}}}*/
+void           StressbalanceAnalysis::GetBprimeSSAFSTria(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute Bprime  matrix. Bprime=[Bprime1 Bprime2 Bprime3] where Bprimei is of size 3*NDOF2. 
+	 * For node i, Bprimei can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bprimei=[  dN/dx    0   ]
+	 *               [    0    dN/dy ]
+	 *               [  dN/dy  dN/dx ]
+	 N               [  dN/dx  dN/dy ]
+	 * where N is the finiteelement function for node i.
+	 *
+	 * We assume Bprime has been allocated already, of size: 3x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
 	int numnodes = element->GetNumberOfNodes();
-	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
-
-	/*Get dbasis in actual coordinate system: */
+
+	/*Get nodal functions*/
+	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
 	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 
-	/*Build B: */
+	/*Build Bprime: */
 	for(int i=0;i<numnodes;i++){
-		B[2*numnodes*0+2*i+0] = dbasis[0*numnodes+i];
-		B[2*numnodes*0+2*i+1] = 0.;
-		B[2*numnodes*1+2*i+0] = 0.;
-		B[2*numnodes*1+2*i+1] = dbasis[1*numnodes+i];
-		B[2*numnodes*2+2*i+0] = .5*dbasis[1*numnodes+i];
-		B[2*numnodes*2+2*i+1] = .5*dbasis[0*numnodes+i];
+		Bprime[2*numnodes*0+2*i+0] = dbasis[0*numnodes+i];
+		Bprime[2*numnodes*0+2*i+1] = 0.;
+		Bprime[2*numnodes*1+2*i+0] = 0.;
+		Bprime[2*numnodes*1+2*i+1] = dbasis[1*numnodes+i];
+		Bprime[2*numnodes*2+2*i+0] = dbasis[1*numnodes+i];
+		Bprime[2*numnodes*2+2*i+1] = dbasis[0*numnodes+i];
+		Bprime[2*numnodes*3+2*i+0] = dbasis[0*numnodes+i];
+		Bprime[2*numnodes*3+2*i+1] = dbasis[1*numnodes+i];
 	}
 
@@ -6357,5 +6435,5 @@
 	xDelete<IssmDouble>(dbasis);
 }/*}}}*/
-void StressbalanceAnalysis::GetBSSAFS(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetBSSAFS(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF2. 
 	 * For node i, Bi can be expressed in the actual coordinate system
@@ -6415,54 +6493,5 @@
 	}
 }/*}}}*/
-void StressbalanceAnalysis::GetBprimeSSAFS(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute Bprime  matrix. Bprime=[Bprime1 Bprime2 Bprime3 Bprime4 Bprime5 Bprime6] where Bprimei is of size 5*NDOF2. 
-	 * For node i, Bprimei can be expressed in the actual coordinate system
-	 * by: 
-	 *       Bprimei=[ 2*dh/dx    dh/dy   0   0 ]
-	 *               [  dh/dx    2*dh/dy  0   0 ]
-	 *               [  dh/dy     dh/dx   0   0 ]
-	 * where h is the interpolation function for node i.
-	 *
-	 * We assume Bprime has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
-	 */
-
-	int    i;
-	IssmDouble dbasismini[3][7];
-
-	/*Get dbasis in actual coordinate system: */
-	element->NodalFunctionsMINIDerivatives(&dbasismini[0][0],xyz_list, gauss);
-
-	/*Build Bprime: */
-	for(i=0;i<6;i++){
-		Bprime[(3*7+6)*0+3*i+0] = 2.*dbasismini[0][i];
-		Bprime[(3*7+6)*0+3*i+1] = dbasismini[1][i];
-		Bprime[(3*7+6)*0+3*i+2] = 0.;
-		Bprime[(3*7+6)*1+3*i+0] = dbasismini[0][i];
-		Bprime[(3*7+6)*1+3*i+1] = 2.*dbasismini[1][i];
-		Bprime[(3*7+6)*1+3*i+2] = 0.;
-		Bprime[(3*7+6)*2+3*i+0] = dbasismini[1][i];
-		Bprime[(3*7+6)*2+3*i+1] = dbasismini[0][i];
-		Bprime[(3*7+6)*2+3*i+2] = 0.;
-	}
-
-	for(i=0;i<1;i++){ //Add zeros for the bubble function
-		Bprime[(3*7+6)*0+3*(6+i)+0] = 0.;
-		Bprime[(3*7+6)*0+3*(6+i)+1] = 0.;
-		Bprime[(3*7+6)*0+3*(6+i)+2] = 0.;
-		Bprime[(3*7+6)*1+3*(6+i)+0] = 0.;
-		Bprime[(3*7+6)*1+3*(6+i)+1] = 0.;
-		Bprime[(3*7+6)*1+3*(6+i)+2] = 0.;
-		Bprime[(3*7+6)*2+3*(6+i)+0] = 0.;
-		Bprime[(3*7+6)*2+3*(6+i)+1] = 0.;
-		Bprime[(3*7+6)*2+3*(6+i)+2] = 0.;
-	}
-
-	for(i=0;i<6;i++){ //last column not for the bubble function
-		Bprime[(3*7+6)*0+7*3+i] = 0.;
-		Bprime[(3*7+6)*1+7*3+i] = 0.;
-		Bprime[(3*7+6)*2+7*3+i] = 0.;
-	}
-}/*}}}*/
-void StressbalanceAnalysis::GetBSSAFSTria(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceAnalysis::GetBSSAFSTria(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
 	 * For node i, Bi can be expressed in the actual coordinate system
@@ -6496,34 +6525,30 @@
 	xDelete<IssmDouble>(dbasis);
 }/*}}}*/
-void StressbalanceAnalysis::GetBprimeSSAFSTria(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute Bprime  matrix. Bprime=[Bprime1 Bprime2 Bprime3] where Bprimei is of size 3*NDOF2. 
-	 * For node i, Bprimei can be expressed in the actual coordinate system
+void           StressbalanceAnalysis::GetBSSAHO(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 3*NDOF2. 
+	 * For node i, Bi can be expressed in the actual coordinate system
 	 * by: 
-	 *       Bprimei=[  dN/dx    0   ]
-	 *               [    0    dN/dy ]
-	 *               [  dN/dy  dN/dx ]
-	 N               [  dN/dx  dN/dy ]
-	 * where N is the finiteelement function for node i.
+	 *       Bi=[ dh/dx          0      ]
+	 *          [   0           dh/dy   ]
+	 *          [ 1/2*dh/dy  1/2*dh/dx  ]
+	 * where h is the interpolation function for node i.
 	 *
-	 * We assume Bprime has been allocated already, of size: 3x(NDOF2*numnodes)
+	 * We assume B has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
 	 */
 
-	/*Fetch number of nodes for this finite element*/
 	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions*/
-	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+
+	/*Get dbasis in actual coordinate system: */
 	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 
-	/*Build Bprime: */
+	/*Build B: */
 	for(int i=0;i<numnodes;i++){
-		Bprime[2*numnodes*0+2*i+0] = dbasis[0*numnodes+i];
-		Bprime[2*numnodes*0+2*i+1] = 0.;
-		Bprime[2*numnodes*1+2*i+0] = 0.;
-		Bprime[2*numnodes*1+2*i+1] = dbasis[1*numnodes+i];
-		Bprime[2*numnodes*2+2*i+0] = dbasis[1*numnodes+i];
-		Bprime[2*numnodes*2+2*i+1] = dbasis[0*numnodes+i];
-		Bprime[2*numnodes*3+2*i+0] = dbasis[0*numnodes+i];
-		Bprime[2*numnodes*3+2*i+1] = dbasis[1*numnodes+i];
+		B[2*numnodes*0+2*i+0] = dbasis[0*numnodes+i];
+		B[2*numnodes*0+2*i+1] = 0.;
+		B[2*numnodes*1+2*i+0] = 0.;
+		B[2*numnodes*1+2*i+1] = dbasis[1*numnodes+i];
+		B[2*numnodes*2+2*i+0] = .5*dbasis[1*numnodes+i];
+		B[2*numnodes*2+2*i+1] = .5*dbasis[0*numnodes+i];
 	}
 
@@ -6531,20 +6556,14 @@
 	xDelete<IssmDouble>(dbasis);
 }/*}}}*/
-void StressbalanceAnalysis::GetLSSAFS(IssmDouble* LFS,Element* element,Gauss* gauss_in){/*{{{*/
-	/*
-	 * Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
-	 * For node i, Li can be expressed in the actual coordinate system
+void           StressbalanceAnalysis::GetLprimeFSSSA(IssmDouble* LprimeFS,Element* element,IssmDouble* xyz_list,Gauss* gauss_in){/*{{{*/
+	/* Compute Lprime  matrix. Lprime=[Lp1 Lp2 Lp3] where Lpi is square and of size numdof. 
+	 * For node i, Lpi can be expressed in the actual coordinate system
 	 * by: 
-	 *       Li=[ h    0 ]
-	 *	 	      [ 0    h ]
-	 *	 	      [ h    0 ]
-	 *	 	      [ 0    h ]
-	 *	 	      [ h    0 ]
-	 *	 	      [ 0    h ]
-	 *	 	      [ h    0 ]
-	 *	 	      [ 0    h ]
+	 *       Lpi=[ h    0 ]
+	 *		       [ 0    h ]
+	 *		       [ h    0 ]
+	 *		       [ 0    h ]
 	 * where h is the interpolation function for node i.
 	 */
-
 	int num_dof=2;
 	IssmDouble basis[3];
@@ -6552,5 +6571,5 @@
 	/*Cast gauss to GaussPenta*/
 	_assert_(gauss_in->Enum()==GaussPentaEnum);
-	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+	GaussPenta* gauss = xDynamicCast<GaussPenta*>(gauss_in);
 
 	/*Get basis in actual coordinate system: */
@@ -6559,25 +6578,17 @@
 	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
 
-	/*Build LFS: */
+	/*Build LprimeFS: */
 	for(int i=0;i<3;i++){
-		LFS[num_dof*3*0+num_dof*i+0] = basis[i];
-		LFS[num_dof*3*0+num_dof*i+1] = 0;
-		LFS[num_dof*3*1+num_dof*i+0] = 0;
-		LFS[num_dof*3*1+num_dof*i+1] = basis[i];
-		LFS[num_dof*3*2+num_dof*i+0] = basis[i];
-		LFS[num_dof*3*2+num_dof*i+1] = 0;
-		LFS[num_dof*3*3+num_dof*i+0] = 0;
-		LFS[num_dof*3*3+num_dof*i+1] = basis[i];
-		LFS[num_dof*3*4+num_dof*i+0] = basis[i];
-		LFS[num_dof*3*4+num_dof*i+1] = 0;
-		LFS[num_dof*3*5+num_dof*i+0] = 0;
-		LFS[num_dof*3*5+num_dof*i+1] = basis[i];
-		LFS[num_dof*3*6+num_dof*i+0] = basis[i];
-		LFS[num_dof*3*6+num_dof*i+1] = 0;
-		LFS[num_dof*3*7+num_dof*i+0] = 0;
-		LFS[num_dof*3*7+num_dof*i+1] = basis[i];
-	}
-}/*}}}*/
-void StressbalanceAnalysis::GetLprimeSSAFS(IssmDouble* LprimeFS,Element* element,IssmDouble* xyz_list,Gauss* gauss_in){/*{{{*/
+		LprimeFS[num_dof*3*0+num_dof*i+0] = basis[i];
+		LprimeFS[num_dof*3*0+num_dof*i+1] = 0.;
+		LprimeFS[num_dof*3*1+num_dof*i+0] = 0.;
+		LprimeFS[num_dof*3*1+num_dof*i+1] = basis[i];
+		LprimeFS[num_dof*3*2+num_dof*i+0] = basis[i];
+		LprimeFS[num_dof*3*2+num_dof*i+1] = 0.;
+		LprimeFS[num_dof*3*3+num_dof*i+0] = 0.;
+		LprimeFS[num_dof*3*3+num_dof*i+1] = basis[i];
+	}
+}/*}}}*/
+void           StressbalanceAnalysis::GetLprimeSSAFS(IssmDouble* LprimeFS,Element* element,IssmDouble* xyz_list,Gauss* gauss_in){/*{{{*/
 	/* Compute Lprime  matrix. Lprime=[Lp1 Lp2 Lp3] where Lpi is square and of size numdof. 
 	 * For node i, Lpi can be expressed in the actual coordinate system
@@ -6601,5 +6612,5 @@
 	/*Cast gauss to GaussPenta*/
 	_assert_(gauss_in->Enum()==GaussPentaEnum);
-	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+	GaussPenta* gauss = xDynamicCast<GaussPenta*>(gauss_in);
 
 	/*Get basis in actual coordinate system: */
@@ -6684,5 +6695,5 @@
 	}
 }/*}}}*/
-void StressbalanceAnalysis::GetLFSSSA(IssmDouble* LFS,Element* element,Gauss* gauss_in){/*{{{*/
+void           StressbalanceAnalysis::GetLFSSSA(IssmDouble* LFS,Element* element,Gauss* gauss_in){/*{{{*/
 	/* Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
 	 * For node i, Li can be expressed in the actual coordinate system
@@ -6700,5 +6711,5 @@
 	/*Cast gauss to GaussPenta*/
 	_assert_(gauss_in->Enum()==GaussPentaEnum);
-	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+	GaussPenta* gauss = xDynamicCast<GaussPenta*>(gauss_in);
 
 	/*Get basis in actual coordinate system: */
@@ -6723,14 +6734,20 @@
 	}
 }/*}}}*/
-void StressbalanceAnalysis::GetLprimeFSSSA(IssmDouble* LprimeFS,Element* element,IssmDouble* xyz_list,Gauss* gauss_in){/*{{{*/
-	/* Compute Lprime  matrix. Lprime=[Lp1 Lp2 Lp3] where Lpi is square and of size numdof. 
-	 * For node i, Lpi can be expressed in the actual coordinate system
+void           StressbalanceAnalysis::GetLSSAFS(IssmDouble* LFS,Element* element,Gauss* gauss_in){/*{{{*/
+	/*
+	 * Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+	 * For node i, Li can be expressed in the actual coordinate system
 	 * by: 
-	 *       Lpi=[ h    0 ]
-	 *		       [ 0    h ]
-	 *		       [ h    0 ]
-	 *		       [ 0    h ]
+	 *       Li=[ h    0 ]
+	 *	 	      [ 0    h ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
+	 *	 	      [ h    0 ]
+	 *	 	      [ 0    h ]
 	 * where h is the interpolation function for node i.
 	 */
+
 	int num_dof=2;
 	IssmDouble basis[3];
@@ -6738,5 +6755,5 @@
 	/*Cast gauss to GaussPenta*/
 	_assert_(gauss_in->Enum()==GaussPentaEnum);
-	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+	GaussPenta* gauss = xDynamicCast<GaussPenta*>(gauss_in);
 
 	/*Get basis in actual coordinate system: */
@@ -6745,17 +6762,25 @@
 	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
 
-	/*Build LprimeFS: */
+	/*Build LFS: */
 	for(int i=0;i<3;i++){
-		LprimeFS[num_dof*3*0+num_dof*i+0] = basis[i];
-		LprimeFS[num_dof*3*0+num_dof*i+1] = 0.;
-		LprimeFS[num_dof*3*1+num_dof*i+0] = 0.;
-		LprimeFS[num_dof*3*1+num_dof*i+1] = basis[i];
-		LprimeFS[num_dof*3*2+num_dof*i+0] = basis[i];
-		LprimeFS[num_dof*3*2+num_dof*i+1] = 0.;
-		LprimeFS[num_dof*3*3+num_dof*i+0] = 0.;
-		LprimeFS[num_dof*3*3+num_dof*i+1] = basis[i];
-	}
-}/*}}}*/
-void StressbalanceAnalysis::InputUpdateFromSolutionHOFS(IssmDouble* solution,Element* element){/*{{{*/
+		LFS[num_dof*3*0+num_dof*i+0] = basis[i];
+		LFS[num_dof*3*0+num_dof*i+1] = 0;
+		LFS[num_dof*3*1+num_dof*i+0] = 0;
+		LFS[num_dof*3*1+num_dof*i+1] = basis[i];
+		LFS[num_dof*3*2+num_dof*i+0] = basis[i];
+		LFS[num_dof*3*2+num_dof*i+1] = 0;
+		LFS[num_dof*3*3+num_dof*i+0] = 0;
+		LFS[num_dof*3*3+num_dof*i+1] = basis[i];
+		LFS[num_dof*3*4+num_dof*i+0] = basis[i];
+		LFS[num_dof*3*4+num_dof*i+1] = 0;
+		LFS[num_dof*3*5+num_dof*i+0] = 0;
+		LFS[num_dof*3*5+num_dof*i+1] = basis[i];
+		LFS[num_dof*3*6+num_dof*i+0] = basis[i];
+		LFS[num_dof*3*6+num_dof*i+1] = 0;
+		LFS[num_dof*3*7+num_dof*i+0] = 0;
+		LFS[num_dof*3*7+num_dof*i+1] = basis[i];
+	}
+}/*}}}*/
+void           StressbalanceAnalysis::InputUpdateFromSolutionHOFS(IssmDouble* solution,Element* element){/*{{{*/
 
 	int         i;
@@ -6854,5 +6879,5 @@
 	xDelete<int>(cs_list);
 }/*}}}*/
-void StressbalanceAnalysis::InputUpdateFromSolutionSSAFS(IssmDouble* solution,Element* element){/*{{{*/
+void           StressbalanceAnalysis::InputUpdateFromSolutionSSAFS(IssmDouble* solution,Element* element){/*{{{*/
 
 	int         i;
@@ -6960,5 +6985,5 @@
 	xDelete<int>(cs_list);
 }/*}}}*/
-void StressbalanceAnalysis::InputUpdateFromSolutionSSAHO(IssmDouble* solution,Element* element){/*{{{*/
+void           StressbalanceAnalysis::InputUpdateFromSolutionSSAHO(IssmDouble* solution,Element* element){/*{{{*/
 
 	int         i,domaintype;
Index: /issm/trunk/src/c/analyses/StressbalanceAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/StressbalanceAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
   public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,90 +26,90 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void GetSolutionFromInputsHoriz(Vector<IssmDouble>* solution,Element* element);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GetSolutionFromInputsHoriz(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 
 		/*SSA*/
 		ElementMatrix* CreateJacobianMatrixSSA(Element* element);
 		ElementMatrix* CreateKMatrixSSA(Element* element);
-		ElementMatrix* CreateKMatrixSSAViscous(Element* element);
 		ElementMatrix* CreateKMatrixSSAFriction(Element* element);
 		ElementMatrix* CreateKMatrixSSALateralFriction(Element* element);
+		ElementMatrix* CreateKMatrixSSAViscous(Element* element);
 		ElementVector* CreatePVectorSSA(Element* element);
+		ElementVector* CreatePVectorSSAFront(Element* element);
 		ElementVector* CreatePVectorSSADrivingStress(Element* element);
-		ElementVector* CreatePVectorSSAFront(Element* element);
-		void GetBSSA(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBSSAprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBSSAFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void InputUpdateFromSolutionSSA(IssmDouble* solution,Element* element);
+		void           GetBSSA(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBSSAFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBSSAprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           InputUpdateFromSolutionSSA(IssmDouble* solution,Element* element);
 		/*L1L2*/
 		ElementMatrix* CreateKMatrixL1L2(Element* element);
+		ElementMatrix* CreateKMatrixL1L2Friction(Element* element);
 		ElementMatrix* CreateKMatrixL1L2Viscous(Element* element);
-		ElementMatrix* CreateKMatrixL1L2Friction(Element* element);
 		ElementVector* CreatePVectorL1L2(Element* element);
+		ElementVector* CreatePVectorL1L2Front(Element* element);
 		ElementVector* CreatePVectorL1L2DrivingStress(Element* element);
-		ElementVector* CreatePVectorL1L2Front(Element* element);
-		void InputUpdateFromSolutionL1L2(IssmDouble* solution,Element* element);
+		void           InputUpdateFromSolutionL1L2(IssmDouble* solution,Element* element);
 		/*HO*/
 		ElementMatrix* CreateJacobianMatrixHO(Element* element);
 		ElementMatrix* CreateKMatrixHO(Element* element);
+		ElementMatrix* CreateKMatrixHOFriction(Element* element);
 		ElementMatrix* CreateKMatrixHOViscous(Element* element);
-		ElementMatrix* CreateKMatrixHOFriction(Element* element);
 		ElementVector* CreatePVectorHO(Element* element);
+		ElementVector* CreatePVectorHOFront(Element* element);
 		ElementVector* CreatePVectorHODrivingStress(Element* element);
-		ElementVector* CreatePVectorHOFront(Element* element);
-		void GetBHO(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBHOprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBHOFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void InputUpdateFromSolutionHO(IssmDouble* solution,Element* element);
+		void           GetBHO(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBHOFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBHOprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           InputUpdateFromSolutionHO(IssmDouble* solution,Element* element);
 		/*FS*/
 		ElementVector* CreateDVectorFS(Element* element);
 		ElementMatrix* CreateJacobianMatrixFS(Element* element);
 		ElementMatrix* CreateKMatrixFS(Element* element);
-		ElementMatrix* CreateKMatrixFSViscousLATH(Element* element);
-		ElementMatrix* CreateKMatrixFSViscousXTH(Element* element);
-		ElementMatrix* CreateKMatrixFSViscous(Element* element);
 		ElementMatrix* CreateKMatrixFSFriction(Element* element);
 		ElementMatrix* CreateKMatrixFSShelf(Element* element);
+		ElementMatrix* CreateKMatrixFSViscous(Element* element);
+		ElementMatrix* CreateKMatrixFSViscousLA(Element* element);
+		ElementMatrix* CreateKMatrixFSViscousXTH(Element* element);
 		ElementVector* CreatePVectorFS(Element* element);
+		ElementVector* CreatePVectorFSFriction(Element* element);
+		ElementVector* CreatePVectorFSFront(Element* element);
+		ElementVector* CreatePVectorFSShelf(Element* element);
+		ElementVector* CreatePVectorFSStress(Element* element);
 		ElementVector* CreatePVectorFSViscous(Element* element);
-		ElementVector* CreatePVectorFSViscousLATH(Element* element);
+		ElementVector* CreatePVectorFSViscousLA(Element* element);
 		ElementVector* CreatePVectorFSViscousXTH(Element* element);
-		ElementVector* CreatePVectorFSShelf(Element* element);
-		ElementVector* CreatePVectorFSFront(Element* element);
-		ElementVector* CreatePVectorFSFriction(Element* element);
-		ElementVector* CreatePVectorFSStress(Element* element);
-		void GetBFS(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBFSprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBFSvel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBFSprimevel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBFSFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBFSUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBFSprimeUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetCFS(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetCFSprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputsFS(Vector<IssmDouble>* solution,Element* element);
-		void InputUpdateFromSolutionFS(IssmDouble* solution,Element* element);
-		void InputUpdateFromSolutionFSXTH_d(Elements* elements,Parameters* parameters);
-		void InputUpdateFromSolutionFSXTH_tau(Elements* elements,Parameters* parameters);
-		void InitializeXTH(Elements* elements,Parameters* parameters);
+		void           GetBFS(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBFSFriction(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBFSprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBFSprimeUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBFSprimevel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBFSUzawa(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBFSvel(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetCFS(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetCFSprime(IssmDouble* B,Element* element,int dim,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputsFS(Vector<IssmDouble>* solution,Element* element);
+		void           InitializeXTH(Elements* elements,Parameters* parameters);
+		void           InputUpdateFromSolutionFS(IssmDouble* solution,Element* element);
+		void           InputUpdateFromSolutionFSXTH_d(Elements* elements,Parameters* parameters);
+		void           InputUpdateFromSolutionFSXTH_tau(Elements* elements,Parameters* parameters);
 		/*Coupling*/
+		ElementMatrix* CreateKMatrixCouplingHOFS(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAFS(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAFSFriction(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAFSViscous(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAHO(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAHOFriction(Element* element);
+		ElementMatrix* CreateKMatrixCouplingSSAHOViscous(Element* element);
+		ElementMatrix* CreateKMatrixHOFS(Element* element);
+		ElementMatrix* CreateKMatrixSSAFS(Element* element);
+		ElementMatrix* CreateKMatrixSSAHO(Element* element);
 		ElementMatrix* CreateKMatrixSSA3d(Element* element);
 		ElementMatrix* CreateKMatrixSSA3dFriction(Element* element);
 		ElementMatrix* CreateKMatrixSSA3dViscous(Element* element);
-		ElementMatrix* CreateKMatrixHOFS(Element* element);
-		ElementMatrix* CreateKMatrixSSAHO(Element* element);
-		ElementMatrix* CreateKMatrixSSAFS(Element* element);
-		ElementMatrix* CreateKMatrixCouplingHOFS(Element* element);
-		ElementMatrix* CreateKMatrixCouplingSSAHO(Element* element);
-		ElementMatrix* CreateKMatrixCouplingSSAHOFriction(Element* element);
-		ElementMatrix* CreateKMatrixCouplingSSAHOViscous(Element* element);
-		ElementMatrix* CreateKMatrixCouplingSSAFS(Element* element);
-		ElementMatrix* CreateKMatrixCouplingSSAFSFriction(Element* element);
-		ElementMatrix* CreateKMatrixCouplingSSAFSViscous(Element* element);
+		ElementVector* CreatePVectorSSAFS(Element* element);
 		ElementVector* CreatePVectorSSAHO(Element* element);
-		ElementVector* CreatePVectorSSAFS(Element* element);
 		ElementVector* CreatePVectorCouplingSSAFS(Element* element);
 		ElementVector* CreatePVectorCouplingSSAFSFriction(Element* element);
@@ -119,16 +119,16 @@
 		ElementVector* CreatePVectorCouplingHOFSFriction(Element* element);
 		ElementVector* CreatePVectorCouplingHOFSViscous(Element* element);
-		void GetBSSAHO(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBSSAFS(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBprimeSSAFS(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBSSAFSTria(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBprimeSSAFSTria(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetLFSSSA(IssmDouble* L,Element* element,Gauss* gauss);
-		void GetLSSAFS(IssmDouble* L,Element* element,Gauss* gauss);
-		void GetLprimeFSSSA(IssmDouble* Lprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetLprimeSSAFS(IssmDouble* Lprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void InputUpdateFromSolutionHOFS(IssmDouble* solution,Element* element);
-		void InputUpdateFromSolutionSSAFS(IssmDouble* solution,Element* element);
-		void InputUpdateFromSolutionSSAHO(IssmDouble* solution,Element* element);
+		void           GetBprimeSSAFS(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBprimeSSAFSTria(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBSSAFS(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBSSAFSTria(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBSSAHO(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetLFSSSA(IssmDouble* L,Element* element,Gauss* gauss);
+		void           GetLprimeFSSSA(IssmDouble* Lprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetLprimeSSAFS(IssmDouble* Lprime,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetLSSAFS(IssmDouble* L,Element* element,Gauss* gauss);
+		void           InputUpdateFromSolutionHOFS(IssmDouble* solution,Element* element);
+		void           InputUpdateFromSolutionSSAFS(IssmDouble* solution,Element* element);
+		void           InputUpdateFromSolutionSSAHO(IssmDouble* solution,Element* element);
 };
 #endif
Index: /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp	(revision 19105)
@@ -7,86 +7,4 @@
 
 /*Model processing*/
-int  StressbalanceSIAAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
-	return 2;
-}/*}}}*/
-void StressbalanceSIAAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-
-	/*No specific parameters*/
-
-}/*}}}*/
-void StressbalanceSIAAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-
-	/*Fetch data needed: */
-	bool   isSIA;
-	bool   islevelset;
-	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
-	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
-
-	/*Now, is the flag SIA on? otherwise, do nothing: */
-	if (!isSIA)return;
-
-	iomodel->FetchData(1,FlowequationElementEquationEnum);
-
-	/*Update elements: */
-	int counter=0;
-	for(int i=0;i<iomodel->numberofelements;i++){
-		if(iomodel->my_elements[i]){
-			Element* element=(Element*)elements->GetObjectByOffset(counter);
-			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
-			counter++;
-		}
-	}
-
-	iomodel->FetchDataToInput(elements,ThicknessEnum);
-	iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
-	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
-	if(islevelset){
-		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
-		if(iomodel->domaintype!=Domain2DhorizontalEnum)
-			iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum); // required for updating active nodes
-	}
-
-	/*Free data: */
-	iomodel->DeleteData(1,FlowequationElementEquationEnum);
-}/*}}}*/
-void StressbalanceSIAAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	/*Intermediaries*/
-	bool  isSIA;
-	Node* node = NULL;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
-
-	/*Now, is the flag isSIA on? otherwise, do nothing: */
-	if(!isSIA) return;
-
-	/*First create nodes*/
-	int    lid=0;
-	iomodel->FetchData(4,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
-	if(iomodel->domaintype!=Domain2DhorizontalEnum){
-		iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	}
-
-	for(int i=0;i<iomodel->numberofvertices;i++){
-		if(iomodel->my_vertices[i]){
-
-			/*Create new node if is in this processor's partition*/
-			node = new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceSIAAnalysisEnum,reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]));
-
-			/*Deactivate node if not SIA*/
-			if(reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i])!=SIAApproximationEnum){
-				node->Deactivate();
-			}
-
-			/*Add to Nodes dataset*/
-			nodes->AddObject(node);
-		}
-	}
-
-	iomodel->DeleteData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
-				FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
-
-}/*}}}*/
 void StressbalanceSIAAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
 
@@ -142,4 +60,86 @@
 
 	/*No loads*/
+
+}/*}}}*/
+void StressbalanceSIAAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*Intermediaries*/
+	bool  isSIA;
+	Node* node = NULL;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+
+	/*Now, is the flag isSIA on? otherwise, do nothing: */
+	if(!isSIA) return;
+
+	/*First create nodes*/
+	int    lid=0;
+	iomodel->FetchData(4,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	}
+
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
+
+			/*Create new node if is in this processor's partition*/
+			node = new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,StressbalanceSIAAnalysisEnum,reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i]));
+
+			/*Deactivate node if not SIA*/
+			if(reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[i])!=SIAApproximationEnum){
+				node->Deactivate();
+			}
+
+			/*Add to Nodes dataset*/
+			nodes->AddObject(node);
+		}
+	}
+
+	iomodel->DeleteData(6,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+				FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+
+}/*}}}*/
+int  StressbalanceSIAAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 2;
+}/*}}}*/
+void StressbalanceSIAAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*Fetch data needed: */
+	bool   isSIA;
+	bool   islevelset;
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
+
+	/*Now, is the flag SIA on? otherwise, do nothing: */
+	if (!isSIA)return;
+
+	iomodel->FetchData(1,FlowequationElementEquationEnum);
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	if(islevelset){
+		iomodel->FetchDataToInput(elements,IceMaskNodeActivationEnum);
+		if(iomodel->domaintype!=Domain2DhorizontalEnum)
+			iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum); // required for updating active nodes
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(1,FlowequationElementEquationEnum);
+}/*}}}*/
+void StressbalanceSIAAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*No specific parameters*/
 
 }/*}}}*/
@@ -461,5 +461,5 @@
 
 }/*}}}*/
-void StressbalanceSIAAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           StressbalanceSIAAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 
 	IssmDouble vx,vy;
@@ -494,8 +494,8 @@
 	xDelete<IssmDouble>(values);
 }/*}}}*/
-void StressbalanceSIAAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           StressbalanceSIAAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void StressbalanceSIAAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           StressbalanceSIAAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int         i,domaintype;
@@ -581,5 +581,5 @@
 	xDelete<int>(doflist);
 }/*}}}*/
-void StressbalanceSIAAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           StressbalanceSIAAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 
 	bool islevelset;
Index: /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -30,8 +30,8 @@
 		ElementVector* CreatePVector2D(Element* element);
 		ElementVector* CreatePVector3D(Element* element);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp	(revision 19105)
@@ -7,49 +7,4 @@
 
 /*Model processing*/
-int  StressbalanceVerticalAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
-	return 1;
-}/*}}}*/
-void StressbalanceVerticalAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-
-	/*No specific parameters*/
-
-}/*}}}*/
-void StressbalanceVerticalAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
-
-	/*return if not 3d mesh*/
-	if(iomodel->domaintype!=Domain3DEnum) return;
-
-	/*Update elements: */
-	int counter=0;
-	for(int i=0;i<iomodel->numberofelements;i++){
-		if(iomodel->my_elements[i]){
-			Element* element=(Element*)elements->GetObjectByOffset(counter);
-			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
-			counter++;
-		}
-	}
-
-	iomodel->FetchDataToInput(elements,ThicknessEnum);
-	iomodel->FetchDataToInput(elements,SurfaceEnum);
-	iomodel->FetchDataToInput(elements,BaseEnum);
-	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
-	if(iomodel->domaintype!=Domain2DhorizontalEnum){
-		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
-		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
-	}
-	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
-	iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum);
-	iomodel->FetchDataToInput(elements,VxEnum,0.);
-	iomodel->FetchDataToInput(elements,VyEnum,0.);
-}/*}}}*/
-void StressbalanceVerticalAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	/*return if not 3d mesh*/
-	if(iomodel->domaintype!=Domain3DEnum) return;
-
-	iomodel->FetchData(3,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
-	::CreateNodes(nodes,iomodel,StressbalanceVerticalAnalysisEnum,P1Enum);
-	iomodel->DeleteData(3,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
-}/*}}}*/
 void StressbalanceVerticalAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
 
@@ -98,4 +53,49 @@
 
 }/*}}}*/
+void StressbalanceVerticalAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	/*return if not 3d mesh*/
+	if(iomodel->domaintype!=Domain3DEnum) return;
+
+	iomodel->FetchData(3,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	::CreateNodes(nodes,iomodel,StressbalanceVerticalAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+}/*}}}*/
+int  StressbalanceVerticalAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
+	return 1;
+}/*}}}*/
+void StressbalanceVerticalAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
+
+	/*return if not 3d mesh*/
+	if(iomodel->domaintype!=Domain3DEnum) return;
+
+	/*Update elements: */
+	int counter=0;
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			Element* element=(Element*)elements->GetObjectByOffset(counter);
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
+			counter++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BaseEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->domaintype!=Domain2DhorizontalEnum){
+		iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
+		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
+	}
+	iomodel->FetchDataToInput(elements,BasalforcingsGroundediceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsFloatingiceMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,VxEnum,0.);
+	iomodel->FetchDataToInput(elements,VyEnum,0.);
+}/*}}}*/
+void StressbalanceVerticalAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	/*No specific parameters*/
+
+}/*}}}*/
 
 /*Finite Element Analysis*/
@@ -125,4 +125,45 @@
 	return Ke;
 
+}/*}}}*/
+ElementMatrix* StressbalanceVerticalAnalysis::CreateKMatrixSurface(Element* element){/*{{{*/
+
+
+	if(!element->IsOnSurface()) return NULL;
+
+	/*Intermediaries*/
+	IssmDouble  D,Jdet,normal[3];
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke    = element->NewElementMatrix(NoneApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinatesTop(&xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss = element->NewGaussTop(2);
+	element->NormalTop(&normal[0],xyz_list);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantTop(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+		D = -gauss->weight*Jdet*normal[2];
+
+		TripleMultiply( basis,1,numnodes,1,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(basis);
+	return Ke;
 }/*}}}*/
 ElementMatrix* StressbalanceVerticalAnalysis::CreateKMatrixVolume(Element* element){/*{{{*/
@@ -167,45 +208,4 @@
 
 }/*}}}*/
-ElementMatrix* StressbalanceVerticalAnalysis::CreateKMatrixSurface(Element* element){/*{{{*/
-
-
-	if(!element->IsOnSurface()) return NULL;
-
-	/*Intermediaries*/
-	IssmDouble  D,Jdet,normal[3];
-	IssmDouble *xyz_list = NULL;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Initialize Element matrix and vectors*/
-	ElementMatrix* Ke    = element->NewElementMatrix(NoneApproximationEnum);
-	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinatesTop(&xyz_list);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss = element->NewGaussTop(2);
-	element->NormalTop(&normal[0],xyz_list);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminantTop(&Jdet,xyz_list,gauss);
-		element->NodalFunctions(basis,gauss);
-		D = -gauss->weight*Jdet*normal[2];
-
-		TripleMultiply( basis,1,numnodes,1,
-					&D,1,1,0,
-					basis,1,numnodes,0,
-					&Ke->values[0],1);
-	}
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(basis);
-	return Ke;
-}/*}}}*/
 ElementVector* StressbalanceVerticalAnalysis::CreatePVector(Element* element){/*{{{*/
 
@@ -218,56 +218,4 @@
 	delete pe1;
 	delete pe2;
-	return pe;
-}/*}}}*/
-ElementVector* StressbalanceVerticalAnalysis::CreatePVectorVolume(Element* element){/*{{{*/
-
-	/*Intermediaries*/
-	int         approximation;
-	IssmDouble  Jdet,dudx,dvdy,dwdz;
-	IssmDouble  du[3],dv[3],dw[3];
-	IssmDouble* xyz_list = NULL;
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Initialize Element vector and basis functions*/
-	ElementVector* pe    = element->NewElementVector();
-	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
-
-	/*Retrieve all inputs and parameters*/
-	element->GetVerticesCoordinates(&xyz_list);
-	element->GetInputValue(&approximation,ApproximationEnum);
-	Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
-	Input* vy_input=element->GetInput(VyEnum); _assert_(vy_input);
-	Input* vzFS_input=NULL;
-	if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
-		vzFS_input=element->GetInput(VzFSEnum); _assert_(vzFS_input);
-	}
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGauss(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		element->NodalFunctions(basis,gauss);
-
-		vx_input->GetInputDerivativeValue(&du[0],xyz_list,gauss);
-		vy_input->GetInputDerivativeValue(&dv[0],xyz_list,gauss);
-		if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
-			vzFS_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
-			dwdz=dw[2];
-		}
-		else dwdz=0;
-		dudx=du[0];
-		dvdy=dv[1];
-
-		for(int i=0;i<numnodes;i++) pe->values[i] += (dudx+dvdy+dwdz)*Jdet*gauss->weight*basis[i];
-	}
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<IssmDouble>(basis);
-	xDelete<IssmDouble>(xyz_list);
 	return pe;
 }/*}}}*/
@@ -338,5 +286,57 @@
 	return pe;
 }/*}}}*/
-void StressbalanceVerticalAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+ElementVector* StressbalanceVerticalAnalysis::CreatePVectorVolume(Element* element){/*{{{*/
+
+	/*Intermediaries*/
+	int         approximation;
+	IssmDouble  Jdet,dudx,dvdy,dwdz;
+	IssmDouble  du[3],dv[3],dw[3];
+	IssmDouble* xyz_list = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = element->GetNumberOfNodes();
+
+	/*Initialize Element vector and basis functions*/
+	ElementVector* pe    = element->NewElementVector();
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	element->GetVerticesCoordinates(&xyz_list);
+	element->GetInputValue(&approximation,ApproximationEnum);
+	Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=element->GetInput(VyEnum); _assert_(vy_input);
+	Input* vzFS_input=NULL;
+	if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+		vzFS_input=element->GetInput(VzFSEnum); _assert_(vzFS_input);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		vx_input->GetInputDerivativeValue(&du[0],xyz_list,gauss);
+		vy_input->GetInputDerivativeValue(&dv[0],xyz_list,gauss);
+		if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+			vzFS_input->GetInputDerivativeValue(&dw[0],xyz_list,gauss);
+			dwdz=dw[2];
+		}
+		else dwdz=0;
+		dudx=du[0];
+		dvdy=dv[1];
+
+		for(int i=0;i<numnodes;i++) pe->values[i] += (dudx+dvdy+dwdz)*Jdet*gauss->weight*basis[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list);
+	return pe;
+}/*}}}*/
+void           StressbalanceVerticalAnalysis::GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*	Compute B  matrix. B=[dh1/dz dh2/dz dh3/dz dh4/dz dh5/dz dh6/dz];
 		where hi is the interpolation function for node i.*/
@@ -357,16 +357,16 @@
 	xDelete<IssmDouble>(dbasis);
 }/*}}}*/
-void StressbalanceVerticalAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void           StressbalanceVerticalAnalysis::GetBprime(IssmDouble* Bprime,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 
 	element->NodalFunctions(Bprime,gauss);
 
 }/*}}}*/
-void StressbalanceVerticalAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           StressbalanceVerticalAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	element->GetSolutionFromInputsOneDof(solution,VzEnum);
 }/*}}}*/
-void StressbalanceVerticalAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           StressbalanceVerticalAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void StressbalanceVerticalAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           StressbalanceVerticalAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int          numnodes = element->GetNumberOfNodes();
@@ -481,5 +481,5 @@
 	xDelete<int>(doflist);
 }/*}}}*/
-void StressbalanceVerticalAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           StressbalanceVerticalAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -25,15 +25,15 @@
 		ElementMatrix* CreateJacobianMatrix(Element* element);
 		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixSurface(Element* element);
 		ElementMatrix* CreateKMatrixVolume(Element* element);
-		ElementMatrix* CreateKMatrixSurface(Element* element);
 		ElementVector* CreatePVector(Element* element);
+		ElementVector* CreatePVectorBase(Element* element);
 		ElementVector* CreatePVectorVolume(Element* element);
-		ElementVector* CreatePVectorBase(Element* element);
-		void GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetB(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/ThermalAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ThermalAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/ThermalAnalysis.cpp	(revision 19105)
@@ -6,26 +6,42 @@
 
 /*Model processing*/
+void ThermalAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+
+	/*Only 3d mesh supported*/
+	int finiteelement = P1Enum;
+	if(iomodel->domaintype==Domain3DEnum){
+		IoModelToConstraintsx(constraints,iomodel,ThermalSpctemperatureEnum,ThermalAnalysisEnum,finiteelement);
+	}
+
+}/*}}}*/
+void ThermalAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+
+	if(iomodel->domaintype==Domain2DhorizontalEnum) _error_("2d meshes not supported yet");
+
+	/*create penalties for nodes: no node can have a temperature over the melting point*/
+	iomodel->FetchData(1,ThermalSpctemperatureEnum);
+	CreateSingleNodeToElementConnectivity(iomodel);
+
+	for(int i=0;i<iomodel->numberofvertices;i++){
+
+		/*keep only this partition's nodes:*/
+		if(iomodel->my_vertices[i]){
+			if (xIsNan<IssmDouble>(iomodel->Data(ThermalSpctemperatureEnum)[i])){ //No penalty applied on spc nodes!
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,ThermalAnalysisEnum));
+			}
+		}
+	}
+	iomodel->DeleteData(1,ThermalSpctemperatureEnum);
+
+}/*}}}*/
+void ThermalAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int finiteelement = P1Enum;
+	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+	::CreateNodes(nodes,iomodel,ThermalAnalysisEnum,finiteelement);
+	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
+}/*}}}*/
 int  ThermalAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
-}/*}}}*/
-void ThermalAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-
-	int     numoutputs;
-	char**  requestedoutputs = NULL;
-
-	parameters->AddObject(iomodel->CopyConstantObject(ThermalMaxiterEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(ThermalStabilizationEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyFactorEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyThresholdEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyLockEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsenthalpyEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsdynamicbasalspcEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(FrictionLawEnum));
-
-	iomodel->FetchData(&requestedoutputs,&numoutputs,ThermalRequestedOutputsEnum);
-	parameters->AddObject(new IntParam(ThermalNumRequestedOutputsEnum,numoutputs));
-	if(numoutputs)parameters->AddObject(new StringArrayParam(ThermalRequestedOutputsEnum,requestedoutputs,numoutputs));
-	iomodel->DeleteData(&requestedoutputs,numoutputs,ThermalRequestedOutputsEnum);
-
 }/*}}}*/
 void ThermalAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
@@ -61,5 +77,4 @@
 		iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
 	}
-	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
 	iomodel->FetchDataToInput(elements,MeshVertexonbaseEnum);
 	iomodel->FetchDataToInput(elements,MeshVertexonsurfaceEnum);
@@ -90,43 +105,56 @@
 			iomodel->FetchDataToInput(elements,FrictionMEnum);
 			break;
+		case 3:
+			iomodel->FetchDataToInput(elements,FrictionCEnum);
+			iomodel->FetchDataToInput(elements,FrictionAsEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			iomodel->FetchDataToInput(elements,FrictionEffectivePressureEnum);
+			break;
+		case 4:
+			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,FrictionPEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			iomodel->FetchDataToInput(elements,PressureEnum);
+			iomodel->FetchDataToInput(elements,TemperatureEnum);
+			break;
+		case 5:
+			iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+			iomodel->FetchDataToInput(elements,FrictionPEnum);
+			iomodel->FetchDataToInput(elements,FrictionQEnum);
+			iomodel->FetchDataToInput(elements,FrictionWaterLayerEnum);
+			break;
+		case 6:
+			iomodel->FetchDataToInput(elements,FrictionCEnum);
+			iomodel->FetchDataToInput(elements,FrictionMEnum);
+			iomodel->FetchDataToInput(elements,PressureEnum);
+			iomodel->FetchDataToInput(elements,TemperatureEnum);
+			break;
 		default:
 			_error_("not supported");
 	}
 }/*}}}*/
-void ThermalAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	int finiteelement = P1Enum;
-	if(iomodel->domaintype==Domain3DEnum) iomodel->FetchData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-	::CreateNodes(nodes,iomodel,ThermalAnalysisEnum,finiteelement);
-	iomodel->DeleteData(2,MeshVertexonbaseEnum,MeshVertexonsurfaceEnum);
-}/*}}}*/
-void ThermalAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-
-	/*Only 3d mesh supported*/
-	int finiteelement = P1Enum;
-	if(iomodel->domaintype==Domain3DEnum){
-		IoModelToConstraintsx(constraints,iomodel,ThermalSpctemperatureEnum,ThermalAnalysisEnum,finiteelement);
-	}
-
-}/*}}}*/
-void ThermalAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-
-	if(iomodel->domaintype==Domain2DhorizontalEnum) _error_("2d meshes not supported yet");
-
-	/*create penalties for nodes: no node can have a temperature over the melting point*/
-	iomodel->FetchData(1,ThermalSpctemperatureEnum);
-	CreateSingleNodeToElementConnectivity(iomodel);
-
-	for(int i=0;i<iomodel->numberofvertices;i++){
-
-		/*keep only this partition's nodes:*/
-		if(iomodel->my_vertices[i]){
-			if (xIsNan<IssmDouble>(iomodel->Data(ThermalSpctemperatureEnum)[i])){ //No penalty applied on spc nodes!
-				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,ThermalAnalysisEnum));
-			}
-		}
-	}
-	iomodel->DeleteData(1,ThermalSpctemperatureEnum);
-
+void ThermalAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	int     numoutputs;
+	char**  requestedoutputs = NULL;
+
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalStabilizationEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyFactorEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyThresholdEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyLockEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsenthalpyEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(ThermalIsdynamicbasalspcEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FrictionLawEnum));
+
+	iomodel->FetchData(&requestedoutputs,&numoutputs,ThermalRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(ThermalNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new StringArrayParam(ThermalRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(&requestedoutputs,numoutputs,ThermalRequestedOutputsEnum);
+
+	/*Deal with friction parameters*/
+	int frictionlaw;
+	iomodel->Constant(&frictionlaw,FrictionLawEnum);
+	if(frictionlaw==4 || frictionlaw==6) parameters->AddObject(iomodel->CopyConstantObject(FrictionGammaEnum));
 }/*}}}*/
 
@@ -155,4 +183,58 @@
 	delete Ke1;
 	delete Ke2;
+	return Ke;
+}/*}}}*/
+ElementMatrix* ThermalAnalysis::CreateKMatrixShelf(Element* element){/*{{{*/
+
+	/* Check if ice in element */
+	if(!element->IsIceInElement()) return NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
+
+	IssmDouble  dt,Jdet,D;
+	IssmDouble *xyz_list_base = NULL;
+
+	/*Get basal element*/
+	if(!element->IsOnBase() || !element->IsFloating()) 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->GetMaterialParameter(ConstantsGEnum);
+	IssmDouble  rho_water           = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+	IssmDouble  mixed_layer_capacity= element->GetMaterialParameter(MaterialsMixedLayerCapacityEnum);
+	IssmDouble  thermal_exchange_vel= element->GetMaterialParameter(MaterialsThermalExchangeVelocityEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		element->JacobianDeterminantBase(&Jdet,xyz_list_base,gauss);
+		element->NodalFunctions(basis,gauss);
+
+		D=gauss->weight*Jdet*rho_water*mixed_layer_capacity*thermal_exchange_vel/(heatcapacity*rho_ice);
+		if(reCast<bool,IssmDouble>(dt)) D=dt*D;
+		TripleMultiply(basis,numnodes,1,0,
+					&D,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(xyz_list_base);
 	return Ke;
 }/*}}}*/
@@ -290,23 +372,38 @@
 	return Ke;
 }/*}}}*/
-ElementMatrix* ThermalAnalysis::CreateKMatrixShelf(Element* element){/*{{{*/
-
+ElementVector* ThermalAnalysis::CreatePVector(Element* element){/*{{{*/
+	
 	/* Check if ice in element */
 	if(!element->IsIceInElement()) return NULL;
 
-	/*Initialize Element matrix and return if necessary*/
-	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
-
-	IssmDouble  dt,Jdet,D;
+	/*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* ThermalAnalysis::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->IsFloating()) return NULL;
+
+	IssmDouble  dt,Jdet,geothermalflux,vx,vy,vz;
+	IssmDouble  alpha2,scalar,basalfriction,heatflux;
 	IssmDouble *xyz_list_base = NULL;
 
-	/*Get basal element*/
-	if(!element->IsOnBase() || !element->IsFloating()) return NULL;
-
 	/*Fetch number of nodes for this finite element*/
 	int numnodes = element->GetNumberOfNodes();
 
 	/*Initialize vectors*/
-	ElementMatrix* Ke    = element->NewElementMatrix();
+	ElementVector* pe    = element->NewElementVector();
 	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
 
@@ -314,4 +411,66 @@
 	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->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
+
+	/*Build friction element, needed later: */
+	Friction* friction=new Friction(element,3);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss   = element->NewGaussBase(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		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* ThermalAnalysis::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->IsFloating()) 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->GetMaterialParameter(ConstantsGEnum);
 	IssmDouble  rho_water           = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
@@ -329,11 +488,11 @@
 		element->NodalFunctions(basis,gauss);
 
-		D=gauss->weight*Jdet*rho_water*mixed_layer_capacity*thermal_exchange_vel/(heatcapacity*rho_ice);
-		if(reCast<bool,IssmDouble>(dt)) D=dt*D;
-		TripleMultiply(basis,numnodes,1,0,
-					&D,1,1,0,
-					basis,1,numnodes,0,
-					&Ke->values[0],1);
-
+		pressure_input->GetInputValue(&pressure,gauss);
+		t_pmp=element->TMeltingPoint(pressure);
+
+		scalar_ocean=gauss->weight*Jdet*rho_water*mixed_layer_capacity*thermal_exchange_vel*(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];
 	}
 
@@ -342,21 +501,4 @@
 	xDelete<IssmDouble>(basis);
 	xDelete<IssmDouble>(xyz_list_base);
-	return Ke;
-}/*}}}*/
-ElementVector* ThermalAnalysis::CreatePVector(Element* element){/*{{{*/
-	
-	/* 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;
 }/*}}}*/
@@ -443,122 +585,63 @@
 
 }/*}}}*/
-ElementVector* ThermalAnalysis::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->IsFloating()) return NULL;
-
-	IssmDouble  dt,Jdet,geothermalflux,vx,vy,vz;
-	IssmDouble  alpha2,scalar,basalfriction,heatflux;
-	IssmDouble *xyz_list_base = NULL;
+void           ThermalAnalysis::GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Bi_advec =[ h ]
+	 *                 [ h ]
+	 *                 [ h ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
+	 */
 
 	/*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->GetMaterialParameter(MaterialsRhoIceEnum);
-	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
-
-	/*Build friction element, needed later: */
-	Friction* friction=new Friction(element,3);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss   = element->NewGaussBase(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		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;
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	element->NodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
+		B[numnodes*2+i] = basis[i];
+	}
+
+	/*Clean-up*/
 	xDelete<IssmDouble>(basis);
-	xDelete<IssmDouble>(xyz_list_base);
-	return pe;
-}/*}}}*/
-ElementVector* ThermalAnalysis::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->IsFloating()) return NULL;
+}/*}}}*/
+void           ThermalAnalysis::GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
+	 * For node i, Bi' can be expressed in the actual coordinate system
+	 * by: 
+	 *       Biprime_advec=[ dh/dx ]
+	 *                     [ dh/dy ]
+	 *                     [ dh/dz ]
+	 * where h is the interpolation function for node i.
+	 *
+	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
+	 */
 
 	/*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->GetMaterialParameter(ConstantsGEnum);
-	IssmDouble  rho_water           = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
-	IssmDouble  rho_ice             = element->GetMaterialParameter(MaterialsRhoIceEnum);
-	IssmDouble  heatcapacity        = element->GetMaterialParameter(MaterialsHeatcapacityEnum);
-	IssmDouble  mixed_layer_capacity= element->GetMaterialParameter(MaterialsMixedLayerCapacityEnum);
-	IssmDouble  thermal_exchange_vel= element->GetMaterialParameter(MaterialsThermalExchangeVelocityEnum);
-
-	/* Start  looping on the number of gaussian points: */
-	Gauss* gauss=element->NewGaussBase(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		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*thermal_exchange_vel*(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;
-}/*}}}*/
-void ThermalAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
-	element->GetSolutionFromInputsOneDof(solution,TemperatureEnum);
-}/*}}}*/
-void ThermalAnalysis::GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = dbasis[0*numnodes+i];
+		B[numnodes*1+i] = dbasis[1*numnodes+i];
+		B[numnodes*2+i] = dbasis[2*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}/*}}}*/
+void           ThermalAnalysis::GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
 	 * For node i, Bi' can be expressed in the actual coordinate system
@@ -589,66 +672,11 @@
 	xDelete<IssmDouble>(dbasis);
 }/*}}}*/
-void ThermalAnalysis::GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
-	 * For node i, Bi' can be expressed in the actual coordinate system
-	 * by: 
-	 *       Bi_advec =[ h ]
-	 *                 [ h ]
-	 *                 [ h ]
-	 * where h is the interpolation function for node i.
-	 *
-	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions*/
-	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	element->NodalFunctions(basis,gauss);
-
-	/*Build B: */
-	for(int i=0;i<numnodes;i++){
-		B[numnodes*0+i] = basis[i];
-		B[numnodes*1+i] = basis[i];
-		B[numnodes*2+i] = basis[i];
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(basis);
-}/*}}}*/
-void ThermalAnalysis::GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 5*NDOF1. 
-	 * For node i, Bi' can be expressed in the actual coordinate system
-	 * by: 
-	 *       Biprime_advec=[ dh/dx ]
-	 *                     [ dh/dy ]
-	 *                     [ dh/dz ]
-	 * where h is the interpolation function for node i.
-	 *
-	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
-	 */
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = element->GetNumberOfNodes();
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
-	element->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
-
-	/*Build B: */
-	for(int i=0;i<numnodes;i++){
-		B[numnodes*0+i] = dbasis[0*numnodes+i];
-		B[numnodes*1+i] = dbasis[1*numnodes+i];
-		B[numnodes*2+i] = dbasis[2*numnodes+i];
-	}
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(dbasis);
-}/*}}}*/
-void ThermalAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           ThermalAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+	element->GetSolutionFromInputsOneDof(solution,TemperatureEnum);
+}/*}}}*/
+void           ThermalAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void ThermalAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           ThermalAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	bool        converged;
@@ -730,5 +758,5 @@
 	xDelete<int>(doflist);
 }/*}}}*/
-void ThermalAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           ThermalAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 
 	bool islevelset;
Index: /issm/trunk/src/c/analyses/ThermalAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/ThermalAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/ThermalAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -25,17 +25,17 @@
 		ElementMatrix* CreateJacobianMatrix(Element* element);
 		ElementMatrix* CreateKMatrix(Element* element);
+		ElementMatrix* CreateKMatrixShelf(Element* element);
 		ElementMatrix* CreateKMatrixVolume(Element* element);
-		ElementMatrix* CreateKMatrixShelf(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		ElementVector* CreatePVectorVolume(Element* element);
 		ElementVector* CreatePVectorSheet(Element* element);
 		ElementVector* CreatePVectorShelf(Element* element);
-		void GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		ElementVector* CreatePVectorVolume(Element* element);
+		void           GetBAdvec(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBAdvecprime(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetBConduct(IssmDouble* B,Element* element,IssmDouble* xyz_list,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/UzawaPressureAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/analyses/UzawaPressureAnalysis.cpp	(revision 19104)
+++ /issm/trunk/src/c/analyses/UzawaPressureAnalysis.cpp	(revision 19105)
@@ -6,17 +6,37 @@
 
 /*Model processing*/
+void UzawaPressureAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
+	return;
+}/*}}}*/
+void UzawaPressureAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
+	return;
+}/*}}}*/
+void UzawaPressureAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
+
+	int finiteelement;
+	int fe_FS;
+
+	iomodel->Constant(&fe_FS,FlowequationFeFSEnum);
+	if(fe_FS==LATaylorHoodEnum) finiteelement = P1Enum;
+	else if(fe_FS==LACrouzeixRaviartEnum) finiteelement = P1DGEnum;
+	else _error_("solution not supported yet");
+
+	::CreateNodes(nodes,iomodel,UzawaPressureAnalysisEnum,finiteelement);
+}/*}}}*/
 int  UzawaPressureAnalysis::DofsPerNode(int** doflist,int domaintype,int approximation){/*{{{*/
 	return 1;
 }/*}}}*/
-void UzawaPressureAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
-
-	parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianRhopEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianRholambdaEnum));
-}/*}}}*/
 void UzawaPressureAnalysis::UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type){/*{{{*/
 
 	/*Update elements: */
-	int finiteelement = P1Enum;
+	int finiteelement;
 	int counter=0;
+	int fe_FS;
+
+	iomodel->Constant(&fe_FS,FlowequationFeFSEnum);
+	if(fe_FS==LATaylorHoodEnum) finiteelement = P1Enum;
+	else if(fe_FS==LACrouzeixRaviartEnum) finiteelement = P1DGEnum;
+	else _error_("solution not supported yet");
+
 	for(int i=0;i<iomodel->numberofelements;i++){
 		if(iomodel->my_elements[i]){
@@ -33,14 +53,8 @@
 	InputUpdateFromConstantx(elements,0.,SigmaNNEnum);
 }/*}}}*/
-void UzawaPressureAnalysis::CreateNodes(Nodes* nodes,IoModel* iomodel){/*{{{*/
-
-	int finiteelement = P1Enum;
-	::CreateNodes(nodes,iomodel,UzawaPressureAnalysisEnum,finiteelement);
-}/*}}}*/
-void UzawaPressureAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
-	return;
-}/*}}}*/
-void UzawaPressureAnalysis::CreateLoads(Loads* loads, IoModel* iomodel){/*{{{*/
-	return;
+void UzawaPressureAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
+
+	parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianRhopEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(AugmentedLagrangianRholambdaEnum));
 }/*}}}*/
 
@@ -67,22 +81,29 @@
 	IssmDouble*    M    = xNew<IssmDouble>(numnodes);
 
+	IssmDouble connectivity;
 	/*Retrieve all inputs and parameters*/
 	element->GetVerticesCoordinates(&xyz_list);
-
-	Gauss* gauss = element->NewGauss(5);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-		gauss->GaussPoint(ig);
-
-		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-		this->GetM(M,element,gauss);
-		D_scalar=gauss->weight*Jdet;
-		TripleMultiply(M,1,numnodes,1,
-					&D_scalar,1,1,0,
-					M,1,numnodes,0,
-					&Ke->values[0],1);
+	int numvertices = element->GetNumberOfVertices();
+
+	//Gauss* gauss = element->NewGauss(5);
+	//for(int ig=gauss->begin();ig<gauss->end();ig++){
+	//	gauss->GaussPoint(ig);
+
+	//	element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+	//	this->GetM(M,element,gauss);
+	//	D_scalar=gauss->weight*Jdet;
+	//	//TripleMultiply(M,1,numnodes,1,
+	//	//			&D_scalar,1,1,0,
+	//	//			M,1,numnodes,0,
+	//	//			&Ke->values[0],1);
+
+	//}
+	for(int iv=0;iv<numvertices;iv++){
+		connectivity=(IssmDouble)element->VertexConnectivity(iv);
+		Ke->values[iv*numvertices+iv]=1./connectivity;
 	}
 
 	/*Clean up and return*/
-	delete gauss;
+	//delete gauss;
 	xDelete<IssmDouble>(xyz_list);
 	xDelete<IssmDouble>(M);
@@ -143,5 +164,5 @@
 	return pe;
 }/*}}}*/
-void UzawaPressureAnalysis::GetM(IssmDouble* M,Element* element,Gauss* gauss){/*{{{*/
+void           UzawaPressureAnalysis::GetM(IssmDouble* M,Element* element,Gauss* gauss){/*{{{*/
 	/*Compute B  matrix. M=[M1 M2 M3] */
 
@@ -161,11 +182,11 @@
 	xDelete<IssmDouble>(basis);
 }/*}}}*/
-void UzawaPressureAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
+void           UzawaPressureAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
 	_error_("not implemented yet");
 }/*}}}*/
-void UzawaPressureAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
+void           UzawaPressureAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index){/*{{{*/
 	_error_("Not implemented yet");
 }/*}}}*/
-void UzawaPressureAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
+void           UzawaPressureAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/
 
 	int        dim;
@@ -176,5 +197,8 @@
 	/*Fetch number of nodes and dof for this finite element*/
 	int numnodes      = element->GetNumberOfNodes();
-	int numnodessigma = element->GetNumberOfNodes(P2Enum);
+	int numnodessigma;
+	if(element->element_type==P1Enum) numnodessigma=element->GetNumberOfNodes(P2Enum);
+	else if(element->element_type==P1DGEnum) numnodessigma=element->GetNumberOfNodes(P2Enum);
+	else _error_("finite element not supported yet");
 
 	element->FindParam(&dim,DomainDimensionEnum);
@@ -185,5 +209,4 @@
 	IssmDouble* valueslambda  = xNewZeroInit<IssmDouble>(numnodessigma);
 	IssmDouble* pressure      = xNew<IssmDouble>(numnodes);
-	Input* sigmann_input      = element->GetInput(SigmaNNEnum); _assert_(sigmann_input);
 	Input* vx_input           = element->GetInput(VxEnum);      _assert_(vx_input);
 	Input* vy_input           = element->GetInput(VyEnum);      _assert_(vy_input);
@@ -199,5 +222,6 @@
 
 	/*Now compute sigmann if on base*/
-	if(element->IsOnBase()){ 
+	if(element->IsOnBase() && 0){ 
+		Input* sigmann_input      = element->GetInput(SigmaNNEnum); _assert_(sigmann_input);
 		if(dim==3) _error_("not implemented yet");
 
@@ -263,6 +287,7 @@
 		xDelete<IssmDouble>(xyz_list_base);
 		xDelete<IssmDouble>(basis);
-	}
-	element->AddInput(SigmaNNEnum,valueslambda,P2Enum);
+
+		element->AddInput(SigmaNNEnum,valueslambda,P2Enum);
+	}
 
 	/*Free ressources:*/
@@ -272,5 +297,5 @@
 	xDelete<int>(doflist);
 }/*}}}*/
-void UzawaPressureAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
+void           UzawaPressureAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
 	/*Default, do nothing*/
 	return;
Index: /issm/trunk/src/c/analyses/UzawaPressureAnalysis.h
===================================================================
--- /issm/trunk/src/c/analyses/UzawaPressureAnalysis.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/UzawaPressureAnalysis.h	(revision 19105)
@@ -13,10 +13,10 @@
 	public:
 		/*Model processing*/
-		int  DofsPerNode(int** doflist,int domaintype,int approximation);
-		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
-		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-		void CreateNodes(Nodes* nodes,IoModel* iomodel);
 		void CreateConstraints(Constraints* constraints,IoModel* iomodel);
 		void CreateLoads(Loads* loads, IoModel* iomodel);
+		void CreateNodes(Nodes* nodes,IoModel* iomodel);
+		int  DofsPerNode(int** doflist,int domaintype,int approximation);
+		void UpdateElements(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+		void UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum);
 
 		/*Finite element Analysis*/
@@ -26,9 +26,9 @@
 		ElementMatrix* CreateKMatrix(Element* element);
 		ElementVector* CreatePVector(Element* element);
-		void GetM(IssmDouble* M,Element* element,Gauss* gauss);
-		void GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
-		void GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
-		void InputUpdateFromSolution(IssmDouble* solution,Element* element);
-		void UpdateConstraints(FemModel* femmodel);
+		void           GetM(IssmDouble* M,Element* element,Gauss* gauss);
+		void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
+		void           GradientJ(Vector<IssmDouble>* gradient,Element* element,int control_type,int control_index);
+		void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
+		void           UpdateConstraints(FemModel* femmodel);
 };
 #endif
Index: /issm/trunk/src/c/analyses/analyses.h
===================================================================
--- /issm/trunk/src/c/analyses/analyses.h	(revision 19104)
+++ /issm/trunk/src/c/analyses/analyses.h	(revision 19105)
@@ -32,6 +32,5 @@
 #include "./MeltingAnalysis.h"
 #include "./MeshdeformationAnalysis.h"
-#include "./SmoothedSurfaceSlopeXAnalysis.h"
-#include "./SmoothedSurfaceSlopeYAnalysis.h"
+#include "./SmoothAnalysis.h"
 #include "./StressbalanceAnalysis.h"
 #include "./StressbalanceSIAAnalysis.h"
Index: /issm/trunk/src/c/bamg/BamgMesh.cpp
===================================================================
--- /issm/trunk/src/c/bamg/BamgMesh.cpp	(revision 19104)
+++ /issm/trunk/src/c/bamg/BamgMesh.cpp	(revision 19105)
@@ -5,5 +5,5 @@
 BamgMesh::BamgMesh(){/*{{{*/
 
-	this->VerticesSize[0]=0,                  this->VerticesSize[1]=0;                 this->Vertices=NULL;
+	this->VerticesSize[0]=0,                  this->VerticesSize[1]=0;                 this->Vertices=NULL;          this->PreviousNumbering = NULL;
 	this->EdgesSize[0]=0,                     this->EdgesSize[1]=0;                    this->Edges=NULL;
 	this->TrianglesSize[0]=0,                 this->TrianglesSize[1]=0;                this->Triangles=NULL;
@@ -30,4 +30,5 @@
 
 	xDelete<double>(this->Vertices);
+	xDelete<double>(this->PreviousNumbering);
 	xDelete<double>(this->Edges);
 	xDelete<double>(this->Triangles);
Index: /issm/trunk/src/c/bamg/BamgMesh.h
===================================================================
--- /issm/trunk/src/c/bamg/BamgMesh.h	(revision 19104)
+++ /issm/trunk/src/c/bamg/BamgMesh.h	(revision 19105)
@@ -11,4 +11,5 @@
 		int     VerticesSize[2];
 		double* Vertices;
+		double* PreviousNumbering;
 		int     EdgesSize[2];
 		double* Edges;
Index: /issm/trunk/src/c/bamg/BamgVertex.cpp
===================================================================
--- /issm/trunk/src/c/bamg/BamgVertex.cpp	(revision 19104)
+++ /issm/trunk/src/c/bamg/BamgVertex.cpp	(revision 19105)
@@ -10,4 +10,9 @@
 namespace bamg {
 
+	/*Constructor/Destructor*/
+	BamgVertex::BamgVertex(){ /*{{{*/
+		this->PreviousNumber = 0;
+	}/*}}}*/
+
 	/*Methods*/
 	void BamgVertex::Echo(void){/*{{{*/
@@ -17,4 +22,5 @@
 		_printf_("  Euclidean coordinates r.x: " << r.x << ", r.y: " << r.y << "\n");
 		_printf_("  ReferenceNumber = " << ReferenceNumber << "\n");
+		_printf_("  PreviousNumber  = " << PreviousNumber << "\n");
 		m.Echo();
 
Index: /issm/trunk/src/c/bamg/BamgVertex.h
===================================================================
--- /issm/trunk/src/c/bamg/BamgVertex.h	(revision 19104)
+++ /issm/trunk/src/c/bamg/BamgVertex.h	(revision 19105)
@@ -23,4 +23,5 @@
 			Metric    m;
 			long      ReferenceNumber;
+			long      PreviousNumber;
 			Direction DirOfSearch;
 			short     IndexInTriangle;              // the vertex number in triangle; varies between 0 and 2 in t
@@ -42,4 +43,5 @@
 
 			/*methods (No constructor and no destructors...)*/
+			BamgVertex();
 			double Smoothing(Mesh & ,const Mesh & ,Triangle  * & ,double =1);
 			void   MetricFromHessian(const double Hxx,const double Hyx, const double Hyy, const double smin,const double smax,const double s,const double err,BamgOpts* bamgopts);
Index: /issm/trunk/src/c/bamg/Mesh.cpp
===================================================================
--- /issm/trunk/src/c/bamg/Mesh.cpp	(revision 19104)
+++ /issm/trunk/src/c/bamg/Mesh.cpp	(revision 19105)
@@ -227,20 +227,20 @@
 		/*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, Mesh2.cpp/Triangles)*/
 
-		//if (vertices)             delete [] vertices;
-		if (edges)                delete [] edges;
-		if (triangles)            delete [] triangles;
-		if (quadtree)             delete    quadtree;
-		//if (orderedvertices)                delete [] orderedvertices;
-		if (subdomains)           delete []  subdomains;
-		if (VerticesOnGeomEdge)   delete [] VerticesOnGeomEdge;
-		if (VerticesOnGeomVertex) delete [] VerticesOnGeomVertex;
-		if (VertexOnBThVertex)    delete [] VertexOnBThVertex;
-		if (VertexOnBThEdge)      delete [] VertexOnBThEdge;
-
-		if (&Gh) {
+		if(vertices)             delete [] vertices;
+		if(edges)                delete [] edges;
+		if(triangles)            delete [] triangles;
+		if(quadtree)             delete    quadtree;
+		if(orderedvertices)      delete [] orderedvertices;
+		if(subdomains)           delete []  subdomains;
+		if(VerticesOnGeomEdge)   delete [] VerticesOnGeomEdge;
+		if(VerticesOnGeomVertex) delete [] VerticesOnGeomVertex;
+		if(VertexOnBThVertex)    delete [] VertexOnBThVertex;
+		if(VertexOnBThEdge)      delete [] VertexOnBThEdge;
+
+		if(&Gh){
 			if (Gh.NbRef>0) Gh.NbRef--;
 			else if (Gh.NbRef==0) delete &Gh;
 		}
-		if (&BTh && (&BTh != this)) {
+		if(&BTh && (&BTh != this)){
 			if (BTh.NbRef>0) BTh.NbRef--;
 			else if (BTh.NbRef==0) delete &BTh;
@@ -571,10 +571,12 @@
 		bamgmesh->VerticesSize[0]=nbv;
 		bamgmesh->VerticesSize[1]=3;
-		if (nbv){
+		if(nbv){
 			bamgmesh->Vertices=xNew<double>(3*nbv);
+			bamgmesh->PreviousNumbering=xNew<double>(nbv);
 			for (i=0;i<nbv;i++){
 				bamgmesh->Vertices[i*3+0]=vertices[i].r.x;
 				bamgmesh->Vertices[i*3+1]=vertices[i].r.y;
 				bamgmesh->Vertices[i*3+2]=vertices[i].GetReferenceNumber();
+				bamgmesh->PreviousNumbering[i]=vertices[i].PreviousNumber;
 			}
 		}
@@ -2726,5 +2728,5 @@
 
 		/*Allocate if maxnbv_in>0*/
-		if (maxnbv_in) {
+		if(maxnbv_in){
 			vertices=new BamgVertex[maxnbv];
 			_assert_(vertices);
@@ -2734,5 +2736,5 @@
 			_assert_(triangles);
 		}
-		else {
+		else{
 			vertices=NULL;
 			orderedvertices=NULL;
@@ -2907,5 +2909,5 @@
 		// for all the new point
 		long iv=nbvold;
-		for (i=nbvold;i<nbv;i++){
+		for(i=nbvold;i<nbv;i++){
 			BamgVertex &vi=*orderedvertices[i];
 			vi.i=R2ToI2(vi.r);
@@ -2914,5 +2916,5 @@
 			vi.m.Box(hx,hy);
 			Icoor1 hi=(Icoor1) (hx*coefIcoor),hj=(Icoor1) (hy*coefIcoor);
-			if (!quadtree->ToClose(vi,seuil,hi,hj)){
+			if(!quadtree->ToClose(vi,seuil,hi,hj)){
 				// a good new point 
 				BamgVertex &vj = vertices[iv];
@@ -2928,4 +2930,7 @@
 				Triangle *tcvj=TriangleFindFromCoord(vj.i,det3);
 				if (tcvj && !tcvj->link){
+					_printf_("While trying to add the following point:\n");
+					vj.Echo();
+					_printf_("BAMG determined that it was inside the following triangle, which probably lies outside of the geometric domain\n");
 					tcvj->Echo();
 					_error_("problem inserting point in InsertNewPoints (tcvj=" << tcvj << " and tcvj->link=" << tcvj->link << ")");
@@ -2935,4 +2940,7 @@
 				NbSwap += vj.Optim(1);          
 				iv++;
+			}
+			else{
+				vi.PreviousNumber = 0;
 			}
 		} 
@@ -3141,16 +3149,36 @@
 
 		/*First, insert old points if requested*/
-		if (KeepVertices && (&Bh != this) && (nbv+Bh.nbv< maxnbv)){
+		if(KeepVertices && (&Bh != this) && (nbv+Bh.nbv< maxnbv)){
 			if (verbose>5) _printf_("         Inserting initial mesh points\n");
-			for (i=0;i<Bh.nbv;i++){ 
+			bool pointsoutside = false;
+			for(i=0;i<Bh.nbv;i++){ 
 				BamgVertex &bv=Bh[i];
-				if (!bv.GeomEdgeHook){
-					vertices[nbv].r   = bv.r;
+				/*Do not insert if the point is outside*/
+				long long det3[3];
+				Triangle* tcvj=TriangleFindFromCoord(bv.i,det3);
+				if(tcvj->det<0 || !tcvj->link){
+					pointsoutside = true;
+					continue;
+				}
+				IssmDouble area_1=((bv.r.x -(*tcvj)(2)->r.x)*((*tcvj)(1)->r.y-(*tcvj)(2)->r.y) 
+						- (bv.r.y -(*tcvj)(2)->r.y)*((*tcvj)(1)->r.x-(*tcvj)(2)->r.x));
+				IssmDouble area_2=(((*tcvj)(0)->r.x -(*tcvj)(2)->r.x)*(bv.r.y -(*tcvj)(2)->r.y) 
+						- ((*tcvj)(0)->r.y -(*tcvj)(2)->r.y)*(bv.r.x -(*tcvj)(2)->r.x));
+				IssmDouble area_3 =((bv.r.x -(*tcvj)(1)->r.x)*((*tcvj)(0)->r.y-(*tcvj)(1)->r.y)
+						- (bv.r.y -(*tcvj)(1)->r.y)*((*tcvj)(0)->r.x-(*tcvj)(1)->r.x));
+				if(area_1<0 || area_2<0 || area_3<0){
+					pointsoutside = true;
+					continue;
+				}
+				if(!bv.GeomEdgeHook){
+					vertices[nbv].r              = bv.r;
+					vertices[nbv].PreviousNumber = i+1;
 					vertices[nbv++].m = bv.m;
 				}
 			}
+			if(pointsoutside) _printf_("WARNING: One or more points of the initial mesh fall outside of the geometric boundary\n");
 			Bh.CreateSingleVertexToTriangleConnectivity();     
 			InsertNewPoints(nbvold,NbTSwap,bamgopts->random);
-		}  
+		}
 		else Bh.CreateSingleVertexToTriangleConnectivity();     
 
Index: /issm/trunk/src/c/bamg/R2.h
===================================================================
--- /issm/trunk/src/c/bamg/R2.h	(revision 19104)
+++ /issm/trunk/src/c/bamg/R2.h	(revision 19105)
@@ -19,8 +19,8 @@
 			  P2 (R a,R b)  :x(a),y(b)  {}
 			  P2 (P2 A,P2 B) : x(B.x-A.x),y(B.y-A.y) {}
-			  void Echo(){
+			  void Echo() const{
 				  printf("Member of P2:\n");
-				  printf("   x: %g or %i\n",x,x);
-				  printf("   y: %g or %i\n",y,y);
+				  std::cout<<"   x: "<<x<<std::endl;
+				  std::cout<<"   y: "<<y<<std::endl;
 			  }
 			  //operators
Index: /issm/trunk/src/c/classes/Constraints/Constraint.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/Constraint.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Constraints/Constraint.h	(revision 19105)
@@ -20,6 +20,8 @@
 
 		virtual      ~Constraint(){};
+		virtual void ActivatePenaltyMethod(void)=0;
 		virtual void ConstrainNode(Nodes* nodes,Parameters* parameters)=0;
 		virtual bool InAnalysis(int analysis_type)=0;
+		virtual void PenaltyDofAndValue(int* dof,IssmDouble* value,Nodes* nodes,Parameters* parameters)=0;
 
 };
Index: /issm/trunk/src/c/classes/Constraints/Constraints.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/Constraints.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Constraints/Constraints.cpp	(revision 19105)
@@ -12,4 +12,5 @@
 
 #include "./Constraints.h"
+#include "./Constraint.h"
 #include "../../shared/shared.h"
 #include "../../toolkits/toolkits.h"
@@ -19,5 +20,16 @@
 
 /*Numerics: */
-int Constraints::NumberOfConstraints(void){/*{{{*/
+void Constraints::ActivatePenaltyMethod(int in_analysis){/*{{{*/
+
+	for(int i=0;i<this->Size();i++){
+		Constraint* constraint=(Constraint*)this->GetObjectByOffset(i);
+		if(constraint->InAnalysis(in_analysis)){
+			constraint->ActivatePenaltyMethod();
+		}
+	}
+
+}
+/*}}}*/
+int  Constraints::NumberOfConstraints(void){/*{{{*/
 
 	int localconstraints;
Index: /issm/trunk/src/c/classes/Constraints/Constraints.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/Constraints.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Constraints/Constraints.h	(revision 19105)
@@ -27,5 +27,6 @@
 
 		/*numerics*/
-		int   NumberOfConstraints(void);
+		void ActivatePenaltyMethod(int in_analysis);
+		int  NumberOfConstraints(void);
 
 };
Index: /issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Constraints/SpcDynamic.cpp	(revision 19105)
@@ -20,10 +20,11 @@
 SpcDynamic::SpcDynamic(int spc_sid,int spc_nodeid, int spc_dof,int spc_analysis_type){/*{{{*/
 
-	sid=spc_sid;
-	nodeid=spc_nodeid;
-	dof=spc_dof;
-	value=0;
-	analysis_type=spc_analysis_type;
-	isset=false;
+	sid           = spc_sid;
+	nodeid        = spc_nodeid;
+	dof           = spc_dof;
+	value         = 0;
+	analysis_type = spc_analysis_type;
+	isset         = false;
+	penalty       = false;
 
 	return;
@@ -36,30 +37,4 @@
 
 /*Object virtual functions definitions:*/
-void SpcDynamic::Echo(void){/*{{{*/
-
-	_printf_("SpcDynamic:\n");
-	_printf_("   sid: " << sid << "\n");
-	_printf_("   nodeid: " << nodeid << "\n");
-	_printf_("   dof: " << dof << "\n");
-	_printf_("   value: " << value << "\n");
-	_printf_("   isset: " <<(isset?"true":"false") << "\n");
-	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
-	return;
-}
-/*}}}*/
-void SpcDynamic::DeepEcho(void){/*{{{*/
-
-	this->Echo();
-	return;
-}		
-/*}}}*/
-int SpcDynamic::Id(void){ return sid; }/*{{{*/
-/*}}}*/
-int SpcDynamic::ObjectEnum(void){/*{{{*/
-
-	return SpcDynamicEnum;
-
-}
-/*}}}*/
 Object* SpcDynamic::copy() {/*{{{*/
 
@@ -76,9 +51,34 @@
 }
 /*}}}*/
+void    SpcDynamic::DeepEcho(void){/*{{{*/
+
+	this->Echo();
+	return;
+}		
+/*}}}*/
+void    SpcDynamic::Echo(void){/*{{{*/
+
+	_printf_("SpcDynamic:\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   nodeid: " << nodeid << "\n");
+	_printf_("   dof: " << dof << "\n");
+	_printf_("   value: " << value << "\n");
+	_printf_("   isset: " <<(isset?"true":"false") << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	return;
+}
+/*}}}*/
+int     SpcDynamic::Id(void){ return sid; }/*{{{*/
+/*}}}*/
+int     SpcDynamic::ObjectEnum(void){/*{{{*/
+
+	return SpcDynamicEnum;
+
+}
+/*}}}*/
 
 /*Constraint virtual functions definitions: */
-bool SpcDynamic::InAnalysis(int in_analysis_type){/*{{{*/
-	if (in_analysis_type==this->analysis_type) return true;
-	else return false;
+void SpcDynamic::ActivatePenaltyMethod(void){/*{{{*/
+	this->penalty = true;
 }
 /*}}}*/
@@ -98,11 +98,16 @@
 }
 /*}}}*/
+bool SpcDynamic::InAnalysis(int in_analysis_type){/*{{{*/
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
 
 /*SpcDynamic functions*/
-int SpcDynamic::GetDof(){/*{{{*/
+int        SpcDynamic::GetDof(){/*{{{*/
 	return dof;
 }
 /*}}}*/
-int   SpcDynamic::GetNodeId(){/*{{{*/
+int        SpcDynamic::GetNodeId(){/*{{{*/
 
 	return nodeid;
@@ -115,5 +120,5 @@
 }
 /*}}}*/
-void SpcDynamic::SetDynamicConstraint(Nodes* nodes,IssmDouble* yg_serial){/*{{{*/
+void       SpcDynamic::SetDynamicConstraint(Nodes* nodes,IssmDouble* yg_serial){/*{{{*/
 
 	int pos;
Index: /issm/trunk/src/c/classes/Constraints/SpcDynamic.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcDynamic.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Constraints/SpcDynamic.h	(revision 19105)
@@ -14,35 +14,37 @@
 
 	private: 
-		int	sid; /*! id, to track it*/
-		int	nodeid; /*!node id*/
-		int dof; /*!component*/
-		IssmDouble value; /*value*/
-		bool isset;
-		int analysis_type;
+		int        sid;             /*! id, to track it */
+		int        nodeid;          /*!node id          */
+		int        dof;             /*!component        */
+		IssmDouble value;           /*value             */
+		bool       isset;
+		int        analysis_type;
+		bool       penalty;         /*Is this a penalty constraint */
 
 	public:
 
-		/*SpcDynamic constructors, destructors:{{{*/
+		/*SpcDynamic constructors, destructors*/
 		SpcDynamic();
 		SpcDynamic(int sid,int nodeid, int dof,int analysis_type);
 		~SpcDynamic();
-		/*}}}*/
-		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   ObjectEnum();
-		Object* copy();
-		/*}}}*/
-		/*Constraint virtual functions definitions: {{{*/
-		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
-		bool   InAnalysis(int analysis_type);
-		/*}}}*/
-		/*SpcDynamic management:{{{ */
-		int    GetNodeId();
-		int    GetDof();
+
+		/*Object virtual functions definitions*/
+		Object *copy();
+		void    DeepEcho();
+		void    Echo();
+		int     Id();
+		int     ObjectEnum();
+
+		/*Constraint virtual functions definitions*/
+		void ActivatePenaltyMethod(void);
+		void ConstrainNode(Nodes* nodes,Parameters* parameters);
+		bool InAnalysis(int analysis_type);
+		void PenaltyDofAndValue(int* dof,IssmDouble* value,Nodes* nodes,Parameters* parameters){_error_("not implemented yet");};
+
+		/*SpcDynamic management*/
+		int        GetDof();
+		int        GetNodeId();
 		IssmDouble GetValue();
-		void   SetDynamicConstraint(Nodes* nodes,IssmDouble *yg_serial);
-		/*}}}*/
+		void       SetDynamicConstraint(Nodes  *nodes,IssmDouble *yg_serial);
 
 };
Index: /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp	(revision 19105)
@@ -25,4 +25,5 @@
 	value         = spc_value;
 	analysis_type = spc_analysis_type;
+	penalty       = false;
 
 	return;
@@ -35,34 +36,4 @@
 
 /*Object virtual functions definitions:*/
-void SpcStatic::Echo(void){/*{{{*/
-
-	_printf_("SpcStatic:\n");
-	_printf_("   sid: " << sid << "\n");
-	_printf_("   nodeid: " << nodeid << "\n");
-	_printf_("   dof: " << dof << "\n");
-	_printf_("   value: " << value << "\n");
-	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
-	return;
-}
-/*}}}*/
-void SpcStatic::DeepEcho(void){/*{{{*/
-
-	_printf_("SpcStatic:\n");
-	_printf_("   sid: " << sid << "\n");
-	_printf_("   nodeid: " << nodeid << "\n");
-	_printf_("   dof: " << dof << "\n");
-	_printf_("   value: " << value << "\n");
-	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
-	return;
-}		
-/*}}}*/
-int SpcStatic::Id(void){ return sid; }/*{{{*/
-/*}}}*/
-int SpcStatic::ObjectEnum(void){/*{{{*/
-
-	return SpcStaticEnum;
-
-}
-/*}}}*/
 Object* SpcStatic::copy() {/*{{{*/
 	
@@ -78,9 +49,38 @@
 }
 /*}}}*/
+void    SpcStatic::DeepEcho(void){/*{{{*/
+
+	_printf_("SpcStatic:\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   nodeid: " << nodeid << "\n");
+	_printf_("   dof: " << dof << "\n");
+	_printf_("   value: " << value << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	return;
+}		
+/*}}}*/
+void    SpcStatic::Echo(void){/*{{{*/
+
+	_printf_("SpcStatic:\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   nodeid: " << nodeid << "\n");
+	_printf_("   dof: " << dof << "\n");
+	_printf_("   value: " << value << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	return;
+}
+/*}}}*/
+int     SpcStatic::Id(void){ return sid; }/*{{{*/
+/*}}}*/
+int     SpcStatic::ObjectEnum(void){/*{{{*/
+
+	return SpcStaticEnum;
+
+}
+/*}}}*/
 
 /*Constraint virtual functions definitions: */
-bool SpcStatic::InAnalysis(int in_analysis_type){/*{{{*/
-	if (in_analysis_type==this->analysis_type) return true;
-	else return false;
+void SpcStatic::ActivatePenaltyMethod(void){/*{{{*/
+	   this->penalty = true;
 }
 /*}}}*/
@@ -98,11 +98,16 @@
 }
 /*}}}*/
+bool SpcStatic::InAnalysis(int in_analysis_type){/*{{{*/
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
 
 /*SpcStatic functions*/
-int SpcStatic::GetDof(){/*{{{*/
+int        SpcStatic::GetDof(){/*{{{*/
 	return dof;
 }
 /*}}}*/
-int   SpcStatic::GetNodeId(){/*{{{*/
+int        SpcStatic::GetNodeId(){/*{{{*/
 
 	return nodeid;
Index: /issm/trunk/src/c/classes/Constraints/SpcStatic.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcStatic.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Constraints/SpcStatic.h	(revision 19105)
@@ -14,9 +14,10 @@
 
 	private: 
-		int	sid; /*! id, to track it*/
-		int	nodeid; /*!node id*/
-		int dof; /*!component*/
-		IssmDouble value; /*value*/
-		int analysis_type;
+		int        sid;             /*! id, to track it */
+		int        nodeid;          /*!node id          */
+		int        dof;             /*!component        */
+		IssmDouble value;           /*value             */
+		int        analysis_type;
+		bool       penalty;         /*Is this a penalty constraint */
 
 	public:
@@ -35,6 +36,8 @@
 		/*}}}*/
 		/*Constraint virtual functions definitions: {{{*/
+		void ActivatePenaltyMethod(void);
 		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
 		bool   InAnalysis(int analysis_type);
+		void   PenaltyDofAndValue(int* dof,IssmDouble* value,Nodes* nodes,Parameters* parameters){_error_("not implemented yet");};
 		/*}}}*/
 		/*SpcStatic management:{{{ */
Index: /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp	(revision 19105)
@@ -15,11 +15,12 @@
 /*SpcTransient constructors and destructor*/
 SpcTransient::SpcTransient(){/*{{{*/
-	sid=-1;
-	nodeid=-1;
-	dof=-1;
-	values=NULL;
-	times=NULL;
-	nsteps=-1;
-	analysis_type=-1;
+	penalty       = false;
+	sid           = -1;
+	nodeid        = -1;
+	dof           = -1;
+	values        = NULL;
+	times         = NULL;
+	nsteps        = -1;
+	analysis_type = -1;
 	return;
 }
@@ -27,11 +28,12 @@
 SpcTransient::SpcTransient(int spc_sid,int spc_nodeid, int spc_dof,int spc_nsteps, IssmDouble* spc_times, IssmDouble* spc_values,int spc_analysis_type){/*{{{*/
 
-	sid=spc_sid;
-	nodeid=spc_nodeid;
-	dof=spc_dof;
-	nsteps=spc_nsteps;
+	penalty = false;
+	sid     = spc_sid;
+	nodeid  = spc_nodeid;
+	dof     = spc_dof;
+	nsteps  = spc_nsteps;
 	if(spc_nsteps){
-		values=xNew<IssmDouble>(spc_nsteps);
-		times=xNew<IssmDouble>(spc_nsteps);
+		values = xNew<IssmDouble>(spc_nsteps);
+		times  = xNew<IssmDouble>(spc_nsteps);
 		xMemCpy<IssmDouble>(values,spc_values,nsteps);
 		xMemCpy<IssmDouble>(times,spc_times,nsteps);
@@ -49,5 +51,13 @@
 
 /*Object virtual functions definitions:*/
-void SpcTransient::Echo(void){/*{{{*/
+Object* SpcTransient::copy() {/*{{{*/
+	return new SpcTransient(sid,nodeid,dof,nsteps,times,values,analysis_type);
+}
+/*}}}*/
+void    SpcTransient::DeepEcho(void){/*{{{*/
+	this->Echo();
+}		
+/*}}}*/
+void    SpcTransient::Echo(void){/*{{{*/
 
 	int i;
@@ -65,11 +75,9 @@
 }
 /*}}}*/
-void SpcTransient::DeepEcho(void){/*{{{*/
-	this->Echo();
-}		
-/*}}}*/
-int    SpcTransient::Id(void){ return sid; }/*{{{*/
-/*}}}*/
-int SpcTransient::ObjectEnum(void){/*{{{*/
+int     SpcTransient::Id(void){/*{{{*/
+	return sid;
+}
+/*}}}*/
+int     SpcTransient::ObjectEnum(void){/*{{{*/
 
 	return SpcTransientEnum;
@@ -77,14 +85,8 @@
 }
 /*}}}*/
-Object* SpcTransient::copy() {/*{{{*/
-	return new SpcTransient(sid,nodeid,dof,nsteps,times,values,analysis_type);
-}
-/*}}}*/
 
 /*Constraint virtual functions definitions:*/
-bool SpcTransient::InAnalysis(int in_analysis_type){/*{{{*/
-
-	if (in_analysis_type==this->analysis_type) return true;
-	else return false;
+void SpcTransient::ActivatePenaltyMethod(void){/*{{{*/
+	   this->penalty = true;
 }
 /*}}}*/
@@ -101,5 +103,5 @@
 	node=(Node*)nodes->GetObjectById(NULL,nodeid);
 
-	if(node){ //in case the spc is dealing with a node on another cpu
+	if(!this->penalty && node){ //in case the spc is dealing with a node on another cpu
 
 		/*Retrieve time in parameters: */
@@ -130,5 +132,4 @@
 		/*Apply or relax constraint: */
 		if(xIsNan<IssmDouble>(value)){
-			printf("-------------- file: SpcTransient.cpp line: %i\n",__LINE__); 
 			node->RelaxConstraint(dof);
 		}
@@ -137,11 +138,73 @@
 }
 /*}}}*/
+bool SpcTransient::InAnalysis(int in_analysis_type){/*{{{*/
+
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
+}
+/*}}}*/
+void SpcTransient::PenaltyDofAndValue(int* pdof,IssmDouble* pvalue,Nodes* nodes,Parameters* parameters){/*{{{*/
+
+	if(!this->penalty) _error_("cannot return dof and value for non penalty constraint");
+
+	Node       *node  = NULL;
+	IssmDouble  time  = 0.;
+	int         i,gdof;
+	IssmDouble  alpha = -1.;
+	IssmDouble  value;
+	bool        found = false;
+
+	/*Chase through nodes and find the node to which this SpcTransient applys: */
+	node=(Node*)nodes->GetObjectById(NULL,nodeid);
+
+	if(node){ //in case the spc is dealing with a node on another cpu
+
+		/*Retrieve time in parameters: */
+		parameters->FindParam(&time,TimeEnum);
+
+		/*Now, go fetch value for this time: */
+		if (time<=times[0]){
+			value=values[0];
+			found=true;
+		}
+		else if (time>=times[nsteps-1]){
+			value=values[nsteps-1];
+			found=true;
+		}
+		else{
+			for(i=0;i<nsteps-1;i++){
+				if (times[i]<=time && time<times[i+1]){
+					alpha=(time-times[i])/(times[i+1]-times[i]);
+					value=(1-alpha)*values[i]+alpha*values[i+1];
+					found=true;
+					break;
+				}
+			}
+		}
+		if(!found)_error_("could not find time segment for constraint");
+
+		/*Get gdof */
+		gdof = node->GetDof(dof,GsetEnum);
+		if(xIsNan<IssmDouble>(value)){
+			gdof = -1;
+		}
+	}
+	else{
+		value = NAN;
+		gdof = -1;
+	}
+
+	/*Assign output pointers*/
+	*pdof   = gdof;
+	*pvalue = value;
+}
+/*}}}*/
 
 /*SpcTransient functions*/
-int SpcTransient::GetDof(){/*{{{*/
+int        SpcTransient::GetDof(){/*{{{*/
 	return dof;
 }
 /*}}}*/
-int   SpcTransient::GetNodeId(){/*{{{*/
+int        SpcTransient::GetNodeId(){/*{{{*/
 
 	return nodeid;
Index: /issm/trunk/src/c/classes/Constraints/SpcTransient.h
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcTransient.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Constraints/SpcTransient.h	(revision 19105)
@@ -14,11 +14,12 @@
 
 	private: 
-		int	sid; /*! id, to track it*/
-		int	nodeid; /*!node id*/
-		int dof; /*!component*/
-		IssmDouble* values; /*different values in time*/
-		IssmDouble* times; /*different time steps*/
-		int nsteps; /*number of time steps*/
-		int analysis_type;
+		int         sid;             /* id, to track it             */
+		int         nodeid;          /*node id                      */
+		int         dof;             /*component                    */
+		IssmDouble *values;          /*different values in time     */
+		IssmDouble *times;           /*different time steps         */
+		int         nsteps;          /*number of time steps         */
+		int         analysis_type;
+		bool        penalty;         /*Is this a penalty constraint */
 
 	public:
@@ -30,17 +31,19 @@
 		/*}}}*/
 		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   ObjectEnum();
 		Object* copy();
+		void    DeepEcho();
+		void    Echo();
+		int     Id(); 
+		int     ObjectEnum();
 		/*}}}*/
 		/*Constraint virtual functions definitions: {{{*/
+		void   ActivatePenaltyMethod(void);
 		void   ConstrainNode(Nodes* nodes,Parameters* parameters);
 		bool   InAnalysis(int analysis_type);
+		void   PenaltyDofAndValue(int* dof,IssmDouble* value,Nodes* nodes,Parameters* parameters);
 		/*}}}*/
 		/*SpcTransient management:{{{ */
-		int    GetNodeId();
-		int    GetDof();
+		int        GetDof();
+		int        GetNodeId();
 		IssmDouble GetValue();
 		/*}}}*/
Index: /issm/trunk/src/c/classes/Definition.h
===================================================================
--- /issm/trunk/src/c/classes/Definition.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Definition.h	(revision 19105)
@@ -13,4 +13,5 @@
 		virtual       ~Definition(){};
 		virtual char*  Name()=0;
+		virtual int    DefinitionEnum()=0;
 		virtual IssmDouble  Response(FemModel*)=0;
 
Index: /issm/trunk/src/c/classes/Elements/Element.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Element.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/Element.cpp	(revision 19105)
@@ -183,4 +183,5 @@
 	IssmDouble* eps_xz = xNew<IssmDouble>(numvertices);
 	IssmDouble* eps_yz = xNew<IssmDouble>(numvertices);
+	IssmDouble* eps_ef = xNew<IssmDouble>(numvertices);
 
 	/* Start looping on the number of vertices: */
@@ -200,4 +201,6 @@
 			eps_yy[iv]=epsilon[1];
 			eps_xy[iv]=epsilon[2];
+			/* eps_eff^2 = 1/2 ( exx^2 + eyy^2 + 2*exy^2 )*/
+			eps_ef[iv] = 1./sqrt(2.)*sqrt(epsilon[0]*epsilon[0] + epsilon[1]*epsilon[1] + 2.*epsilon[2]*epsilon[2]);
 		}
 		else{
@@ -209,4 +212,6 @@
 			eps_xz[iv]=epsilon[4];
 			eps_yz[iv]=epsilon[5];
+			/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
+			eps_ef[iv] = sqrt(epsilon[0]*epsilon[0] + epsilon[1]*epsilon[1] + epsilon[3]*epsilon[3] +  epsilon[4]*epsilon[4] + epsilon[5]*epsilon[5] + epsilon[0]*epsilon[1]);
 		}
 	}
@@ -219,4 +224,5 @@
 	this->AddInput(StrainRateyzEnum,eps_yz,P1Enum);
 	this->AddInput(StrainRatezzEnum,eps_zz,P1Enum);
+	this->AddInput(StrainRateeffectiveEnum,eps_ef,P1Enum);
 
 	/*Clean up and return*/
@@ -306,7 +312,4 @@
 }
 /*}}}*/
-void       Element::DeleteMaterials(void){/*{{{*/
-	delete this->material;
-}/*}}}*/
 void       Element::DeepEcho(void){/*{{{*/
 
@@ -343,38 +346,13 @@
 }
 /*}}}*/
-void       Element::Echo(void){/*{{{*/
-	_printf_(EnumToStringx(this->ObjectEnum())<<" element:\n");
-	_printf_("   id : "<<this->id <<"\n");
-	_printf_("   sid: "<<this->sid<<"\n");
-	if(vertices){
-		int numvertices = this->GetNumberOfVertices();
-		for(int i=0;i<numvertices;i++) vertices[i]->Echo();
-	}
-	else _printf_("vertices = NULL\n");
-
-	if(nodes){
-		int numnodes = this->GetNumberOfNodes();
-		for(int i=0;i<numnodes;i++) {
-			_printf_("nodes[" << i << "] = " << nodes[i]);	
-			nodes[i]->Echo();
-		}
-	}
-	else _printf_("nodes = NULL\n");
-
-	if (material) material->Echo();
-	else _printf_("material = NULL\n");
-
-	if (matpar) matpar->Echo();
-	else _printf_("matpar = NULL\n");
-
-	_printf_("   parameters\n");
-	if (parameters) parameters->Echo();
-	else _printf_("parameters = NULL\n");
-
-	_printf_("   inputs\n");
-	if (inputs) inputs->Echo();
-	else _printf_("inputs=NULL\n");
-}
-/*}}}*/
+void       Element::DeleteInput(int input_enum){/*{{{*/
+
+	inputs->DeleteInput(input_enum);
+
+}
+/*}}}*/
+void       Element::DeleteMaterials(void){/*{{{*/
+	delete this->material;
+}/*}}}*/
 IssmDouble Element::Divergence(void){/*{{{*/
 	/*Compute element divergence*/
@@ -419,4 +397,58 @@
 	return divergence;
 }/*}}}*/
+void       Element::dViscositydBFS(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dmudB;
+	IssmDouble epsilon3d[6];/* epsilon=[exx,eyy,exy,exy,exz,eyz];    */
+	IssmDouble epsilon2d[3];/* epsilon=[exx,eyy,exy];    */
+	IssmDouble eps_eff;
+	IssmDouble eps0=1.e-27;
+
+	if(dim==3){
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
+		this->StrainRateFS(&epsilon3d[0],xyz_list,gauss,vx_input,vy_input,vz_input);
+		eps_eff = sqrt(epsilon3d[0]*epsilon3d[0] + epsilon3d[1]*epsilon3d[1] + epsilon3d[3]*epsilon3d[3] +  epsilon3d[4]*epsilon3d[4] + epsilon3d[5]*epsilon3d[5] + epsilon3d[0]*epsilon3d[1]+eps0*eps0);
+	}
+	else{
+		/* eps_eff^2 = 1/2 ( exx^2 + eyy^2 + 2*exy^2 )*/
+		this->StrainRateSSA(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = 1./sqrt(2.)*sqrt(epsilon2d[0]*epsilon2d[0] + epsilon2d[1]*epsilon2d[1] + 2.*epsilon2d[2]*epsilon2d[2]);
+	}
+	/*Get viscosity*/
+	material->GetViscosity_B(&dmudB,eps_eff);
+
+	/*Assign output pointer*/
+	*pdmudB=dmudB;
+
+}
+/*}}}*/
+void       Element::dViscositydBHO(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dmudB;
+	IssmDouble epsilon3d[5];/* epsilon=[exx,eyy,exy,exy,exz,eyz];    */
+	IssmDouble epsilon2d[2];/* epsilon=[exx,eyy,exy];    */
+	IssmDouble eps_eff;
+	IssmDouble eps0=1.e-27;
+
+	if(dim==3){
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
+		this->StrainRateHO(&epsilon3d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = sqrt(epsilon3d[0]*epsilon3d[0] + epsilon3d[1]*epsilon3d[1] + epsilon3d[2]*epsilon3d[2] + epsilon3d[3]*epsilon3d[3] +  epsilon3d[4]*epsilon3d[4] + epsilon3d[0]*epsilon3d[1]+eps0*eps0);
+	}
+	else{
+		/* eps_eff^2 = 1/2 ( exx^2 + eyy^2 + 2*exy^2 )*/
+		this->StrainRateHO2dvertical(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = 1./sqrt(2.)*sqrt(epsilon2d[0]*epsilon2d[0] + 2.*epsilon2d[1]*epsilon2d[1] + eps0*eps0);
+	}
+	/*Get viscosity*/
+	material->GetViscosity_B(&dmudB,eps_eff);
+
+	/*Assign output pointer*/
+	*pdmudB=dmudB;
+
+}
+/*}}}*/
 void       Element::dViscositydBSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
 
@@ -473,15 +505,46 @@
 }
 /*}}}*/
-void       Element::ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){/*{{{*/
-	matpar->ThermalToEnthalpy(penthalpy,temperature,waterfraction,pressure);
+void       Element::Echo(void){/*{{{*/
+	_printf_(EnumToStringx(this->ObjectEnum())<<" element:\n");
+	_printf_("   id : "<<this->id <<"\n");
+	_printf_("   sid: "<<this->sid<<"\n");
+	if(vertices){
+		int numvertices = this->GetNumberOfVertices();
+		for(int i=0;i<numvertices;i++) vertices[i]->Echo();
+	}
+	else _printf_("vertices = NULL\n");
+
+	if(nodes){
+		int numnodes = this->GetNumberOfNodes();
+		for(int i=0;i<numnodes;i++) {
+			_printf_("nodes[" << i << "] = " << nodes[i]);	
+			nodes[i]->Echo();
+		}
+	}
+	else _printf_("nodes = NULL\n");
+
+	if (material) material->Echo();
+	else _printf_("material = NULL\n");
+
+	if (matpar) matpar->Echo();
+	else _printf_("matpar = NULL\n");
+
+	_printf_("   parameters\n");
+	if (parameters) parameters->Echo();
+	else _printf_("parameters = NULL\n");
+
+	_printf_("   inputs\n");
+	if (inputs) inputs->Echo();
+	else _printf_("inputs=NULL\n");
+}
+/*}}}*/
+IssmDouble Element::EnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
+	return matpar->GetEnthalpyDiffusionParameter(enthalpy,pressure);
+}/*}}}*/
+IssmDouble Element::EnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure){/*{{{*/
+	return matpar->GetEnthalpyDiffusionParameterVolume(numvertices,enthalpy,pressure);
 }/*}}}*/
 void       Element::EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
 	matpar->EnthalpyToThermal(ptemperature,pwaterfraction,enthalpy,pressure);
-}/*}}}*/
-IssmDouble Element::EnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
-	return matpar->GetEnthalpyDiffusionParameter(enthalpy,pressure);
-}/*}}}*/
-IssmDouble Element::EnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure){/*{{{*/
-	return matpar->GetEnthalpyDiffusionParameterVolume(numvertices,enthalpy,pressure);
 }/*}}}*/
 void       Element::FindParam(bool* pvalue,int paramenum){/*{{{*/
@@ -520,4 +583,28 @@
 }
 /*}}}*/
+void       Element::GetDofListPressure(int** pdoflist,int setenum){/*{{{*/
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*First, figure out size of doflist and create it: */
+	int numberofdofs=0;
+	for(int i=vnumnodes;i<vnumnodes+pnumnodes;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(FSApproximationEnum,setenum);
+
+	/*Allocate output*/
+	int* doflist=xNew<int>(numberofdofs);
+
+	/*Populate: */
+	int count=0;
+	for(int i=vnumnodes;i<vnumnodes+pnumnodes;i++){
+		nodes[i]->GetDofList(doflist+count,FSApproximationEnum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(FSApproximationEnum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
 void       Element::GetDofListVelocity(int** pdoflist,int setenum){/*{{{*/
 
@@ -543,28 +630,165 @@
 }
 /*}}}*/
-void       Element::GetDofListPressure(int** pdoflist,int setenum){/*{{{*/
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int vnumnodes = this->NumberofNodesVelocity();
-	int pnumnodes = this->NumberofNodesPressure();
-
-	/*First, figure out size of doflist and create it: */
-	int numberofdofs=0;
-	for(int i=vnumnodes;i<vnumnodes+pnumnodes;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(FSApproximationEnum,setenum);
-
-	/*Allocate output*/
-	int* doflist=xNew<int>(numberofdofs);
-
-	/*Populate: */
-	int count=0;
-	for(int i=vnumnodes;i<vnumnodes+pnumnodes;i++){
-		nodes[i]->GetDofList(doflist+count,FSApproximationEnum,setenum);
-		count+=nodes[i]->GetNumberOfDofs(FSApproximationEnum,setenum);
-	}
-
-	/*Assign output pointers:*/
-	*pdoflist=doflist;
-}
-/*}}}*/
+Input*     Element::GetInput(int inputenum){/*{{{*/
+	return inputs->GetInput(inputenum);
+}/*}}}*/
+void       Element::GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){/*{{{*/
+
+	_assert_(pvalue);
+
+	Input *input    = this->GetInput(enumtype);
+	int    numnodes = this->GetNumberOfNodes();
+
+	/* Start looping on the number of vertices: */
+	if(input){
+		Gauss* gauss=this->NewGauss();
+		for(int iv=0;iv<numnodes;iv++){
+			gauss->GaussNode(this->FiniteElement(),iv);
+			input->GetInputValue(&pvalue[iv],gauss);
+		}
+		delete gauss;
+	}
+	else{
+		for(int iv=0;iv<numnodes;iv++) pvalue[iv]=defaultvalue;
+	}
+}
+/*}}}*/
+void       Element::GetInputListOnNodes(IssmDouble* pvalue,int enumtype){/*{{{*/
+
+	_assert_(pvalue);
+
+	int    numnodes = this->GetNumberOfNodes();
+	Input *input    = this->GetInput(enumtype);
+	if(!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
+
+	/* Start looping on the number of vertices: */
+	Gauss* gauss=this->NewGauss();
+	for(int iv=0;iv<numnodes;iv++){
+		gauss->GaussNode(this->FiniteElement(),iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+	delete gauss;
+}
+/*}}}*/
+void       Element::GetInputListOnNodesVelocity(IssmDouble* pvalue,int enumtype){/*{{{*/
+
+	_assert_(pvalue);
+
+	int    numnodes = this->NumberofNodesVelocity();
+	Input *input    = this->GetInput(enumtype);
+	if(!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
+
+	/* Start looping on the number of vertices: */
+	Gauss* gauss=this->NewGauss();
+	for(int iv=0;iv<numnodes;iv++){
+		gauss->GaussNode(this->VelocityInterpolation(),iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+	delete gauss;
+}
+/*}}}*/
+void       Element::GetInputListOnVertices(IssmDouble* pvalue,int enumtype){/*{{{*/
+
+	/*Recover input*/
+	Input* input=this->GetInput(enumtype);
+	if (!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
+
+	/*Fetch number vertices for this element*/
+	int numvertices = this->GetNumberOfVertices();
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/* Start looping on the number of vertices: */
+	Gauss*gauss=this->NewGauss();
+	for(int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+void       Element::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){/*{{{*/
+
+	/*Recover input*/
+	Input* input=this->GetInput(enumtype);
+
+	/*Checks in debugging mode*/
+	_assert_(pvalue);
+
+	/*Fetch number vertices for this element*/
+	int numvertices = this->GetNumberOfVertices();
+
+	/* Start looping on the number of vertices: */
+	if (input){
+		Gauss* gauss=this->NewGauss();
+		for (int iv=0;iv<numvertices;iv++){
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&pvalue[iv],gauss);
+		}
+		delete gauss;
+	}
+	else{
+		for(int iv=0;iv<numvertices;iv++) pvalue[iv]=defaultvalue;
+	}
+}
+/*}}}*/
+void       Element::GetInputLocalMinMaxOnNodes(IssmDouble* min,IssmDouble* max,IssmDouble* ug){/*{{{*/
+
+
+	/*Get number of nodes for this element*/
+	int numnodes = this->GetNumberOfNodes();
+
+	/*Some checks to avoid segmentation faults*/
+	_assert_(ug);
+	_assert_(numnodes>0);
+	_assert_(nodes);
+
+	/*Get element minimum/maximum*/
+	IssmDouble input_min = ug[nodes[0]->GetDof(0,GsetEnum)];
+	IssmDouble input_max = input_min;
+	for(int i=1;i<numnodes;i++){
+		if(ug[nodes[i]->GetDof(0,GsetEnum)] < input_min) input_min = ug[nodes[i]->GetDof(0,GsetEnum)];
+		if(ug[nodes[i]->GetDof(0,GsetEnum)] > input_max) input_max = ug[nodes[i]->GetDof(0,GsetEnum)];
+	}
+
+
+	/*Second loop to reassign min and max with local extrema*/
+	for(int i=0;i<numnodes;i++){
+		if(min[nodes[i]->GetDof(0,GsetEnum)]>input_min) min[nodes[i]->GetDof(0,GsetEnum)] = input_min;
+		if(max[nodes[i]->GetDof(0,GsetEnum)]<input_max) max[nodes[i]->GetDof(0,GsetEnum)] = input_max;
+	}
+}
+/*}}}*/
+void       Element::GetInputValue(bool* pvalue,int inputenum){/*{{{*/
+
+	Input* input=inputs->GetInput(inputenum);
+	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
+	input->GetInputValue(pvalue);
+
+}/*}}}*/
+void       Element::GetInputValue(int* pvalue,int inputenum){/*{{{*/
+
+	Input* input=inputs->GetInput(inputenum);
+	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
+	input->GetInputValue(pvalue);
+
+}/*}}}*/
+void       Element::GetInputValue(IssmDouble* pvalue,int inputenum){/*{{{*/
+
+	Input* input=inputs->GetInput(inputenum);
+	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
+	input->GetInputValue(pvalue);
+
+}/*}}}*/
+void       Element::GetInputValue(IssmDouble* pvalue,Gauss* gauss,int inputenum){/*{{{*/
+
+	Input* input=inputs->GetInput(inputenum);
+	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
+	input->GetInputValue(pvalue,gauss);
+
+}/*}}}*/
 IssmDouble Element::GetMaterialParameter(int enum_in){/*{{{*/
 
@@ -581,4 +805,24 @@
 	}
 }/*}}}*/
+void       Element::GetNodesLidList(int* lidlist){/*{{{*/
+
+	_assert_(lidlist);
+	_assert_(nodes);
+	int numnodes = this->GetNumberOfNodes();
+	for(int i=0;i<numnodes;i++){
+		lidlist[i]=nodes[i]->Lid();
+	}
+}
+/*}}}*/
+void       Element::GetNodesSidList(int* sidlist){/*{{{*/
+
+	_assert_(sidlist);
+	_assert_(nodes);
+	int numnodes = this->GetNumberOfNodes();
+	for(int i=0;i<numnodes;i++){
+		sidlist[i]=nodes[i]->Sid();
+	}
+}
+/*}}}*/
 void       Element::GetPhi(IssmDouble* phi, IssmDouble*  epsilon, IssmDouble viscosity){/*{{{*/
 	/*Compute deformational heating from epsilon and viscosity */
@@ -618,172 +862,69 @@
 }
 /*}}}*/
-Input*     Element::GetInput(int inputenum){/*{{{*/
-	return inputs->GetInput(inputenum);
-}/*}}}*/
-void       Element::GetInputListOnVertices(IssmDouble* pvalue,int enumtype){/*{{{*/
-
-	/*Recover input*/
-	Input* input=this->GetInput(enumtype);
-	if (!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
-
-	/*Fetch number vertices for this element*/
-	int numvertices = this->GetNumberOfVertices();
-
-	/*Checks in debugging mode*/
-	_assert_(pvalue);
-
-	/* Start looping on the number of vertices: */
-	Gauss*gauss=this->NewGauss();
-	for(int iv=0;iv<numvertices;iv++){
-		gauss->GaussVertex(iv);
-		input->GetInputValue(&pvalue[iv],gauss);
-	}
-
-	/*clean-up*/
-	delete gauss;
-}
-/*}}}*/
-void       Element::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){/*{{{*/
-
-	/*Recover input*/
-	Input* input=this->GetInput(enumtype);
-
-	/*Checks in debugging mode*/
-	_assert_(pvalue);
-
-	/*Fetch number vertices for this element*/
-	int numvertices = this->GetNumberOfVertices();
-
-	/* Start looping on the number of vertices: */
-	if (input){
-		Gauss* gauss=this->NewGauss();
-		for (int iv=0;iv<numvertices;iv++){
-			gauss->GaussVertex(iv);
-			input->GetInputValue(&pvalue[iv],gauss);
-		}
-		delete gauss;
-	}
-	else{
-		for(int iv=0;iv<numvertices;iv++) pvalue[iv]=defaultvalue;
-	}
-}
-/*}}}*/
-void       Element::GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){/*{{{*/
-
-	_assert_(pvalue);
-
-	Input *input    = this->GetInput(enumtype);
-	int    numnodes = this->GetNumberOfNodes();
-
-	/* Start looping on the number of vertices: */
-	if(input){
-		Gauss* gauss=this->NewGauss();
-		for(int iv=0;iv<numnodes;iv++){
-			gauss->GaussNode(this->FiniteElement(),iv);
-			input->GetInputValue(&pvalue[iv],gauss);
-		}
-		delete gauss;
-	}
-	else{
-		for(int iv=0;iv<numnodes;iv++) pvalue[iv]=defaultvalue;
-	}
-}
-/*}}}*/
-void       Element::GetInputListOnNodes(IssmDouble* pvalue,int enumtype){/*{{{*/
-
-	_assert_(pvalue);
-
-	int    numnodes = this->GetNumberOfNodes();
-	Input *input    = this->GetInput(enumtype);
-	if(!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
-
-	/* Start looping on the number of vertices: */
-	Gauss* gauss=this->NewGauss();
-	for(int iv=0;iv<numnodes;iv++){
-		gauss->GaussNode(this->FiniteElement(),iv);
-		input->GetInputValue(&pvalue[iv],gauss);
-	}
-	delete gauss;
-}
-/*}}}*/
-void       Element::GetInputListOnNodesVelocity(IssmDouble* pvalue,int enumtype){/*{{{*/
-
-	_assert_(pvalue);
-
-	int    numnodes = this->NumberofNodesVelocity();
-	Input *input    = this->GetInput(enumtype);
-	if(!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
-
-	/* Start looping on the number of vertices: */
-	Gauss* gauss=this->NewGauss();
-	for(int iv=0;iv<numnodes;iv++){
-		gauss->GaussNode(this->VelocityInterpolation(),iv);
-		input->GetInputValue(&pvalue[iv],gauss);
-	}
-	delete gauss;
-}
-/*}}}*/
-void       Element::GetInputValue(bool* pvalue,int inputenum){/*{{{*/
-
-	Input* input=inputs->GetInput(inputenum);
-	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
-	input->GetInputValue(pvalue);
-
-}/*}}}*/
-void       Element::GetInputValue(int* pvalue,int inputenum){/*{{{*/
-
-	Input* input=inputs->GetInput(inputenum);
-	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
-	input->GetInputValue(pvalue);
-
-}/*}}}*/
-void       Element::GetInputValue(IssmDouble* pvalue,int inputenum){/*{{{*/
-
-	Input* input=inputs->GetInput(inputenum);
-	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
-	input->GetInputValue(pvalue);
-
-}/*}}}*/
-void       Element::GetInputValue(IssmDouble* pvalue,Gauss* gauss,int inputenum){/*{{{*/
-
-	Input* input=inputs->GetInput(inputenum);
-	if(!input) _error_("Input " << EnumToStringx(inputenum) << " not found in element");
-	input->GetInputValue(pvalue,gauss);
-
-}/*}}}*/
-void       Element::GetNodesSidList(int* sidlist){/*{{{*/
-
-	_assert_(sidlist);
-	_assert_(nodes);
-	int numnodes = this->GetNumberOfNodes();
-	for(int i=0;i<numnodes;i++){
-		sidlist[i]=nodes[i]->Sid();
-	}
-}
-/*}}}*/
-void       Element::GetNodesLidList(int* lidlist){/*{{{*/
-
-	_assert_(lidlist);
-	_assert_(nodes);
-	int numnodes = this->GetNumberOfNodes();
-	for(int i=0;i<numnodes;i++){
-		lidlist[i]=nodes[i]->Lid();
-	}
-}
-/*}}}*/
-void       Element::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){/*{{{*/
+/* void       Element::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){/\*{{{*\/ */
+
+/* 	/\*Fetch number vertices for this element and allocate arrays*\/ */
+/* 	int numvertices = this->GetNumberOfVertices(); */
+/* 	int*        vertexpidlist = xNew<int>(numvertices); */
+/* 	IssmDouble* values        = xNew<IssmDouble>(numvertices); */
+
+/* 	/\*Fill in values*\/ */
+/* 	this->GetVertexPidList(vertexpidlist); */
+/* 	this->GetInputListOnVertices(values,input_enum); */
+/* 	vector->SetValues(numvertices,vertexpidlist,values,INS_VAL); */
+
+/* 	/\*Clean up*\/ */
+/* 	xDelete<int>(vertexpidlist); */
+/* 	xDelete<IssmDouble>(values); */
+
+/* } */
+/* /\*}}}*\/ */
+void       Element::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum,int type){/*{{{*/
 
 	/*Fetch number vertices for this element and allocate arrays*/
-	int numvertices = this->GetNumberOfVertices();
-	int*        vertexpidlist = xNew<int>(numvertices);
-	IssmDouble* values        = xNew<IssmDouble>(numvertices);
-
-	/*Fill in values*/
-	this->GetVertexPidList(vertexpidlist);
-	this->GetInputListOnVertices(values,input_enum);
-	vector->SetValues(numvertices,vertexpidlist,values,INS_VAL);
-
+	int         numvertices = this->GetNumberOfVertices();
+	int         numnodes    = this->GetNumberOfNodes();
+	int*        doflist     = NULL;
+	IssmDouble* values      = NULL;
+
+	switch(type){
+	case VertexPIdEnum:
+		doflist = xNew<int>(numvertices);
+		values = xNew<IssmDouble>(numvertices);
+		/*Fill in values*/
+		this->GetVertexPidList(doflist);
+		this->GetInputListOnVertices(values,input_enum);
+		vector->SetValues(numvertices,doflist,values,INS_VAL);
+		break;
+	case VertexSIdEnum:
+		doflist = xNew<int>(numvertices);
+		values = xNew<IssmDouble>(numvertices);
+		/*Fill in values*/
+		this->GetVerticesSidList(doflist);
+		this->GetInputListOnVertices(values,input_enum);
+		vector->SetValues(numvertices,doflist,values,INS_VAL);
+		break;
+	case NodesEnum:
+		doflist = xNew<int>(numnodes);
+		values = xNew<IssmDouble>(numnodes);
+		/*Fill in values*/
+		this->GetInputListOnNodes(values,input_enum);
+		this->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+		vector->SetValues(numnodes,doflist,values,INS_VAL);
+		break;
+	case NodeSIdEnum:
+		doflist = xNew<int>(numnodes);
+		values = xNew<IssmDouble>(numnodes);
+		/*Fill in values*/
+		this->GetNodesSidList(doflist);
+		this->GetInputListOnNodes(values,input_enum);
+		vector->SetValues(numnodes,doflist,values,INS_VAL);
+		break;
+	default:
+		_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+	
 	/*Clean up*/
-	xDelete<int>(vertexpidlist);
+	xDelete<int>(doflist);
 	xDelete<IssmDouble>(values);
 
@@ -795,4 +936,10 @@
 	for(int i=0;i<numvertices;i++) pidlist[i]=vertices[i]->Pid();
 
+}
+/*}}}*/
+void       Element::GetVerticesConnectivityList(int* connectivity){/*{{{*/
+
+	int numvertices = this->GetNumberOfVertices();
+	for(int i=0;i<numvertices;i++) connectivity[i]=this->vertices[i]->Connectivity();
 }
 /*}}}*/
@@ -812,10 +959,4 @@
 }
 /*}}}*/
-void       Element::GetVerticesConnectivityList(int* connectivity){/*{{{*/
-
-	int numvertices = this->GetNumberOfVertices();
-	for(int i=0;i<numvertices;i++) connectivity[i]=this->vertices[i]->Connectivity();
-}
-/*}}}*/
 IssmDouble Element::GetXcoord(IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 
@@ -863,5 +1004,5 @@
 	return z;
 }/*}}}*/
-void       Element::GradientIndexing(int* indexing,int control_index){/*{{{*/
+void       Element::GradientIndexing(int* indexing,int control_index,bool onsid){/*{{{*/
 
 	/*Get number of controls*/
@@ -873,6 +1014,13 @@
 
 	/*get gradient indices*/
-	for(int i=0;i<numvertices;i++){
-		indexing[i]=num_controls*this->vertices[i]->Pid() + control_index;
+	if(onsid){
+		for(int i=0;i<numvertices;i++){
+			indexing[i]=num_controls*this->vertices[i]->Sid() + control_index;
+		}
+	}
+	else{
+		for(int i=0;i<numvertices;i++){
+			indexing[i]=num_controls*this->vertices[i]->Pid() + control_index;
+		}
 	}
 
@@ -1003,9 +1151,13 @@
 	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
 
-	if(migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum || migration_style==ContactEnum){ //Floating if all nodes are floating
+	if(migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){ //Floating if all nodes are floating
 		if(this->inputs->Max(MaskGroundediceLevelsetEnum) <= 0.) shelf=true;
 		else shelf=false;
 	}
-	else if(migration_style==NoneEnum || migration_style==AggressiveMigrationEnum || migration_style==SoftMigrationEnum){ //Floating if all nodes are floating
+	else if(migration_style==ContactEnum){
+		if(this->inputs->Max(MaskGroundediceLevelsetEnum) > 0.) shelf=false;
+		else shelf=true;
+	}
+	else if(migration_style==NoneEnum || migration_style==AggressiveMigrationEnum || migration_style==SoftMigrationEnum || migration_style==GroundingOnlyEnum){ //Floating if all nodes are floating
 		if(this->inputs->Min(MaskGroundediceLevelsetEnum) > 0.) shelf=false;
 		else shelf=true;
@@ -1026,5 +1178,5 @@
 				name==BedEnum ||
 				name==BalancethicknessThickeningRateEnum ||
-				name==BalancethicknessApparentMassbalanceEnum ||
+				name==BalancethicknessOmegaEnum ||
 				name==SigmaNNEnum ||
 				name==SurfaceSlopeXEnum ||
@@ -1053,4 +1205,5 @@
 				name==WatercolumnEnum || 
 				name==FrictionCoefficientEnum ||
+				name==FrictionAsEnum ||
 				name==MaskGroundediceLevelsetEnum ||
 				name==MaskIceLevelsetEnum ||
@@ -1059,5 +1212,5 @@
 				name==LevelsetfunctionSlopeYEnum ||
 				name==LevelsetfunctionPicardEnum ||
-				name==MasstransportCalvingrateEnum ||
+				//name==CalvingCalvingrateEnum ||
 				name==GradientEnum ||
 				name==OldGradientEnum  ||
@@ -1072,4 +1225,7 @@
 				name==SedimentHeadOldEnum ||
 				name==EplHeadOldEnum ||
+				name==StressIntensityFactorEnum ||
+				name==StrainRateparallelEnum ||
+				name==StrainRateperpendicularEnum ||
 				name==HydrologydcEplThicknessOldEnum ||
 				name==HydrologydcEplInitialThicknessEnum ||
@@ -1103,16 +1259,108 @@
 
 	this->AddInput(BasalforcingsFloatingiceMeltingRateEnum,values,P1Enum);
-
-}/*}}}*/
+	xDelete<IssmDouble>(base);
+	xDelete<IssmDouble>(values);
+
+}/*}}}*/
+void       Element::MigrateGroundingLine(IssmDouble* phi_ungrounding){/*{{{*/
+
+	int         numvertices = this->GetNumberOfVertices();
+	int        i,migration_style;
+	IssmDouble bed_hydro,yts;
+	IssmDouble rho_water,rho_ice,density;
+	IssmDouble* melting = xNew<IssmDouble>(numvertices);
+	IssmDouble* phi     = xNew<IssmDouble>(numvertices);
+	IssmDouble* h       = xNew<IssmDouble>(numvertices);
+	IssmDouble* s       = xNew<IssmDouble>(numvertices);
+	IssmDouble* b       = xNew<IssmDouble>(numvertices);
+	IssmDouble* r       = xNew<IssmDouble>(numvertices);
+
+	/*Recover info at the vertices: */
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&yts,ConstantsYtsEnum);
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&s[0],SurfaceEnum);
+	GetInputListOnVertices(&b[0],BaseEnum);
+	GetInputListOnVertices(&r[0],BedEnum);
+	GetInputListOnVertices(&phi[0],MaskGroundediceLevelsetEnum);
+	rho_water   = matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	rho_ice     = matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+	density     = rho_ice/rho_water;
+
+	/*go through vertices, and update inputs, considering them to be TriaVertex type: */
+	for(i=0;i<numvertices;i++){
+		/* Contact FS*/
+		if(migration_style == ContactEnum && phi_ungrounding[vertices[i]->Pid()]<10){
+			phi[i]=phi_ungrounding[vertices[i]->Pid()]; 
+			if(phi[i]>=0.) b[i]=r[i];
+		}
+		else if(migration_style == GroundingOnlyEnum && b[i]<r[i]) b[i]=r[i];
+		/*Ice shelf: if bed below bathymetry, impose it at the bathymetry and update surface, elso do nothing */
+		else if(phi[i]<=0.){
+			if(b[i]<=r[i]){ 
+				b[i]        = r[i];
+				s[i]        = b[i]+h[i];
+			}
+		}
+		/*Ice sheet: if hydrostatic bed above bathymetry, ice sheet starts to unground, elso do nothing */
+		/*Change only if AggressiveMigration or if the ice sheet is in contact with the ocean*/
+		else{ // phi>0
+			bed_hydro=-density*h[i];
+			if (bed_hydro>r[i]){
+				/*Unground only if the element is connected to the ice shelf*/
+				if(migration_style==AggressiveMigrationEnum || migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
+					s[i]        = (1-density)*h[i];
+					b[i]        = -density*h[i];
+				}
+				else if(migration_style==SoftMigrationEnum && phi_ungrounding[vertices[i]->Pid()]<0.){
+					s[i]        = (1-density)*h[i];
+					b[i]        = -density*h[i];
+				}
+				else{
+					if(migration_style!=SoftMigrationEnum && migration_style!=ContactEnum && migration_style!=GroundingOnlyEnum) _error_("Error: migration should be Aggressive, Soft, Subelement, Contact or GroundingOnly");
+				}
+			}
+		}
+	}
+
+	/*Recalculate phi*/
+	for(i=0;i<numvertices;i++){
+		if(migration_style==SoftMigrationEnum){
+			bed_hydro=-density*h[i];
+			if(phi[i]<0. || bed_hydro<=r[i] || phi_ungrounding[vertices[i]->Pid()]<0.){
+				phi[i]=h[i]+r[i]/density;
+			}
+		}
+		else if(migration_style!=ContactEnum) phi[i]=h[i]+r[i]/density;
+		else{
+			/*do nothing*/
+		}
+	}
+	this->AddInput(MaskGroundediceLevelsetEnum,&phi[0],P1Enum);
+
+	/*Update inputs*/
+	this->AddInput(SurfaceEnum,&s[0],P1Enum);
+	this->AddInput(BaseEnum,&b[0],P1Enum);
+
+	/*Delete*/
+	xDelete<IssmDouble>(melting);
+	xDelete<IssmDouble>(phi);
+	xDelete<IssmDouble>(r);
+	xDelete<IssmDouble>(b);
+	xDelete<IssmDouble>(s);
+	xDelete<IssmDouble>(h);
+
+}
+/*}}}*/
+ElementMatrix* Element::NewElementMatrix(int approximation_enum){/*{{{*/
+	return new ElementMatrix(nodes,this->GetNumberOfNodes(),this->parameters,approximation_enum);
+}
+/*}}}*/
+ElementMatrix* Element::NewElementMatrixCoupling(int number_nodes,int approximation_enum){/*{{{*/
+	return new ElementMatrix(nodes,number_nodes,this->parameters,approximation_enum);
+}
+/*}}}*/
 ElementVector* Element::NewElementVector(int approximation_enum){/*{{{*/
 	return new ElementVector(nodes,this->GetNumberOfNodes(),this->parameters,approximation_enum);
-}
-/*}}}*/
-ElementMatrix* Element::NewElementMatrix(int approximation_enum){/*{{{*/
-	return new ElementMatrix(nodes,this->GetNumberOfNodes(),this->parameters,approximation_enum);
-}
-/*}}}*/
-ElementMatrix* Element::NewElementMatrixCoupling(int number_nodes,int approximation_enum){/*{{{*/
-	return new ElementMatrix(nodes,number_nodes,this->parameters,approximation_enum);
 }
 /*}}}*/
@@ -1129,4 +1377,8 @@
 			case ViscousHeatingEnum:
 				this->ViscousHeatingCreateInput();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StressMaxPrincipalEnum:
+				this->StressMaxPrincipalCreateInput();
 				input=this->inputs->GetInput(output_enum);
 				break;
@@ -1146,4 +1398,5 @@
 			case StrainRateyzEnum:
 			case StrainRatezzEnum:
+			case StrainRateeffectiveEnum:
 				this->ComputeStrainRate();
 				input=this->inputs->GetInput(output_enum);
@@ -1166,4 +1419,38 @@
 				input=this->inputs->GetInput(output_enum);
 				break;
+			case StressIntensityFactorEnum:
+				this->StressIntensityFactor();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case CalvingratexEnum:
+			case CalvingrateyEnum:
+			case CalvingCalvingrateEnum:
+				this->StrainRateparallel();
+				this->StrainRateperpendicular();
+				int calvinglaw;
+				this->FindParam(&calvinglaw,CalvingLawEnum);
+					switch(calvinglaw){
+						case DefaultCalvingEnum:
+							//do nothing
+							break;
+						case CalvingLevermannEnum:
+							this->CalvingRateLevermann();
+							break;
+						case CalvingPiEnum:
+							this->CalvingRatePi();
+							break;
+						default:
+							_error_("Calving law "<<EnumToStringx(calvinglaw)<<" not supported yet");
+				}
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StrainRateparallelEnum:
+				this->StrainRateparallel();
+				input=this->inputs->GetInput(output_enum);
+				break;
+			case StrainRateperpendicularEnum:
+				this->StrainRateperpendicular();
+				input=this->inputs->GetInput(output_enum);
+				break;
 			default:
 				_error_("input "<<EnumToStringx(output_enum)<<" not found in element");
@@ -1172,7 +1459,16 @@
 
 	/*Assign output pointer*/
+	_assert_(input);
 	*pinterpolation   = input->GetResultInterpolation();
 	*pnodesperelement = input->GetResultNumberOfNodes();
 }/*}}}*/
+void       Element::ResultToPatch(IssmDouble* values,int nodesperelement,int output_enum){/*{{{*/
+
+	Input* input=this->inputs->GetInput(output_enum);
+	if(!input) _error_("input "<<EnumToStringx(output_enum)<<" not found in element");
+
+	input->ResultToPatch(values,nodesperelement,this->Sid());
+
+} /*}}}*/
 void       Element::ResultToVector(Vector<IssmDouble>* vector,int output_enum){/*{{{*/
 
@@ -1222,12 +1518,4 @@
 					 _error_("interpolation "<<EnumToStringx(input->GetResultInterpolation())<<" not supported yet");
 	}
-} /*}}}*/
-void       Element::ResultToPatch(IssmDouble* values,int nodesperelement,int output_enum){/*{{{*/
-
-	Input* input=this->inputs->GetInput(output_enum);
-	if(!input) _error_("input "<<EnumToStringx(output_enum)<<" not found in element");
-
-	input->ResultToPatch(values,nodesperelement,this->Sid());
-
 } /*}}}*/
 void       Element::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){/*{{{*/
@@ -1307,27 +1595,151 @@
 }
 /*}}}*/
-IssmDouble Element::TMeltingPoint(IssmDouble pressure){/*{{{*/
-	_assert_(matpar);
-	return this->matpar->TMeltingPoint(pressure);
-}/*}}}*/
-void       Element::ViscousHeatingCreateInput(void){/*{{{*/
+void       Element::StrainRateFS(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){/*{{{*/
+	/*Compute the 3d Strain Rate (6 components):
+	 *
+	 * epsilon=[exx eyy ezz exy exz eyz]
+	 */
 
 	/*Intermediaries*/
-	IssmDouble phi;
-	IssmDouble viscosity;
-	IssmDouble epsilon[6];
-	IssmDouble thickness;
+	IssmDouble dvx[3];
+	IssmDouble dvy[3];
+	IssmDouble dvz[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input || !vz_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << ", vz: " << vz_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+	vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+	vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
+	epsilon[0] = dvx[0];
+	epsilon[1] = dvy[1];
+	epsilon[2] = dvz[2];
+	epsilon[3] = 0.5*(dvx[1] + dvy[0]);
+	epsilon[4] = 0.5*(dvx[2] + dvz[0]);
+	epsilon[5] = 0.5*(dvy[2] + dvz[1]);
+
+}/*}}}*/
+void       Element::StrainRateHO(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+	/*Compute the 3d Blatter/HOStrain Rate (5 components):
+	 *
+	 * epsilon=[exx eyy exy exz eyz]
+	 *
+	 * with exz=1/2 du/dz
+	 *      eyz=1/2 dv/dz
+	 *
+	 * the contribution of vz is neglected
+	 */
+
+	/*Intermediaries*/
+	IssmDouble dvx[3];
+	IssmDouble dvy[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input || !vy_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+	vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+	epsilon[0] = dvx[0];
+	epsilon[1] = dvy[1];
+	epsilon[2] = 0.5*(dvx[1] + dvy[0]);
+	epsilon[3] = 0.5*dvx[2];
+	epsilon[4] = 0.5*dvy[2];
+
+}/*}}}*/
+void       Element::StrainRateHO2dvertical(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+	/*Compute the 2d Blatter/HOStrain Rate (2 components):
+	 *
+	 * epsilon=[exx exz]
+	 *
+	 * with exz=1/2 du/dz
+	 *
+	 * the contribution of vz is neglected
+	 */
+
+	/*Intermediaries*/
+	IssmDouble dvx[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input <<"\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+	epsilon[0] = dvx[0];
+	epsilon[1] = 0.5*dvx[1];
+
+}/*}}}*/
+void       Element::StrainRateSSA(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dvx[3];
+	IssmDouble dvy[3];
+
+	/*Check that both inputs have been found*/
+	if(!vx_input || !vy_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+	vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
+	epsilon[0] = dvx[0];
+	epsilon[1] = dvy[1];
+	epsilon[2] = 0.5*(dvx[1] + dvy[0]);
+
+}/*}}}*/
+void       Element::StrainRateSSA1d(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble dvx[3];
+
+	/*Check that both inputs have been found*/
+	if (!vx_input){
+		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << "\n");
+	}
+
+	/*Get strain rate assuming that epsilon has been allocated*/
+	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
+	*epsilon = dvx[0];
+
+}/*}}}*/
+void       Element::StressMaxPrincipalCreateInput(void){/*{{{*/
+
+	/*Intermediaries*/
 	IssmDouble *xyz_list = NULL;
+	IssmDouble  sigma_xx,sigma_yy,sigma_zz,sigma_xy,sigma_xz,sigma_yz;
+	IssmDouble  a,b,c,d,x[3],max;
+	int         dim,numroots;
+
+	/*First: get stress tensor*/
+	this->ComputeStressTensor();
+
+	/*Get domain dimension*/
+	this->FindParam(&dim,DomainDimensionEnum);
 
 	/*Fetch number vertices and allocate memory*/
-	int         numvertices    = this->GetNumberOfVertices();
-	IssmDouble* viscousheating = xNew<IssmDouble>(numvertices);
+	int         numvertices  = this->GetNumberOfVertices();
+	IssmDouble* maxprincipal = xNew<IssmDouble>(numvertices);
 
 	/*Retrieve all inputs and parameters*/
 	this->GetVerticesCoordinatesBase(&xyz_list);
-	Input* vx_input        = this->GetInput(VxEnum); _assert_(vx_input);
-	Input* vy_input        = this->GetInput(VyEnum); _assert_(vy_input);
-	Input* vz_input        = this->GetInput(VzEnum); _assert_(vz_input);
-	Input* thickness_input = this->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* sigma_xx_input  = this->GetInput(StressTensorxxEnum); _assert_(sigma_xx_input);
+	Input* sigma_yy_input  = this->GetInput(StressTensoryyEnum); _assert_(sigma_yy_input);
+	Input* sigma_xy_input  = this->GetInput(StressTensorxyEnum); _assert_(sigma_xy_input);
+	Input* sigma_xz_input  = NULL;
+	Input* sigma_yz_input  = NULL;
+	Input* sigma_zz_input  = NULL;
+	if(dim==3){
+		sigma_xz_input  = this->GetInput(StressTensorxzEnum); _assert_(sigma_xz_input);
+		sigma_yz_input  = this->GetInput(StressTensoryzEnum); _assert_(sigma_yz_input);
+		sigma_zz_input  = this->GetInput(StressTensorzzEnum); _assert_(sigma_zz_input);
+	}
 
 	/*loop over vertices: */
@@ -1336,21 +1748,283 @@
 		gauss->GaussVertex(iv);
 
-		thickness_input->GetInputValue(&thickness,gauss);
-
-		this->StrainRateFS(&epsilon[0],xyz_list,gauss,vx_input,vy_input,vz_input);
-		this->ViscosityFS(&viscosity,3,xyz_list,gauss,vx_input,vy_input,vz_input);
-		this->GetPhi(&phi,&epsilon[0],viscosity);
-
-		viscousheating[iv]=phi*thickness;
-	}
-
-	/*Create PentaVertex input, which will hold the basal friction:*/
-	this->AddInput(ViscousHeatingEnum,viscousheating,P1Enum);
+		sigma_xx_input->GetInputValue(&sigma_xx,gauss);
+		sigma_yy_input->GetInputValue(&sigma_yy,gauss);
+		sigma_xy_input->GetInputValue(&sigma_xy,gauss);
+		if(dim==3){
+			sigma_xz_input->GetInputValue(&sigma_xz,gauss);
+			sigma_yz_input->GetInputValue(&sigma_yz,gauss);
+			sigma_zz_input->GetInputValue(&sigma_zz,gauss);
+		}
+
+		if(dim==2){
+			a = 0.;
+			b = 1.;
+			c = -sigma_yy -sigma_xx;
+			d = sigma_xx*sigma_yy - sigma_xy*sigma_xy;
+		}
+		else{
+			a = -1.;
+			b = sigma_xx+sigma_yy+sigma_zz;
+			c = -sigma_xx*sigma_yy -sigma_xx*sigma_zz -sigma_yy*sigma_zz + sigma_xy*sigma_xy +sigma_xz*sigma_xz +sigma_yz*sigma_yz;
+			d = sigma_xx*sigma_yy*sigma_zz - sigma_xx*sigma_yz*sigma_yz -sigma_yy*sigma_xz*sigma_xz - sigma_zz*sigma_xy*sigma_xy + 2.*sigma_xy*sigma_xz*sigma_yz;
+		}
+
+		/*Get roots of polynomials*/
+		cubic(a,b,c,d,x,&numroots);
+
+		/*Initialize maximum eigne value*/
+		if(numroots>0){
+			max = fabs(x[0]);
+		}
+		else{
+			_error_("No eigen value found");
+		}
+
+		/*Get max*/
+		for(int i=1;i<numroots;i++){
+			if(fabs(x[i])>max) max = fabs(x[i]);
+		}
+
+		maxprincipal[iv]=max;
+	}
+
+	/*Create input*/
+	this->AddInput(StressMaxPrincipalEnum,maxprincipal,P1Enum);
 
 	/*Clean up and return*/
-	xDelete<IssmDouble>(viscousheating);
+	xDelete<IssmDouble>(maxprincipal);
 	delete gauss;
 }
 /*}}}*/
+void       Element::ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){/*{{{*/
+	matpar->ThermalToEnthalpy(penthalpy,temperature,waterfraction,pressure);
+}/*}}}*/
+IssmDouble Element::TMeltingPoint(IssmDouble pressure){/*{{{*/
+	_assert_(matpar);
+	return this->matpar->TMeltingPoint(pressure);
+}/*}}}*/
+void       Element::TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,int transformenum){/*{{{*/
+
+	/*All nodes have the same Coordinate System*/
+	int numnodes  = this->GetNumberOfNodes();
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	TransformInvStiffnessMatrixCoord(Ke,this->nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
+
+	int         i,j;
+	int         numdofs   = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case PressureEnum: numdofs+=1; break;
+			case XYEnum:       numdofs+=2; break;
+			case XYZEnum:      numdofs+=3; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current stiffness matrix*/
+	values=xNew<IssmDouble>(Ke->nrows*Ke->ncols);
+	for(i=0;i<Ke->nrows;i++) for(j=0;j<Ke->ncols;j++) values[i*Ke->ncols+j]=Ke->values[i*Ke->ncols+j];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
+
+	/*Transform matrix: R*Ke*R^T */
+	TripleMultiply(transform,numdofs,numdofs,0,
+				values,Ke->nrows,Ke->ncols,0,
+				transform,numdofs,numdofs,1,
+				&Ke->values[0],0);
+
+	/*Free Matrix*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
+void       Element::TransformLoadVectorCoord(ElementVector* pe,int transformenum){/*{{{*/
+
+	/*All nodes have the same Coordinate System*/
+	int  numnodes = this->GetNumberOfNodes();
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	this->TransformLoadVectorCoord(pe,this->nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformLoadVectorCoord(ElementVector* pe,int* cs_array){/*{{{*/
+
+	this->TransformLoadVectorCoord(pe,this->nodes,this->GetNumberOfNodes(),cs_array);
+
+}/*}}}*/
+void       Element::TransformLoadVectorCoord(ElementVector* pe,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
+
+	int         i;
+	int         numdofs   = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case PressureEnum: numdofs+=1; break;
+			case XYEnum:       numdofs+=2; break;
+			case XYZEnum:      numdofs+=3; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current load vector*/
+	values=xNew<IssmDouble>(pe->nrows);
+	for(i=0;i<pe->nrows;i++) values[i]=pe->values[i];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
+
+	/*Transform matrix: R^T*pe */
+	MatrixMultiply(transform,numdofs,numdofs,1,
+				values,pe->nrows,1,0,
+				&pe->values[0],0);
+
+	/*Free Matrices*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* values,int transformenum){/*{{{*/
+
+	/*All nodes have the same Coordinate System*/
+	int  numnodes = this->GetNumberOfNodes();
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	this->TransformSolutionCoord(values,this->nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* values,int* transformenum_list){/*{{{*/
+	this->TransformSolutionCoord(values,this->nodes,this->GetNumberOfNodes(),transformenum_list);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* values,int numnodes,int transformenum){/*{{{*/
+
+	/*All nodes have the same Coordinate System*/
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	this->TransformSolutionCoord(values,this->nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* solution,int numnodes,int* cs_array){/*{{{*/
+	this->TransformSolutionCoord(solution,this->nodes,numnodes,cs_array);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* values,Node** nodes_list,int numnodes,int transformenum){/*{{{*/
+	/*NOT NEEDED*/
+	/*All nodes have the same Coordinate System*/
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	this->TransformSolutionCoord(values,nodes_list,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformSolutionCoord(IssmDouble* solution,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
+
+	int         i;
+	int         numdofs   = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case PressureEnum: numdofs+=1; break;
+			case XYEnum:       numdofs+=2; break;
+			case XYZEnum:      numdofs+=3; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current solution vector*/
+	values=xNew<IssmDouble>(numdofs);
+	for(i=0;i<numdofs;i++) values[i]=solution[i];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
+
+	/*Transform matrix: R*U */
+	MatrixMultiply(transform,numdofs,numdofs,0,
+				values,numdofs,1,0,
+				&solution[0],0);
+
+	/*Free Matrices*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
+void       Element::TransformStiffnessMatrixCoord(ElementMatrix* Ke,int transformenum){/*{{{*/
+
+	/*All nodes have the same Coordinate System*/
+	int  numnodes = this->GetNumberOfNodes();
+	int* cs_array = xNew<int>(numnodes);
+	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
+
+	/*Call core*/
+	this->TransformStiffnessMatrixCoord(Ke,this->nodes,numnodes,cs_array);
+
+	/*Clean-up*/
+	xDelete<int>(cs_array);
+}/*}}}*/
+void       Element::TransformStiffnessMatrixCoord(ElementMatrix* Ke,int* transformenum_list){/*{{{*/
+	this->TransformStiffnessMatrixCoord(Ke,this->nodes,this->GetNumberOfNodes(),transformenum_list);
+}/*}}}*/
+void       Element::TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
+
+	int         numdofs = 0;
+	IssmDouble *transform = NULL;
+	IssmDouble *values    = NULL;
+
+	/*Get total number of dofs*/
+	for(int i=0;i<numnodes;i++){
+		switch(cs_array[i]){
+			case PressureEnum: numdofs+=1; break;
+			case XYEnum:       numdofs+=2; break;
+			case XYZEnum:      numdofs+=3; break;
+			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
+		}
+	}
+
+	/*Copy current stiffness matrix*/
+	values=xNew<IssmDouble>(Ke->nrows*Ke->ncols);
+	for(int i=0;i<Ke->nrows*Ke->ncols;i++) values[i]=Ke->values[i];
+
+	/*Get Coordinate Systems transform matrix*/
+	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
+
+	/*Transform matrix: R^T*Ke*R */
+	TripleMultiply(transform,numdofs,numdofs,1,
+				values,Ke->nrows,Ke->ncols,0,
+				transform,numdofs,numdofs,0,
+				&Ke->values[0],0);
+
+	/*Free Matrix*/
+	xDelete<IssmDouble>(transform);
+	xDelete<IssmDouble>(values);
+}/*}}}*/
 void       Element::ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){/*{{{*/
 	/*The effective strain rate is defined in Paterson 3d Ed p 91 eq 9,
@@ -1392,4 +2066,35 @@
 }
 /*}}}*/
+void       Element::ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
+	this->material->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon);
+}/*}}}*/
+void       Element::ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble viscosity;
+	IssmDouble epsilon3d[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble epsilon2d[2];/* epsilon=[exx,exy];            */
+	IssmDouble eps_eff;
+
+	if(dim==3){
+		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
+		this->StrainRateHO(&epsilon3d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = sqrt(epsilon3d[0]*epsilon3d[0] + epsilon3d[1]*epsilon3d[1] + epsilon3d[2]*epsilon3d[2] +  epsilon3d[3]*epsilon3d[3] + epsilon3d[4]*epsilon3d[4] + epsilon3d[0]*epsilon3d[1]);
+	}
+	else{
+		/* eps_eff^2 = 1/2 (exx^2 + 2*exy^2 )*/
+		this->StrainRateHO2dvertical(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
+		eps_eff = 1./sqrt(2.)*sqrt(epsilon2d[0]*epsilon2d[0] + 2.*epsilon2d[1]*epsilon2d[1]);
+	}
+
+	/*Get viscosity*/
+	material->GetViscosity(&viscosity,eps_eff);
+
+	/*Assign output pointer*/
+	*pviscosity=viscosity;
+}/*}}}*/
+void       Element::ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
+	this->material->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon);
+}/*}}}*/
 void       Element::ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surface_input){/*{{{*/
 	/*Compute the L1L2 viscosity
@@ -1422,5 +2127,5 @@
 	surface_input->GetInputDerivativeValue(&slope[0],xyz_list,gauss);
 	z=this->GetZcoord(xyz_list,gauss);
-	tau_perp = matpar->GetRhoIce() * matpar->GetG() * fabs(s-z)*sqrt(slope[0]*slope[0]+slope[1]*slope[1]);
+	tau_perp = matpar->GetMaterialParameter(MaterialsRhoIceEnum) * matpar->GetMaterialParameter(ConstantsGEnum) * fabs(s-z)*sqrt(slope[0]*slope[0]+slope[1]*slope[1]);
 
 	/* Get eps_b*/
@@ -1450,29 +2155,4 @@
 	/*Assign output pointer*/
 	*pviscosity = viscosity;
-}/*}}}*/
-void       Element::ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
-
-	/*Intermediaries*/
-	IssmDouble viscosity;
-	IssmDouble epsilon3d[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
-	IssmDouble epsilon2d[2];/* epsilon=[exx,exy];            */
-	IssmDouble eps_eff;
-
-	if(dim==3){
-		/* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
-		this->StrainRateHO(&epsilon3d[0],xyz_list,gauss,vx_input,vy_input);
-		eps_eff = sqrt(epsilon3d[0]*epsilon3d[0] + epsilon3d[1]*epsilon3d[1] + epsilon3d[2]*epsilon3d[2] +  epsilon3d[3]*epsilon3d[3] + epsilon3d[4]*epsilon3d[4] + epsilon3d[0]*epsilon3d[1]);
-	}
-	else{
-		/* eps_eff^2 = 1/2 (exx^2 + 2*exy^2 )*/
-		this->StrainRateHO2dvertical(&epsilon2d[0],xyz_list,gauss,vx_input,vy_input);
-		eps_eff = 1./sqrt(2.)*sqrt(epsilon2d[0]*epsilon2d[0] + 2.*epsilon2d[1]*epsilon2d[1]);
-	}
-
-	/*Get viscosity*/
-	material->GetViscosity(&viscosity,eps_eff);
-
-	/*Assign output pointer*/
-	*pviscosity=viscosity;
 }/*}}}*/
 void       Element::ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
@@ -1504,347 +2184,44 @@
 	this->material->GetViscosity2dDerivativeEpsSquare(pmu_prime,epsilon);
 }/*}}}*/
-void       Element::ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
-	this->material->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon);
-}/*}}}*/
-void       Element::ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon){/*{{{*/
-	this->material->GetViscosityDerivativeEpsSquare(pmu_prime,epsilon);
-}/*}}}*/
-void       Element::StrainRateFS(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){/*{{{*/
-	/*Compute the 3d Strain Rate (6 components):
-	 *
-	 * epsilon=[exx eyy ezz exy exz eyz]
-	 */
+void       Element::ViscousHeatingCreateInput(void){/*{{{*/
 
 	/*Intermediaries*/
-	IssmDouble dvx[3];
-	IssmDouble dvy[3];
-	IssmDouble dvz[3];
-
-	/*Check that both inputs have been found*/
-	if (!vx_input || !vy_input || !vz_input){
-		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << ", vz: " << vz_input << "\n");
-	}
-
-	/*Get strain rate assuming that epsilon has been allocated*/
-	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
-	vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
-	vz_input->GetInputDerivativeValue(&dvz[0],xyz_list,gauss);
-	epsilon[0] = dvx[0];
-	epsilon[1] = dvy[1];
-	epsilon[2] = dvz[2];
-	epsilon[3] = 0.5*(dvx[1] + dvy[0]);
-	epsilon[4] = 0.5*(dvx[2] + dvz[0]);
-	epsilon[5] = 0.5*(dvy[2] + dvz[1]);
-
-}/*}}}*/
-void       Element::StrainRateHO(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
-	/*Compute the 3d Blatter/HOStrain Rate (5 components):
-	 *
-	 * epsilon=[exx eyy exy exz eyz]
-	 *
-	 * with exz=1/2 du/dz
-	 *      eyz=1/2 dv/dz
-	 *
-	 * the contribution of vz is neglected
-	 */
-
-	/*Intermediaries*/
-	IssmDouble dvx[3];
-	IssmDouble dvy[3];
-
-	/*Check that both inputs have been found*/
-	if (!vx_input || !vy_input){
-		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
-	}
-
-	/*Get strain rate assuming that epsilon has been allocated*/
-	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
-	vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
-	epsilon[0] = dvx[0];
-	epsilon[1] = dvy[1];
-	epsilon[2] = 0.5*(dvx[1] + dvy[0]);
-	epsilon[3] = 0.5*dvx[2];
-	epsilon[4] = 0.5*dvy[2];
-
-}/*}}}*/
-void       Element::StrainRateHO2dvertical(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
-	/*Compute the 2d Blatter/HOStrain Rate (2 components):
-	 *
-	 * epsilon=[exx exz]
-	 *
-	 * with exz=1/2 du/dz
-	 *
-	 * the contribution of vz is neglected
-	 */
-
-	/*Intermediaries*/
-	IssmDouble dvx[3];
-
-	/*Check that both inputs have been found*/
-	if (!vx_input){
-		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input <<"\n");
-	}
-
-	/*Get strain rate assuming that epsilon has been allocated*/
-	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
-	epsilon[0] = dvx[0];
-	epsilon[1] = 0.5*dvx[1];
-
-}/*}}}*/
-void       Element::StrainRateSSA(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){/*{{{*/
-
-	/*Intermediaries*/
-	IssmDouble dvx[3];
-	IssmDouble dvy[3];
-
-	/*Check that both inputs have been found*/
-	if(!vx_input || !vy_input){
-		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << ", vy: " << vy_input << "\n");
-	}
-
-	/*Get strain rate assuming that epsilon has been allocated*/
-	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
-	vy_input->GetInputDerivativeValue(&dvy[0],xyz_list,gauss);
-	epsilon[0] = dvx[0];
-	epsilon[1] = dvy[1];
-	epsilon[2] = 0.5*(dvx[1] + dvy[0]);
-
-}/*}}}*/
-void       Element::StrainRateSSA1d(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input){/*{{{*/
-
-	/*Intermediaries*/
-	IssmDouble dvx[3];
-
-	/*Check that both inputs have been found*/
-	if (!vx_input){
-		_error_("Input missing. Here are the input pointers we have for vx: " << vx_input << "\n");
-	}
-
-	/*Get strain rate assuming that epsilon has been allocated*/
-	vx_input->GetInputDerivativeValue(&dvx[0],xyz_list,gauss);
-	*epsilon = dvx[0];
-
-}/*}}}*/
-void       Element::TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,int transformenum){/*{{{*/
-
-	/*All nodes have the same Coordinate System*/
-	int numnodes  = this->GetNumberOfNodes();
-	int* cs_array = xNew<int>(numnodes);
-	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
-
-	/*Call core*/
-	TransformInvStiffnessMatrixCoord(Ke,this->nodes,numnodes,cs_array);
-
-	/*Clean-up*/
-	xDelete<int>(cs_array);
-}/*}}}*/
-void       Element::TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
-
-	int         i,j;
-	int         numdofs   = 0;
-	IssmDouble *transform = NULL;
-	IssmDouble *values    = NULL;
-
-	/*Get total number of dofs*/
-	for(i=0;i<numnodes;i++){
-		switch(cs_array[i]){
-			case PressureEnum: numdofs+=1; break;
-			case XYEnum:       numdofs+=2; break;
-			case XYZEnum:      numdofs+=3; break;
-			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
-		}
-	}
-
-	/*Copy current stiffness matrix*/
-	values=xNew<IssmDouble>(Ke->nrows*Ke->ncols);
-	for(i=0;i<Ke->nrows;i++) for(j=0;j<Ke->ncols;j++) values[i*Ke->ncols+j]=Ke->values[i*Ke->ncols+j];
-
-	/*Get Coordinate Systems transform matrix*/
-	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
-
-	/*Transform matrix: R*Ke*R^T */
-	TripleMultiply(transform,numdofs,numdofs,0,
-				values,Ke->nrows,Ke->ncols,0,
-				transform,numdofs,numdofs,1,
-				&Ke->values[0],0);
-
-	/*Free Matrix*/
-	xDelete<IssmDouble>(transform);
-	xDelete<IssmDouble>(values);
-}/*}}}*/
-void       Element::TransformLoadVectorCoord(ElementVector* pe,int transformenum){/*{{{*/
-
-	/*All nodes have the same Coordinate System*/
-	int  numnodes = this->GetNumberOfNodes();
-	int* cs_array = xNew<int>(numnodes);
-	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
-
-	/*Call core*/
-	this->TransformLoadVectorCoord(pe,this->nodes,numnodes,cs_array);
-
-	/*Clean-up*/
-	xDelete<int>(cs_array);
-}/*}}}*/
-void       Element::TransformLoadVectorCoord(ElementVector* pe,int* cs_array){/*{{{*/
-
-	this->TransformLoadVectorCoord(pe,this->nodes,this->GetNumberOfNodes(),cs_array);
-
-}/*}}}*/
-void       Element::TransformLoadVectorCoord(ElementVector* pe,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
-
-	int         i;
-	int         numdofs   = 0;
-	IssmDouble *transform = NULL;
-	IssmDouble *values    = NULL;
-
-	/*Get total number of dofs*/
-	for(i=0;i<numnodes;i++){
-		switch(cs_array[i]){
-			case PressureEnum: numdofs+=1; break;
-			case XYEnum:       numdofs+=2; break;
-			case XYZEnum:      numdofs+=3; break;
-			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
-		}
-	}
-
-	/*Copy current load vector*/
-	values=xNew<IssmDouble>(pe->nrows);
-	for(i=0;i<pe->nrows;i++) values[i]=pe->values[i];
-
-	/*Get Coordinate Systems transform matrix*/
-	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
-
-	/*Transform matrix: R^T*pe */
-	MatrixMultiply(transform,numdofs,numdofs,1,
-				values,pe->nrows,1,0,
-				&pe->values[0],0);
-
-	/*Free Matrices*/
-	xDelete<IssmDouble>(transform);
-	xDelete<IssmDouble>(values);
-}/*}}}*/
-void       Element::TransformSolutionCoord(IssmDouble* values,int transformenum){/*{{{*/
-
-	/*All nodes have the same Coordinate System*/
-	int  numnodes = this->GetNumberOfNodes();
-	int* cs_array = xNew<int>(numnodes);
-	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
-
-	/*Call core*/
-	this->TransformSolutionCoord(values,this->nodes,numnodes,cs_array);
-
-	/*Clean-up*/
-	xDelete<int>(cs_array);
-}/*}}}*/
-void       Element::TransformSolutionCoord(IssmDouble* values,int* transformenum_list){/*{{{*/
-	this->TransformSolutionCoord(values,this->nodes,this->GetNumberOfNodes(),transformenum_list);
-}/*}}}*/
-void       Element::TransformSolutionCoord(IssmDouble* values,int numnodes,int transformenum){/*{{{*/
-
-	/*All nodes have the same Coordinate System*/
-	int* cs_array = xNew<int>(numnodes);
-	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
-
-	/*Call core*/
-	this->TransformSolutionCoord(values,this->nodes,numnodes,cs_array);
-
-	/*Clean-up*/
-	xDelete<int>(cs_array);
-}/*}}}*/
-void       Element::TransformSolutionCoord(IssmDouble* solution,int numnodes,int* cs_array){/*{{{*/
-	this->TransformSolutionCoord(solution,this->nodes,numnodes,cs_array);
-}/*}}}*/
-void       Element::TransformSolutionCoord(IssmDouble* values,Node** nodes_list,int numnodes,int transformenum){/*{{{*/
-	/*NOT NEEDED*/
-	/*All nodes have the same Coordinate System*/
-	int* cs_array = xNew<int>(numnodes);
-	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
-
-	/*Call core*/
-	this->TransformSolutionCoord(values,nodes_list,numnodes,cs_array);
-
-	/*Clean-up*/
-	xDelete<int>(cs_array);
-}/*}}}*/
-void       Element::TransformSolutionCoord(IssmDouble* solution,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
-
-	int         i;
-	int         numdofs   = 0;
-	IssmDouble *transform = NULL;
-	IssmDouble *values    = NULL;
-
-	/*Get total number of dofs*/
-	for(i=0;i<numnodes;i++){
-		switch(cs_array[i]){
-			case PressureEnum: numdofs+=1; break;
-			case XYEnum:       numdofs+=2; break;
-			case XYZEnum:      numdofs+=3; break;
-			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
-		}
-	}
-
-	/*Copy current solution vector*/
-	values=xNew<IssmDouble>(numdofs);
-	for(i=0;i<numdofs;i++) values[i]=solution[i];
-
-	/*Get Coordinate Systems transform matrix*/
-	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
-
-	/*Transform matrix: R*U */
-	MatrixMultiply(transform,numdofs,numdofs,0,
-				values,numdofs,1,0,
-				&solution[0],0);
-
-	/*Free Matrices*/
-	xDelete<IssmDouble>(transform);
-	xDelete<IssmDouble>(values);
-}/*}}}*/
-void       Element::TransformStiffnessMatrixCoord(ElementMatrix* Ke,int transformenum){/*{{{*/
-
-	/*All nodes have the same Coordinate System*/
-	int  numnodes = this->GetNumberOfNodes();
-	int* cs_array = xNew<int>(numnodes);
-	for(int i=0;i<numnodes;i++) cs_array[i]=transformenum;
-
-	/*Call core*/
-	this->TransformStiffnessMatrixCoord(Ke,this->nodes,numnodes,cs_array);
-
-	/*Clean-up*/
-	xDelete<int>(cs_array);
-}/*}}}*/
-void       Element::TransformStiffnessMatrixCoord(ElementMatrix* Ke,int* transformenum_list){/*{{{*/
-	this->TransformStiffnessMatrixCoord(Ke,this->nodes,this->GetNumberOfNodes(),transformenum_list);
-}/*}}}*/
-void       Element::TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes_list,int numnodes,int* cs_array){/*{{{*/
-
-	int         numdofs = 0;
-	IssmDouble *transform = NULL;
-	IssmDouble *values    = NULL;
-
-	/*Get total number of dofs*/
-	for(int i=0;i<numnodes;i++){
-		switch(cs_array[i]){
-			case PressureEnum: numdofs+=1; break;
-			case XYEnum:       numdofs+=2; break;
-			case XYZEnum:      numdofs+=3; break;
-			default: _error_("Coordinate system " << EnumToStringx(cs_array[i]) << " not supported yet");
-		}
-	}
-
-	/*Copy current stiffness matrix*/
-	values=xNew<IssmDouble>(Ke->nrows*Ke->ncols);
-	for(int i=0;i<Ke->nrows*Ke->ncols;i++) values[i]=Ke->values[i];
-
-	/*Get Coordinate Systems transform matrix*/
-	CoordinateSystemTransform(&transform,nodes_list,numnodes,cs_array);
-
-	/*Transform matrix: R^T*Ke*R */
-	TripleMultiply(transform,numdofs,numdofs,1,
-				values,Ke->nrows,Ke->ncols,0,
-				transform,numdofs,numdofs,0,
-				&Ke->values[0],0);
-
-	/*Free Matrix*/
-	xDelete<IssmDouble>(transform);
-	xDelete<IssmDouble>(values);
-}/*}}}*/
+	IssmDouble phi;
+	IssmDouble viscosity;
+	IssmDouble epsilon[6];
+	IssmDouble thickness;
+	IssmDouble *xyz_list = NULL;
+
+	/*Fetch number vertices and allocate memory*/
+	int         numvertices    = this->GetNumberOfVertices();
+	IssmDouble* viscousheating = xNew<IssmDouble>(numvertices);
+
+	/*Retrieve all inputs and parameters*/
+	this->GetVerticesCoordinatesBase(&xyz_list);
+	Input* vx_input        = this->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input        = this->GetInput(VyEnum); _assert_(vy_input);
+	Input* vz_input        = this->GetInput(VzEnum); _assert_(vz_input);
+	Input* thickness_input = this->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/*loop over vertices: */
+	Gauss* gauss=this->NewGauss();
+	for (int iv=0;iv<numvertices;iv++){
+		gauss->GaussVertex(iv);
+
+		thickness_input->GetInputValue(&thickness,gauss);
+
+		this->StrainRateFS(&epsilon[0],xyz_list,gauss,vx_input,vy_input,vz_input);
+		this->ViscosityFS(&viscosity,3,xyz_list,gauss,vx_input,vy_input,vz_input);
+		this->GetPhi(&phi,&epsilon[0],viscosity);
+
+		viscousheating[iv]=phi*thickness;
+	}
+
+	/*Create PentaVertex input, which will hold the basal friction:*/
+	this->AddInput(ViscousHeatingEnum,viscousheating,P1Enum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(viscousheating);
+	delete gauss;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/Element.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Element.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/Element.h	(revision 19105)
@@ -56,236 +56,236 @@
 
 		/*Functions*/
-		void       AddInput(Input* input_in);
-		/* bool       AllActive(void); */
-		/* bool       AnyActive(void); */
-		void       ComputeNewDamage();
-		void       ComputeStrainRate();
-		void       CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes,int numnodes,int* cs_array);
-		void       Echo();
-		void       DeepEcho();
-		void       DeleteMaterials(void);
-		void       dViscositydBSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		void       dViscositydDSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		IssmDouble Divergence(void);
-		void       ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure);
-		void       EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure);
-		IssmDouble EnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure);
-		IssmDouble EnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure);
-		void       FindParam(bool* pvalue,int paramenum);
-		void       FindParam(int* pvalue,int paramenum);
-		void       FindParam(IssmDouble* pvalue,int paramenum);
-		void       FindParam(int** pvalues,int* psize,int paramenum);
-		void	     GetDofList(int** pdoflist,int approximation_enum,int setenum);
-		void	     GetDofListVelocity(int** pdoflist,int setenum);
-		void	     GetDofListPressure(int** pdoflist,int setenum);
-		Input*     GetInput(int inputenum);
-		void       GetInputListOnNodes(IssmDouble* pvalue,int enumtype);
-		void       GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
-		void       GetInputListOnNodesVelocity(IssmDouble* pvalue,int enumtype);
-		void       GetInputListOnVertices(IssmDouble* pvalue,int enumtype);
-		void       GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
-		void       GetInputValue(bool* pvalue,int enum_type);
-		void       GetInputValue(int* pvalue,int enum_type);
-		void       GetInputValue(IssmDouble* pvalue,int enum_type);
-		void       GetInputValue(IssmDouble* pvalue,Gauss* gauss,int enum_type);
-		IssmDouble GetMaterialParameter(int enum_in);
-		void       GetNodesSidList(int* sidlist);
-		void       GetNodesLidList(int* lidlist);
-		void       GetPhi(IssmDouble* phi, IssmDouble*  epsilon, IssmDouble viscosity);
-		void       GetVectorFromInputs(Vector<IssmDouble>* vector, int name_enum);
-		void	     GetVertexPidList(int* pidlist);
-		void       GetVerticesCoordinates(IssmDouble** xyz_list);
-		void       GetVerticesSidList(int* sidlist);
-		void       GetVerticesConnectivityList(int* connectivitylist);
-		IssmDouble GetXcoord(IssmDouble* xyz_list,Gauss* gauss);
-		IssmDouble GetYcoord(IssmDouble* xyz_list,Gauss* gauss);
-		IssmDouble GetZcoord(IssmDouble* xyz_list,Gauss* gauss);
-		void       GradientIndexing(int* indexing,int control_index);
-		bool       HasNodeOnBase();
-		bool       HasNodeOnSurface();
-		int        Id();
-		int        Sid();
-		void       InputChangeName(int enum_type,int enum_type_old);
-		void       InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
-		void       InputDuplicate(int original_enum,int new_enum);
-		void       InputUpdateFromConstant(IssmDouble constant, int name);
-		void       InputUpdateFromConstant(int constant, int name);
-		void       InputUpdateFromConstant(bool constant, int name);
-		bool       IsIceInElement();
-		bool	     IsInput(int name);
-		bool       IsFloating(); 
-		void       LinearFloatingiceMeltingRate(); 
-		ElementVector*  NewElementVector(int approximation_enum=NoneApproximationEnum);
-		ElementMatrix*  NewElementMatrix(int approximation_enum=NoneApproximationEnum);
-		ElementMatrix*  NewElementMatrixCoupling(int number_nodes,int approximation_enum=NoneApproximationEnum);
-		IssmDouble PureIceEnthalpy(IssmDouble pressure);
-		void       ResultInterpolation(int* pinterpolation,int*nodesperelement,int output_enum);
-		void       ResultToVector(Vector<IssmDouble>* vector,int output_enum);
-		void       ResultToPatch(IssmDouble* values,int nodesperelement,int output_enum);
-		void       SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum);
-		void       StrainRateSSA(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		void       StrainRateSSA1d(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input);
-		void       StrainRateHO(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		void       StrainRateHO2dvertical(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		void       StrainRateFS(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
-		IssmDouble TMeltingPoint(IssmDouble pressure);
-		void       TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,int cs_enum);
-		void       TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
-		void       TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
-		void       TransformLoadVectorCoord(ElementVector* pe,int cs_enum);
-		void       TransformLoadVectorCoord(ElementVector* pe,int* cs_array);
-		void       TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int cs_enum);
-		void       TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array);
-		void       TransformSolutionCoord(IssmDouble* solution,int cs_enum);
-		void       TransformSolutionCoord(IssmDouble* solution,int* cs_array);
-		void       TransformSolutionCoord(IssmDouble* solution,int numnodes,int cs_enum);
-		void       TransformSolutionCoord(IssmDouble* solution,int numnodes,int* cs_array);
-		void       TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int cs_enum);
-		void       TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int* cs_array);
-		void       TransformStiffnessMatrixCoord(ElementMatrix* Ke,int cs_enum);
-		void       TransformStiffnessMatrixCoord(ElementMatrix* Ke,int* cs_array);
-		void       TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
-		void       TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
-		void       ViscousHeatingCreateInput(void);
-		void       ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
-		void       ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		void       ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf);
-		void       ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
-		void       ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
-		void       ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
-		void       ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
-		void       TransformLoadVectorCoord(ElementVector* pe,int numnodes,int transformenum){_error_("not implemented yet");};/*Tiling only*/
-		void       TransformLoadVectorCoord(ElementVector* pe,int numnodes,int* transformenum_list){_error_("not implemented yet");};/*Tiling only*/
-		void       TransformStiffnessMatrixCoord(ElementMatrix* Ke,int numnodes,int* transformenum_list){_error_("not implemented yet");};/*Tiling only*/
+		void               AddInput(Input* input_in);
+		/*bool               AllActive(void);*/
+		/*bool               AnyActive(void);*/
+		void               ComputeNewDamage();
+		void               ComputeStrainRate();
+		void               CoordinateSystemTransform(IssmDouble** ptransform,Node** nodes,int numnodes,int* cs_array);
+		void               Echo();
+		void               DeepEcho();
+		void               DeleteInput(int input_enum);
+		void               DeleteMaterials(void);
+		IssmDouble         Divergence(void);
+		void               dViscositydBFS(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
+		void               dViscositydBHO(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void               dViscositydBSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void               dViscositydDSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		IssmDouble         EnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure);
+		IssmDouble         EnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure);
+		void               EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure);
+		void               FindParam(bool* pvalue,int paramenum);
+		void               FindParam(int* pvalue,int paramenum);
+		void               FindParam(IssmDouble* pvalue,int paramenum);
+		void               FindParam(int** pvalues,int* psize,int paramenum);
+		void	             GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void	             GetDofListPressure(int** pdoflist,int setenum);
+		void	             GetDofListVelocity(int** pdoflist,int setenum);
+		Input*             GetInput(int inputenum);
+		void               GetInputListOnNodes(IssmDouble* pvalue,int enumtype);
+		void               GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
+		void               GetInputListOnNodesVelocity(IssmDouble* pvalue,int enumtype);
+		void               GetInputListOnVertices(IssmDouble* pvalue,int enumtype);
+		void               GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
+		void               GetInputLocalMinMaxOnNodes(IssmDouble* min,IssmDouble* max,IssmDouble* ug);
+		void               GetInputValue(bool* pvalue,int enum_type);
+		void               GetInputValue(int* pvalue,int enum_type);
+		void               GetInputValue(IssmDouble* pvalue,int enum_type);
+		void               GetInputValue(IssmDouble* pvalue,Gauss* gauss,int enum_type);
+		IssmDouble         GetMaterialParameter(int enum_in);
+		void               GetNodesLidList(int* lidlist);
+		void               GetNodesSidList(int* sidlist);
+		void               GetPhi(IssmDouble* phi, IssmDouble*  epsilon, IssmDouble viscosity);
+		void               GetVectorFromInputs(Vector<IssmDouble>* vector, int name_enum, int type);
+		void	             GetVertexPidList(int* pidlist);
+		void               GetVerticesConnectivityList(int* connectivitylist);
+		void               GetVerticesCoordinates(IssmDouble** xyz_list);
+		void               GetVerticesSidList(int* sidlist);
+		IssmDouble         GetXcoord(IssmDouble* xyz_list,Gauss* gauss);
+		IssmDouble         GetYcoord(IssmDouble* xyz_list,Gauss* gauss);
+		IssmDouble         GetZcoord(IssmDouble* xyz_list,Gauss* gauss);
+		void               GradientIndexing(int* indexing,int control_index,bool onsid=false);
+		bool               HasNodeOnBase();
+		bool               HasNodeOnSurface();
+		int                Id();
+		void               InputChangeName(int enum_type,int enum_type_old);
+		void               InputCreate(IssmDouble* vector,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
+		void               InputDuplicate(int original_enum,int new_enum);
+		void               InputUpdateFromConstant(IssmDouble constant, int name);
+		void               InputUpdateFromConstant(int constant, int name);
+		void               InputUpdateFromConstant(bool constant, int name);
+		bool               IsFloating(); 
+		bool               IsIceInElement();
+		bool	             IsInput(int name);
+		void               LinearFloatingiceMeltingRate(); 
+		void               MigrateGroundingLine(IssmDouble* sheet_ungrounding);
+		ElementMatrix*     NewElementMatrix(int approximation_enum=NoneApproximationEnum);
+		ElementMatrix*     NewElementMatrixCoupling(int number_nodes,int approximation_enum=NoneApproximationEnum);
+		ElementVector*     NewElementVector(int approximation_enum=NoneApproximationEnum);
+		IssmDouble         PureIceEnthalpy(IssmDouble pressure);
+		void               ResultInterpolation(int* pinterpolation,int*nodesperelement,int output_enum);
+		void               ResultToPatch(IssmDouble* values,int nodesperelement,int output_enum);
+		void               ResultToVector(Vector<IssmDouble>* vector,int output_enum);
+		void               SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum);
+		int                Sid();
+		void               StrainRateFS(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
+		void               StrainRateHO(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void               StrainRateHO2dvertical(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void               StrainRateSSA(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void               StrainRateSSA1d(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input);
+		void               StressMaxPrincipalCreateInput(void);
+		void               ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure);
+		IssmDouble         TMeltingPoint(IssmDouble pressure);
+		void               TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,int cs_enum);
+		void               TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
+		void               TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
+		void               TransformLoadVectorCoord(ElementVector* pe,int cs_enum);
+		void               TransformLoadVectorCoord(ElementVector* pe,int* cs_array);
+		void               TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int cs_enum);
+		void               TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array);
+		void               TransformLoadVectorCoord(ElementVector* pe,int numnodes,int transformenum){_error_("not implemented yet");};/*Tiling only*/
+		void               TransformLoadVectorCoord(ElementVector* pe,int numnodes,int* transformenum_list){_error_("not implemented yet");};/*Tiling only*/
+		void               TransformSolutionCoord(IssmDouble* solution,int cs_enum);
+		void               TransformSolutionCoord(IssmDouble* solution,int* cs_array);
+		void               TransformSolutionCoord(IssmDouble* solution,int numnodes,int cs_enum);
+		void               TransformSolutionCoord(IssmDouble* solution,int numnodes,int* cs_array);
+		void               TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int cs_enum);
+		void               TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int* cs_array);
+		void               TransformStiffnessMatrixCoord(ElementMatrix* Ke,int cs_enum);
+		void               TransformStiffnessMatrixCoord(ElementMatrix* Ke,int* cs_array);
+		void               TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
+		void               TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
+		void               TransformStiffnessMatrixCoord(ElementMatrix* Ke,int numnodes,int* transformenum_list){_error_("not implemented yet");};/*Tiling only*/
+		void               ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
+		void               ViscosityFSDerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
+		void               ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void               ViscosityHODerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
+		void               ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf);
+		void               ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
+		void               ViscositySSADerivativeEpsSquare(IssmDouble* pmu_prime,IssmDouble* epsilon);
+		void               ViscousHeatingCreateInput(void);
 
 		/*Virtual functions*/
 		virtual void       AddBasalInput(int input_enum, IssmDouble* values, int interpolation_enum)=0;
 		virtual void       AddInput(int input_enum, IssmDouble* values, int interpolation_enum)=0;
+		virtual void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part)=0;
+		virtual void	    CalvingRateLevermann(void)=0;
+		virtual void       CalvingRatePi(void)=0;
+		virtual void       CalvingRateDev(void){_error_("not implemented yet");};
 		virtual IssmDouble CharacteristicLength(void)=0;
+		virtual void       ComputeBasalStress(Vector<IssmDouble>* sigma_b)=0;
+		virtual void       ComputeDeviatoricStressTensor(void)=0;
+		virtual void       ComputeSigmaNN(void)=0;
+		virtual void       ComputeStressTensor(void)=0;
 		virtual void       Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index)=0;
+		virtual void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum)=0;
+		virtual void       Delta18oParameterization(void)=0;
+		virtual void       MungsmtpParameterization(void)=0;
+		virtual void       ElementResponse(IssmDouble* presponse,int response_enum)=0;
+		virtual void       ElementSizes(IssmDouble* phx,IssmDouble* phy,IssmDouble* phz)=0;
+		virtual int        FiniteElement(void)=0;
+		virtual void       FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating)=0;
+		virtual Element*   GetBasalElement(void)=0;
+		virtual int        GetElementType(void)=0;
+		virtual void       GetGroundedPart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlyfloating)=0;
+		virtual IssmDouble GetGroundedPortion(IssmDouble* xyz_list)=0;
+		virtual void       GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum)=0;
+		virtual void       GetInputValue(IssmDouble* pvalue,Node* node,int enumtype)=0;
+		virtual void       GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level)=0;
+		virtual void       GetLevelsetPositivePart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlynegative,IssmDouble* levelsetvalues)=0;
+		virtual Node*      GetNode(int node_number)=0;
+		virtual int        GetNodeIndex(Node* node)=0;
+		virtual int        GetNumberOfNodes(void)=0;
+		virtual int        GetNumberOfNodes(int enum_type)=0;
+		virtual int        GetNumberOfVertices(void)=0;
+		virtual void       GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int solutionenum)=0;
+		virtual Element*   GetUpperElement(void)=0;
+		virtual void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,bool onsid)=0;
+		virtual void       GetVerticesCoordinatesBase(IssmDouble** xyz_list)=0;
+		virtual void       GetVerticesCoordinatesTop(IssmDouble** xyz_list)=0;
+		virtual IssmDouble IceMass(void)=0;
+		virtual IssmDouble IceVolume(void)=0;
+		virtual IssmDouble IceVolumeAboveFloatation(void)=0;
+		virtual void       InputControlUpdate(IssmDouble scalar,bool save_parameter)=0;
+		virtual void       InputDepthAverageAtBase(int enum_type,int average_enum_type)=0;
+		virtual void       InputExtrude(int input_enum,int start)=0;
+		virtual void       InputScale(int enum_type,IssmDouble scale_factor)=0;
+		virtual void       InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int inputenum)=0;
+		virtual void       InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum)=0;
+		virtual bool       IsFaceOnBoundary(void)=0;
+		virtual bool       IsIcefront(void)=0;
+		virtual bool       IsNodeOnShelfFromFlags(IssmDouble* flags)=0; 
+		virtual bool       IsOnBase()=0;
+		virtual bool       IsOnSurface()=0;
+		virtual bool       IsZeroLevelset(int levelset_enum)=0;
+		virtual void       JacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void       JacobianDeterminantBase(IssmDouble* Jdet,IssmDouble* xyz_list_base,Gauss* gauss)=0;
+		virtual void       JacobianDeterminantLine(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void       JacobianDeterminantSurface(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void       JacobianDeterminantTop(IssmDouble* Jdet,IssmDouble* xyz_list_base,Gauss* gauss)=0;
+		virtual IssmDouble Masscon(IssmDouble* levelset)=0;
+		virtual IssmDouble MassFlux(IssmDouble* segment)=0;
+		virtual IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id)=0;
+		virtual IssmDouble MinEdgeLength(IssmDouble* xyz_list)=0;
+		virtual IssmDouble Misfit(int modelenum,int observationenum,int weightsenum)=0;
+		virtual IssmDouble MisfitArea(int weightsenum)=0;
+		virtual Gauss*     NewGauss(void)=0;
+		virtual Gauss*     NewGauss(int order)=0;
+      virtual Gauss*     NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order)=0;
+      virtual Gauss*     NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert)=0;
+      virtual Gauss*     NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order)=0;
+		virtual Gauss*     NewGaussBase(int order)=0;
+		virtual Gauss*     NewGaussLine(int vertex1,int vertex2,int order)=0;
+		virtual Gauss*     NewGaussTop(int order)=0;
+		virtual void       NodalFunctions(IssmDouble* basis,Gauss* gauss)=0;
+		virtual void       NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void       NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void       NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void       NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss)=0;
+		virtual void       NodalFunctionsP1(IssmDouble* basis,Gauss* gauss)=0;
+		virtual void       NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void       NodalFunctionsP2(IssmDouble* basis,Gauss* gauss)=0;
+		virtual void       NodalFunctionsVelocity(IssmDouble* basis, Gauss* gauss)=0;
+		virtual void       NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss)=0;
+		virtual int        NodalValue(IssmDouble* pvalue, int index, int natureofdataenum)=0;
+		virtual void       NormalBase(IssmDouble* normal,IssmDouble* xyz_list)=0;
+		virtual void       NormalSection(IssmDouble* normal,IssmDouble* xyz_list)=0;
+		virtual void       NormalTop(IssmDouble* normal,IssmDouble* xyz_list)=0;
+		virtual int        NumberofNodesPressure(void)=0;
+		virtual int        NumberofNodesVelocity(void)=0;
+		virtual void       PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm)=0;
+		virtual void       PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding)=0;
+		virtual int        PressureInterpolation()=0;
+		virtual void       ReduceMatrices(ElementMatrix* Ke,ElementVector* pe)=0;
+		virtual void       ResetFSBasalBoundaryCondition()=0;
+		virtual void       ResetHooks()=0;
+		virtual void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index)=0;
 		virtual void       SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters)=0;
-		virtual void       ResetHooks()=0;
-		virtual void   ElementSizes(IssmDouble* phx,IssmDouble* phy,IssmDouble* phz)=0;
-
-		virtual int    FiniteElement(void)=0;
-		virtual IssmDouble MinEdgeLength(IssmDouble* xyz_list)=0;
-		virtual void   NodalFunctions(IssmDouble* basis,Gauss* gauss)=0;
-		virtual void   NodalFunctionsP1(IssmDouble* basis,Gauss* gauss)=0;
-		virtual void   NodalFunctionsP2(IssmDouble* basis,Gauss* gauss)=0;
-		virtual void   NodalFunctionsVelocity(IssmDouble* basis, Gauss* gauss)=0;
-		virtual void   NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss)=0;
-		virtual void   NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss)=0;
-		virtual void   NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
-		virtual void   NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
-		virtual void   NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
-		virtual void   NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss)=0;
-		virtual void   NormalSection(IssmDouble* normal,IssmDouble* xyz_list)=0;
-		virtual void   NormalTop(IssmDouble* normal,IssmDouble* xyz_list)=0;
-		virtual void   NormalBase(IssmDouble* normal,IssmDouble* xyz_list)=0;
-
-		virtual Element* GetUpperElement(void)=0;
-		virtual Element* GetBasalElement(void)=0;
-
-		virtual void   JacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss)=0;
-		virtual void   JacobianDeterminantLine(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss)=0;
-		virtual void   JacobianDeterminantSurface(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss)=0;
-		virtual void   JacobianDeterminantBase(IssmDouble* Jdet,IssmDouble* xyz_list_base,Gauss* gauss)=0;
-		virtual void   JacobianDeterminantTop(IssmDouble* Jdet,IssmDouble* xyz_list_base,Gauss* gauss)=0;
-		virtual void   GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int solutionenum)=0;
-		virtual int    GetNodeIndex(Node* node)=0;
-		virtual int    GetNumberOfNodes(void)=0;
-		virtual int    GetNumberOfNodes(int enum_type)=0;
-		virtual int    GetNumberOfVertices(void)=0;
-
-		virtual bool   IsNodeOnShelfFromFlags(IssmDouble* flags)=0; 
-		virtual bool   IsOnBase()=0;
-		virtual bool   IsOnSurface()=0;
-		virtual void   GetGroundedPart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlyfloating)=0;
-		virtual IssmDouble GetGroundedPortion(IssmDouble* xyz_list)=0;
-		virtual void   GetInputValue(IssmDouble* pvalue,Node* node,int enumtype)=0;
-		virtual Node*  GetNode(int node_number)=0;
-		virtual void   GetVerticesCoordinatesBase(IssmDouble** xyz_list)=0;
-		virtual void   GetVerticesCoordinatesTop(IssmDouble** xyz_list)=0;
-
-		virtual int    GetElementType(void)=0;
-
-		virtual IssmDouble SurfaceArea(void)=0;
-		virtual void   InputDepthAverageAtBase(int enum_type,int average_enum_type)=0;
-		virtual void   ComputeSigmaNN(void)=0;
-		virtual void   ComputeBasalStress(Vector<IssmDouble>* sigma_b)=0;
-		virtual void   ComputeStressTensor(void)=0;
-		virtual void   ComputeDeviatoricStressTensor(void)=0;
-
-		virtual void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finite_element)=0;
-		virtual void   InputExtrude(int input_enum)=0;
-		virtual void   InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int inputenum)=0;
-		virtual void   InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum)=0;
-
-		virtual int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum)=0;
-		virtual int    NumberofNodesVelocity(void)=0;
-		virtual int    NumberofNodesPressure(void)=0;
-		virtual Gauss* NewGauss(void)=0;
-		virtual Gauss* NewGauss(int order)=0;
-      virtual Gauss* NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order)=0;
-      virtual Gauss* NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert)=0;
-      virtual Gauss* NewGauss(int point1,IssmDouble fraction1,IssmDouble fraction2,bool mainlyfloating,int order)=0;
-		virtual Gauss* NewGaussBase(int order)=0;
-		virtual Gauss* NewGaussLine(int vertex1,int vertex2,int order)=0;
-		virtual Gauss* NewGaussTop(int order)=0;
-
-		virtual void   InputScale(int enum_type,IssmDouble scale_factor)=0;
-		virtual IssmDouble TimeAdapt()=0;
-		virtual void   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm)=0;
-		virtual void   Delta18oParameterization(void)=0;
+		virtual void       SetTemporaryElementType(int element_type_in)=0;
 	   virtual Element*   SpawnBasalElement(void)=0;
 		virtual Element*   SpawnTopElement(void)=0;
-		virtual void   ReduceMatrices(ElementMatrix* Ke,ElementVector* pe)=0;
-		virtual void   ResetFSBasalBoundaryCondition()=0;
-		virtual void   SetTemporaryElementType(int element_type_in)=0;
 		virtual IssmDouble StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa)=0;
-		virtual void   ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss)=0;
-		virtual void   ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss)=0;
-		virtual void   ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input)=0;
-
-		virtual int    VelocityInterpolation()=0;
-		virtual int    PressureInterpolation()=0;
-		virtual int    TensorInterpolation()=0;
-		virtual bool   IsZeroLevelset(int levelset_enum)=0;
-		virtual bool   IsIcefront(void)=0;
-		virtual bool   IsFaceOnBoundary(void)=0;
-		virtual void   ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum)=0;
-		virtual void   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum)=0;
-		virtual void   GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level)=0;
-
-		virtual void   AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part)=0;
-		virtual IssmDouble MassFlux(IssmDouble* segment)=0;
-		virtual IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id)=0;
-		virtual void   ElementResponse(IssmDouble* presponse,int response_enum)=0;
-		virtual IssmDouble IceVolume(void)=0;
-		virtual IssmDouble IceVolumeAboveFloatation(void)=0;
+		virtual void	    StrainRateparallel(void)=0;
+		virtual void	    StrainRateperpendicular(void)=0;
+		virtual void	    StressIntensityFactor(void)=0;
+		virtual IssmDouble SurfaceArea(void)=0;
+		virtual int        TensorInterpolation()=0;
+		virtual IssmDouble TimeAdapt()=0;
 		virtual IssmDouble TotalSmb(void)=0;
-		virtual IssmDouble Misfit(int modelenum,int observationenum,int weightsenum)=0;
-		virtual IssmDouble MisfitArea(int weightsenum)=0;
-		virtual int    VertexConnectivity(int vertexindex)=0;
-		virtual void   VerticalSegmentIndices(int** pindices,int* pnumseg)=0;
+		virtual void       Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finite_element)=0;
+		virtual void       UpdateConstraintsExtrudeFromBase(void)=0;
+		virtual void       UpdateConstraintsExtrudeFromTop(void)=0;
+		virtual int        UpdatePotentialUngrounding(IssmDouble* potential_sheet_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf)=0;
+		virtual void       ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss)=0;
+		virtual void       ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss)=0;
+		virtual int        VelocityInterpolation()=0;
+		virtual int        VertexConnectivity(int vertexindex)=0;
+		virtual void       VerticalSegmentIndices(int** pindices,int* pnumseg)=0;
+		virtual void       ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input)=0;
+		virtual void       ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum)=0;
 
 		#ifdef _HAVE_GIA_
-		virtual void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y)=0;
+		virtual void       GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y)=0;
 		#endif
-
-		virtual void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index)=0;
-		virtual void   ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum)=0;
-		virtual void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data)=0;
-		virtual void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index)=0;
-		virtual void   InputControlUpdate(IssmDouble scalar,bool save_parameter)=0;
-
-		virtual void UpdateConstraintsExtrudeFromBase(void)=0;
-		virtual void UpdateConstraintsExtrudeFromTop(void)=0;
-
-		virtual void   MigrateGroundingLine(IssmDouble* sheet_ungrounding)=0;
-		virtual void   FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating)=0;
-		virtual void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding)=0;
-		virtual int    UpdatePotentialUngrounding(IssmDouble* potential_sheet_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf)=0;
-
 };
 #endif
Index: /issm/trunk/src/c/classes/Elements/ElementHook.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 19105)
@@ -75,10 +75,36 @@
 /*}}}*/
 
+void ElementHook::InitHookNeighbors(int* element_ids){/*{{{*/
+	this->hneighbors=new Hook(element_ids,2);
+}
+/*}}}*/
 void ElementHook::SetHookNodes(int* node_ids,int numnodes,int analysis_counter){/*{{{*/
 	if(this->hnodes) this->hnodes[analysis_counter]= new Hook(node_ids,numnodes);
 }
 /*}}}*/
-void ElementHook::InitHookNeighbors(int* element_ids){/*{{{*/
-	this->hneighbors=new Hook(element_ids,2);
+void ElementHook::SpawnSegHook(ElementHook* triahook,int index1,int index2){/*{{{*/
+
+	triahook->numanalyses=this->numanalyses;
+
+	int indices[2];
+	indices[0]=index1;
+	indices[1]=index2;
+
+	/*Spawn nodes hook*/
+	triahook->hnodes=new Hook*[this->numanalyses];
+	for(int i=0;i<this->numanalyses;i++){
+		/*Do not do anything if Hook is empty*/
+		if (!this->hnodes[i] || this->hnodes[i]->GetNum()==0){
+			triahook->hnodes[i]=NULL;
+		}
+		else{
+			triahook->hnodes[i]=this->hnodes[i]->Spawn(indices,2);
+		}
+	}
+
+	/*do not spawn hmaterial. material will be taken care of by Tria*/
+	triahook->hmaterial=NULL;
+	triahook->hvertices=(Hook*)this->hvertices->Spawn(indices,2);
+	triahook->hmatpar=(Hook*)this->hmatpar->copy();
 }
 /*}}}*/
@@ -111,28 +137,2 @@
 }
 /*}}}*/
-void ElementHook::SpawnSegHook(ElementHook* triahook,int index1,int index2){/*{{{*/
-
-	triahook->numanalyses=this->numanalyses;
-
-	int indices[2];
-	indices[0]=index1;
-	indices[1]=index2;
-
-	/*Spawn nodes hook*/
-	triahook->hnodes=new Hook*[this->numanalyses];
-	for(int i=0;i<this->numanalyses;i++){
-		/*Do not do anything if Hook is empty*/
-		if (!this->hnodes[i] || this->hnodes[i]->GetNum()==0){
-			triahook->hnodes[i]=NULL;
-		}
-		else{
-			triahook->hnodes[i]=this->hnodes[i]->Spawn(indices,2);
-		}
-	}
-
-	/*do not spawn hmaterial. material will be taken care of by Tria*/
-	triahook->hmaterial=NULL;
-	triahook->hvertices=(Hook*)this->hvertices->Spawn(indices,2);
-	triahook->hmatpar=(Hook*)this->hmatpar->copy();
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/ElementHook.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/ElementHook.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/ElementHook.h	(revision 19105)
@@ -24,8 +24,8 @@
 		~ElementHook();
 
+		void InitHookNeighbors(int* element_ids);               //3d only
 		void SetHookNodes(int* node_ids,int numnodes,int analysis_counter);
+		void SpawnSegHook(ElementHook* triahook,int ndex1,int index2); //2d only
 		void SpawnTriaHook(ElementHook* triahook,int index1,int index2,int index3); //3d only
-		void SpawnSegHook(ElementHook* triahook,int ndex1,int index2); //2d only
-		void InitHookNeighbors(int* element_ids);               //3d only
 };
 
Index: /issm/trunk/src/c/classes/Elements/Elements.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Elements.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/Elements.cpp	(revision 19105)
@@ -41,5 +41,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		element=dynamic_cast<Element*>((*object));
+		element=xDynamicCast<Element*>((*object));
 		element->Configure(elements,loads,nodes,vertices,materials,parameters);
 
@@ -55,5 +55,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		element=dynamic_cast<Element*>((*object));
+		element=xDynamicCast<Element*>((*object));
 		element->SetCurrentConfiguration(elements,loads,nodes,materials,parameters);
 
@@ -69,5 +69,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		element=dynamic_cast<Element*>((*object));
+		element=xDynamicCast<Element*>((*object));
 		element->ResetHooks();
 
@@ -85,5 +85,5 @@
 	for(int i=0;i<this->Size();i++){
 
-		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->GetObjectByOffset(i));
 		numnodes=element->GetNumberOfNodes();
 		if(numnodes>max)max=numnodes;
@@ -111,5 +111,5 @@
 
 	for(int i=0;i<this->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->GetObjectByOffset(i));
 		element->InputDuplicate(input_enum,output_enum);
 	}
Index: /issm/trunk/src/c/classes/Elements/Penta.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 19105)
@@ -125,10 +125,4 @@
 
 /*Other*/
-void       Penta::AddInput(int input_enum,IssmDouble* values, int interpolation_enum){/*{{{*/
-
-	_assert_(this->inputs);
-	this->inputs->AddInput(new PentaInput(input_enum,values,interpolation_enum));
-}
-/*}}}*/
 void       Penta::AddBasalInput(int input_enum,IssmDouble* values, int interpolation_enum){/*{{{*/
 
@@ -154,4 +148,144 @@
 		else _error_("not implemented yet");
 	}
+}
+/*}}}*/
+void       Penta::AddInput(int input_enum,IssmDouble* values, int interpolation_enum){/*{{{*/
+
+	_assert_(this->inputs);
+	this->inputs->AddInput(new PentaInput(input_enum,values,interpolation_enum));
+}
+/*}}}*/
+void       Penta::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){/*{{{*/
+	_error_("Not supported yet!");
+}
+/*}}}*/
+void       Penta::CalvingRateLevermann(){/*{{{*/
+
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	GaussPenta* gauss=NULL;
+	IssmDouble  vx,vy,vel;
+	IssmDouble  strainparallel;
+	IssmDouble  propcoeff;
+	IssmDouble  strainperpendicular;
+	IssmDouble  calvingratex[NUMVERTICES];
+	IssmDouble  calvingratey[NUMVERTICES];
+	IssmDouble  calvingrate[NUMVERTICES];
+
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs and parameters we will need*/
+	Input* vx_input=inputs->GetInput(VxEnum);																		_assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);																		_assert_(vy_input);
+	Input* strainparallel_input=inputs->GetInput(StrainRateparallelEnum);								_assert_(strainparallel_input);
+	Input* strainperpendicular_input=inputs->GetInput(StrainRateperpendicularEnum);              _assert_(strainperpendicular_input);
+	Input* levermanncoeff_input=inputs->GetInput(CalvinglevermannCoeffEnum);                     _assert_(levermanncoeff_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/* Get the value we need*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel=vx*vx+vy*vy;
+		strainparallel_input->GetInputValue(&strainparallel,gauss);
+		strainperpendicular_input->GetInputValue(&strainperpendicular,gauss);
+		levermanncoeff_input->GetInputValue(&propcoeff,gauss);
+
+		/*Calving rate proportionnal to the positive product of the strain rate along the ice flow direction and the strain rate perpendicular to the ice flow */
+		calvingrate[iv]=propcoeff*strainparallel*strainperpendicular;	
+		if(calvingrate[iv]<0){
+			calvingrate[iv]=0;
+		}
+		calvingratex[iv]=calvingrate[iv]*vx/(sqrt(vel)+1.e-14);
+		calvingratey[iv]=calvingrate[iv]*vy/(sqrt(vel)+1.e-14);
+	}
+
+	/*Add input*/
+	this->inputs->AddInput(new PentaInput(CalvingratexEnum,&calvingratex[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(CalvingrateyEnum,&calvingratey[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(CalvingCalvingrateEnum,&calvingrate[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+
+}
+/*}}}*/
+void       Penta::CalvingRatePi(){/*{{{*/
+
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	GaussPenta* gauss=NULL;
+	IssmDouble  vx,vy,vel;
+	IssmDouble  strainparallel;
+	IssmDouble  sxx;
+	IssmDouble  sxy;
+	IssmDouble  syy;
+	IssmDouble  sigVM;
+	IssmDouble  thickness;
+	IssmDouble  base;
+	IssmDouble  hAB;
+	IssmDouble  propcoeff;
+	IssmDouble  calvingratex[NUMVERTICES];
+	IssmDouble  calvingratey[NUMVERTICES];
+	IssmDouble  calvingrate[NUMVERTICES];
+
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs and parameters we will need*/
+	Input* vx_input=inputs->GetInput(VxEnum);                                                    _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                                                    _assert_(vy_input);
+	Input* strainparallel_input=inputs->GetInput(StrainRateparallelEnum);                        _assert_(strainparallel_input);
+	Input* sxx_input=inputs->GetInput(DeviatoricStressxxEnum);                                   _assert_(sxx_input);
+	Input* sxy_input=inputs->GetInput(DeviatoricStressxyEnum);                                   _assert_(sxy_input);
+	Input* syy_input=inputs->GetInput(DeviatoricStressyyEnum);                                   _assert_(syy_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);                                      _assert_(thickness_input);
+	Input* base_input=inputs->GetInput(BaseEnum);                                                _assert_(base_input);
+	Input* picoeff_input=inputs->GetInput(CalvingpiCoeffEnum);                                   _assert_(picoeff_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/* Get the value we need*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel=vx*vx+vy*vy;
+		strainparallel_input->GetInputValue(&strainparallel,gauss);
+		sxx_input->GetInputValue(&sxx,gauss);
+		sxy_input->GetInputValue(&sxy,gauss);
+		syy_input->GetInputValue(&syy,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+		base_input->GetInputValue(&base,gauss);
+		picoeff_input->GetInputValue(&propcoeff,gauss);
+
+		/* Computing sigma Von Mises*/
+		sigVM=sqrt(sxx*sxx+syy*syy+3*sxy*sxy-sxx*syy);
+
+		/* Computing heigth above buoyancy*/
+		hAB=thickness+1028/920*base;
+
+		/*Calving rate for Pi criterion proportionnal to the product of the strain rate along the ice flow direction and the Von Mises stress and the square of the glacier width (hardcoded) divided by the height above buoyancy and the max of the ice velocity power 3 and the ice density (ignored here)*/
+		calvingrate[iv]=propcoeff*strainparallel*sigVM*25.e6/hAB/1e9;
+		if(calvingrate[iv]<0){
+			calvingrate[iv]=0;
+		}
+		calvingratex[iv]=calvingrate[iv]*vx/(sqrt(vel)+1.e-6);
+		calvingratey[iv]=calvingrate[iv]*vy/(sqrt(vel)+1.e-6);
+	}
+
+	/*Add input*/
+	this->inputs->AddInput(new PentaInput(CalvingratexEnum,&calvingratex[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(CalvingrateyEnum,&calvingratey[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(CalvingCalvingrateEnum,&calvingrate[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+
 }
 /*}}}*/
@@ -193,6 +327,6 @@
 
 	/*recovre material parameters: */
-	rho_ice=matpar->GetRhoIce();
-	gravity=matpar->GetG();
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+	gravity=matpar->GetMaterialParameter(ConstantsGEnum);
 
 	/* Get node coordinates and dof list: */
@@ -243,15 +377,66 @@
 }
 /*}}}*/
+void       Penta::ComputeDeviatoricStressTensor(){/*{{{*/
+
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  viscosity;
+	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble  tau_xx[NUMVERTICES];
+	IssmDouble	tau_yy[NUMVERTICES];
+	IssmDouble	tau_zz[NUMVERTICES];
+	IssmDouble  tau_xy[NUMVERTICES];
+	IssmDouble	tau_xz[NUMVERTICES];
+	IssmDouble	tau_yz[NUMVERTICES];
+	GaussPenta* gauss=NULL;
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);             _assert_(vz_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate viscosity and pressure: */
+		this->StrainRateFS(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		this->ViscosityFS(&viscosity,3,&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+
+		/*Compute Stress*/
+		tau_xx[iv]=2*viscosity*epsilon[0]; // tau = nu eps 
+		tau_yy[iv]=2*viscosity*epsilon[1];
+		tau_zz[iv]=2*viscosity*epsilon[2];
+		tau_xy[iv]=2*viscosity*epsilon[3];
+		tau_xz[iv]=2*viscosity*epsilon[4];
+		tau_yz[iv]=2*viscosity*epsilon[5];
+	}
+
+	/*Add Stress tensor components into inputs*/
+	this->inputs->AddInput(new PentaInput(DeviatoricStressxxEnum,&tau_xx[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(DeviatoricStressxyEnum,&tau_xy[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(DeviatoricStressxzEnum,&tau_xz[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(DeviatoricStressyyEnum,&tau_yy[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(DeviatoricStressyzEnum,&tau_yz[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(DeviatoricStresszzEnum,&tau_zz[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
 void       Penta::ComputeStressTensor(){/*{{{*/
 
-	IssmDouble      xyz_list[NUMVERTICES][3];
-	IssmDouble      pressure,viscosity;
-	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,exy];*/
-	IssmDouble      sigma_xx[NUMVERTICES];
-	IssmDouble		sigma_yy[NUMVERTICES];
-	IssmDouble		sigma_zz[NUMVERTICES];
-	IssmDouble      sigma_xy[NUMVERTICES];
-	IssmDouble		sigma_xz[NUMVERTICES];
-	IssmDouble		sigma_yz[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  pressure,viscosity;
+	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble  sigma_xx[NUMVERTICES];
+	IssmDouble	sigma_yy[NUMVERTICES];
+	IssmDouble	sigma_zz[NUMVERTICES];
+	IssmDouble  sigma_xy[NUMVERTICES];
+	IssmDouble	sigma_xz[NUMVERTICES];
+	IssmDouble	sigma_yz[NUMVERTICES];
 	GaussPenta* gauss=NULL;
 
@@ -296,55 +481,4 @@
 }
 /*}}}*/
-void       Penta::ComputeDeviatoricStressTensor(){/*{{{*/
-
-	IssmDouble      xyz_list[NUMVERTICES][3];
-	IssmDouble      viscosity;
-	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,exy];*/
-	IssmDouble      tau_xx[NUMVERTICES];
-	IssmDouble		tau_yy[NUMVERTICES];
-	IssmDouble		tau_zz[NUMVERTICES];
-	IssmDouble      tau_xy[NUMVERTICES];
-	IssmDouble		tau_xz[NUMVERTICES];
-	IssmDouble		tau_yz[NUMVERTICES];
-	GaussPenta* gauss=NULL;
-
-	/* Get node coordinates and dof list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*Retrieve all inputs we will be needing: */
-	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
-	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
-	Input* vz_input=inputs->GetInput(VzEnum);             _assert_(vz_input);
-
-	/* Start looping on the number of vertices: */
-	gauss=new GaussPenta();
-	for (int iv=0;iv<NUMVERTICES;iv++){
-		gauss->GaussVertex(iv);
-
-		/*Compute strain rate viscosity and pressure: */
-		this->StrainRateFS(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		this->ViscosityFS(&viscosity,3,&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-
-		/*Compute Stress*/
-		tau_xx[iv]=2*viscosity*epsilon[0]; // tau = nu eps 
-		tau_yy[iv]=2*viscosity*epsilon[1];
-		tau_zz[iv]=2*viscosity*epsilon[2];
-		tau_xy[iv]=2*viscosity*epsilon[3];
-		tau_xz[iv]=2*viscosity*epsilon[4];
-		tau_yz[iv]=2*viscosity*epsilon[5];
-	}
-
-	/*Add Stress tensor components into inputs*/
-	this->inputs->AddInput(new PentaInput(StressTensorxxEnum,&tau_xx[0],P1Enum));
-	this->inputs->AddInput(new PentaInput(StressTensorxyEnum,&tau_xy[0],P1Enum));
-	this->inputs->AddInput(new PentaInput(StressTensorxzEnum,&tau_xz[0],P1Enum));
-	this->inputs->AddInput(new PentaInput(StressTensoryyEnum,&tau_yy[0],P1Enum));
-	this->inputs->AddInput(new PentaInput(StressTensoryzEnum,&tau_yz[0],P1Enum));
-	this->inputs->AddInput(new PentaInput(StressTensorzzEnum,&tau_zz[0],P1Enum));
-
-	/*Clean up and return*/
-	delete gauss;
-}
-/*}}}*/
 void       Penta::Configure(Elements* elementsin, Loads* loadsin, Nodes* nodesin,Vertices* verticesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
 
@@ -380,4 +514,70 @@
 }
 /*}}}*/
+void       Penta::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){/*{{{*/
+
+	int    vertexpidlist[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+	Input* input=NULL;
+
+	if(enum_type==MaterialsRheologyBbarEnum){
+		input=(Input*)inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(enum_type==DamageDbarEnum){
+		input=(Input*)inputs->GetInput(DamageDEnum);
+	}
+	else{
+		input=inputs->GetInput(enum_type);
+	}
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&vertexpidlist[0],control_index);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
+	grad_input=new PentaInput(GradientEnum,grad_list,P1Enum);
+	((ControlInput*)input)->SetGradient(grad_input);
+
+}/*}}}*/
+void       Penta::ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){/*{{{*/
+
+	Input* input=NULL;
+
+	if(control_enum==MaterialsRheologyBbarEnum){
+		input=(Input*)inputs->GetInput(MaterialsRheologyBEnum);
+	}
+	else if(control_enum==DamageDbarEnum){
+		input=(Input*)inputs->GetInput(DamageDEnum);
+	}
+	else{
+		input=inputs->GetInput(control_enum);
+	}
+	if (!input) _error_("Input " << EnumToStringx(control_enum) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(control_enum) << " is not a ControlInput");
+
+	int         sidlist[NUMVERTICES];
+	int         connectivity[NUMVERTICES];
+	IssmPDouble values[NUMVERTICES];
+	IssmPDouble gradients[NUMVERTICES]; 
+	IssmDouble  value,gradient;
+
+	this->GetVerticesConnectivityList(&connectivity[0]);
+	this->GetVerticesSidList(&sidlist[0]);
+
+	GaussPenta* gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		((ControlInput*)input)->GetInputValue(&value,gauss);
+		((ControlInput*)input)->GetGradientValue(&gradient,gauss);
+
+		values[iv]    = reCast<IssmPDouble>(value)/reCast<IssmPDouble>(connectivity[iv]);
+		gradients[iv] = reCast<IssmPDouble>(gradient)/reCast<IssmPDouble>(connectivity[iv]);
+	}
+	delete gauss;
+
+	vector_control->SetValues(NUMVERTICES,&sidlist[0],&values[0],ADD_VAL);
+	vector_gradient->SetValues(NUMVERTICES,&sidlist[0],&gradients[0],ADD_VAL);
+
+}/*}}}*/
 void       Penta::Delta18oParameterization(void){/*{{{*/
 
@@ -408,5 +608,4 @@
 			input2->GetInputValue(&TemperaturesLgm[iv][month],gauss,month/12.*yts);
 			input3->GetInputValue(&PrecipitationsPresentday[iv][month],gauss,month/12.*yts);
-			PrecipitationsPresentday[iv][month]=PrecipitationsPresentday[iv][month]/yts; // converion in m/sec
 		}
 	}
@@ -447,6 +646,6 @@
 	this->inputs->AddInput(NewPrecipitationInput);
 
-	this->InputExtrude(SurfaceforcingsMonthlytemperaturesEnum);
-	this->InputExtrude(SurfaceforcingsPrecipitationEnum);
+	this->InputExtrude(SurfaceforcingsMonthlytemperaturesEnum,-1);
+	this->InputExtrude(SurfaceforcingsPrecipitationEnum,-1);
 
 	/*clean-up*/
@@ -454,4 +653,126 @@
 }
 /*}}}*/
+void       Penta::MungsmtpParameterization(void){/*{{{*/
+	/*Are we on the base? If not, return*/
+	if(!IsOnBase()) return;
+
+	int        i;
+	IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+	IssmDouble TemperaturesPresentday[NUMVERTICES][12],TemperaturesLgm[NUMVERTICES][12];
+	IssmDouble PrecipitationsPresentday[NUMVERTICES][12],PrecipitationsLgm[NUMVERTICES][12];
+	IssmDouble tmp[NUMVERTICES];
+	IssmDouble TdiffTime,PfacTime;
+	IssmDouble time,yts;
+	this->parameters->FindParam(&time,TimeEnum);
+	this->parameters->FindParam(&yts,ConstantsYtsEnum);
+
+	/*Recover present day temperature and precipitation*/
+	Input*     input=inputs->GetInput(SurfaceforcingsTemperaturesPresentdayEnum);    _assert_(input);
+	Input*     input2=inputs->GetInput(SurfaceforcingsTemperaturesLgmEnum);          _assert_(input2);
+	Input*     input3=inputs->GetInput(SurfaceforcingsPrecipitationsPresentdayEnum); _assert_(input3);
+	Input*     input4=inputs->GetInput(SurfaceforcingsPrecipitationsLgmEnum);        _assert_(input4);
+	GaussPenta* gauss=new GaussPenta();
+	for(int month=0;month<12;month++) {
+		for(int iv=0;iv<NUMVERTICES;iv++) {
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&TemperaturesPresentday[iv][month],gauss,month/12.*yts);
+			input2->GetInputValue(&TemperaturesLgm[iv][month],gauss,month/12.*yts);
+			input3->GetInputValue(&PrecipitationsPresentday[iv][month],gauss,month/12.*yts);
+			input4->GetInputValue(&PrecipitationsLgm[iv][month],gauss,month/12.*yts);
+		}
+	}
+
+	/*Recover interpolation parameters at time t*/
+	this->parameters->FindParam(&TdiffTime,SurfaceforcingsTdiffEnum,time);
+	this->parameters->FindParam(&PfacTime,SurfaceforcingsPfacEnum,time);
+
+	/*Compute the temperature and precipitation*/
+	for(int iv=0;iv<NUMVERTICES;iv++){
+	  ComputeMungsmTemperaturePrecipitation(TdiffTime,PfacTime,
+					&PrecipitationsLgm[iv][0],&PrecipitationsPresentday[iv][0], 
+					&TemperaturesLgm[iv][0], &TemperaturesPresentday[iv][0], 
+					&monthlytemperatures[iv][0], &monthlyprec[iv][0]);
+	}
+
+	/*Update inputs*/ 
+	TransientInput* NewTemperatureInput = new TransientInput(SurfaceforcingsMonthlytemperaturesEnum);
+	TransientInput* NewPrecipitationInput = new TransientInput(SurfaceforcingsPrecipitationEnum);
+	for (int imonth=0;imonth<12;imonth++) {
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
+		PentaInput* newmonthinput1 = new PentaInput(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0],P1Enum);
+		NewTemperatureInput->AddTimeInput(newmonthinput1,time+imonth/12.*yts);
+	
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlyprec[i][imonth];
+		PentaInput* newmonthinput2 = new PentaInput(SurfaceforcingsPrecipitationEnum,&tmp[0],P1Enum);
+		NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
+	}
+	NewTemperatureInput->Configure(this->parameters);
+	NewPrecipitationInput->Configure(this->parameters);
+
+	this->inputs->AddInput(NewTemperatureInput);
+	this->inputs->AddInput(NewPrecipitationInput);
+	
+	this->InputExtrude(SurfaceforcingsMonthlytemperaturesEnum,-1);
+	this->InputExtrude(SurfaceforcingsPrecipitationEnum,-1);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+void       Penta::ElementResponse(IssmDouble* presponse,int response_enum){/*{{{*/
+
+	switch(response_enum){
+		case MaterialsRheologyBbarEnum:
+			*presponse=this->material->GetBbar();
+			break;
+		case DamageDbarEnum:
+			*presponse=this->material->GetDbar();
+			break;
+		case VelEnum:
+			{
+
+				/*Get input:*/
+				IssmDouble vel;
+				Input* vel_input;
+
+				vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+				vel_input->GetInputAverage(&vel);
+
+				/*Assign output pointers:*/
+				*presponse=vel;
+			}
+			break;
+		default:  
+			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
+	}
+
+}
+/*}}}*/
+void       Penta::ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){/*{{{*/
+
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xmin,ymin,zmin;
+	IssmDouble xmax,ymax,zmax;
+
+	/*Get xyz list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	xmin=xyz_list[0][0]; xmax=xyz_list[0][0];
+	ymin=xyz_list[0][1]; ymax=xyz_list[0][1];
+	zmin=xyz_list[0][2]; zmax=xyz_list[0][2];
+
+	for(int i=1;i<NUMVERTICES;i++){
+		if(xyz_list[i][0]<xmin) xmin=xyz_list[i][0];
+		if(xyz_list[i][0]>xmax) xmax=xyz_list[i][0];
+		if(xyz_list[i][1]<ymin) ymin=xyz_list[i][1];
+		if(xyz_list[i][1]>ymax) ymax=xyz_list[i][1];
+		if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
+		if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
+	}
+
+	*hx=xmax-xmin;
+	*hy=ymax-ymin;
+	*hz=zmax-zmin;
+}
+/*}}}*/
 int        Penta::FiniteElement(void){/*{{{*/
 	return this->element_type;
@@ -462,30 +783,38 @@
 	if(!IsOnBase()) return;
 
-	/*Intermediaries*/
-	IssmDouble* xyz_list = NULL;
-	IssmDouble  pressure,water_pressure,sigma_nn,viscosity,bed,base;
-	IssmDouble  bed_normal[3];
-	IssmDouble  epsilon[6]; /* epsilon=[exx eyy ezz exy exz eyz];*/
-	IssmDouble  surface=0,value=0;
-	bool grounded;
-
-	/* Get node coordinates and dof list: */
-	GetVerticesCoordinates(&xyz_list);
-
-	/*Retrieve all inputs we will be needing: */
-	Input* pressure_input = inputs->GetInput(PressureEnum); _assert_(pressure_input);
-	Input* base_input     = inputs->GetInput(BaseEnum);     _assert_(base_input);
-	Input* bed_input      = inputs->GetInput(BedEnum);      _assert_(bed_input);
-	Input* vx_input       = inputs->GetInput(VxEnum);       _assert_(vx_input);
-	Input* vy_input       = inputs->GetInput(VyEnum);       _assert_(vy_input);
-	Input* vz_input       = inputs->GetInput(VzEnum);       _assert_(vz_input);
-
-	/*Create gauss point in the middle of the basal edge*/
-	Gauss* gauss=NewGaussBase(1);
-	gauss->GaussPoint(0);
-
-	if(!IsFloating()){ 
-		/*Check for basal force only if grounded and touching GL*/
-		if(this->inputs->Min(MaskGroundediceLevelsetEnum)==0.){
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation==HOApproximationEnum || approximation==SSAApproximationEnum || approximation==SSAHOApproximationEnum){
+		for(int i=0;i<NUMVERTICES;i++){
+			vertexgrounded->SetValue(vertices[i]->Pid(),+9999.,INS_VAL);
+			vertexfloating->SetValue(vertices[i]->Pid(),+9999.,INS_VAL);
+		}
+	}
+	else {
+		/*Intermediaries*/
+		IssmDouble* xyz_list = NULL;
+		IssmDouble  pressure,water_pressure,sigma_nn,viscosity,bed,base;
+		IssmDouble  bed_normal[3];
+		IssmDouble  epsilon[6]; /* epsilon=[exx eyy ezz exy exz eyz];*/
+		IssmDouble  surface=0,value=0;
+		bool grounded;
+
+		/* Get node coordinates and dof list: */
+		GetVerticesCoordinates(&xyz_list);
+
+		/*Retrieve all inputs we will be needing: */
+		Input* pressure_input = inputs->GetInput(PressureEnum); _assert_(pressure_input);
+		Input* base_input     = inputs->GetInput(BaseEnum);     _assert_(base_input);
+		Input* bed_input      = inputs->GetInput(BedEnum);      _assert_(bed_input);
+		Input* vx_input       = inputs->GetInput(VxEnum);       _assert_(vx_input);
+		Input* vy_input       = inputs->GetInput(VyEnum);       _assert_(vy_input);
+		Input* vz_input       = inputs->GetInput(VzEnum);       _assert_(vz_input);
+
+		/*Create gauss point in the middle of the basal edge*/
+		Gauss* gauss=NewGaussBase(1);
+		gauss->GaussPoint(0);
+
+		if(!IsFloating()){ 
+			/*Check for basal force only if grounded and touching GL*/
 			this->StrainRateFS(&epsilon[0],xyz_list,gauss,vx_input,vy_input,vz_input);
 			this->ViscosityFS(&viscosity,3,xyz_list,gauss,vx_input,vy_input,vz_input);
@@ -509,7 +838,7 @@
 
 			/*Compute water pressure*/
-			IssmDouble rho_ice   = matpar->GetRhoIce();
-			IssmDouble rho_water = matpar->GetRhoWater();
-			IssmDouble gravity   = matpar->GetG();
+			IssmDouble rho_ice   = matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+			IssmDouble rho_water = matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+			IssmDouble gravity   = matpar->GetMaterialParameter(ConstantsGEnum);
 			water_pressure=gravity*rho_water*base;
 
@@ -519,28 +848,19 @@
 		}
 		else{
-			grounded=true;
-		}
-	}
-	else{
-		/*Check for basal elevation if floating*/
-		base_input->GetInputValue(&base, gauss);
-		bed_input->GetInputValue(&bed, gauss);
-		if (base<bed) grounded=true;
-		else          grounded=false;
-	}
-	for(int i=0;i<NUMVERTICES;i++){
-		if(grounded) vertexgrounded->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
-		else         vertexfloating->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
-	}
-
-	/*clean up*/
-	delete gauss;
-	xDelete<IssmDouble>(xyz_list);
-}
-/*}}}*/
-int        Penta::ObjectEnum(void){/*{{{*/
-
-	return PentaEnum;
-
+			/*Check for basal elevation if floating*/
+			base_input->GetInputValue(&base, gauss);
+			bed_input->GetInputValue(&bed, gauss);
+			if(base<bed) grounded=true;
+			else          grounded=false;
+		}
+		for(int i=0;i<NUMVERTICES;i++){
+			if(grounded) vertexgrounded->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
+			else         vertexfloating->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
+		}
+
+		/*clean up*/
+		delete gauss;
+		xDelete<IssmDouble>(xyz_list);
+	}
 }
 /*}}}*/
@@ -580,11 +900,243 @@
 }
 /*}}}*/
-Penta*     Penta::GetUpperPenta(void){/*{{{*/
-
-	Penta* upper_penta=NULL;
-
-	upper_penta=(Penta*)verticalneighbors[1]; //first one (0) under, second one (1) above
-
-	return upper_penta;
+Element*   Penta::GetBasalElement(void){/*{{{*/
+
+	/*Output*/
+	Element* element=this->GetBasalPenta();
+	return element;
+}
+/*}}}*/
+Penta*     Penta::GetBasalPenta(void){/*{{{*/
+
+	/*Output*/
+	Penta* penta=NULL;
+
+	/*Go through all pentas till the bed is reached*/
+	penta=this;
+	for(;;){
+		/*Stop if we have reached the surface, else, take lower penta*/
+		if (penta->IsOnBase()) break;
+
+		/* get lower Penta*/
+		penta=penta->GetLowerPenta();
+		_assert_(penta->Id()!=this->id);
+	}
+
+	/*return output*/
+	return penta;
+}
+/*}}}*/
+int        Penta::GetElementType(){/*{{{*/
+
+	/*return PentaRef field*/
+	return this->element_type;
+}
+/*}}}*/
+void       Penta::GetGroundedPart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlyfloating){/*{{{*/
+	/*Computeportion of the element that is grounded*/ 
+
+	bool               floating=true;
+	int                point;
+	const IssmPDouble  epsilon= 1.e-15;
+	IssmDouble         gl[NUMVERTICES];
+	IssmDouble         f1,f2;
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
+
+	/*Be sure that values are not zero*/
+	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
+	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
+	if(gl[2]==0.) gl[2]=gl[2]+epsilon;
+
+	/*Check that not all nodes are grounded or floating*/
+	if(gl[0]>0 && gl[1]>0 && gl[2]>0){ // All grounded
+		point=0;
+		f1=1.;
+		f2=1.;
+	}
+	else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
+		point=0;
+		f1=0.;
+		f2=0.;
+	}
+	else{
+		if(gl[0]*gl[1]*gl[2]<0) floating=false;
+
+		if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+			point=2;
+			f1=gl[2]/(gl[2]-gl[0]);
+			f2=gl[2]/(gl[2]-gl[1]);
+		}
+		else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+			point=0;
+			f1=gl[0]/(gl[0]-gl[1]);
+			f2=gl[0]/(gl[0]-gl[2]);
+		}
+		else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+			point=1;
+			f1=gl[1]/(gl[1]-gl[2]);
+			f2=gl[1]/(gl[1]-gl[0]);
+		}
+	}
+	*point1=point;
+	*fraction1=f1;
+	*fraction2=f2;
+	*mainlyfloating=floating;
+}
+/*}}}*/
+IssmDouble Penta::GetGroundedPortion(IssmDouble* xyz_list){/*{{{*/
+	/*Computeportion of the element that is grounded*/ 
+
+	bool               mainlyfloating = true;
+	const IssmPDouble  epsilon= 1.e-15;
+	IssmDouble         phi,s1,s2,area_init,area_grounded;
+	IssmDouble         gl[NUMVERTICES];
+	IssmDouble         xyz_bis[NUMVERTICES2D][3];
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
+
+	/*Be sure that values are not zero*/
+	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
+	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
+	if(gl[2]==0.) gl[2]=gl[2]+epsilon;
+
+	/*Check that not all nodes are grounded or floating*/
+	if(gl[0]>0 && gl[1]>0 && gl[2]>0){ // All grounded
+		phi=1;
+	}
+	else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
+		phi=0;
+	}
+	else{
+		/*Figure out if two nodes are floating or grounded*/
+		if(gl[0]*gl[1]*gl[2]>0) mainlyfloating=false;
+
+		if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+			/*Coordinates of point 2: same as initial point 2*/
+			xyz_bis[2][0]=xyz_list[3*2+0];
+			xyz_bis[2][1]=xyz_list[3*2+1];
+			xyz_bis[2][2]=xyz_list[3*2+2];
+
+			/*Portion of the segments*/
+			s1=gl[2]/(gl[2]-gl[1]);
+			s2=gl[2]/(gl[2]-gl[0]);
+
+			/*New point 1*/
+			xyz_bis[1][0]=xyz_list[3*2+0]+s1*(xyz_list[3*1+0]-xyz_list[3*2+0]);
+			xyz_bis[1][1]=xyz_list[3*2+1]+s1*(xyz_list[3*1+1]-xyz_list[3*2+1]);
+			xyz_bis[1][2]=xyz_list[3*2+2]+s1*(xyz_list[3*1+2]-xyz_list[3*2+2]);
+
+			/*New point 0*/
+			xyz_bis[0][0]=xyz_list[3*2+0]+s2*(xyz_list[3*0+0]-xyz_list[3*2+0]);
+			xyz_bis[0][1]=xyz_list[3*2+1]+s2*(xyz_list[3*0+1]-xyz_list[3*2+1]);
+			xyz_bis[0][2]=xyz_list[3*2+2]+s2*(xyz_list[3*0+2]-xyz_list[3*2+2]);
+		}
+		else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+			/*Coordinates of point 0: same as initial point 2*/
+			xyz_bis[0][0]=*(xyz_list+3*0+0);
+			xyz_bis[0][1]=*(xyz_list+3*0+1);
+			xyz_bis[0][2]=*(xyz_list+3*0+2);
+
+			/*Portion of the segments*/
+			s1=gl[0]/(gl[0]-gl[1]);
+			s2=gl[0]/(gl[0]-gl[2]);
+
+			/*New point 1*/
+			xyz_bis[1][0]=*(xyz_list+3*0+0)+s1*(*(xyz_list+3*1+0)-*(xyz_list+3*0+0));
+			xyz_bis[1][1]=*(xyz_list+3*0+1)+s1*(*(xyz_list+3*1+1)-*(xyz_list+3*0+1));
+			xyz_bis[1][2]=*(xyz_list+3*0+2)+s1*(*(xyz_list+3*1+2)-*(xyz_list+3*0+2));
+
+			/*New point 2*/
+			xyz_bis[2][0]=*(xyz_list+3*0+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*0+0));
+			xyz_bis[2][1]=*(xyz_list+3*0+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*0+1));
+			xyz_bis[2][2]=*(xyz_list+3*0+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*0+2));
+		}
+		else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+			/*Coordinates of point 1: same as initial point 2*/
+			xyz_bis[1][0]=*(xyz_list+3*1+0);
+			xyz_bis[1][1]=*(xyz_list+3*1+1);
+			xyz_bis[1][2]=*(xyz_list+3*1+2);
+
+			/*Portion of the segments*/
+			s1=gl[1]/(gl[1]-gl[0]);
+			s2=gl[1]/(gl[1]-gl[2]);
+
+			/*New point 0*/
+			xyz_bis[0][0]=*(xyz_list+3*1+0)+s1*(*(xyz_list+3*0+0)-*(xyz_list+3*1+0));
+			xyz_bis[0][1]=*(xyz_list+3*1+1)+s1*(*(xyz_list+3*0+1)-*(xyz_list+3*1+1));
+			xyz_bis[0][2]=*(xyz_list+3*1+2)+s1*(*(xyz_list+3*0+2)-*(xyz_list+3*1+2));
+
+			/*New point 2*/
+			xyz_bis[2][0]=*(xyz_list+3*1+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*1+0));
+			xyz_bis[2][1]=*(xyz_list+3*1+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*1+1));
+			xyz_bis[2][2]=*(xyz_list+3*1+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*1+2));
+		}
+
+		/*Compute fraction of grounded element*/
+		GetTriaJacobianDeterminant(&area_init, xyz_list,NULL);
+		GetTriaJacobianDeterminant(&area_grounded, &xyz_bis[0][0],NULL);
+		if(mainlyfloating==true) area_grounded=area_init-area_grounded;
+		phi=area_grounded/area_init;
+	}
+
+	if(phi>1. || phi<0.) _error_("Error. Problem with portion of grounded element: value should be between 0 and 1");
+
+	return phi;
+}
+/*}}}*/
+void       Penta::GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
+	
+	/* Intermediaries */
+	const int dim=3;
+	int i, dir,nrfrontnodes;
+	IssmDouble  levelset[NUMVERTICES];
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&levelset[0],levelsetenum);
+
+	int* indicesfront = xNew<int>(NUMVERTICES);
+	/* Get basal nodes where there is no ice */
+	nrfrontnodes=0;
+	for(i=0;i<NUMVERTICES2D;i++){
+		if(levelset[i]>=0.){
+			indicesfront[nrfrontnodes]=i;
+			nrfrontnodes++;
+		}
+	}
+	_assert_(nrfrontnodes==2);
+
+	/* arrange order of basal frontnodes such that they are oriented counterclockwise */
+	if((NUMVERTICES2D+indicesfront[0]-indicesfront[1])%NUMVERTICES2D!=NUMVERTICES2D-1){
+		int index=indicesfront[0];
+		indicesfront[0]=indicesfront[1];
+		indicesfront[1]=index;
+	}	
+
+	IssmDouble* xyz_front = xNew<IssmDouble>(2*dim*nrfrontnodes);
+	/* Return basal and top front nodes */
+	for(i=0;i<nrfrontnodes;i++){
+		for(dir=0;dir<dim;dir++){
+			int ind1=i*dim+dir, ind2=(2*nrfrontnodes-1-i)*dim+dir; // vertex structure front segment: base0, base1, top1, top0
+			xyz_front[ind1]=xyz_list[dim*indicesfront[i]+dir];
+			xyz_front[ind2]=xyz_list[dim*(indicesfront[i]+NUMVERTICES2D)+dir];
+		}
+	}
+
+	*pxyz_front=xyz_front;
+
+	xDelete<int>(indicesfront);
+}/*}}}*/
+void       Penta::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){/*{{{*/
+
+	Input* input=inputs->GetInput(enumtype);
+	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+
+	GaussPenta* gauss=new GaussPenta();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
 }
 /*}}}*/
@@ -596,4 +1148,64 @@
 
 	return lower_penta;
+}
+/*}}}*/
+Node*      Penta::GetNode(int node_number){/*{{{*/
+	_assert_(node_number>=0); 
+	_assert_(node_number<this->NumberofNodes(this->element_type)); 
+	return this->nodes[node_number];
+}
+/*}}}*/
+int        Penta::GetNodeIndex(Node* node){/*{{{*/
+
+	_assert_(nodes);
+	int numnodes = this->NumberofNodes(this->element_type);
+
+	for(int i=0;i<numnodes;i++){
+		if(node==nodes[i]) return i;
+	}
+	_error_("Node provided not found among element nodes");
+
+}
+/*}}}*/
+int        Penta::GetNumberOfNodes(void){/*{{{*/
+	return this->NumberofNodes(this->element_type);
+}
+/*}}}*/
+int        Penta::GetNumberOfNodes(int enum_type){/*{{{*/
+	return this->NumberofNodes(enum_type);
+}
+/*}}}*/
+int        Penta::GetNumberOfVertices(void){/*{{{*/
+	return NUMVERTICES; 
+}
+/*}}}*/
+void       Penta::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){/*{{{*/
+
+	const int    numdof=NDOF1*NUMVERTICES;
+
+	int          i;
+	int*         doflist=NULL;
+	IssmDouble   values[numdof];
+	IssmDouble   enum_value;
+	GaussPenta   *gauss=NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);
+
+	gauss=new GaussPenta();
+	for(i=0;i<NUMVERTICES;i++){
+		/*Recover temperature*/
+		gauss->GaussVertex(i);
+		enum_input->GetInputValue(&enum_value,gauss);
+		values[i]=enum_value;
+	}
+
+	/*Add value to global vector*/
+	solution->SetValues(numdof,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	delete gauss;
+	xDelete<int>(doflist);
 }
 /*}}}*/
@@ -618,24 +1230,4 @@
 }
 /*}}}*/
-Penta*     Penta::GetBasalPenta(void){/*{{{*/
-
-	/*Output*/
-	Penta* penta=NULL;
-
-	/*Go through all pentas till the bed is reached*/
-	penta=this;
-	for(;;){
-		/*Stop if we have reached the surface, else, take lower penta*/
-		if (penta->IsOnBase()) break;
-
-		/* get lower Penta*/
-		penta=penta->GetLowerPenta();
-		_assert_(penta->Id()!=this->id);
-	}
-
-	/*return output*/
-	return penta;
-}
-/*}}}*/
 Element*   Penta::GetUpperElement(void){/*{{{*/
 
@@ -645,237 +1237,34 @@
 }
 /*}}}*/
-Element*   Penta::GetBasalElement(void){/*{{{*/
-
-	/*Output*/
-	Element* element=this->GetBasalPenta();
-	return element;
-}
-/*}}}*/
-void       Penta::GetGroundedPart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlyfloating){/*{{{*/
-	/*Computeportion of the element that is grounded*/ 
-
-	bool               floating=true;
-	int                point;
-	const IssmPDouble  epsilon= 1.e-15;
-	IssmDouble         gl[NUMVERTICES];
-	IssmDouble         f1,f2;
-
-	/*Recover parameters and values*/
-	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
-
-	/*Be sure that values are not zero*/
-	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
-	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
-	if(gl[2]==0.) gl[2]=gl[2]+epsilon;
-
-	/*Check that not all nodes are grounded or floating*/
-	if(gl[0]>0 && gl[1]>0 && gl[2]>0){ // All grounded
-		point=0;
-		f1=1.;
-		f2=1.;
-	}
-	else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
-		point=0;
-		f1=0.;
-		f2=0.;
-	}
-	else{
-		if(gl[0]*gl[1]*gl[2]<0) floating=false;
-
-		if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
-			point=2;
-			f1=gl[2]/(gl[2]-gl[0]);
-			f2=gl[2]/(gl[2]-gl[1]);
-		}
-		else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
-			point=0;
-			f1=gl[0]/(gl[0]-gl[1]);
-			f2=gl[0]/(gl[0]-gl[2]);
-		}
-		else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
-			point=1;
-			f1=gl[1]/(gl[1]-gl[2]);
-			f2=gl[1]/(gl[1]-gl[0]);
-		}
-	}
-	*point1=point;
-	*fraction1=f1;
-	*fraction2=f2;
-	*mainlyfloating=floating;
-}
-/*}}}*/
-IssmDouble Penta::GetGroundedPortion(IssmDouble* xyz_list){/*{{{*/
-	/*Computeportion of the element that is grounded*/ 
-
-	bool               mainlyfloating = true;
-	const IssmPDouble  epsilon= 1.e-15;
-	IssmDouble         phi,s1,s2,area_init,area_grounded;
-	IssmDouble         gl[NUMVERTICES];
-	IssmDouble         xyz_bis[NUMVERTICES2D][3];
-
-	/*Recover parameters and values*/
-	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
-
-	/*Be sure that values are not zero*/
-	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
-	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
-	if(gl[2]==0.) gl[2]=gl[2]+epsilon;
-
-	/*Check that not all nodes are grounded or floating*/
-	if(gl[0]>0 && gl[1]>0 && gl[2]>0){ // All grounded
-		phi=1;
-	}
-	else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All floating
-		phi=0;
-	}
-	else{
-		/*Figure out if two nodes are floating or grounded*/
-		if(gl[0]*gl[1]*gl[2]>0) mainlyfloating=false;
-
-		if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
-			/*Coordinates of point 2: same as initial point 2*/
-			xyz_bis[2][0]=xyz_list[3*2+0];
-			xyz_bis[2][1]=xyz_list[3*2+1];
-			xyz_bis[2][2]=xyz_list[3*2+2];
-
-			/*Portion of the segments*/
-			s1=gl[2]/(gl[2]-gl[1]);
-			s2=gl[2]/(gl[2]-gl[0]);
-
-			/*New point 1*/
-			xyz_bis[1][0]=xyz_list[3*2+0]+s1*(xyz_list[3*1+0]-xyz_list[3*2+0]);
-			xyz_bis[1][1]=xyz_list[3*2+1]+s1*(xyz_list[3*1+1]-xyz_list[3*2+1]);
-			xyz_bis[1][2]=xyz_list[3*2+2]+s1*(xyz_list[3*1+2]-xyz_list[3*2+2]);
-
-			/*New point 0*/
-			xyz_bis[0][0]=xyz_list[3*2+0]+s2*(xyz_list[3*0+0]-xyz_list[3*2+0]);
-			xyz_bis[0][1]=xyz_list[3*2+1]+s2*(xyz_list[3*0+1]-xyz_list[3*2+1]);
-			xyz_bis[0][2]=xyz_list[3*2+2]+s2*(xyz_list[3*0+2]-xyz_list[3*2+2]);
-		}
-		else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
-			/*Coordinates of point 0: same as initial point 2*/
-			xyz_bis[0][0]=*(xyz_list+3*0+0);
-			xyz_bis[0][1]=*(xyz_list+3*0+1);
-			xyz_bis[0][2]=*(xyz_list+3*0+2);
-
-			/*Portion of the segments*/
-			s1=gl[0]/(gl[0]-gl[1]);
-			s2=gl[0]/(gl[0]-gl[2]);
-
-			/*New point 1*/
-			xyz_bis[1][0]=*(xyz_list+3*0+0)+s1*(*(xyz_list+3*1+0)-*(xyz_list+3*0+0));
-			xyz_bis[1][1]=*(xyz_list+3*0+1)+s1*(*(xyz_list+3*1+1)-*(xyz_list+3*0+1));
-			xyz_bis[1][2]=*(xyz_list+3*0+2)+s1*(*(xyz_list+3*1+2)-*(xyz_list+3*0+2));
-
-			/*New point 2*/
-			xyz_bis[2][0]=*(xyz_list+3*0+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*0+0));
-			xyz_bis[2][1]=*(xyz_list+3*0+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*0+1));
-			xyz_bis[2][2]=*(xyz_list+3*0+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*0+2));
-		}
-		else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
-			/*Coordinates of point 1: same as initial point 2*/
-			xyz_bis[1][0]=*(xyz_list+3*1+0);
-			xyz_bis[1][1]=*(xyz_list+3*1+1);
-			xyz_bis[1][2]=*(xyz_list+3*1+2);
-
-			/*Portion of the segments*/
-			s1=gl[1]/(gl[1]-gl[0]);
-			s2=gl[1]/(gl[1]-gl[2]);
-
-			/*New point 0*/
-			xyz_bis[0][0]=*(xyz_list+3*1+0)+s1*(*(xyz_list+3*0+0)-*(xyz_list+3*1+0));
-			xyz_bis[0][1]=*(xyz_list+3*1+1)+s1*(*(xyz_list+3*0+1)-*(xyz_list+3*1+1));
-			xyz_bis[0][2]=*(xyz_list+3*1+2)+s1*(*(xyz_list+3*0+2)-*(xyz_list+3*1+2));
-
-			/*New point 2*/
-			xyz_bis[2][0]=*(xyz_list+3*1+0)+s2*(*(xyz_list+3*2+0)-*(xyz_list+3*1+0));
-			xyz_bis[2][1]=*(xyz_list+3*1+1)+s2*(*(xyz_list+3*2+1)-*(xyz_list+3*1+1));
-			xyz_bis[2][2]=*(xyz_list+3*1+2)+s2*(*(xyz_list+3*2+2)-*(xyz_list+3*1+2));
-		}
-
-		/*Compute fraction of grounded element*/
-		GetTriaJacobianDeterminant(&area_init, xyz_list,NULL);
-		GetTriaJacobianDeterminant(&area_grounded, &xyz_bis[0][0],NULL);
-		if(mainlyfloating==true) area_grounded=area_init-area_grounded;
-		phi=area_grounded/area_init;
-	}
-
-	if(phi>1. || phi<0.) _error_("Error. Problem with portion of grounded element: value should be between 0 and 1");
-
-	return phi;
-}
-/*}}}*/
-int        Penta::GetElementType(){/*{{{*/
-
-	/*return PentaRef field*/
-	return this->element_type;
-}
-/*}}}*/
-void       Penta::ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){/*{{{*/
-
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble xmin,ymin,zmin;
-	IssmDouble xmax,ymax,zmax;
-
-	/*Get xyz list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	xmin=xyz_list[0][0]; xmax=xyz_list[0][0];
-	ymin=xyz_list[0][1]; ymax=xyz_list[0][1];
-	zmin=xyz_list[0][2]; zmax=xyz_list[0][2];
-
-	for(int i=1;i<NUMVERTICES;i++){
-		if(xyz_list[i][0]<xmin) xmin=xyz_list[i][0];
-		if(xyz_list[i][0]>xmax) xmax=xyz_list[i][0];
-		if(xyz_list[i][1]<ymin) ymin=xyz_list[i][1];
-		if(xyz_list[i][1]>ymax) ymax=xyz_list[i][1];
-		if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
-		if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
-	}
-
-	*hx=xmax-xmin;
-	*hy=ymax-ymin;
-	*hz=zmax-zmin;
-}
-/*}}}*/
-int        Penta::GetNodeIndex(Node* node){/*{{{*/
-
-	_assert_(nodes);
-	int numnodes = this->NumberofNodes(this->element_type);
-
-	for(int i=0;i<numnodes;i++){
-		if(node==nodes[i]) return i;
-	}
-	_error_("Node provided not found among element nodes");
-
-}
-/*}}}*/
-int        Penta::GetNumberOfNodes(void){/*{{{*/
-	return this->NumberofNodes(this->element_type);
-}
-/*}}}*/
-int        Penta::GetNumberOfNodes(int enum_type){/*{{{*/
-	return this->NumberofNodes(enum_type);
-}
-/*}}}*/
-int        Penta::GetNumberOfVertices(void){/*{{{*/
-	return NUMVERTICES; 
-}
-/*}}}*/
-Node*      Penta::GetNode(int node_number){/*{{{*/
-	_assert_(node_number>=0); 
-	_assert_(node_number<this->NumberofNodes(this->element_type)); 
-	return this->nodes[node_number];
-}
-/*}}}*/
-void       Penta::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){/*{{{*/
-
-	Input* input=inputs->GetInput(enumtype);
-	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
-
-	GaussPenta* gauss=new GaussPenta();
-	gauss->GaussVertex(this->GetNodeIndex(node));
-
-	input->GetInputValue(pvalue,gauss);
-	delete gauss;
+Penta*     Penta::GetUpperPenta(void){/*{{{*/
+
+	Penta* upper_penta=NULL;
+
+	upper_penta=(Penta*)verticalneighbors[1]; //first one (0) under, second one (1) above
+
+	return upper_penta;
+}
+/*}}}*/
+void       Penta::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data,bool onsid){/*{{{*/
+
+	int vertexidlist[NUMVERTICES];
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexidlist[0],control_index,onsid);
+
+	/*Get input (either in element or material)*/
+	if(control_enum==MaterialsRheologyBbarEnum) control_enum=MaterialsRheologyBEnum;
+	Input* input=inputs->GetInput(control_enum);
+	if(!input) _error_("Input " << EnumToStringx(control_enum) << " not found in element");
+
+	/*Check that it is a ControlInput*/
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexidlist[0],data);
 }
 /*}}}*/
@@ -898,194 +1287,109 @@
 
 }/*}}}*/
-void       Penta::NormalSection(IssmDouble* normal,IssmDouble* xyz_list){/*{{{*/
-
-	/*Build unit outward pointing vector*/
-	IssmDouble AB[3];
-	IssmDouble AC[3];
-	IssmDouble norm;
-
-	AB[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
-	AB[1]=xyz_list[1*3+1] - xyz_list[0*3+1];
-	AB[2]=xyz_list[1*3+2] - xyz_list[0*3+2];
-	AC[0]=xyz_list[2*3+0] - xyz_list[0*3+0];
-	AC[1]=xyz_list[2*3+1] - xyz_list[0*3+1];
-	AC[2]=xyz_list[2*3+2] - xyz_list[0*3+2];
-
-	cross(normal,AB,AC);
-	norm=sqrt(normal[0]*normal[0]+normal[1]*normal[1]+normal[2]*normal[2]);
-
-	for(int i=0;i<3;i++) normal[i]=normal[i]/norm;
-}
-/*}}}*/
-IssmDouble Penta::StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){/*{{{*/
-	/*Compute stabilization parameter*/
-	/*kappa=thermalconductivity/(rho_ice*hearcapacity) for thermal model*/
-	/*kappa=enthalpydiffusionparameter for enthalpy model*/
-
-	IssmDouble normu;
-	IssmDouble tau_parameter;
-
-	normu=pow(pow(u,2)+pow(v,2)+pow(w,2),0.5);
-	if(normu*diameter/(3*2*kappa)<1){ 
-		tau_parameter=pow(diameter,2)/(3*2*2*kappa);
-	}
-	else tau_parameter=diameter/(2*normu);
-
-	return tau_parameter;
-}
-/*}}}*/
-void       Penta::ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
-	/*Compute portion of the element that is grounded*/ 
-
-	int         normal_orientation=0;
-	IssmDouble  s1,s2;
-	IssmDouble  levelset[NUMVERTICES];
-	IssmDouble* xyz_zero = xNew<IssmDouble>(4*3);
-
-	/*Recover parameters and values*/
-	GetInputListOnVertices(&levelset[0],levelsetenum);
-
-	if(levelset[0]*levelset[1]>0.){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
-		/*Portion of the segments*/
-		s1=levelset[2]/(levelset[2]-levelset[1]);
-		s2=levelset[2]/(levelset[2]-levelset[0]);
-
-		if(levelset[2]<0.) normal_orientation=1; //orientation of quadrangle at base and top, depending on distribution of levelsetfunction
-		/*New point 1*/
-		xyz_zero[3*normal_orientation+0]=xyz_list[2*3+0]+s1*(xyz_list[1*3+0]-xyz_list[2*3+0]);
-		xyz_zero[3*normal_orientation+1]=xyz_list[2*3+1]+s1*(xyz_list[1*3+1]-xyz_list[2*3+1]);
-		xyz_zero[3*normal_orientation+2]=xyz_list[2*3+2]+s1*(xyz_list[1*3+2]-xyz_list[2*3+2]);
-
-		/*New point 0*/
-		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[2*3+0]+s2*(xyz_list[0*3+0]-xyz_list[2*3+0]);
-		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[2*3+1]+s2*(xyz_list[0*3+1]-xyz_list[2*3+1]);
-		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[2*3+2]+s2*(xyz_list[0*3+2]-xyz_list[2*3+2]);
-
-		/*New point 3*/
-		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[5*3+0]+s1*(xyz_list[4*3+0]-xyz_list[5*3+0]);
-		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[5*3+1]+s1*(xyz_list[4*3+1]-xyz_list[5*3+1]);
-		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[5*3+2]+s1*(xyz_list[4*3+2]-xyz_list[5*3+2]);
-
-		/*New point 4*/
-		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[5*3+0]+s2*(xyz_list[3*3+0]-xyz_list[5*3+0]);
-		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[5*3+1]+s2*(xyz_list[3*3+1]-xyz_list[5*3+1]);
-		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[5*3+2]+s2*(xyz_list[3*3+2]-xyz_list[5*3+2]);
-	}
-	else if(levelset[1]*levelset[2]>0.){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
-		/*Portion of the segments*/
-		s1=levelset[0]/(levelset[0]-levelset[2]);
-		s2=levelset[0]/(levelset[0]-levelset[1]);
-
-		if(levelset[0]<0.) normal_orientation=1;
-		/*New point 1*/
-		xyz_zero[3*normal_orientation+0]=xyz_list[0*3+0]+s1*(xyz_list[2*3+0]-xyz_list[0*3+0]);
-		xyz_zero[3*normal_orientation+1]=xyz_list[0*3+1]+s1*(xyz_list[2*3+1]-xyz_list[0*3+1]);
-		xyz_zero[3*normal_orientation+2]=xyz_list[0*3+2]+s1*(xyz_list[2*3+2]-xyz_list[0*3+2]);
-
-		/*New point 2*/
-		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[0*3+0]+s2*(xyz_list[1*3+0]-xyz_list[0*3+0]);
-		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[0*3+1]+s2*(xyz_list[1*3+1]-xyz_list[0*3+1]);
-		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[0*3+2]+s2*(xyz_list[1*3+2]-xyz_list[0*3+2]);
-
-		/*New point 3*/
-		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[3*3+0]+s1*(xyz_list[5*3+0]-xyz_list[3*3+0]);
-		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[3*3+1]+s1*(xyz_list[5*3+1]-xyz_list[3*3+1]);
-		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[3*3+2]+s1*(xyz_list[5*3+2]-xyz_list[3*3+2]);
-
-		/*New point 4*/
-		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[3*3+0]+s2*(xyz_list[4*3+0]-xyz_list[3*3+0]);
-		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[3*3+1]+s2*(xyz_list[4*3+1]-xyz_list[3*3+1]);
-		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[3*3+2]+s2*(xyz_list[4*3+2]-xyz_list[3*3+2]);
-	}
-	else if(levelset[0]*levelset[2]>0.){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
-		/*Portion of the segments*/
-		s1=levelset[1]/(levelset[1]-levelset[0]);
-		s2=levelset[1]/(levelset[1]-levelset[2]);
-
-		if(levelset[1]<0.) normal_orientation=1;
-		/*New point 0*/
-		xyz_zero[3*normal_orientation+0]=xyz_list[1*3+0]+s1*(xyz_list[0*3+0]-xyz_list[1*3+0]);
-		xyz_zero[3*normal_orientation+1]=xyz_list[1*3+1]+s1*(xyz_list[0*3+1]-xyz_list[1*3+1]);
-		xyz_zero[3*normal_orientation+2]=xyz_list[1*3+2]+s1*(xyz_list[0*3+2]-xyz_list[1*3+2]);
-
-		/*New point 2*/
-		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[1*3+0]+s2*(xyz_list[2*3+0]-xyz_list[1*3+0]);
-		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[1*3+1]+s2*(xyz_list[2*3+1]-xyz_list[1*3+1]);
-		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[1*3+2]+s2*(xyz_list[2*3+2]-xyz_list[1*3+2]);
-
-		/*New point 3*/
-		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[4*3+0]+s1*(xyz_list[3*3+0]-xyz_list[4*3+0]);
-		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[4*3+1]+s1*(xyz_list[3*3+1]-xyz_list[4*3+1]);
-		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[4*3+2]+s1*(xyz_list[3*3+2]-xyz_list[4*3+2]);
-
-		/*New point 4*/
-		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[4*3+0]+s2*(xyz_list[5*3+0]-xyz_list[4*3+0]);
-		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[4*3+1]+s2*(xyz_list[5*3+1]-xyz_list[4*3+1]);
-		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[4*3+2]+s2*(xyz_list[5*3+2]-xyz_list[4*3+2]);
-	}
-	else if(levelset[0]==0. && levelset[1]==0.){ //front is on point 0 and 1
-		xyz_zero[3*0+0]=xyz_list[0*3+0];
-		xyz_zero[3*0+1]=xyz_list[0*3+1];
-		xyz_zero[3*0+2]=xyz_list[0*3+2];
-
-		/*New point 2*/
-		xyz_zero[3*1+0]=xyz_list[1*3+0];
-		xyz_zero[3*1+1]=xyz_list[1*3+1];
-		xyz_zero[3*1+2]=xyz_list[1*3+2];
-
-		/*New point 3*/
-		xyz_zero[3*2+0]=xyz_list[4*3+0];
-		xyz_zero[3*2+1]=xyz_list[4*3+1];
-		xyz_zero[3*2+2]=xyz_list[4*3+2];
-
-		/*New point 4*/
-		xyz_zero[3*3+0]=xyz_list[3*3+0];
-		xyz_zero[3*3+1]=xyz_list[3*3+1];
-		xyz_zero[3*3+2]=xyz_list[3*3+2];
-	}
-	else if(levelset[0]==0. && levelset[2]==0.){ //front is on point 0 and 1
-		xyz_zero[3*0+0]=xyz_list[2*3+0];
-		xyz_zero[3*0+1]=xyz_list[2*3+1];
-		xyz_zero[3*0+2]=xyz_list[2*3+2];
-
-		/*New point 2*/
-		xyz_zero[3*1+0]=xyz_list[0*3+0];
-		xyz_zero[3*1+1]=xyz_list[0*3+1];
-		xyz_zero[3*1+2]=xyz_list[0*3+2];
-
-		/*New point 3*/
-		xyz_zero[3*2+0]=xyz_list[3*3+0];
-		xyz_zero[3*2+1]=xyz_list[3*3+1];
-		xyz_zero[3*2+2]=xyz_list[3*3+2];
-
-		/*New point 4*/
-		xyz_zero[3*3+0]=xyz_list[5*3+0];
-		xyz_zero[3*3+1]=xyz_list[5*3+1];
-		xyz_zero[3*3+2]=xyz_list[5*3+2];
-	}
-	else if(levelset[1]==0. && levelset[2]==0.){ //front is on point 0 and 1
-		xyz_zero[3*0+0]=xyz_list[1*3+0];
-		xyz_zero[3*0+1]=xyz_list[1*3+1];
-		xyz_zero[3*0+2]=xyz_list[1*3+2];
-
-		/*New point 2*/
-		xyz_zero[3*1+0]=xyz_list[2*3+0];
-		xyz_zero[3*1+1]=xyz_list[2*3+1];
-		xyz_zero[3*1+2]=xyz_list[2*3+2];
-
-		/*New point 3*/
-		xyz_zero[3*2+0]=xyz_list[5*3+0];
-		xyz_zero[3*2+1]=xyz_list[5*3+1];
-		xyz_zero[3*2+2]=xyz_list[5*3+2];
-
-		/*New point 4*/
-		xyz_zero[3*3+0]=xyz_list[4*3+0];
-		xyz_zero[3*3+1]=xyz_list[4*3+1];
-		xyz_zero[3*3+2]=xyz_list[4*3+2];
-	}
-	else _error_("Case not covered");
-
-	/*Assign output pointer*/
-	*pxyz_zero= xyz_zero;
+IssmDouble Penta::IceMass(void){/*{{{*/
+
+	IssmDouble rho_ice; 
+	
+	if(!IsIceInElement())return 0.; //do not contribute to the volume of the ice!
+
+	/*recover ice density: */
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+
+	return rho_ice*this->IceVolume();
+}
+/*}}}*/
+IssmDouble Penta::IceVolume(void){/*{{{*/
+
+	/*The volume of a troncated prism is base * 1/3 sum(length of edges)*/
+	IssmDouble base,height;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	if(!IsIceInElement())return 0;
+
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Pentangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height*/
+	height = 1./3.*((xyz_list[3][2]-xyz_list[0][2])+(xyz_list[4][2]-xyz_list[1][2])+(xyz_list[5][2]-xyz_list[2][2]));
+
+	/*Return: */
+	return base*height;
+}
+/*}}}*/
+IssmDouble Penta::IceVolumeAboveFloatation(void){/*{{{*/
+
+	/*Volume above floatation: H + rho_water/rho_ice*bathymetry for nodes on the bed*/
+	IssmDouble rho_ice,rho_water;
+	IssmDouble base,bed,surface,bathymetry;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	if(!IsIceInElement() || IsFloating() || !IsOnBase())return 0;
+
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+	rho_water=matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Pentangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height above floatation*/
+	Input* surface_input    = inputs->GetInput(SurfaceEnum);    _assert_(surface_input);
+	Input* base_input        = inputs->GetInput(BaseEnum);        _assert_(base_input);
+	Input* bed_input = inputs->GetInput(BedEnum); _assert_(bed_input);
+	surface_input->GetInputAverage(&surface);
+	base_input->GetInputAverage(&bed);
+	bed_input->GetInputAverage(&bathymetry);
+
+	/*Return: */
+	return base*(surface - bed + min( rho_water/rho_ice * bathymetry, 0.) );
+}
+/*}}}*/
+void       Penta::InputControlUpdate(IssmDouble scalar,bool save_parameter){/*{{{*/
+
+	/*Intermediary*/
+	int    num_controls;
+	int*   control_type=NULL;
+	Input* input=NULL;
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	for(int i=0;i<num_controls;i++){
+
+		if(control_type[i]==MaterialsRheologyBbarEnum){
+			if (!IsOnBase()) goto cleanup_and_return;
+			input=(Input*)this->inputs->GetInput(MaterialsRheologyBEnum); _assert_(input);
+		}
+		else if(control_type[i]==DamageDbarEnum){
+			if (!IsOnBase()) goto cleanup_and_return;
+			input=(Input*)this->inputs->GetInput(DamageDEnum); _assert_(input);
+		}
+		else{
+			input=(Input*)this->inputs->GetInput(control_type[i]); _assert_(input);
+		}
+		if(input->ObjectEnum()!=ControlInputEnum) _error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
+
+		((ControlInput*)input)->UpdateValue(scalar);
+		((ControlInput*)input)->Constrain();
+		if (save_parameter) ((ControlInput*)input)->SaveValue();
+
+		if(control_type[i]==MaterialsRheologyBbarEnum){
+			this->InputExtrude(MaterialsRheologyBEnum,-1);
+		}
+		else if(control_type[i]==DamageDbarEnum){
+			this->InputExtrude(DamageDEnum,-1);
+		}
+	}
+
+	/*Clean up and return*/
+cleanup_and_return:
+	xDelete<int>(control_type);
 }
 /*}}}*/
@@ -1191,22 +1495,27 @@
 }
 /*}}}*/
-void       Penta::InputExtrude(int enum_type){/*{{{*/
-
-	/*Are we on the base, not on the surface?:*/
-	if(!IsOnBase()) return;
+void       Penta::InputExtrude(int enum_type,int start){/*{{{*/
+
+	_assert_(start==-1 || start==+1);
+
+	/*Are we on the the boundary we want to be?*/
+	if(start==-1 && !IsOnBase())    return;
+	if(start==+1 && !IsOnSurface()) return;
 
 	/*Step1: Get and Extrude original input: */
 	Input* base_input=(Input*)this->inputs->GetInput(enum_type);
 	if(!base_input) _error_("could not find input with enum " << EnumToStringx(enum_type));
-	base_input->Extrude();
+	base_input->Extrude(start);
 
 	/*Stop if there is only one layer of element*/
-	if(this->IsOnSurface()) return;
+	if(start==-1 && this->IsOnSurface()) return;
+	if(start==+1 && this->IsOnBase())    return;
 
 	/*Step 2: this input has been extruded for this element, now follow the upper element*/
 	Penta* penta=this;
 	for(;;){
-		/* get upper Penta*/
-		penta=penta->GetUpperPenta();
+		/*get upper/lower Penta*/
+		if(start==-1) penta=penta->GetUpperPenta();
+		else          penta=penta->GetLowerPenta();
 		_assert_(penta->Id()!=this->id);
 
@@ -1215,6 +1524,7 @@
 		penta->inputs->AddInput((Input*)copy);
 
-		/*Stop if we have reached the surface*/
-		if(penta->IsOnSurface()) break;
+		/*Stop if we have reached the surface/base*/
+		if(start==-1 && penta->IsOnSurface()) break;
+		if(start==+1 && penta->IsOnBase())    break;
 	}
 }
@@ -1277,4 +1587,6 @@
 				case ThicknessEnum:
 				case FrictionCoefficientEnum:
+			  case FrictionAsEnum:	
+				case MaterialsRheologyBEnum:
 					if(iomodel->Data(control)){
 						for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(control)[penta_vertex_ids[j]-1];
@@ -1452,4 +1764,37 @@
 }
 /*}}}*/
+bool       Penta::IsIcefront(void){/*{{{*/
+
+	bool isicefront;
+	int i,nrice;
+   IssmDouble ls[NUMVERTICES];
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/* If only one vertex has ice, there is an ice front here */
+	isicefront=false;
+	if(IsIceInElement()){
+		nrice=0;       
+		for(i=0;i<NUMVERTICES2D;i++)
+			if(ls[i]<0.) nrice++;
+		if(nrice==1) isicefront= true;
+	}
+	return isicefront;
+}/*}}}*/
+bool       Penta::IsNodeOnShelfFromFlags(IssmDouble* flags){/*{{{*/
+
+	int  i;
+	bool shelf=false;
+
+	for(i=0;i<NUMVERTICES;i++){
+		if (flags[vertices[i]->Pid()]<0.){
+			shelf=true;
+			break;
+		}
+	}
+	return shelf;
+}
+/*}}}*/
 bool       Penta::IsOnBase(void){/*{{{*/
 
@@ -1488,16 +1833,20 @@
 }
 /*}}}*/
-bool       Penta::IsNodeOnShelfFromFlags(IssmDouble* flags){/*{{{*/
-
-	int  i;
-	bool shelf=false;
-
-	for(i=0;i<NUMVERTICES;i++){
-		if (flags[vertices[i]->Pid()]<0.){
-			shelf=true;
-			break;
-		}
-	}
-	return shelf;
+bool       Penta::IsZeroLevelset(int levelset_enum){/*{{{*/
+
+	bool        iszerols;
+	IssmDouble  ls[NUMVERTICES];
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],levelset_enum);
+
+	/*If the level set has always same sign, there is no ice front here*/
+	iszerols = false;
+	if(IsIceInElement()){
+		if(ls[0]*ls[1]<0. || ls[0]*ls[2]<0. || (ls[0]*ls[1]*ls[2]==0. && ls[0]*ls[1]+ls[0]*ls[2]+ls[1]*ls[2]<=0.)){
+			iszerols = true;
+		}
+	}
+	return iszerols;
 }
 /*}}}*/
@@ -1523,4 +1872,11 @@
 }
 /*}}}*/
+void       Penta::JacobianDeterminantSurface(IssmDouble* pJdet,IssmDouble* xyz_list_quad,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetQuadJacobianDeterminant(pJdet,xyz_list_quad,(GaussPenta*)gauss);
+
+}
+/*}}}*/
 void       Penta::JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_top,Gauss* gauss){/*{{{*/
 
@@ -1530,9 +1886,48 @@
 }
 /*}}}*/
-void       Penta::JacobianDeterminantSurface(IssmDouble* pJdet,IssmDouble* xyz_list_quad,Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetQuadJacobianDeterminant(pJdet,xyz_list_quad,(GaussPenta*)gauss);
-
+IssmDouble Penta::MassFlux(IssmDouble* segment){/*{{{*/
+
+	IssmDouble mass_flux=0;
+
+	if(!IsOnBase()) return mass_flux;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Spawn Tria element from the base of the Penta: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2);
+	mass_flux=tria->MassFlux(segment);
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return mass_flux;
+}
+/*}}}*/
+IssmDouble Penta::MassFlux(IssmDouble x1, IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){/*{{{*/
+
+	IssmDouble mass_flux=0;
+
+	if(!IsOnBase()) return mass_flux;
+
+	/*Depth Averaging Vx and Vy*/
+	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+
+	/*Spawn Tria element from the base of the Penta: */
+	Tria* tria=(Tria*)SpawnTria(0,1,2);
+	mass_flux=tria->MassFlux(x1,y1,x2,y2,segment_id);
+	delete tria->material; delete tria;
+
+	/*Delete Vx and Vy averaged*/
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+
+	/*clean up and return*/
+	return mass_flux;
 }
 /*}}}*/
@@ -1556,4 +1951,103 @@
 
 	return minlength;
+}
+/*}}}*/
+Gauss*     Penta::NewGauss(void){/*{{{*/
+	return new GaussPenta();
+}
+/*}}}*/
+Gauss*     Penta::NewGauss(int order){/*{{{*/
+	return new GaussPenta(order,order);
+}
+/*}}}*/
+Gauss*     Penta::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){/*{{{*/
+
+	IssmDouble  area_coordinates[4][3];
+
+	GetAreaCoordinates(&area_coordinates[0][0],xyz_list_front,xyz_list,4);
+
+	return new GaussPenta(area_coordinates,order_horiz,order_vert);
+}
+/*}}}*/
+Gauss*     Penta::NewGaussBase(int order){/*{{{*/
+	return new GaussPenta(0,1,2,order);
+}
+/*}}}*/
+Gauss*     Penta::NewGaussLine(int vertex1,int vertex2,int order){/*{{{*/
+	return new GaussPenta(vertex1,vertex2,order);
+}
+/*}}}*/
+Gauss*     Penta::NewGaussTop(int order){/*{{{*/
+	return new GaussPenta(3,4,5,order);
+}
+/*}}}*/
+void       Penta::NodalFunctions(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->element_type);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,this->element_type);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,this->VelocityInterpolation());
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,P1bubbleEnum);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->PressureInterpolation());
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsP1(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,P1Enum);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,P1Enum);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsP2(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,P2Enum);
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsVelocity(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->VelocityInterpolation());
+
+}
+/*}}}*/
+void       Penta::NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussPentaEnum);
+	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->TensorInterpolation());
+
 }
 /*}}}*/
@@ -1589,103 +2083,4 @@
 }
 /*}}}*/
-Gauss*     Penta::NewGauss(void){/*{{{*/
-	return new GaussPenta();
-}
-/*}}}*/
-Gauss*     Penta::NewGauss(int order){/*{{{*/
-	return new GaussPenta(order,order);
-}
-/*}}}*/
-Gauss*     Penta::NewGauss(IssmDouble* xyz_list, IssmDouble* xyz_list_front,int order_horiz,int order_vert){/*{{{*/
-
-	IssmDouble  area_coordinates[4][3];
-
-	GetAreaCoordinates(&area_coordinates[0][0],xyz_list_front,xyz_list,4);
-
-	return new GaussPenta(area_coordinates,order_horiz,order_vert);
-}
-/*}}}*/
-Gauss*     Penta::NewGaussBase(int order){/*{{{*/
-	return new GaussPenta(0,1,2,order);
-}
-/*}}}*/
-Gauss*     Penta::NewGaussLine(int vertex1,int vertex2,int order){/*{{{*/
-	return new GaussPenta(vertex1,vertex2,order);
-}
-/*}}}*/
-Gauss*     Penta::NewGaussTop(int order){/*{{{*/
-	return new GaussPenta(3,4,5,order);
-}
-/*}}}*/
-void       Penta::NodalFunctions(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->element_type);
-
-}
-/*}}}*/
-void       Penta::NodalFunctionsP1(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctions(basis,(GaussPenta*)gauss,P1Enum);
-
-}
-/*}}}*/
-void       Penta::NodalFunctionsP2(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctions(basis,(GaussPenta*)gauss,P2Enum);
-
-}
-/*}}}*/
-void       Penta::NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,this->element_type);
-
-}
-/*}}}*/
-void       Penta::NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,P1Enum);
-
-}
-/*}}}*/
-void       Penta::NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,P1bubbleEnum);
-
-}
-/*}}}*/
-void       Penta::NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussPenta*)gauss,this->VelocityInterpolation());
-
-}
-/*}}}*/
-void       Penta::NodalFunctionsVelocity(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->VelocityInterpolation());
-
-}
-/*}}}*/
-void       Penta::NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->PressureInterpolation());
-
-}
-/*}}}*/
-void       Penta::NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussPentaEnum);
-	this->GetNodalFunctions(basis,(GaussPenta*)gauss,this->TensorInterpolation());
-
-}
-/*}}}*/
 void       Penta::NormalBase(IssmDouble* bed_normal,IssmDouble* xyz_list){/*{{{*/
 
@@ -1710,4 +2105,24 @@
 }
 /*}}}*/
+void       Penta::NormalSection(IssmDouble* normal,IssmDouble* xyz_list){/*{{{*/
+
+	/*Build unit outward pointing vector*/
+	IssmDouble AB[3];
+	IssmDouble AC[3];
+	IssmDouble norm;
+
+	AB[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
+	AB[1]=xyz_list[1*3+1] - xyz_list[0*3+1];
+	AB[2]=xyz_list[1*3+2] - xyz_list[0*3+2];
+	AC[0]=xyz_list[2*3+0] - xyz_list[0*3+0];
+	AC[1]=xyz_list[2*3+1] - xyz_list[0*3+1];
+	AC[2]=xyz_list[2*3+2] - xyz_list[0*3+2];
+
+	cross(normal,AB,AC);
+	norm=sqrt(normal[0]*normal[0]+normal[1]*normal[1]+normal[2]*normal[2]);
+
+	for(int i=0;i<3;i++) normal[i]=normal[i]/norm;
+}
+/*}}}*/
 void       Penta::NormalTop(IssmDouble* top_normal,IssmDouble* xyz_list){/*{{{*/
 
@@ -1740,10 +2155,30 @@
 }
 /*}}}*/
-void       Penta::PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){/*{{{*/
-
+int        Penta::ObjectEnum(void){/*{{{*/
+
+	return PentaEnum;
+
+}
+/*}}}*/
+void       Penta::PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm){/*{{{*/
+
+   int        i;
    IssmDouble agd[NUMVERTICES];             // surface mass balance
    IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
-   IssmDouble h[NUMVERTICES],s[NUMVERTICES]; // ,b
-   IssmDouble rho_water,rho_ice,desfac,s0p;
+   IssmDouble tmp[NUMVERTICES];
+   IssmDouble h[NUMVERTICES],s[NUMVERTICES];
+   IssmDouble rho_water,rho_ice,desfac,s0p,s0t,rlaps,rlapslgm;
+   IssmDouble PfacTime,TdiffTime,sealevTime;
+
+   /*Get material parameters :*/
+   rho_water=matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+   rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+
+  /*Get some pdd parameters*/
+  desfac=matpar->GetMaterialParameter(SurfaceforcingsDesfacEnum);
+  s0p=matpar->GetMaterialParameter(SurfaceforcingsS0pEnum);
+  s0t=matpar->GetMaterialParameter(SurfaceforcingsS0tEnum);
+  rlaps=matpar->GetMaterialParameter(SurfaceforcingsRlapsEnum);
+  rlapslgm=matpar->GetMaterialParameter(SurfaceforcingsRlapslgmEnum);
 
    /*Recover monthly temperatures and precipitation*/
@@ -1754,4 +2189,5 @@
    this->parameters->FindParam(&time,TimeEnum);
    this->parameters->FindParam(&yts,ConstantsYtsEnum);
+   
    for(int month=0;month<12;month++) {
      for(int iv=0;iv<NUMVERTICES;iv++) {
@@ -1760,33 +2196,90 @@
        monthlytemperatures[iv][month]=monthlytemperatures[iv][month]-273.15; // conversion from Kelvin to celcius
        input2->GetInputValue(&monthlyprec[iv][month],gauss,time+month/12.*yts);
-       monthlyprec[iv][month]=monthlyprec[iv][month]*yts; // convertion to m/yr
      }
    } 
 
+  /*Recover Pfac, Tdiff and sealev at time t:
+    This parameters are used to interpolate the temperature 
+    and precipitaton between PD and LGM when ismungsm==1 */ 
+  if (ismungsm==1){  
+    this->parameters->FindParam(&TdiffTime,SurfaceforcingsTdiffEnum,time);
+    this->parameters->FindParam(&sealevTime,SurfaceforcingsSealevEnum,time);
+  }
+  else {
+    TdiffTime=0;
+    sealevTime=0;  
+  }
+
   /*Recover info at the vertices: */
   GetInputListOnVertices(&h[0],ThicknessEnum);
-  GetInputListOnVertices(&s[0],SurfaceEnum);
-
-  /*Get material parameters :*/
-  rho_ice=matpar->GetRhoIce();
-  rho_water=matpar->GetRhoFreshwater();
-
-  /*Get desertification effect parameters*/
-  desfac=matpar->GetDesFac();
-  s0p=matpar->GetS0p();
+  GetInputListOnVertices(&s[0],SurfaceEnum); 
+
 
    /*measure the surface mass balance*/
    for (int iv = 0; iv < NUMVERTICES; iv++){
-     agd[iv]=PddSurfaceMassBlance(&monthlytemperatures[iv][0], &monthlyprec[iv][0], pdds, pds, 
-				  signorm, yts, h[iv], s[iv], rho_ice, rho_water, desfac, s0p);
+     agd[iv]=PddSurfaceMassBalance(&monthlytemperatures[iv][0], &monthlyprec[iv][0],  
+				  pdds,pds, signorm, yts, h[iv], s[iv],
+				  desfac, s0t, s0p,rlaps,rlapslgm,TdiffTime,sealevTime,
+				  rho_water,rho_ice);
    }
 
    /*Update inputs*/    
+   // TransientInput* NewTemperatureInput = new TransientInput(SurfaceforcingsMonthlytemperaturesEnum);
+   // TransientInput* NewPrecipitationInput = new TransientInput(SurfaceforcingsPrecipitationEnum);
+   // for (int imonth=0;imonth<12;imonth++) {
+   //   for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
+   //   PentaInput* newmonthinput1 = new PentaInput(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0],P1Enum);
+   //   NewTemperatureInput->AddTimeInput(newmonthinput1,time+imonth/12.*yts);
+   // 
+   //   for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlyprec[i][imonth];
+   //   PentaInput* newmonthinput2 = new PentaInput(SurfaceforcingsPrecipitationEnum,&tmp[0],P1Enum);
+   //   NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
+   // }
+   // NewTemperatureInput->Configure(this->parameters);
+   // NewPrecipitationInput->Configure(this->parameters);
+
+
+
    this->inputs->AddInput(new PentaInput(SurfaceforcingsMassBalanceEnum,&agd[0],P1Enum));
-   //this->inputs->AddInput(new PentaVertexInput(ThermalSpcTemperatureEnum,&Tsurf[0]));
-   this->InputExtrude(SurfaceforcingsMassBalanceEnum);
-
-	/*clean-up*/
-	delete gauss;
+   // this->inputs->AddInput(NewTemperatureInput);
+   // this->inputs->AddInput(NewPrecipitationInput);
+   // //this->inputs->AddInput(new PentaVertexInput(ThermalSpcTemperatureEnum,&Tsurf[0]));
+    this->InputExtrude(SurfaceforcingsMassBalanceEnum,-1);
+   // this->InputExtrude(SurfaceforcingsMonthlytemperaturesEnum,-1);
+   // this->InputExtrude(SurfaceforcingsPrecipitationEnum,-1);
+
+   /*clean-up*/
+   delete gauss;
+}
+/*}}}*/
+void       Penta::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){/*{{{*/
+
+	IssmDouble  h[NUMVERTICES],r[NUMVERTICES],gl[NUMVERTICES];
+	IssmDouble  bed_hydro;
+	IssmDouble  rho_water,rho_ice,density;
+
+	/*material parameters: */
+	rho_water=matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+	density=rho_ice/rho_water;
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&r[0],BedEnum);
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
+
+	/*go through vertices, and figure out which ones are on the ice sheet, and want to unground: */
+	for(int i=0;i<NUMVERTICES;i++){
+		/*Find if grounded vertices want to start floating*/
+		if (gl[i]>0.){
+			bed_hydro=-density*h[i];
+			if(bed_hydro>r[i]){
+				/*Vertex that could potentially unground, flag it*/
+				potential_ungrounding->SetValue(vertices[i]->Pid(),1,INS_VAL);
+			}
+		}
+	}
+}
+/*}}}*/
+int        Penta::PressureInterpolation(void){/*{{{*/
+	return PentaRef::PressureInterpolation(this->element_type);
 }
 /*}}}*/
@@ -1909,24 +2402,4 @@
 }
 /*}}}*/
-void       Penta::SetClone(int* minranks){/*{{{*/
-
-	_error_("not implemented yet");
-}
-/*}}}*/
-void       Penta::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
-
-	/*go into parameters and get the analysis_counter: */
-	int analysis_counter;
-	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
-
-	/*Get Element type*/
-	this->element_type=this->element_type_list[analysis_counter];
-
-	/*Pick up nodes*/
-	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
-	else this->nodes=NULL;
-
-}
-/*}}}*/
 void       Penta::ResetHooks(){/*{{{*/
 
@@ -1947,6 +2420,98 @@
 }
 /*}}}*/
+void       Penta::SetClone(int* minranks){/*{{{*/
+
+	_error_("not implemented yet");
+}
+/*}}}*/
+void       Penta::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){/*{{{*/
+
+	IssmDouble  values[NUMVERTICES];
+	int         vertexpidlist[NUMVERTICES],control_init;
+
+	/*Specific case for depth averaged quantities*/
+	control_init=control_enum;
+	if(control_enum==MaterialsRheologyBbarEnum){
+		control_enum=MaterialsRheologyBEnum;
+		if(!IsOnBase()) return;
+	}
+	if(control_enum==DamageDbarEnum){
+		control_enum=DamageDEnum;
+		if(!IsOnBase()) return;
+	}
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Get values on vertices*/
+	for(int i=0;i<NUMVERTICES;i++){
+		values[i]=vector[vertexpidlist[i]];
+	}
+	Input* new_input = new PentaInput(control_enum,values,P1Enum);
+	Input* input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	if(input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->SetInput(new_input);
+
+	if(control_init==MaterialsRheologyBbarEnum){
+		this->InputExtrude(control_enum,-1);
+	}
+	if(control_init==DamageDbarEnum){
+		this->InputExtrude(control_enum,-1);
+	}
+}
+/*}}}*/
+void       Penta::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
+
+	/*go into parameters and get the analysis_counter: */
+	int analysis_counter;
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Pick up nodes*/
+	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+
+}
+/*}}}*/
 void       Penta::SetTemporaryElementType(int element_type_in){/*{{{*/
 	this->element_type=element_type_in;
+}
+/*}}}*/
+Element*   Penta::SpawnBasalElement(void){/*{{{*/
+
+	_assert_(this->IsOnBase());
+
+	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
+	if(this->material->IsDamage())this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum);
+	if(this->inputs->GetInput(VxEnum)) this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
+	if(this->inputs->GetInput(VyEnum)) this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
+	if(this->inputs->GetInput(CalvingratexEnum)) this->InputDepthAverageAtBase(CalvingratexEnum,CalvingratexAverageEnum);
+	if(this->inputs->GetInput(CalvingrateyEnum)) this->InputDepthAverageAtBase(CalvingrateyEnum,CalvingrateyAverageEnum);
+	Tria* tria=(Tria*)SpawnTria(0,1,2);
+	this->inputs->DeleteInput(MaterialsRheologyBbarEnum);
+	this->inputs->DeleteInput(DamageDbarEnum);
+	this->inputs->DeleteInput(VxAverageEnum);
+	this->inputs->DeleteInput(VyAverageEnum);
+	this->inputs->DeleteInput(CalvingratexAverageEnum);
+	this->inputs->DeleteInput(CalvingrateyAverageEnum);
+
+	return tria;
+}
+/*}}}*/
+Element*   Penta::SpawnTopElement(void){/*{{{*/
+
+	_assert_(this->IsOnSurface());
+
+	Tria* tria=(Tria*)SpawnTria(3,4,5);
+
+	return tria;
 }
 /*}}}*/
@@ -1964,5 +2529,5 @@
 	tria->parameters=this->parameters;
 	tria->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
-	this->SpawnTriaHook(dynamic_cast<ElementHook*>(tria),index1,index2,index3);
+	this->SpawnTriaHook(xDynamicCast<ElementHook*>(tria),index1,index2,index3);
 
 	/*Spawn material*/
@@ -1978,28 +2543,190 @@
 }
 /*}}}*/
-Element*   Penta::SpawnBasalElement(void){/*{{{*/
-
-	_assert_(this->IsOnBase());
-
-	this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
-	if(this->material->IsDamage())this->InputDepthAverageAtBase(DamageDEnum,DamageDbarEnum);
-	if(this->inputs->GetInput(VxEnum)) this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
-	if(this->inputs->GetInput(VyEnum)) this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
-	Tria* tria=(Tria*)SpawnTria(0,1,2);
-	this->inputs->DeleteInput(MaterialsRheologyBbarEnum);
-	this->inputs->DeleteInput(DamageDbarEnum);
-	this->inputs->DeleteInput(VxAverageEnum);
-	this->inputs->DeleteInput(VyAverageEnum);
-
-	return tria;
-}
-/*}}}*/
-Element*   Penta::SpawnTopElement(void){/*{{{*/
-
-	_assert_(this->IsOnSurface());
-
-	Tria* tria=(Tria*)SpawnTria(3,4,5);
-
-	return tria;
+IssmDouble Penta::StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){/*{{{*/
+	/*Compute stabilization parameter*/
+	/*kappa=thermalconductivity/(rho_ice*hearcapacity) for thermal model*/
+	/*kappa=enthalpydiffusionparameter for enthalpy model*/
+
+	IssmDouble normu;
+	IssmDouble tau_parameter;
+
+	normu=pow(pow(u,2)+pow(v,2)+pow(w,2),0.5);
+	if(normu*diameter/(3*2*kappa)<1){ 
+		tau_parameter=pow(diameter,2)/(3*2*2*kappa);
+	}
+	else tau_parameter=diameter/(2*normu);
+
+	return tau_parameter;
+}
+/*}}}*/
+void       Penta::StrainRateparallel(){/*{{{*/
+
+	IssmDouble *xyz_list = NULL;
+	IssmDouble  epsilon[6];
+	GaussPenta* gauss=NULL;
+	IssmDouble  vx,vy,vel;
+	IssmDouble  strainxx;
+	IssmDouble  strainxy;
+	IssmDouble  strainyy;
+	IssmDouble  strainparallel[NUMVERTICES];
+
+	/* Get node coordinates and dof list: */
+	this->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will need*/
+	Input* vx_input=inputs->GetInput(VxEnum);                                  _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                                  _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);												_assert_(vz_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/* Get the value we need*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel=vx*vx+vy*vy;
+
+		/*Compute strain rate and viscosity: */
+		this->StrainRateFS(&epsilon[0],xyz_list,gauss,vx_input,vy_input,vz_input);
+		strainxx=epsilon[0];
+		strainyy=epsilon[1];
+		strainxy=epsilon[3];
+
+		/*strainparallel= Strain rate along the ice flow direction */
+		strainparallel[iv]=(vx*vx*(strainxx)+vy*vy*(strainyy)+2*vy*vx*strainxy)/(vel+1.e-14);
+	}
+
+	/*Add input*/
+	this->inputs->AddInput(new PentaInput(StrainRateparallelEnum,&strainparallel[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+}
+/*}}}*/
+void       Penta::StrainRateperpendicular(){/*{{{*/
+
+	IssmDouble *xyz_list = NULL;
+	IssmDouble  epsilon[6];
+	GaussPenta* gauss=NULL;
+	IssmDouble  vx,vy,vel;
+	IssmDouble  strainxx;
+	IssmDouble  strainxy;
+	IssmDouble  strainyy;
+	IssmDouble  strainperpendicular[NUMVERTICES];
+
+	/* Get node coordinates and dof list: */
+	this->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will need*/
+	Input* vx_input=inputs->GetInput(VxEnum);                                  _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                                  _assert_(vy_input);
+	Input* vz_input=inputs->GetInput(VzEnum);												_assert_(vz_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussPenta();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/* Get the value we need*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel=vx*vx+vy*vy;
+
+		/*Compute strain rate and viscosity: */
+		this->StrainRateFS(&epsilon[0],xyz_list,gauss,vx_input,vy_input,vz_input);
+		strainxx=epsilon[0];
+		strainyy=epsilon[1];
+		strainxy=epsilon[3];
+
+		/*strainperpendicular= Strain rate perpendicular to the ice flow direction */
+		strainperpendicular[iv]=(vx*vx*(strainyy)+vy*vy*(strainxx)-2*vy*vx*strainxy)/(vel+1.e-14);
+	}
+
+	/*Add input*/
+	this->inputs->AddInput(new PentaInput(StrainRateperpendicularEnum,&strainperpendicular[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+}
+/*}}}*/
+void       Penta::StressIntensityFactor(){/*{{{*/
+
+	/* Check if we are on the base */
+	if(!IsOnBase()) return;
+
+	IssmDouble  ki[6]={0.};
+	IssmDouble  const_grav=9.81;
+	IssmDouble  rho_ice=900;
+	IssmDouble  rho_water=1000;
+	IssmDouble  Jdet[3];
+	IssmDouble  pressure,vx,vy,vel,deviaxx,deviaxy,deviayy,water_depth,prof,stress_xx,thickness;
+
+	Penta* penta=this;
+	for(;;){
+	
+		IssmDouble  xyz_list[NUMVERTICES][3];
+		/* Get node coordinates and dof list: */
+		::GetVerticesCoordinates(&xyz_list[0][0],penta->vertices,NUMVERTICES);
+
+		///*Compute the Jacobian for the vertical integration*/
+		Jdet[0]=(xyz_list[3][2]-xyz_list[0][2])*0.5;
+		Jdet[1]=(xyz_list[4][2]-xyz_list[1][2])*0.5;
+		Jdet[2]=(xyz_list[5][2]-xyz_list[2][2])*0.5;
+	
+		/*Retrieve all inputs we will need*/
+		Input* vx_input=inputs->GetInput(VxEnum);                                  _assert_(vx_input);
+		Input* vy_input=inputs->GetInput(VyEnum);                                  _assert_(vy_input);
+		Input* vel_input=inputs->GetInput(VelEnum);                                _assert_(vel_input);
+		Input* pressure_input=inputs->GetInput(PressureEnum);                      _assert_(pressure_input);
+		Input* deviaxx_input=inputs->GetInput(DeviatoricStressxxEnum);             _assert_(deviaxx_input);
+		Input* deviaxy_input=inputs->GetInput(DeviatoricStressxyEnum);             _assert_(deviaxy_input);
+		Input* deviayy_input=inputs->GetInput(DeviatoricStressyyEnum);             _assert_(deviayy_input);
+		Input* surface_input=inputs->GetInput(SurfaceEnum);								_assert_(surface_input);
+		Input* thickness_input=inputs->GetInput(ThicknessEnum);							_assert_(thickness_input);
+		
+		/* Start looping on the number of 2D vertices: */
+		for(int ig=0;ig<3;ig++){
+			GaussPenta* gauss=new GaussPenta(ig,3+ig,11);
+			for (int iv=gauss->begin();iv<gauss->end();iv++){
+				gauss->GaussPoint(iv);
+
+				/* Get the value we need*/
+				pressure_input->GetInputValue(&pressure,gauss);
+				vx_input->GetInputValue(&vx,gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				vel_input->GetInputValue(&vel,gauss);
+				deviaxx_input->GetInputValue(&deviaxx,gauss);
+				deviaxy_input->GetInputValue(&deviaxy,gauss);
+				deviayy_input->GetInputValue(&deviayy,gauss);
+				surface_input->GetInputValue(&water_depth,gauss);
+				thickness_input->GetInputValue(&thickness,gauss);
+				prof=water_depth-penta->GetZcoord(&xyz_list[0][0],gauss);
+
+				/*stress_xx= Deviatoric stress along the ice flow direction plus cryostatic pressure */
+				stress_xx=(vx*vx*(deviaxx)+vy*vy*(deviayy)+2*vy*vx*deviaxy)/(vel*vel+1.e-6);
+
+				if(prof<water_depth&prof<thickness){
+					/* Compute the local stress intensity factor*/ 
+					ki[ig]+=Jdet[ig]*gauss->weight*stress_xx*StressIntensityIntegralWeight(prof,min(water_depth,thickness),thickness);
+				}
+			}
+			delete gauss;
+		}
+			
+		/*Stop if we have reached the surface/base*/
+		if(penta->IsOnSurface()) break;
+		
+		/*get upper Penta*/
+		penta=penta->GetUpperPenta();
+		_assert_(penta->Id()!=this->id);
+	}
+
+	/*Add input*/
+	this->inputs->AddInput(new PentaInput(StressIntensityFactorEnum,&ki[0],P1Enum));
+	this->InputExtrude(StressIntensityFactorEnum,-1);
 }
 /*}}}*/
@@ -2083,4 +2810,33 @@
 	return dt;
 }/*}}}*/
+IssmDouble Penta::TotalSmb(void){/*{{{*/
+
+	/*The smb[Gt yr-1] of one element is area[m2] * smb [ m ice yr^-1] * rho_ice [kg m-3] / 1e+10^12 */
+	IssmDouble base,smb,rho_ice;
+	IssmDouble Total_Smb=0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+
+	if(!IsIceInElement() || !IsOnSurface()) return 0.;
+
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Triangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average SMB over the element*/
+	Input* smb_input = inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(smb_input);
+
+	smb_input->GetInputAverage(&smb);
+	Total_Smb=rho_ice*base*smb;// smb on element in kg s-1
+
+	/*Return: */
+	return Total_Smb;
+}
+/*}}}*/
 void       Penta::Update(int index,IoModel* iomodel,int analysis_counter,int analysis_type,int finiteelement_type){ /*{{{*/
 
@@ -2091,5 +2847,4 @@
 	IssmDouble yts;
 	bool       dakota_analysis;
-	bool       isFS;
 	int        numnodes;
 	int*       penta_node_ids = NULL;
@@ -2098,5 +2853,4 @@
 	iomodel->Constant(&yts,ConstantsYtsEnum);
 	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
-	iomodel->Constant(&isFS,FlowequationIsFSEnum);
 
 	/*Checks if debuging*/
@@ -2413,4 +3167,27 @@
 			penta_node_ids[24]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+iomodel->numberofelements+6*index+6;
 			break;
+		case LACrouzeixRaviartEnum:
+			numnodes         = 19;
+			penta_node_ids   = xNew<int>(numnodes);
+			penta_node_ids[ 0]=iomodel->nodecounter+iomodel->elements[6*index+0];
+			penta_node_ids[ 1]=iomodel->nodecounter+iomodel->elements[6*index+1];
+			penta_node_ids[ 2]=iomodel->nodecounter+iomodel->elements[6*index+2];
+			penta_node_ids[ 3]=iomodel->nodecounter+iomodel->elements[6*index+3];
+			penta_node_ids[ 4]=iomodel->nodecounter+iomodel->elements[6*index+4];
+			penta_node_ids[ 5]=iomodel->nodecounter+iomodel->elements[6*index+5];
+			penta_node_ids[ 6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+0]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+1]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+2]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+3]+1;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+4]+1;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+5]+1;
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+6]+1;
+			penta_node_ids[13]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+7]+1;
+			penta_node_ids[14]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
+			penta_node_ids[15]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+2]+1;
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+3]+1;
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elementtofaceconnectivity[5*index+4]+1;
+			penta_node_ids[18]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberoffaces+index+1;
+			break;
 		default:
 			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
@@ -2428,4 +3205,5 @@
 
 		case StressbalanceAnalysisEnum:
+			_assert_(iomodel->Data(FlowequationElementEquationEnum));
 
 			if(*(iomodel->Data(FlowequationElementEquationEnum)+index)==HOFSApproximationEnum){
@@ -2509,10 +3287,33 @@
 }
 /*}}}*/
+int        Penta::UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){/*{{{*/
+
+	int i;
+	int nflipped=0;
+
+	/*Go through nodes, and whoever is on the potential_ungrounding, ends up in nodes_on_iceshelf: */
+	for(i=0;i<NUMVERTICES;i++){
+		if (reCast<bool,IssmDouble>(vertices_potentially_ungrounding[vertices[i]->Pid()])){
+			vec_nodes_on_iceshelf->SetValue(vertices[i]->Pid(),-1.,INS_VAL);
+
+			/*If node was not on ice shelf, we flipped*/
+			if(nodes_on_iceshelf[vertices[i]->Pid()]>=0.){
+				nflipped++;
+			}
+		}
+	}
+	return nflipped;
+}
+/*}}}*/
+void       Penta::ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	PentaRef::GetInputDerivativeValue(dvalue,values,xyz_list,gauss,P1Enum);
+}
+/*}}}*/
 void       Penta::ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss){/*{{{*/
 	PentaRef::GetInputValue(pvalue,values,gauss,P1Enum);
 }
 /*}}}*/
-void       Penta::ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	PentaRef::GetInputDerivativeValue(dvalue,values,xyz_list,gauss,P1Enum);
+int        Penta::VelocityInterpolation(void){/*{{{*/
+	return PentaRef::VelocityInterpolation(this->element_type);
 }
 /*}}}*/
@@ -2551,207 +3352,157 @@
 }
 /*}}}*/
-int        Penta::VelocityInterpolation(void){/*{{{*/
-	return PentaRef::VelocityInterpolation(this->element_type);
-}
-/*}}}*/
-int        Penta::PressureInterpolation(void){/*{{{*/
-	return PentaRef::PressureInterpolation(this->element_type);
-}
-/*}}}*/
-bool       Penta::IsZeroLevelset(int levelset_enum){/*{{{*/
-
-	bool        iszerols;
-	IssmDouble  ls[NUMVERTICES];
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&ls[0],levelset_enum);
-
-	/*If the level set has always same sign, there is no ice front here*/
-	iszerols = false;
-	if(IsIceInElement()){
-		if(ls[0]*ls[1]<0. || ls[0]*ls[2]<0. || (ls[0]*ls[1]*ls[2]==0. && ls[0]*ls[1]+ls[0]*ls[2]+ls[1]*ls[2]<=0.)){
-			iszerols = true;
-		}
-	}
-	return iszerols;
-}
-/*}}}*/
-bool       Penta::IsIcefront(void){/*{{{*/
-
-	bool isicefront;
-	int i,nrice;
-   IssmDouble ls[NUMVERTICES];
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
-
-	/* If only one vertex has ice, there is an ice front here */
-	isicefront=false;
-	if(IsIceInElement()){
-		nrice=0;       
-		for(i=0;i<NUMVERTICES2D;i++)
-			if(ls[i]<0.) nrice++;
-		if(nrice==1) isicefront= true;
-	}
-	return isicefront;
-}/*}}}*/
-void       Penta::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){/*{{{*/
-	_error_("Not supported yet!");
-}
-/*}}}*/
-IssmDouble Penta::IceVolume(void){/*{{{*/
-
-	/*The volume of a troncated prism is base * 1/3 sum(length of edges)*/
-	IssmDouble base,height;
-	IssmDouble xyz_list[NUMVERTICES][3];
-
-	if(!IsIceInElement())return 0;
-
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*First calculate the area of the base (cross section triangle)
-	 * http://en.wikipedia.org/wiki/Pentangle
-	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
-	base = 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
-
-	/*Now get the average height*/
-	height = 1./3.*((xyz_list[3][2]-xyz_list[0][2])+(xyz_list[4][2]-xyz_list[1][2])+(xyz_list[5][2]-xyz_list[2][2]));
-
-	/*Return: */
-	return base*height;
-}
-/*}}}*/
-IssmDouble Penta::IceVolumeAboveFloatation(void){/*{{{*/
-
-	/*Volume above floatation: H + rho_water/rho_ice*bathymetry for nodes on the bed*/
-	IssmDouble rho_ice,rho_water;
-	IssmDouble base,bed,surface,bathymetry;
-	IssmDouble xyz_list[NUMVERTICES][3];
-
-	if(!IsIceInElement() || IsFloating() || !IsOnBase())return 0;
-
-	rho_ice=matpar->GetRhoIce();
-	rho_water=matpar->GetRhoWater();
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*First calculate the area of the base (cross section triangle)
-	 * http://en.wikipedia.org/wiki/Pentangle
-	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
-	base = 1./2.*fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
-
-	/*Now get the average height above floatation*/
-	Input* surface_input    = inputs->GetInput(SurfaceEnum);    _assert_(surface_input);
-	Input* base_input        = inputs->GetInput(BaseEnum);        _assert_(base_input);
-	Input* bed_input = inputs->GetInput(BedEnum); _assert_(bed_input);
-	surface_input->GetInputAverage(&surface);
-	base_input->GetInputAverage(&bed);
-	bed_input->GetInputAverage(&bathymetry);
-
-	/*Return: */
-	return base*(surface - bed + min( rho_water/rho_ice * bathymetry, 0.) );
-}
-/*}}}*/
-IssmDouble Penta::MassFlux( IssmDouble* segment){/*{{{*/
-
-	IssmDouble mass_flux=0;
-
-	if(!IsOnBase()) return mass_flux;
-
-	/*Depth Averaging Vx and Vy*/
-	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
-	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
-
-	/*Spawn Tria element from the base of the Penta: */
-	Tria* tria=(Tria*)SpawnTria(0,1,2);
-	mass_flux=tria->MassFlux(segment);
-	delete tria->material; delete tria;
-
-	/*Delete Vx and Vy averaged*/
-	this->inputs->DeleteInput(VxAverageEnum);
-	this->inputs->DeleteInput(VyAverageEnum);
-
-	/*clean up and return*/
-	return mass_flux;
-}
-/*}}}*/
-IssmDouble Penta::MassFlux( IssmDouble x1, IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){/*{{{*/
-
-	IssmDouble mass_flux=0;
-
-	if(!IsOnBase()) return mass_flux;
-
-	/*Depth Averaging Vx and Vy*/
-	this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
-	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
-
-	/*Spawn Tria element from the base of the Penta: */
-	Tria* tria=(Tria*)SpawnTria(0,1,2);
-	mass_flux=tria->MassFlux(x1,y1,x2,y2,segment_id);
-	delete tria->material; delete tria;
-
-	/*Delete Vx and Vy averaged*/
-	this->inputs->DeleteInput(VxAverageEnum);
-	this->inputs->DeleteInput(VyAverageEnum);
-
-	/*clean up and return*/
-	return mass_flux;
-}
-/*}}}*/
-void       Penta::ElementResponse(IssmDouble* presponse,int response_enum){/*{{{*/
-
-	switch(response_enum){
-		case MaterialsRheologyBbarEnum:
-			*presponse=this->material->GetBbar();
-			break;
-		case DamageDbarEnum:
-			*presponse=this->material->GetDbar();
-			break;
-		case VelEnum:
-			{
-
-				/*Get input:*/
-				IssmDouble vel;
-				Input* vel_input;
-
-				vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
-				vel_input->GetInputAverage(&vel);
-
-				/*Assign output pointers:*/
-				*presponse=vel;
-			}
-			break;
-		default:  
-			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
-	}
-
-}
-/*}}}*/
-IssmDouble Penta::TotalSmb(void){/*{{{*/
-
-	/*The smb[Gt yr-1] of one element is area[m2] * smb [ m ice yr^-1] * rho_ice [kg m-3] / 1e+10^12 */
-	IssmDouble base,smb,rho_ice;
-	IssmDouble Total_Smb=0;
-	IssmDouble xyz_list[NUMVERTICES][3];
-
-	/*Get material parameters :*/
-	rho_ice=matpar->GetRhoIce();
-
-	if(!IsIceInElement() || !IsOnSurface()) return 0.;
-
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*First calculate the area of the base (cross section triangle)
-	 * http://en.wikipedia.org/wiki/Triangle
-	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
-	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
-
-	/*Now get the average SMB over the element*/
-	Input* smb_input = inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(smb_input);
-
-	smb_input->GetInputAverage(&smb);
-	Total_Smb=rho_ice*base*smb;// smb on element in kg s-1
-
-	/*Return: */
-	return Total_Smb;
+void       Penta::ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
+	/*Compute portion of the element that is grounded*/ 
+
+	int         normal_orientation=0;
+	IssmDouble  s1,s2;
+	IssmDouble  levelset[NUMVERTICES];
+	IssmDouble* xyz_zero = xNew<IssmDouble>(4*3);
+
+	/*Recover parameters and values*/
+	GetInputListOnVertices(&levelset[0],levelsetenum);
+
+	if(levelset[0]*levelset[1]>0.){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+		/*Portion of the segments*/
+		s1=levelset[2]/(levelset[2]-levelset[1]);
+		s2=levelset[2]/(levelset[2]-levelset[0]);
+
+		if(levelset[2]<0.) normal_orientation=1; //orientation of quadrangle at base and top, depending on distribution of levelsetfunction
+		/*New point 1*/
+		xyz_zero[3*normal_orientation+0]=xyz_list[2*3+0]+s1*(xyz_list[1*3+0]-xyz_list[2*3+0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[2*3+1]+s1*(xyz_list[1*3+1]-xyz_list[2*3+1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[2*3+2]+s1*(xyz_list[1*3+2]-xyz_list[2*3+2]);
+
+		/*New point 0*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[2*3+0]+s2*(xyz_list[0*3+0]-xyz_list[2*3+0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[2*3+1]+s2*(xyz_list[0*3+1]-xyz_list[2*3+1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[2*3+2]+s2*(xyz_list[0*3+2]-xyz_list[2*3+2]);
+
+		/*New point 3*/
+		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[5*3+0]+s1*(xyz_list[4*3+0]-xyz_list[5*3+0]);
+		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[5*3+1]+s1*(xyz_list[4*3+1]-xyz_list[5*3+1]);
+		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[5*3+2]+s1*(xyz_list[4*3+2]-xyz_list[5*3+2]);
+
+		/*New point 4*/
+		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[5*3+0]+s2*(xyz_list[3*3+0]-xyz_list[5*3+0]);
+		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[5*3+1]+s2*(xyz_list[3*3+1]-xyz_list[5*3+1]);
+		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[5*3+2]+s2*(xyz_list[3*3+2]-xyz_list[5*3+2]);
+	}
+	else if(levelset[1]*levelset[2]>0.){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+		/*Portion of the segments*/
+		s1=levelset[0]/(levelset[0]-levelset[2]);
+		s2=levelset[0]/(levelset[0]-levelset[1]);
+
+		if(levelset[0]<0.) normal_orientation=1;
+		/*New point 1*/
+		xyz_zero[3*normal_orientation+0]=xyz_list[0*3+0]+s1*(xyz_list[2*3+0]-xyz_list[0*3+0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[0*3+1]+s1*(xyz_list[2*3+1]-xyz_list[0*3+1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[0*3+2]+s1*(xyz_list[2*3+2]-xyz_list[0*3+2]);
+
+		/*New point 2*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[0*3+0]+s2*(xyz_list[1*3+0]-xyz_list[0*3+0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[0*3+1]+s2*(xyz_list[1*3+1]-xyz_list[0*3+1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[0*3+2]+s2*(xyz_list[1*3+2]-xyz_list[0*3+2]);
+
+		/*New point 3*/
+		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[3*3+0]+s1*(xyz_list[5*3+0]-xyz_list[3*3+0]);
+		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[3*3+1]+s1*(xyz_list[5*3+1]-xyz_list[3*3+1]);
+		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[3*3+2]+s1*(xyz_list[5*3+2]-xyz_list[3*3+2]);
+
+		/*New point 4*/
+		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[3*3+0]+s2*(xyz_list[4*3+0]-xyz_list[3*3+0]);
+		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[3*3+1]+s2*(xyz_list[4*3+1]-xyz_list[3*3+1]);
+		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[3*3+2]+s2*(xyz_list[4*3+2]-xyz_list[3*3+2]);
+	}
+	else if(levelset[0]*levelset[2]>0.){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+		/*Portion of the segments*/
+		s1=levelset[1]/(levelset[1]-levelset[0]);
+		s2=levelset[1]/(levelset[1]-levelset[2]);
+
+		if(levelset[1]<0.) normal_orientation=1;
+		/*New point 0*/
+		xyz_zero[3*normal_orientation+0]=xyz_list[1*3+0]+s1*(xyz_list[0*3+0]-xyz_list[1*3+0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[1*3+1]+s1*(xyz_list[0*3+1]-xyz_list[1*3+1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[1*3+2]+s1*(xyz_list[0*3+2]-xyz_list[1*3+2]);
+
+		/*New point 2*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[1*3+0]+s2*(xyz_list[2*3+0]-xyz_list[1*3+0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[1*3+1]+s2*(xyz_list[2*3+1]-xyz_list[1*3+1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[1*3+2]+s2*(xyz_list[2*3+2]-xyz_list[1*3+2]);
+
+		/*New point 3*/
+		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[4*3+0]+s1*(xyz_list[3*3+0]-xyz_list[4*3+0]);
+		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[4*3+1]+s1*(xyz_list[3*3+1]-xyz_list[4*3+1]);
+		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[4*3+2]+s1*(xyz_list[3*3+2]-xyz_list[4*3+2]);
+
+		/*New point 4*/
+		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[4*3+0]+s2*(xyz_list[5*3+0]-xyz_list[4*3+0]);
+		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[4*3+1]+s2*(xyz_list[5*3+1]-xyz_list[4*3+1]);
+		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[4*3+2]+s2*(xyz_list[5*3+2]-xyz_list[4*3+2]);
+	}
+	else if(levelset[0]==0. && levelset[1]==0.){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[0*3+0];
+		xyz_zero[3*0+1]=xyz_list[0*3+1];
+		xyz_zero[3*0+2]=xyz_list[0*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[1*3+0];
+		xyz_zero[3*1+1]=xyz_list[1*3+1];
+		xyz_zero[3*1+2]=xyz_list[1*3+2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[4*3+0];
+		xyz_zero[3*2+1]=xyz_list[4*3+1];
+		xyz_zero[3*2+2]=xyz_list[4*3+2];
+
+		/*New point 4*/
+		xyz_zero[3*3+0]=xyz_list[3*3+0];
+		xyz_zero[3*3+1]=xyz_list[3*3+1];
+		xyz_zero[3*3+2]=xyz_list[3*3+2];
+	}
+	else if(levelset[0]==0. && levelset[2]==0.){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[2*3+0];
+		xyz_zero[3*0+1]=xyz_list[2*3+1];
+		xyz_zero[3*0+2]=xyz_list[2*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[0*3+0];
+		xyz_zero[3*1+1]=xyz_list[0*3+1];
+		xyz_zero[3*1+2]=xyz_list[0*3+2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[3*3+0];
+		xyz_zero[3*2+1]=xyz_list[3*3+1];
+		xyz_zero[3*2+2]=xyz_list[3*3+2];
+
+		/*New point 4*/
+		xyz_zero[3*3+0]=xyz_list[5*3+0];
+		xyz_zero[3*3+1]=xyz_list[5*3+1];
+		xyz_zero[3*3+2]=xyz_list[5*3+2];
+	}
+	else if(levelset[1]==0. && levelset[2]==0.){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[1*3+0];
+		xyz_zero[3*0+1]=xyz_list[1*3+1];
+		xyz_zero[3*0+2]=xyz_list[1*3+2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[2*3+0];
+		xyz_zero[3*1+1]=xyz_list[2*3+1];
+		xyz_zero[3*1+2]=xyz_list[2*3+2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[5*3+0];
+		xyz_zero[3*2+1]=xyz_list[5*3+1];
+		xyz_zero[3*2+2]=xyz_list[5*3+2];
+
+		/*New point 4*/
+		xyz_zero[3*3+0]=xyz_list[4*3+0];
+		xyz_zero[3*3+1]=xyz_list[4*3+1];
+		xyz_zero[3*3+2]=xyz_list[4*3+2];
+	}
+	else _error_("Case not covered");
+
+	/*Assign output pointer*/
+	*pxyz_zero= xyz_zero;
 }
 /*}}}*/
@@ -2763,179 +3514,4 @@
 /*}}}*/
 #endif
-
-void       Penta::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){/*{{{*/
-
-	int    vertexpidlist[NUMVERTICES];
-	IssmDouble grad_list[NUMVERTICES];
-	Input* grad_input=NULL;
-	Input* input=NULL;
-
-	if(enum_type==MaterialsRheologyBbarEnum){
-		input=(Input*)inputs->GetInput(MaterialsRheologyBEnum);
-	}
-	else if(enum_type==DamageDbarEnum){
-		input=(Input*)inputs->GetInput(DamageDEnum);
-	}
-	else{
-		input=inputs->GetInput(enum_type);
-	}
-	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
-	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
-
-	GradientIndexing(&vertexpidlist[0],control_index);
-	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
-	grad_input=new PentaInput(GradientEnum,grad_list,P1Enum);
-	((ControlInput*)input)->SetGradient(grad_input);
-
-}/*}}}*/
-void       Penta::ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){/*{{{*/
-
-	Input* input=NULL;
-
-	if(control_enum==MaterialsRheologyBbarEnum){
-		input=(Input*)inputs->GetInput(MaterialsRheologyBEnum);
-	}
-	else if(control_enum==DamageDbarEnum){
-		input=(Input*)inputs->GetInput(DamageDEnum);
-	}
-	else{
-		input=inputs->GetInput(control_enum);
-	}
-	if (!input) _error_("Input " << EnumToStringx(control_enum) << " not found");
-	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(control_enum) << " is not a ControlInput");
-
-	int         sidlist[NUMVERTICES];
-	int         connectivity[NUMVERTICES];
-	IssmPDouble values[NUMVERTICES];
-	IssmPDouble gradients[NUMVERTICES]; 
-	IssmDouble  value,gradient;
-
-	this->GetVerticesConnectivityList(&connectivity[0]);
-	this->GetVerticesSidList(&sidlist[0]);
-
-	GaussPenta* gauss=new GaussPenta();
-	for (int iv=0;iv<NUMVERTICES;iv++){
-		gauss->GaussVertex(iv);
-
-		((ControlInput*)input)->GetInputValue(&value,gauss);
-		((ControlInput*)input)->GetGradientValue(&gradient,gauss);
-
-		values[iv]    = reCast<IssmPDouble>(value)/reCast<IssmPDouble>(connectivity[iv]);
-		gradients[iv] = reCast<IssmPDouble>(gradient)/reCast<IssmPDouble>(connectivity[iv]);
-	}
-	delete gauss;
-
-	vector_control->SetValues(NUMVERTICES,&sidlist[0],&values[0],ADD_VAL);
-	vector_gradient->SetValues(NUMVERTICES,&sidlist[0],&gradients[0],ADD_VAL);
-
-}/*}}}*/
-void       Penta::InputControlUpdate(IssmDouble scalar,bool save_parameter){/*{{{*/
-
-	/*Intermediary*/
-	int    num_controls;
-	int*   control_type=NULL;
-	Input* input=NULL;
-
-	/*retrieve some parameters: */
-	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
-
-	for(int i=0;i<num_controls;i++){
-
-		if(control_type[i]==MaterialsRheologyBbarEnum){
-			if (!IsOnBase()) goto cleanup_and_return;
-			input=(Input*)this->inputs->GetInput(MaterialsRheologyBEnum); _assert_(input);
-		}
-		else if(control_type[i]==DamageDbarEnum){
-			if (!IsOnBase()) goto cleanup_and_return;
-			input=(Input*)this->inputs->GetInput(DamageDEnum); _assert_(input);
-		}
-		else{
-			input=(Input*)this->inputs->GetInput(control_type[i]); _assert_(input);
-		}
-		if(input->ObjectEnum()!=ControlInputEnum) _error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
-
-		((ControlInput*)input)->UpdateValue(scalar);
-		((ControlInput*)input)->Constrain();
-		if (save_parameter) ((ControlInput*)input)->SaveValue();
-
-		if(control_type[i]==MaterialsRheologyBbarEnum){
-			this->InputExtrude(MaterialsRheologyBEnum);
-		}
-		else if(control_type[i]==DamageDbarEnum){
-			this->InputExtrude(DamageDEnum);
-		}
-	}
-
-	/*Clean up and return*/
-cleanup_and_return:
-	xDelete<int>(control_type);
-}
-/*}}}*/
-void       Penta::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){/*{{{*/
-
-	int vertexpidlist[NUMVERTICES];
-
-	/*Get out if this is not an element input*/
-	if(!IsInput(control_enum)) return;
-
-	/*Prepare index list*/
-	GradientIndexing(&vertexpidlist[0],control_index);
-
-	/*Get input (either in element or material)*/
-	if(control_enum==MaterialsRheologyBbarEnum) control_enum=MaterialsRheologyBEnum;
-	Input* input=inputs->GetInput(control_enum);
-	if(!input) _error_("Input " << EnumToStringx(control_enum) << " not found in element");
-
-	/*Check that it is a ControlInput*/
-	if (input->ObjectEnum()!=ControlInputEnum){
-		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
-	}
-
-	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexpidlist[0],data);
-}
-/*}}}*/
-void       Penta::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){/*{{{*/
-
-	IssmDouble  values[NUMVERTICES];
-	int         vertexpidlist[NUMVERTICES],control_init;
-
-	/*Specific case for depth averaged quantities*/
-	control_init=control_enum;
-	if(control_enum==MaterialsRheologyBbarEnum){
-		control_enum=MaterialsRheologyBEnum;
-		if(!IsOnBase()) return;
-	}
-	if(control_enum==DamageDbarEnum){
-		control_enum=DamageDEnum;
-		if(!IsOnBase()) return;
-	}
-
-	/*Get out if this is not an element input*/
-	if(!IsInput(control_enum)) return;
-
-	/*Prepare index list*/
-	GradientIndexing(&vertexpidlist[0],control_index);
-
-	/*Get values on vertices*/
-	for(int i=0;i<NUMVERTICES;i++){
-		values[i]=vector[vertexpidlist[i]];
-	}
-	Input* new_input = new PentaInput(control_enum,values,P1Enum);
-	Input* input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
-	if(input->ObjectEnum()!=ControlInputEnum){
-		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
-	}
-
-	((ControlInput*)input)->SetInput(new_input);
-
-	if(control_init==MaterialsRheologyBbarEnum){
-		this->InputExtrude(control_enum);
-	}
-	if(control_init==DamageDbarEnum){
-		this->InputExtrude(control_enum);
-	}
-}
-/*}}}*/
 
 #ifdef _HAVE_DAKOTA_
@@ -2982,6 +3558,6 @@
 						/*hydrostatic equilibrium: */
 						IssmDouble rho_ice,rho_water,di;
-						rho_ice=this->matpar->GetRhoIce();
-						rho_water=this->matpar->GetRhoWater();
+						rho_ice=this->matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+						rho_water=this->matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
 
 						di=rho_ice/rho_water;
@@ -3079,152 +3655,2 @@
 /*}}}*/
 #endif
-void       Penta::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){/*{{{*/
-
-	const int    numdof=NDOF1*NUMVERTICES;
-
-	int          i;
-	int*         doflist=NULL;
-	IssmDouble   values[numdof];
-	IssmDouble   enum_value;
-	GaussPenta   *gauss=NULL;
-
-	/*Get dof list: */
-	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);
-
-	gauss=new GaussPenta();
-	for(i=0;i<NUMVERTICES;i++){
-		/*Recover temperature*/
-		gauss->GaussVertex(i);
-		enum_input->GetInputValue(&enum_value,gauss);
-		values[i]=enum_value;
-	}
-
-	/*Add value to global vector*/
-	solution->SetValues(numdof,doflist,values,INS_VAL);
-
-	/*Free ressources:*/
-	delete gauss;
-	xDelete<int>(doflist);
-}
-/*}}}*/
-void       Penta::MigrateGroundingLine(IssmDouble* phi_ungrounding){/*{{{*/
-
-	int        i,migration_style;
-	IssmDouble bed_hydro,yts;
-	IssmDouble rho_water,rho_ice,density;
-	IssmDouble h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],r[NUMVERTICES];
-	IssmDouble melting[NUMVERTICES],phi[NUMVERTICES];
-
-	if(!IsOnBase()) return;
-
-	/*Recover info at the vertices: */
-	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
-	parameters->FindParam(&yts,ConstantsYtsEnum);
-	GetInputListOnVertices(&h[0],ThicknessEnum);
-	GetInputListOnVertices(&s[0],SurfaceEnum);
-	GetInputListOnVertices(&b[0],BaseEnum);
-	GetInputListOnVertices(&r[0],BedEnum);
-	GetInputListOnVertices(&phi[0],MaskGroundediceLevelsetEnum);
-	rho_water   = matpar->GetRhoWater();
-	rho_ice     = matpar->GetRhoIce();
-	density     = rho_ice/rho_water;
-
-	/*go through vertices, and update inputs, considering them to be PentaVertex type: */
-	for(i=0;i<NUMVERTICES;i++){
-		/*Ice shelf: if bed below bathymetry, impose it at the bathymetry and update surface, elso do nothing */
-		if(phi[i]<=0){
-			if(b[i]<=r[i]){ 
-				b[i]        = r[i];
-				s[i]        = b[i]+h[i];
-			}
-		}
-		/*Ice sheet: if hydrostatic bed above bathymetry, ice sheet starts to unground, elso do nothing */
-		/*Change only if AggressiveMigration or if the ice sheet is in contact with the ocean*/
-		else{
-			bed_hydro=-density*h[i];
-			if(bed_hydro>r[i]){
-				/*Unground only if the element is connected to the ice shelf*/
-				if(migration_style==AggressiveMigrationEnum || migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
-					s[i]        = (1-density)*h[i];
-					b[i]        = -density*h[i];
-				}
-				else if(migration_style==SoftMigrationEnum && phi_ungrounding[vertices[i]->Pid()]<0.){
-					s[i]        = (1-density)*h[i];
-					b[i]        = -density*h[i];
-				}
-				else{
-					if(migration_style!=SoftMigrationEnum) _error_("Error: migration should be Aggressive, Soft or Subelement");
-				}
-			}
-		}
-	}
-
-	/*Recalculate phi*/
-	for(i=0;i<NUMVERTICES;i++){
-		if(migration_style==SoftMigrationEnum){
-			bed_hydro=-density*h[i];
-			if(phi[i]<0. || bed_hydro<=r[i] || phi_ungrounding[vertices[i]->Pid()]<0.){
-				phi[i]=h[i]+r[i]/density;
-			}
-		}
-		else phi[i]=h[i]+r[i]/density;
-	}
-	this->inputs->AddInput(new PentaInput(MaskGroundediceLevelsetEnum,&phi[0],P1Enum));
-	this->InputExtrude(MaskGroundediceLevelsetEnum);
-
-	/*Update inputs*/
-	this->inputs->AddInput(new PentaInput(SurfaceEnum,&s[0],P1Enum));
-	this->inputs->AddInput(new PentaInput(BaseEnum,&b[0],P1Enum));
-
-	/*Extrude inputs*/
-	this->InputExtrude(SurfaceEnum);
-	this->InputExtrude(BaseEnum);
-}
-/*}}}*/
-void       Penta::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){/*{{{*/
-
-	IssmDouble  h[NUMVERTICES],r[NUMVERTICES],gl[NUMVERTICES];
-	IssmDouble  bed_hydro;
-	IssmDouble  rho_water,rho_ice,density;
-
-	/*material parameters: */
-	rho_water=matpar->GetRhoWater();
-	rho_ice=matpar->GetRhoIce();
-	density=rho_ice/rho_water;
-	GetInputListOnVertices(&h[0],ThicknessEnum);
-	GetInputListOnVertices(&r[0],BedEnum);
-	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
-
-	/*go through vertices, and figure out which ones are on the ice sheet, and want to unground: */
-	for(int i=0;i<NUMVERTICES;i++){
-		/*Find if grounded vertices want to start floating*/
-		if (gl[i]>0.){
-			bed_hydro=-density*h[i];
-			if(bed_hydro>r[i]){
-				/*Vertex that could potentially unground, flag it*/
-				potential_ungrounding->SetValue(vertices[i]->Pid(),1,INS_VAL);
-			}
-		}
-	}
-}
-/*}}}*/
-int        Penta::UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){/*{{{*/
-
-	int i;
-	int nflipped=0;
-
-	/*Go through nodes, and whoever is on the potential_ungrounding, ends up in nodes_on_iceshelf: */
-	for(i=0;i<NUMVERTICES;i++){
-		if (reCast<bool,IssmDouble>(vertices_potentially_ungrounding[vertices[i]->Pid()])){
-			vec_nodes_on_iceshelf->SetValue(vertices[i]->Pid(),-1.,INS_VAL);
-
-			/*If node was not on ice shelf, we flipped*/
-			if(nodes_on_iceshelf[vertices[i]->Pid()]>=0.){
-				nflipped++;
-			}
-		}
-	}
-	return nflipped;
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/Penta.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Penta.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/Penta.h	(revision 19105)
@@ -43,116 +43,76 @@
 		int     ObjectEnum();
 		/*}}}*/
-		/*Update virtual functions definitions: {{{*/
-		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		#ifdef _HAVE_DAKOTA_
-		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type);
-		#endif
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
-		/*}}}*/
-		/*Element virtual functions definitions: {{{*/
-		IssmDouble CharacteristicLength(void){_error_("not implemented yet");};
-		void   ComputeBasalStress(Vector<IssmDouble>* sigma_b);
-		void   ComputeSigmaNN(){_error_("not implemented yet");};
-		void   ComputeStressTensor();
-		void   ComputeDeviatoricStressTensor();
-		void   Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
-		void   ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
-		int    FiniteElement(void);
-		void   FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating);
-		void   SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
-		void   ResetHooks();
-		void   Delta18oParameterization(void);
-		Penta* GetUpperPenta(void);
-		Penta* GetLowerPenta(void);
-		Penta* GetSurfacePenta(void);
-		Penta* GetBasalPenta(void);
-		Element* GetUpperElement(void);
-		Element* GetBasalElement(void);
-		void   GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating);
-		IssmDouble GetGroundedPortion(IssmDouble* xyz_list);
-		int    GetNodeIndex(Node* node);
-		int    GetNumberOfNodes(void);
-		int    GetNumberOfNodes(int enum_type);
-		int    GetNumberOfVertices(void);
-		void   GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type);
-		void   GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
-		void   GetVerticesCoordinatesTop(IssmDouble** pxyz_list);
-
-		void   InputDepthAverageAtBase(int enum_type,int average_enum_type);
-		void   InputScale(int enum_type,IssmDouble scale_factor);
-		int    NumberofNodesVelocity(void);
-		int    NumberofNodesPressure(void);
-		int    VelocityInterpolation();
-		int    PressureInterpolation();
-		int    TensorInterpolation(){_error_("not implemented yet");};
-		bool   IsZeroLevelset(int levelset_enum);
-		bool   IsIcefront(void);
-		bool   IsFaceOnBoundary(void){_error_("not implemented yet");};
-		void   ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum);
-		void   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){_error_("not implemented yet");};
-		void   GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level){_error_("not implemented yet");};
-		void   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm);
-		void   ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
-		void   ResetFSBasalBoundaryCondition(void);
-		void   SetTemporaryElementType(int element_type_in);
-	   Element* SpawnBasalElement(void);
-		Element* SpawnTopElement(void);
-		IssmDouble SurfaceArea(void);
-		void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
-		int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum);
-		IssmDouble TimeAdapt();
-		void   ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
-		void   ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss);
-		int    VertexConnectivity(int vertexindex);
-		void   VerticalSegmentIndices(int** pindices,int* pnumseg);
-		void   ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
-
-		void   AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
-		IssmDouble IceVolume(void);
-		IssmDouble IceVolumeAboveFloatation(void);
-		IssmDouble TotalSmb(void);
-		IssmDouble MassFlux(IssmDouble* segment);
-		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id);
-		void   ElementResponse(IssmDouble* presponse,int response_enum);
-
-		#ifdef _HAVE_GIA_
-		void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y);
-		#endif
-
-		void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data);
-		void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
-		void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
-		void   ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
-		void   InputControlUpdate(IssmDouble scalar,bool save_parameter);
-		IssmDouble Misfit(int modelenum,int observationenum,int weightsenum){_error_("not implemented yet");};
-		IssmDouble MisfitArea(int weightsenum){_error_("not implemented yet");};
-
-		void   MigrateGroundingLine(IssmDouble* sheet_ungrounding);
-		void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding);
-		int    UpdatePotentialUngrounding(IssmDouble* potential_sheet_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
-		/*}}}*/
-		/*Penta specific routines:{{{*/
+		/*Penta routines:{{{*/
 		void           AddBasalInput(int input_enum, IssmDouble* values, int interpolation_enum);
 		void           AddInput(int input_enum, IssmDouble* values, int interpolation_enum);
-		void	         NormalBase(IssmDouble* bed_normal, IssmDouble* xyz_list);
-		void           NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
-		void	         NormalTop(IssmDouble* bed_normal, IssmDouble* xyz_list);
+		void           AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
+		IssmDouble     CharacteristicLength(void){_error_("not implemented yet");};
+		void           CalvingRateLevermann();
+		void           CalvingRatePi();
+		void           ComputeBasalStress(Vector<IssmDouble>* sigma_b);
+		void           ComputeDeviatoricStressTensor();
+		void           ComputeSigmaNN(){_error_("not implemented yet");};
+		void           ComputeStressTensor();
+		void           Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void           ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
+		void           ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
 		ElementMatrix* CreateBasalMassMatrix(void);
+		void           Delta18oParameterization(void);
+		void           MungsmtpParameterization(void);
+		void           ElementResponse(IssmDouble* presponse,int response_enum);
+		void           ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
+		int            FiniteElement(void);
+		void           FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating);
 		void           GetAreaCoordinates(IssmDouble *area_coordinates,IssmDouble* xyz_zero,IssmDouble* xyz_list,int numpoints);
+		Element*       GetBasalElement(void);
+		Penta*         GetBasalPenta(void);
 		int            GetElementType(void);
+		void           GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating);
+		IssmDouble     GetGroundedPortion(IssmDouble* xyz_list);
+		void           GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum);
 		void           GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
+		void           GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level){_error_("not implemented yet");};
+		void           GetLevelsetPositivePart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlynegative,IssmDouble* levelsetvalues){_error_("not implemented yet");};
 		Node*          GetNode(int node_number);
-		void	         InputExtrude(int enum_type);
+		int            GetNodeIndex(Node* node);
+		int            GetNumberOfNodes(void);
+		int            GetNumberOfNodes(int enum_type);
+		int            GetNumberOfVertices(void);
+		Penta*         GetLowerPenta(void);
+		void           GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type);
+		Penta*         GetSurfacePenta(void);
+		Element*       GetUpperElement(void);
+		Penta*         GetUpperPenta(void);
+		void           GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,bool onsid);
+		void           GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
+		void           GetVerticesCoordinatesTop(IssmDouble** pxyz_list);
+		IssmDouble     IceMass(void);
+		IssmDouble     IceVolume(void);
+		IssmDouble     IceVolumeAboveFloatation(void);
+		void           InputControlUpdate(IssmDouble scalar,bool save_parameter);
+		void           InputDepthAverageAtBase(int enum_type,int average_enum_type);
+		void	         InputExtrude(int enum_type,int start);
+		void           InputScale(int enum_type,IssmDouble scale_factor);
+		void           InputUpdateFromIoModel(int index, IoModel* iomodel);
 		void           InputUpdateFromSolutionOneDof(IssmDouble* solutiong,int enum_type);
 		void           InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solutiong,int enum_type);
+		void           InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		bool           IsFaceOnBoundary(void){_error_("not implemented yet");};
+		bool           IsIcefront(void);
+		bool           IsNodeOnShelfFromFlags(IssmDouble* flags);
+		bool	         IsOnBase(void);
 		bool	         IsOnSurface(void);
-		bool	         IsOnBase(void);
-		bool           IsNodeOnShelfFromFlags(IssmDouble* flags);
+		bool           IsZeroLevelset(int levelset_enum);
 		void           JacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void           JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
 		void           JacobianDeterminantLine(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss);
 		void           JacobianDeterminantSurface(IssmDouble*  pJdet, IssmDouble* xyz_list,Gauss* gauss);
-		void           JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
 		void           JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
+		IssmDouble     Masscon(IssmDouble* levelset){_error_("not implemented yet");};
+		IssmDouble     MassFlux(IssmDouble* segment);
+		IssmDouble     MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id);
+		IssmDouble     MinEdgeLength(IssmDouble* xyz_list);
+		IssmDouble     Misfit(int modelenum,int observationenum,int weightsenum){_error_("not implemented yet");};
+		IssmDouble     MisfitArea(int weightsenum){_error_("not implemented yet");};
 		Gauss*         NewGauss(void);
 		Gauss*         NewGauss(int order);
@@ -164,20 +124,60 @@
 		Gauss*         NewGaussTop(int order);
 		void           NodalFunctions(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss);
 		void           NodalFunctionsP1(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
 		void           NodalFunctionsP2(IssmDouble* basis,Gauss* gauss);
-		void           NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
-		void           NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
-		void           NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
-		void           NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss);
 		void           NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss);
-		void           NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss);
-		void           NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss);
-		IssmDouble     MinEdgeLength(IssmDouble* xyz_list);
+		void	         NormalBase(IssmDouble* bed_normal, IssmDouble* xyz_list);
+		void           NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
+		void	         NormalTop(IssmDouble* bed_normal, IssmDouble* xyz_list);
+		int            NodalValue(IssmDouble* pvalue, int index, int natureofdataenum);
+		int            NumberofNodesPressure(void);
+		int            NumberofNodesVelocity(void);
+		void           PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm);
+		void           PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding);
+		int            PressureInterpolation();
+		void           ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
+		void           ResetFSBasalBoundaryCondition(void);
+		void           ResetHooks();
 		void	         SetClone(int* minranks);
+		void           SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
+		void           SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
+		void           SetTemporaryElementType(int element_type_in);
+	   Element*       SpawnBasalElement(void);
+		Element*       SpawnTopElement(void);
 		Tria*	         SpawnTria(int index1,int index2,int index3);
 		IssmDouble     StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa);
-
+		void           StressIntensityFactor();
+		void           StrainRateparallel();
+		void           StrainRateperpendicular();
+		IssmDouble     SurfaceArea(void);
+		int            TensorInterpolation(){_error_("not implemented yet");};
+		IssmDouble     TimeAdapt();
+		IssmDouble     TotalSmb(void);
+		void           Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
 		void           UpdateConstraintsExtrudeFromBase(void);
 		void           UpdateConstraintsExtrudeFromTop(void);
+		int            UpdatePotentialUngrounding(IssmDouble* potential_sheet_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
+		void           ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss);
+		void           ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
+		int            VelocityInterpolation();
+		int            VertexConnectivity(int vertexindex);
+		void           VerticalSegmentIndices(int** pindices,int* pnumseg);
+		void           ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
+		void           ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum);
+
+		#ifdef _HAVE_DAKOTA_
+		void           InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
+		void           InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type);
+		#endif
+
+		#ifdef _HAVE_GIA_
+		void           GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y);
+		#endif
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Elements/PentaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 19105)
@@ -1,3 +1,3 @@
-/*!\file PentaRef.c
+/*!\file PentaRef.cpp
  * \brief: implementation of the PentaRef object
  */
@@ -26,4 +26,5 @@
 #define NUMNODESP2b   19
 #define NUMNODESP2xP4 30
+#define NUMNODESMAX   30
 
 /*Object constructors and destructor*/
@@ -36,4 +37,148 @@
 
 /*Reference Element numerics*/
+void PentaRef::BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement){/*{{{*/
+
+	/*Output*/
+	int  numindices;
+	int* indices = NULL;
+
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			break;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			break;
+		case P2xP1Enum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			indices[3] = 6;
+			indices[4] = 7;
+			indices[5] = 8;
+			break;
+		case P1xP2Enum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			break;
+		case P1xP3Enum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			break;
+		case P2Enum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			indices[3] = 9;
+			indices[4] = 10;
+			indices[5] = 11;
+			break;
+		case P2bubbleEnum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			indices[3] = 9;
+			indices[4] = 10;
+			indices[5] = 11;
+			break;
+		case P2xP4Enum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			indices[3] = 9;
+			indices[4] = 10;
+			indices[5] = 11;
+			break;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+	/*Assign output pointer*/
+	*pnumindices = numindices;
+	*pindices    = indices;
+}
+/*}}}*/
+void PentaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
+	/*From node values of parameter p (p_list[0], p_list[1], p_list[2],
+	 * p_list[3], p_list[4] and p_list[4]), return parameter derivative value at
+	 * gaussian point specified by gauss_coord:
+	 *   dp/dx=p_list[0]*dh1/dx+p_list[1]*dh2/dx+p_list[2]*dh3/dx+p_list[3]*dh4/dx+p_list[4]*dh5/dx+p_list[5]*dh6/dx;
+	 *   dp/dy=p_list[0]*dh1/dy+p_list[1]*dh2/dy+p_list[2]*dh3/dy+p_list[3]*dh4/dy+p_list[4]*dh5/dy+p_list[5]*dh6/dy;
+	 *   dp/dz=p_list[0]*dh1/dz+p_list[1]*dh2/dz+p_list[2]*dh3/dz+p_list[3]*dh4/dz+p_list[4]*dh5/dz+p_list[5]*dh6/dz;
+	 *
+	 *   p is a vector of size 3x1 already allocated.
+	 *
+	 * WARNING: For a significant gain in performance, it is better to use
+	 * static memory allocation instead of dynamic.
+	 */
+
+	/*Allocate derivatives of basis functions*/
+	IssmDouble  dbasis[3*NUMNODESMAX];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+	_assert_(numnodes<=NUMNODESMAX);
+
+	/*Get basis functions derivatives at this point*/
+	GetNodalFunctionsDerivatives(&dbasis[0],xyz_list,gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	IssmDouble dpx=0.;
+	IssmDouble dpy=0.;
+	IssmDouble dpz=0.;
+	for(int i=0;i<numnodes;i++) dpx += dbasis[0*numnodes+i]*plist[i];
+	for(int i=0;i<numnodes;i++) dpy += dbasis[1*numnodes+i]*plist[i];
+	for(int i=0;i<numnodes;i++) dpz += dbasis[2*numnodes+i]*plist[i];
+
+	/*Assign values*/
+	p[0]=dpx;
+	p[1]=dpy;
+	p[2]=dpz;
+}
+/*}}}*/
+void PentaRef::GetInputValue(IssmDouble* pvalue,IssmDouble* plist,Gauss* gauss,int finiteelement){/*{{{*/
+	/* WARNING: For a significant gain in performance, it is better to use
+	 * static memory allocation instead of dynamic.*/
+
+	/*Allocate basis functions*/
+	IssmDouble  basis[NUMNODESMAX];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+	_assert_(numnodes<=NUMNODESMAX);
+
+	/*Get basis functions at this point*/
+	GetNodalFunctions(&basis[0],gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	IssmDouble value =0.;
+	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
+
+	/*Assign output pointer*/
+	*pvalue = value;
+}
+/*}}}*/
 void PentaRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,Gauss* gauss_in){/*{{{*/
 	/*The Jacobian is constant over the element, discard the gaussian points. 
@@ -48,5 +193,5 @@
 	/*Cast gauss to GaussPenta*/
 	_assert_(gauss_in->Enum()==GaussPentaEnum);
-	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+	GaussPenta* gauss = xDynamicCast<GaussPenta*>(gauss_in);
 
 	/*Figure out xi,eta and zi (parametric coordinates), for this gaussian point: */
@@ -106,39 +251,4 @@
 }
 /*}}}*/
-void PentaRef::GetTriaJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
-	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
-
-	IssmDouble x1=xyz_list[3*0+0];
-	IssmDouble y1=xyz_list[3*0+1];
-	IssmDouble z1=xyz_list[3*0+2];
-	IssmDouble x2=xyz_list[3*1+0];
-	IssmDouble y2=xyz_list[3*1+1];
-	IssmDouble z2=xyz_list[3*1+2];
-	IssmDouble x3=xyz_list[3*2+0];
-	IssmDouble y3=xyz_list[3*2+1];
-	IssmDouble z3=xyz_list[3*2+2];
-
-	/*Jdet = norm( AB ^ AC ) / (2 * area of the reference triangle), with areaRef=sqrt(3) */
-	*Jdet=SQRT3/6.*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2),0.5);
-	if(*Jdet<0) _error_("negative jacobian determinant!");
-}
-/*}}}*/
-void PentaRef::GetSegmentJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
-	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
-
-	IssmDouble x1=xyz_list[3*0+0];
-	IssmDouble y1=xyz_list[3*0+1];
-	IssmDouble z1=xyz_list[3*0+2];
-	IssmDouble x2=xyz_list[3*1+0];
-	IssmDouble y2=xyz_list[3*1+1];
-	IssmDouble z2=xyz_list[3*1+2];
-
-	*Jdet=.5*sqrt(pow(x2-x1,2) + pow(y2-y1,2) + pow(z2-z1,2));
-	if(*Jdet<0) _error_("negative jacobian determinant!");
-
-}
-/*}}}*/
 void PentaRef::GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 
@@ -160,5 +270,5 @@
 	/*Cast gauss to GaussPenta*/
 	_assert_(gauss_in->Enum()==GaussPentaEnum);
-	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+	GaussPenta* gauss = xDynamicCast<GaussPenta*>(gauss_in);
 
 	/*Get current coordinates in reference element*/
@@ -365,5 +475,5 @@
 	/*Cast gauss to GaussPenta*/
 	_assert_(gauss_in->Enum()==GaussPentaEnum);
-	GaussPenta* gauss = dynamic_cast<GaussPenta*>(gauss_in);
+	GaussPenta* gauss = xDynamicCast<GaussPenta*>(gauss_in);
 
 	/*Get current coordinates in reference element*/
@@ -885,59 +995,37 @@
 }
 /*}}}*/
-void PentaRef::GetInputValue(IssmDouble* pvalue,IssmDouble* plist,Gauss* gauss,int finiteelement){/*{{{*/
-
-	/*Output*/
-	IssmDouble value =0.;
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes(finiteelement);
-
-	/*Get nodal functions*/
-	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	GetNodalFunctions(basis, gauss,finiteelement);
-
-	/*Calculate parameter for this Gauss point*/
-	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
-
-	/*Assign output pointer*/
-	xDelete<IssmDouble>(basis);
-	*pvalue = value;
-
-}
-/*}}}*/
-void PentaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
-	/*From node values of parameter p (p_list[0], p_list[1], p_list[2],
-	 * p_list[3], p_list[4] and p_list[4]), return parameter derivative value at
-	 * gaussian point specified by gauss_coord:
-	 *   dp/dx=p_list[0]*dh1/dx+p_list[1]*dh2/dx+p_list[2]*dh3/dx+p_list[3]*dh4/dx+p_list[4]*dh5/dx+p_list[5]*dh6/dx;
-	 *   dp/dy=p_list[0]*dh1/dy+p_list[1]*dh2/dy+p_list[2]*dh3/dy+p_list[3]*dh4/dy+p_list[4]*dh5/dy+p_list[5]*dh6/dy;
-	 *   dp/dz=p_list[0]*dh1/dz+p_list[1]*dh2/dz+p_list[2]*dh3/dz+p_list[3]*dh4/dz+p_list[4]*dh5/dz+p_list[5]*dh6/dz;
-	 *
-	 *   p is a vector of size 3x1 already allocated.
-	 */
-
-	/*Output*/
-	IssmDouble dpx=0.;
-	IssmDouble dpy=0.;
-	IssmDouble dpz=0.;
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes(finiteelement);
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
-
-	/*Calculate parameter for this Gauss point*/
-	for(int i=0;i<numnodes;i++) dpx += dbasis[0*numnodes+i]*plist[i];
-	for(int i=0;i<numnodes;i++) dpy += dbasis[1*numnodes+i]*plist[i];
-	for(int i=0;i<numnodes;i++) dpz += dbasis[2*numnodes+i]*plist[i];
-
-	/*Assign values*/
-	xDelete<IssmDouble>(dbasis);
-	p[0]=dpx;
-	p[1]=dpy;
-	p[2]=dpz;
-
+void PentaRef::GetSegmentJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1=xyz_list[3*0+0];
+	IssmDouble y1=xyz_list[3*0+1];
+	IssmDouble z1=xyz_list[3*0+2];
+	IssmDouble x2=xyz_list[3*1+0];
+	IssmDouble y2=xyz_list[3*1+1];
+	IssmDouble z2=xyz_list[3*1+2];
+
+	*Jdet=.5*sqrt(pow(x2-x1,2) + pow(y2-y1,2) + pow(z2-z1,2));
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+void PentaRef::GetTriaJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1=xyz_list[3*0+0];
+	IssmDouble y1=xyz_list[3*0+1];
+	IssmDouble z1=xyz_list[3*0+2];
+	IssmDouble x2=xyz_list[3*1+0];
+	IssmDouble y2=xyz_list[3*1+1];
+	IssmDouble z2=xyz_list[3*1+2];
+	IssmDouble x3=xyz_list[3*2+0];
+	IssmDouble y3=xyz_list[3*2+1];
+	IssmDouble z3=xyz_list[3*2+2];
+
+	/*Jdet = norm( AB ^ AC ) / (2 * area of the reference triangle), with areaRef=sqrt(3) */
+	*Jdet=SQRT3/6.*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2),0.5);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
 }
 /*}}}*/
@@ -966,4 +1054,5 @@
 		case OneLayerP4zEnum:       return NUMNODESP2xP4+NUMNODESP1;
 		case CrouzeixRaviartEnum:   return NUMNODESP2b+NUMNODESP1;
+		case LACrouzeixRaviartEnum: return NUMNODESP2b;
 		default:       _error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
 	}
@@ -972,130 +1061,20 @@
 }
 /*}}}*/
-int  PentaRef::VelocityInterpolation(int fe_stokes){/*{{{*/
+int  PentaRef::PressureInterpolation(int fe_stokes){/*{{{*/
 
 	switch(fe_stokes){
-		case P1P1Enum:           return P1Enum;
-		case P1P1GLSEnum:        return P1Enum;
-		case MINIcondensedEnum:  return P1bubbleEnum;
-		case MINIEnum:           return P1bubbleEnum;
-		case TaylorHoodEnum:     return P2Enum;
-		case LATaylorHoodEnum:   return P2Enum;
-		case OneLayerP4zEnum:    return P2xP4Enum;
-		case CrouzeixRaviartEnum:return P2bubbleEnum;
+		case P1P1Enum:              return P1Enum;
+		case P1P1GLSEnum:           return P1Enum;
+		case MINIcondensedEnum:     return P1Enum;
+		case MINIEnum:              return P1Enum;
+		case TaylorHoodEnum:        return P1Enum;
+		case LATaylorHoodEnum:      return NoneEnum;
+		case OneLayerP4zEnum:       return P1Enum;
+		case CrouzeixRaviartEnum:   return P1DGEnum;
+		case LACrouzeixRaviartEnum: return NoneEnum;
 		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
 	}
 
 	return -1;
-}
-/*}}}*/
-int  PentaRef::PressureInterpolation(int fe_stokes){/*{{{*/
-
-	switch(fe_stokes){
-		case P1P1Enum:           return P1Enum;
-		case P1P1GLSEnum:        return P1Enum;
-		case MINIcondensedEnum:  return P1Enum;
-		case MINIEnum:           return P1Enum;
-		case TaylorHoodEnum:     return P1Enum;
-		case LATaylorHoodEnum:   return NoneEnum;
-		case OneLayerP4zEnum:    return P1Enum;
-		case CrouzeixRaviartEnum:return P1DGEnum;
-		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
-	}
-
-	return -1;
-}
-/*}}}*/
-int  PentaRef::TensorInterpolation(int fe_stokes){/*{{{*/
-
-	switch(fe_stokes){
-		case XTaylorHoodEnum:    return P1DGEnum;
-		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
-	}
-
-	return -1;
-}
-/*}}}*/
-void PentaRef::BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement){/*{{{*/
-
-	/*Output*/
-	int  numindices;
-	int* indices = NULL;
-
-	switch(finiteelement){
-		case P1Enum: case P1DGEnum:
-			numindices = 3;
-			indices    = xNew<int>(numindices);
-			indices[0] = 0;
-			indices[1] = 1;
-			indices[2] = 2;
-			break;
-		case P1bubbleEnum: case P1bubblecondensedEnum:
-			numindices = 3;
-			indices    = xNew<int>(numindices);
-			indices[0] = 0;
-			indices[1] = 1;
-			indices[2] = 2;
-			break;
-		case P2xP1Enum:
-			numindices = 6;
-			indices    = xNew<int>(numindices);
-			indices[0] = 0;
-			indices[1] = 1;
-			indices[2] = 2;
-			indices[3] = 6;
-			indices[4] = 7;
-			indices[5] = 8;
-			break;
-		case P1xP2Enum:
-			numindices = 3;
-			indices    = xNew<int>(numindices);
-			indices[0] = 0;
-			indices[1] = 1;
-			indices[2] = 2;
-			break;
-		case P1xP3Enum:
-			numindices = 3;
-			indices    = xNew<int>(numindices);
-			indices[0] = 0;
-			indices[1] = 1;
-			indices[2] = 2;
-			break;
-		case P2Enum:
-			numindices = 6;
-			indices    = xNew<int>(numindices);
-			indices[0] = 0;
-			indices[1] = 1;
-			indices[2] = 2;
-			indices[3] = 9;
-			indices[4] = 10;
-			indices[5] = 11;
-			break;
-		case P2bubbleEnum:
-			numindices = 6;
-			indices    = xNew<int>(numindices);
-			indices[0] = 0;
-			indices[1] = 1;
-			indices[2] = 2;
-			indices[3] = 9;
-			indices[4] = 10;
-			indices[5] = 11;
-			break;
-		case P2xP4Enum:
-			numindices = 6;
-			indices    = xNew<int>(numindices);
-			indices[0] = 0;
-			indices[1] = 1;
-			indices[2] = 2;
-			indices[3] = 9;
-			indices[4] = 10;
-			indices[5] = 11;
-			break;
-		default:
-			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
-	}
-
-	/*Assign output pointer*/
-	*pnumindices = numindices;
-	*pindices    = indices;
 }
 /*}}}*/
@@ -1157,2 +1136,30 @@
 }
 /*}}}*/
+int  PentaRef::TensorInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case XTaylorHoodEnum:    return P1DGEnum;
+		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+int  PentaRef::VelocityInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:              return P1Enum;
+		case P1P1GLSEnum:           return P1Enum;
+		case MINIcondensedEnum:     return P1bubbleEnum;
+		case MINIEnum:              return P1bubbleEnum;
+		case TaylorHoodEnum:        return P2Enum;
+		case LATaylorHoodEnum:      return P2Enum;
+		case OneLayerP4zEnum:       return P2xP4Enum;
+		case CrouzeixRaviartEnum:   return P2bubbleEnum;
+		case LACrouzeixRaviartEnum: return P2bubbleEnum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/PentaRef.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/PentaRef.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/PentaRef.h	(revision 19105)
@@ -15,23 +15,22 @@
 
 		/*Numerics*/
+		void BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement);
+		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
+		void GetInputValue(IssmDouble* pvalue,IssmDouble* plist, Gauss* gauss,int finiteelement);
+		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,Gauss* gauss);
+		void GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,Gauss* gauss);
+		void GetLprimeFSSSA(IssmDouble* LprimeFSSSA, IssmDouble* xyz_list, Gauss* gauss);
 		void GetNodalFunctions(IssmDouble* basis, Gauss* gauss,int finiteelement);
 		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss,int finiteelement);
 		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss,int finiteelement);
 		void GetQuadJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
-		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,Gauss* gauss);
-		void GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void GetSegmentJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
 		void GetTriaJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
-		void GetSegmentJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
-		void GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,Gauss* gauss);
-		void GetLprimeFSSSA(IssmDouble* LprimeFSSSA, IssmDouble* xyz_list, Gauss* gauss);
-		void GetInputValue(IssmDouble* pvalue,IssmDouble* plist, Gauss* gauss,int finiteelement);
-		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
-
-		void BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement);
+		int  NumberofNodes(int finiteelement);
+		int  PressureInterpolation(int fe_stokes);
 		void SurfaceNodeIndices(int* pnumindices,int** pindices,int finiteelement);
-		int  NumberofNodes(int finiteelement);
+		int  TensorInterpolation(int fe_stokes);
 		int  VelocityInterpolation(int fe_stokes);
-		int  PressureInterpolation(int fe_stokes);
-		int  TensorInterpolation(int fe_stokes);
 };
 #endif
Index: /issm/trunk/src/c/classes/Elements/Seg.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Seg.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/Seg.cpp	(revision 19105)
@@ -68,10 +68,4 @@
 }
 /*}}}*/
-int        Seg::ObjectEnum(void){/*{{{*/
-
-	return SegEnum;
-
-}
-/*}}}*/
 void       Seg::GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
 	
@@ -102,18 +96,4 @@
 	*pxyz_front=xyz_front;
 }/*}}}*/
-void       Seg::NodalFunctionsP1(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussSegEnum);
-	this->GetNodalFunctions(basis,(GaussSeg*)gauss,P1Enum);
-
-}
-/*}}}*/
-void       Seg::NodalFunctionsP2(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussSegEnum);
-	this->GetNodalFunctions(basis,(GaussSeg*)gauss,P2Enum);
-
-}
-/*}}}*/
 int        Seg::GetNumberOfNodes(void){/*{{{*/
 	return this->NumberofNodes(this->element_type);
@@ -205,4 +185,18 @@
 }
 /*}}}*/
+void       Seg::NodalFunctionsP1(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussSegEnum);
+	this->GetNodalFunctions(basis,(GaussSeg*)gauss,P1Enum);
+
+}
+/*}}}*/
+void       Seg::NodalFunctionsP2(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussSegEnum);
+	this->GetNodalFunctions(basis,(GaussSeg*)gauss,P2Enum);
+
+}
+/*}}}*/
 void       Seg::NormalSection(IssmDouble* normal,IssmDouble* xyz_list_front){/*{{{*/
 
@@ -218,2 +212,8 @@
 }
 /*}}}*/
+int        Seg::ObjectEnum(void){/*{{{*/
+
+	return SegEnum;
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/Seg.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Seg.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/Seg.h	(revision 19105)
@@ -39,75 +39,72 @@
 		Object *copy();
 		/*}}}*/
-		/*Update virtual functions resolution: {{{*/
-		void  InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int inputenum){_error_("not implemented yet");};
-		void  InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum){_error_("not implemented yet");};
-		void  InputUpdateFromVector(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
-#ifdef _HAVE_DAKOTA_
-		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
-		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type){_error_("not implemented yet");};
-#endif
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
-		/*}}}*/
 		/*Element virtual functions definitions: {{{*/
 		void        AddBasalInput(int input_enum, IssmDouble* values, int interpolation_enum){_error_("not implemented yet");};
 		void        AddInput(int input_enum, IssmDouble* values, int interpolation_enum){_error_("not implemented yet");};
+		void        AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){_error_("not implemented yet");};
+		void        CalvingRateLevermann(void){_error_("not implemented yet");};
 		IssmDouble  CharacteristicLength(void);
 		void        ComputeBasalStress(Vector<IssmDouble>* sigma_b){_error_("not implemented yet");};
+		void        ComputeDeviatoricStressTensor(){_error_("not implemented yet");};
 		void        ComputeSigmaNN(){_error_("not implemented yet");};
 		void        ComputeStressTensor(){_error_("not implemented yet");};
-		void        ComputeDeviatoricStressTensor(){_error_("not implemented yet");};
+		void        CalvingRatePi(void){_error_("not implemented yet");};
 		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters){_error_("not implemented yet");};
-		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters){_error_("not implemented yet");};
-		void        ResetHooks(){_error_("not implemented yet");};
+		void        ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){_error_("not implemented yet");};
+		void        ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){_error_("not implemented yet");};
 		void        Delta18oParameterization(void){_error_("not implemented yet");};
+		void        MungsmtpParameterization(void){_error_("not implemented yet");};
+		void        ElementResponse(IssmDouble* presponse,int response_enum){_error_("not implemented yet");};
 		void        ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){_error_("not implemented yet");};
 		void        FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating){_error_("not implemented yet");};
 		int         FiniteElement(void);
-		Element*    GetUpperElement(void){_error_("not implemented yet");};
 		Element*    GetBasalElement(void){_error_("not implemented yet");};
+		int         GetElementType(void){_error_("not implemented yet");};
+		void        GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating){_error_("not implemented yet");};
+		IssmDouble  GetGroundedPortion(IssmDouble* xyz_list){_error_("not implemented yet");};
+		void		   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum);
+		void        GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){_error_("not implemented yet");};
+		void		   GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level){_error_("not implemented");};
+		void        GetLevelsetPositivePart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlynegative,IssmDouble* levelsetvalues){_error_("not implemented yet");};
+		Node*       GetNode(int node_number){_error_("Not implemented");};
 		int         GetNodeIndex(Node* node){_error_("not implemented yet");};
 		int         GetNumberOfNodes(void);
 		int         GetNumberOfNodes(int enum_type){_error_("not implemented yet");};
 		int         GetNumberOfVertices(void);
+		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type){_error_("not implemented yet");};
+		Element*    GetUpperElement(void){_error_("not implemented yet");};
+		void        GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,bool onsid){_error_("not implemented yet");};
 		void        GetVerticesCoordinates(IssmDouble** pxyz_list);
 		void        GetVerticesCoordinatesBase(IssmDouble** pxyz_list){_error_("not implemented yet");};
 		void        GetVerticesCoordinatesTop(IssmDouble** pxyz_list){_error_("not implemented yet");};
+		IssmDouble  IceMass(void){_error_("not implemented yet");};
+		IssmDouble  IceVolume(void){_error_("not implemented yet");};
+		IssmDouble  IceVolumeAboveFloatation(void){_error_("not implemented yet");};
+		void        InputControlUpdate(IssmDouble scalar,bool save_parameter){_error_("not implemented yet");};
+		void        InputDepthAverageAtBase(int enum_type,int average_enum_type){_error_("not implemented yet");};
+		void        InputExtrude(int enum_type,int start){_error_("not implemented"); /*For penta only*/};
+		void        InputScale(int enum_type,IssmDouble scale_factor){_error_("not implemented yet");};
+		void        InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		void        InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum){_error_("not implemented yet");};
+		void        InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int inputenum){_error_("not implemented yet");};
+		void        InputUpdateFromVector(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
+		bool        IsFaceOnBoundary(void){_error_("not implemented yet");};
+		bool		   IsIcefront(void);
+		bool        IsNodeOnShelfFromFlags(IssmDouble* flags){_error_("not implemented yet");};
 		bool        IsOnBase(){_error_("not implemented yet");};
 		bool        IsOnSurface(){_error_("not implemented yet");};
-		bool        IsNodeOnShelfFromFlags(IssmDouble* flags){_error_("not implemented yet");};
+		bool        IsZeroLevelset(int levelset_enum){_error_("not implemented");};
 		void        JacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void        JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){_error_("not implemented yet");};
 		void        JacobianDeterminantLine(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
 		void        JacobianDeterminantSurface(IssmDouble*  pJdet, IssmDouble* xyz_list,Gauss* gauss);
-		void        JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){_error_("not implemented yet");};
 		void        JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){_error_("not implemented yet");};
+		IssmDouble  Masscon(IssmDouble* levelset){_error_("not implemented yet");};
+		IssmDouble  MassFlux(IssmDouble* segment){_error_("not implemented yet");};
+		IssmDouble  MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){_error_("not implemented yet");}
+		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
 		IssmDouble  MinEdgeLength(IssmDouble* xyz_list){_error_("not implemented yet");};
-		void        NodalFunctions(IssmDouble* basis,Gauss* gauss);
-		void        NodalFunctionsP1(IssmDouble* basis,Gauss* gauss);
-		void        NodalFunctionsP2(IssmDouble* basis,Gauss* gauss);
-		void        NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
-		void        NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
-		void        NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
-		void        NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
-		void        NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
-		void        NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
-		void        NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
-		void        NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
-		void        NormalTop(IssmDouble* normal,IssmDouble* xyz_list){_error_("not implemented yet");};
-		void        NormalBase(IssmDouble* normal,IssmDouble* xyz_list){_error_("not implemented yet");};
-		int         NumberofNodesVelocity(void){_error_("not implemented yet");};
-		int         NumberofNodesPressure(void){_error_("not implemented yet");};
-	   Element*    SpawnBasalElement(void){_error_("not implemented yet");};
-		Element*    SpawnTopElement(void){_error_("not implemented yet");};
-		IssmDouble  StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){_error_("not implemented yet");};
-		int         PressureInterpolation(void){_error_("not implemented yet");};
-		void        ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss){_error_("not implemented yet");};
-		void        ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
-		int         VelocityInterpolation(void){_error_("not implemented yet");};
-		int         TensorInterpolation(void){_error_("not implemented yet");};
-		void        GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating){_error_("not implemented yet");};
-		IssmDouble  GetGroundedPortion(IssmDouble* xyz_list){_error_("not implemented yet");};
-		void        GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){_error_("not implemented yet");};
-		Node*       GetNode(int node_number){_error_("Not implemented");};
-		int         GetElementType(void){_error_("not implemented yet");};
+		IssmDouble  Misfit(int modelenum,int observationenum,int weightsenum){_error_("not implemented yet");};
+		IssmDouble  MisfitArea(int weightsenum){_error_("not implemented yet");};
 		Gauss*      NewGauss(void);
 		Gauss*      NewGauss(int order);
@@ -118,53 +115,59 @@
 		Gauss*      NewGaussLine(int vertex1,int vertex2,int order){_error_("not implemented yet");};
 		Gauss*      NewGaussTop(int order){_error_("not implemented yet");};
+		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){_error_("not implemented yet");};
+		void        NodalFunctions(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void        NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsP1(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsP2(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void        NormalBase(IssmDouble* normal,IssmDouble* xyz_list){_error_("not implemented yet");};
+		void        NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
+		void        NormalTop(IssmDouble* normal,IssmDouble* xyz_list){_error_("not implemented yet");};
+		int         NumberofNodesPressure(void){_error_("not implemented yet");};
+		int         NumberofNodesVelocity(void){_error_("not implemented yet");};
+		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm){_error_("not implemented yet");};
+		void        PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding){_error_("not implemented yet");};
+		int         PressureInterpolation(void){_error_("not implemented yet");};
+		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe){_error_("not implemented yet");};
+		void        ResetFSBasalBoundaryCondition(void){_error_("not implemented yet");};
+		void        ResetHooks(){_error_("not implemented yet");};
+		void        SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){_error_("not implemented yet");};
+		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters){_error_("not implemented yet");};
+		void        SetTemporaryElementType(int element_type_in){_error_("not implemented yet");};
+	   Element*    SpawnBasalElement(void){_error_("not implemented yet");};
+		Element*    SpawnTopElement(void){_error_("not implemented yet");};
+		IssmDouble  StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){_error_("not implemented yet");};
+		void        StrainRateparallel(void){_error_("not implemented yet");};
+		void        StrainRateperpendicular(void){_error_("not implemented yet");};
+		void        StressIntensityFactor(void){_error_("not implemented yet");};
+		IssmDouble  SurfaceArea(void){_error_("not implemented yet");};
+		int         TensorInterpolation(void){_error_("not implemented yet");};
+		IssmDouble  TimeAdapt(){_error_("not implemented yet");};
+		IssmDouble  TotalSmb(void){_error_("not implemented yet");};
+		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement){_error_("not implemented yet");};
+		void        UpdateConstraintsExtrudeFromBase(){_error_("not implemented");};
+		void        UpdateConstraintsExtrudeFromTop(){_error_("not implemented");};
+		int         UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){_error_("not implemented yet");};
+		void        ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss){_error_("not implemented yet");};
+		int         VelocityInterpolation(void){_error_("not implemented yet");};
 		int         VertexConnectivity(int vertexindex){_error_("not implemented yet");};
 		void        VerticalSegmentIndices(int** pindices,int* pnumseg){_error_("not implemented yet");};
 		void        ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){_error_("not implemented yet");};
-		bool        IsZeroLevelset(int levelset_enum){_error_("not implemented");};
-		bool		   IsIcefront(void);
-		bool        IsFaceOnBoundary(void){_error_("not implemented yet");};
 		void        ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){_error_("not implemented");};
-		void		   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum);
-		void		   GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level){_error_("not implemented");};
-
-		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type){_error_("not implemented yet");};
-		void        InputDepthAverageAtBase(int enum_type,int average_enum_type){_error_("not implemented yet");};
-		void        InputExtrude(int enum_type){_error_("not implemented"); /*For penta only*/};
-		void        InputScale(int enum_type,IssmDouble scale_factor){_error_("not implemented yet");};
-		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
-		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){_error_("not implemented yet");};
-		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){_error_("not implemented yet");};
-		void        ResetFSBasalBoundaryCondition(void){_error_("not implemented yet");};
-		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe){_error_("not implemented yet");};
-		void        SetTemporaryElementType(int element_type_in){_error_("not implemented yet");};
-		IssmDouble  SurfaceArea(void){_error_("not implemented yet");};
-		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement){_error_("not implemented yet");};
-		IssmDouble  TimeAdapt(){_error_("not implemented yet");};
-		void UpdateConstraintsExtrudeFromBase(){_error_("not implemented");};
-		void UpdateConstraintsExtrudeFromTop(){_error_("not implemented");};
-
-		void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){_error_("not implemented yet");};
-		IssmDouble IceVolume(void){_error_("not implemented yet");};
-		IssmDouble IceVolumeAboveFloatation(void){_error_("not implemented yet");};
-		IssmDouble TotalSmb(void){_error_("not implemented yet");};
-		IssmDouble MassFlux(IssmDouble* segment){_error_("not implemented yet");};
-		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){_error_("not implemented yet");}
-		void       ElementResponse(IssmDouble* presponse,int response_enum){_error_("not implemented yet");};
-		IssmDouble Misfit(int modelenum,int observationenum,int weightsenum){_error_("not implemented yet");};
-		IssmDouble MisfitArea(int weightsenum){_error_("not implemented yet");};
 
 #ifdef _HAVE_GIA_
-		void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y){_error_("not implemented yet");};
+		void        GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y){_error_("not implemented yet");};
 #endif
 
-		void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data){_error_("not implemented yet");};
-		void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){_error_("not implemented yet");};
-		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){_error_("not implemented yet");};
-		void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){_error_("not implemented yet");};
-		void       InputControlUpdate(IssmDouble scalar,bool save_parameter){_error_("not implemented yet");};
-
-		void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding){_error_("not implemented yet");};
-		void   MigrateGroundingLine(IssmDouble* sheet_ungrounding){_error_("not implemented yet");};
-		int    UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){_error_("not implemented yet");};
+#ifdef _HAVE_DAKOTA_
+		void        InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type){_error_("not implemented yet");};
+		void        InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
+#endif
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Elements/SegRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/SegRef.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/SegRef.cpp	(revision 19105)
@@ -18,4 +18,5 @@
 #define NUMNODESP0  1
 #define NUMNODESP1  2
+#define NUMNODESMAX 2
 
 /*Object constructors and destructor*/
@@ -28,4 +29,88 @@
 
 /*Reference Element numerics*/
+void SegRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement){/*{{{*/
+
+	/*From node values of parameter p (plist[0],plist[1]), return parameter derivative value at gaussian 
+	 * point specified by gauss_basis:
+	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx
+	 *
+	 * p is a vector already allocated.
+	 *
+	 * WARNING: For a significant gain in performance, it is better to use
+	 * static memory allocation instead of dynamic.
+	 */
+
+	/*Allocate derivatives of basis functions*/
+	IssmDouble  dbasis[1*NUMNODESMAX];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+	_assert_(numnodes<=NUMNODESMAX);
+
+	/*Get basis functions derivatives at this point*/
+	GetNodalFunctionsDerivatives(&dbasis[0],xyz_list,gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	IssmDouble dpx=0.;
+	for(int i=0;i<numnodes;i++) dpx += dbasis[0*numnodes+i]*plist[i];
+
+	/*Assign values*/
+	p[0]=dpx;
+}
+/*}}}*/
+void SegRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss,int finiteelement){/*{{{*/
+	/* WARNING: For a significant gain in performance, it is better to use
+	 * static memory allocation instead of dynamic.*/
+
+	/*Allocate basis functions*/
+	IssmDouble  basis[NUMNODESMAX];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+	_assert_(numnodes<=NUMNODESMAX);
+
+	/*Get basis functions at this point*/
+	GetNodalFunctions(&basis[0],gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	IssmDouble value =0.;
+	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
+
+	/*Assign output pointer*/
+	*p = value;
+}
+/*}}}*/
+void SegRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussSeg* gauss){/*{{{*/
+	/*The Jacobian is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size 1*/
+
+	IssmDouble x1=xyz_list[3*0+0];
+	IssmDouble x2=xyz_list[3*1+0];
+
+	*J=.5*fabs(x2-x1);
+}
+/*}}}*/
+void SegRef::GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussSeg* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(Jdet, xyz_list, gauss);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+void SegRef::GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussSeg* gauss){/*{{{*/
+
+	/*Jacobian*/
+	IssmDouble J;
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J, xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	*Jinv = 1./J;
+}
+/*}}}*/
 void SegRef::GetNodalFunctions(IssmDouble* basis,GaussSeg* gauss,int finiteelement){/*{{{*/
 	/*This routine returns the values of the nodal functions  at the gaussian point.*/
@@ -108,84 +193,4 @@
 }
 /*}}}*/
-void SegRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement){/*{{{*/
-
-	/*From node values of parameter p (plist[0],plist[1]), return parameter derivative value at gaussian 
-	 * point specified by gauss_basis:
-	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx
-	 *
-	 * p is a vector already allocated.
-	 */
-
-	/*Output*/
-	IssmDouble dpx = 0.;
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes(finiteelement);
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* dbasis=xNew<IssmDouble>(1*numnodes);
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
-
-	/*Calculate parameter for this Gauss point*/
-	for(int i=0;i<numnodes;i++) dpx += dbasis[i]*plist[i];
-
-	/*Assign values*/
-	xDelete<IssmDouble>(dbasis);
-	*p=dpx;
-
-}
-/*}}}*/
-void SegRef::GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss,int finiteelement){/*{{{*/
-
-	/*Output*/
-	IssmDouble value =0.;
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes(finiteelement);
-
-	/*Get nodal functions*/
-	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	GetNodalFunctions(basis, gauss,finiteelement);
-
-	/*Calculate parameter for this Gauss point*/
-	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
-
-	/*Assign output pointer*/
-	xDelete<IssmDouble>(basis);
-	*p = value;
-}
-/*}}}*/
-void SegRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussSeg* gauss){/*{{{*/
-	/*The Jacobian is constant over the element, discard the gaussian points. 
-	 * J is assumed to have been allocated of size 1*/
-
-	IssmDouble x1=xyz_list[3*0+0];
-	IssmDouble x2=xyz_list[3*1+0];
-
-	*J=.5*fabs(x2-x1);
-}
-/*}}}*/
-void SegRef::GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussSeg* gauss){/*{{{*/
-	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
-	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
-
-	/*Call Jacobian routine to get the jacobian:*/
-	GetJacobian(Jdet, xyz_list, gauss);
-	if(*Jdet<0) _error_("negative jacobian determinant!");
-
-}
-/*}}}*/
-void SegRef::GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussSeg* gauss){/*{{{*/
-
-	/*Jacobian*/
-	IssmDouble J;
-
-	/*Call Jacobian routine to get the jacobian:*/
-	GetJacobian(&J, xyz_list, gauss);
-
-	/*Invert Jacobian matrix: */
-	*Jinv = 1./J;
-}
-/*}}}*/
 int  SegRef::NumberofNodes(int finiteelement){/*{{{*/
 
Index: /issm/trunk/src/c/classes/Elements/SegRef.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/SegRef.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/SegRef.h	(revision 19105)
@@ -16,4 +16,6 @@
 		~SegRef();
 
+		void GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement);
+		void GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss,int finiteelement);
 		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussSeg* gauss);
 		void GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussSeg* gauss);
@@ -22,6 +24,4 @@
 		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement);
 		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussSeg* gauss,int finiteelement);
-		void GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussSeg* gauss,int finiteelement);
-		void GetInputValue(IssmDouble* p, IssmDouble* plist, GaussSeg* gauss,int finiteelement);
 		int  NumberofNodes(int finiteelement);
 };
Index: /issm/trunk/src/c/classes/Elements/Tetra.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tetra.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/Tetra.cpp	(revision 19105)
@@ -104,12 +104,4 @@
 /*}}}*/
 
-int      Tetra::FiniteElement(void){/*{{{*/
-	return this->element_type;
-} /*}}}*/
-int      Tetra::ObjectEnum(void){/*{{{*/
-
-	return TetraEnum;
-
-}/*}}}*/
 void     Tetra::AddInput(int input_enum,IssmDouble* values, int interpolation_enum){/*{{{*/
 
@@ -196,4 +188,24 @@
 }
 /*}}}*/
+void     Tetra::FaceOnFrontIndices(int* pindex1,int* pindex2,int* pindex3){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[4][3] = {{0,1,2},{0,3,1},{1,3,2},{0,2,3}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MaskIceLevelsetEnum);
+
+	for(int i=0;i<4;i++){
+		if(values[indices[i][0]] == 0. && values[indices[i][1]] == 0. && values[indices[i][2]] == 0.){
+			*pindex1 = indices[i][0];
+			*pindex2 = indices[i][1];
+			*pindex3 = indices[i][2];
+			return;
+		}
+	}
+
+	_error_("Could not find 3 vertices on bed");
+}
+/*}}}*/
 void     Tetra::FaceOnSurfaceIndices(int* pindex1,int* pindex2,int* pindex3){/*{{{*/
 
@@ -216,24 +228,7 @@
 }
 /*}}}*/
-void     Tetra::FaceOnFrontIndices(int* pindex1,int* pindex2,int* pindex3){/*{{{*/
-
-	IssmDouble values[NUMVERTICES];
-	int        indices[4][3] = {{0,1,2},{0,3,1},{1,3,2},{0,2,3}};
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&values[0],MaskIceLevelsetEnum);
-
-	for(int i=0;i<4;i++){
-		if(values[indices[i][0]] == 0. && values[indices[i][1]] == 0. && values[indices[i][2]] == 0.){
-			*pindex1 = indices[i][0];
-			*pindex2 = indices[i][1];
-			*pindex3 = indices[i][2];
-			return;
-		}
-	}
-
-	_error_("Could not find 3 vertices on bed");
-}
-/*}}}*/
+int      Tetra::FiniteElement(void){/*{{{*/
+	return this->element_type;
+} /*}}}*/
 int      Tetra::GetElementType(){/*{{{*/
 
@@ -475,12 +470,4 @@
 }
 /*}}}*/
-bool     Tetra::IsOnBase(){/*{{{*/
-	return HasFaceOnBase();
-}
-/*}}}*/
-bool     Tetra::IsOnSurface(){/*{{{*/
-	return HasFaceOnSurface();
-}
-/*}}}*/
 bool     Tetra::IsIcefront(void){/*{{{*/
 
@@ -497,4 +484,12 @@
 	return false;
 }/*}}}*/
+bool     Tetra::IsOnBase(){/*{{{*/
+	return HasFaceOnBase();
+}
+/*}}}*/
+bool     Tetra::IsOnSurface(){/*{{{*/
+	return HasFaceOnSurface();
+}
+/*}}}*/
 void     Tetra::JacobianDeterminant(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 
@@ -504,15 +499,15 @@
 }
 /*}}}*/
+void     Tetra::JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetJacobianDeterminantFace(pJdet,xyz_list_base,(GaussTetra*)gauss);
+
+}
+/*}}}*/
 void     Tetra::JacobianDeterminantSurface(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 
 	_assert_(gauss->Enum()==GaussTetraEnum);
 	this->GetJacobianDeterminantFace(pJdet,xyz_list,(GaussTetra*)gauss);
-
-}
-/*}}}*/
-void     Tetra::JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussTetraEnum);
-	this->GetJacobianDeterminantFace(pJdet,xyz_list_base,(GaussTetra*)gauss);
 
 }
@@ -561,4 +556,32 @@
 }
 /*}}}*/
+void     Tetra::NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTetra*)gauss,this->element_type);
+
+}
+/*}}}*/
+void     Tetra::NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTetra*)gauss,this->VelocityInterpolation());
+
+}
+/*}}}*/
+void     Tetra::NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetNodalFunctions(basis,(GaussTetra*)gauss,this->PressureInterpolation());
+
+}
+/*}}}*/
+void     Tetra::NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTetraEnum);
+	this->GetNodalFunctions(basis,(GaussTetra*)gauss,this->TensorInterpolation());
+
+}
+/*}}}*/
 void     Tetra::NodalFunctionsVelocity(IssmDouble* basis, Gauss* gauss){/*{{{*/
 
@@ -568,30 +591,26 @@
 }
 /*}}}*/
-void     Tetra::NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussTetraEnum);
-	this->GetNodalFunctions(basis,(GaussTetra*)gauss,this->PressureInterpolation());
-
-}
-/*}}}*/
-void     Tetra::NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussTetraEnum);
-	this->GetNodalFunctions(basis,(GaussTetra*)gauss,this->TensorInterpolation());
-
-}
-/*}}}*/
-void     Tetra::NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussTetraEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTetra*)gauss,this->element_type);
-
-}
-/*}}}*/
-void     Tetra::NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussTetraEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTetra*)gauss,this->VelocityInterpolation());
-
+void     Tetra::NormalBase(IssmDouble* bed_normal,IssmDouble* xyz_list){/*{{{*/
+
+	IssmDouble v13[3],v23[3];
+	IssmDouble normal[3];
+	IssmDouble normal_norm;
+
+	for(int i=0;i<3;i++){
+		v13[i]=xyz_list[0*3+i]-xyz_list[2*3+i];
+		v23[i]=xyz_list[1*3+i]-xyz_list[2*3+i];
+	}
+
+	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
+	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
+	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
+	normal_norm=sqrt(normal[0]*normal[0]+ normal[1]*normal[1]+ normal[2]*normal[2]);
+
+	/*Bed normal is opposite to surface normal*/
+	bed_normal[0]=-normal[0]/normal_norm;
+	bed_normal[1]=-normal[1]/normal_norm;
+	bed_normal[2]=-normal[2]/normal_norm;
+
+	_assert_(bed_normal[2]<0.);
 }
 /*}}}*/
@@ -616,5 +635,5 @@
 }
 /*}}}*/
-void     Tetra::NormalBase(IssmDouble* bed_normal,IssmDouble* xyz_list){/*{{{*/
+void     Tetra::NormalTop(IssmDouble* top_normal,IssmDouble* xyz_list){/*{{{*/
 
 	IssmDouble v13[3],v23[3];
@@ -632,28 +651,4 @@
 	normal_norm=sqrt(normal[0]*normal[0]+ normal[1]*normal[1]+ normal[2]*normal[2]);
 
-	/*Bed normal is opposite to surface normal*/
-	bed_normal[0]=-normal[0]/normal_norm;
-	bed_normal[1]=-normal[1]/normal_norm;
-	bed_normal[2]=-normal[2]/normal_norm;
-
-	_assert_(bed_normal[2]<0.);
-}
-/*}}}*/
-void     Tetra::NormalTop(IssmDouble* top_normal,IssmDouble* xyz_list){/*{{{*/
-
-	IssmDouble v13[3],v23[3];
-	IssmDouble normal[3];
-	IssmDouble normal_norm;
-
-	for(int i=0;i<3;i++){
-		v13[i]=xyz_list[0*3+i]-xyz_list[2*3+i];
-		v23[i]=xyz_list[1*3+i]-xyz_list[2*3+i];
-	}
-
-	normal[0]=v13[1]*v23[2]-v13[2]*v23[1];
-	normal[1]=v13[2]*v23[0]-v13[0]*v23[2];
-	normal[2]=v13[0]*v23[1]-v13[1]*v23[0];
-	normal_norm=sqrt(normal[0]*normal[0]+ normal[1]*normal[1]+ normal[2]*normal[2]);
-
 	top_normal[0]=normal[0]/normal_norm;
 	top_normal[1]=normal[1]/normal_norm;
@@ -668,4 +663,13 @@
 int      Tetra::NumberofNodesVelocity(void){/*{{{*/
 	return TetraRef::NumberofNodes(this->VelocityInterpolation());
+}
+/*}}}*/
+int      Tetra::ObjectEnum(void){/*{{{*/
+
+	return TetraEnum;
+
+}/*}}}*/
+int      Tetra::PressureInterpolation(void){/*{{{*/
+	return TetraRef::PressureInterpolation(this->element_type);
 }
 /*}}}*/
@@ -764,19 +768,4 @@
 }
 /*}}}*/
-void     Tetra::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
-
-	/*go into parameters and get the analysis_counter: */
-	int analysis_counter;
-	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
-
-	/*Get Element type*/
-	this->element_type=this->element_type_list[analysis_counter];
-
-	/*Pick up nodes*/
-	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
-	else this->nodes=NULL;
-
-}
-/*}}}*/
 void     Tetra::ResetHooks(){/*{{{*/
 
@@ -795,4 +784,19 @@
 }
 /*}}}*/
+void     Tetra::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
+
+	/*go into parameters and get the analysis_counter: */
+	int analysis_counter;
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	this->element_type=this->element_type_list[analysis_counter];
+
+	/*Pick up nodes*/
+	if(this->hnodes[analysis_counter]) this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	else this->nodes=NULL;
+
+}
+/*}}}*/
 Element* Tetra::SpawnBasalElement(void){/*{{{*/
 
@@ -824,5 +828,5 @@
 	tria->parameters=this->parameters;
 	tria->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
-	this->SpawnTriaHook(dynamic_cast<ElementHook*>(tria),index1,index2,index3);
+	this->SpawnTriaHook(xDynamicCast<ElementHook*>(tria),index1,index2,index3);
 
 	/*Spawn material*/
@@ -836,4 +840,8 @@
 	/*Return new Tria*/
 	return tria;
+}
+/*}}}*/
+int      Tetra::TensorInterpolation(void){/*{{{*/
+	return TetraRef::TensorInterpolation(this->element_type);
 }
 /*}}}*/
@@ -981,12 +989,4 @@
 }
 /*}}}*/
-int      Tetra::PressureInterpolation(void){/*{{{*/
-	return TetraRef::PressureInterpolation(this->element_type);
-}
-/*}}}*/
-int      Tetra::TensorInterpolation(void){/*{{{*/
-	return TetraRef::TensorInterpolation(this->element_type);
-}
-/*}}}*/
 void     Tetra::ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
 	/*Compute portion of the element that is grounded*/ 
Index: /issm/trunk/src/c/classes/Elements/Tetra.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tetra.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/Tetra.h	(revision 19105)
@@ -39,17 +39,9 @@
 		Object *copy();
 		/*}}}*/
-		/*Update virtual functions resolution: {{{*/
-		void  InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int inputenum){_error_("not implemented yet");};
-		void  InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum);
-		void  InputUpdateFromVector(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
-#ifdef _HAVE_DAKOTA_
-		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
-		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type){_error_("not implemented yet");};
-#endif
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
-		/*}}}*/
 		/*Element virtual functions definitions: {{{*/
 		void        AddBasalInput(int input_enum, IssmDouble* values, int interpolation_enum){_error_("not implemented yet");};
 		void        AddInput(int input_enum, IssmDouble* values, int interpolation_enum);
+		void        AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){_error_("not implemented yet");};
+		void        CalvingRateLevermann(void){_error_("not implemented yet");};
 		IssmDouble  CharacteristicLength(void){_error_("not implemented yet");};
 		void        ComputeBasalStress(Vector<IssmDouble>* sigma_b){_error_("not implemented yet");};
@@ -57,62 +49,68 @@
 		void        ComputeStressTensor(){_error_("not implemented yet");};
 		void        ComputeDeviatoricStressTensor(){_error_("not implemented yet");};
+		void        CalvingRatePi(void){_error_("not implemented yet");};
 		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters);
-		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
-		void        ResetHooks();
+		void        ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){_error_("not implemented yet");};
+		void        ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){_error_("not implemented yet");};
 		void        Delta18oParameterization(void){_error_("not implemented yet");};
+		void        MungsmtpParameterization(void){_error_("not implemented yet");};
+		IssmDouble  DragCoefficientAbsGradient(void){_error_("not implemented yet");};
+		void        ElementResponse(IssmDouble* presponse,int response_enum){_error_("not implemented yet");};
 		void        ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
+		void        FaceOnBaseIndices(int* pindex1,int* pindex2,int* pindex3);
 		void        FaceOnFrontIndices(int* pindex1,int* pindex2,int* pindex3);
-		void        FaceOnBaseIndices(int* pindex1,int* pindex2,int* pindex3);
 		void        FaceOnSurfaceIndices(int* pindex1,int* pindex2,int* pindex3);
+		int         FiniteElement(void);
 		void        FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating){_error_("not implemented yet");};
-		int         FiniteElement(void);
-		Element*    GetUpperElement(void){_error_("not implemented yet");};
 		Element*    GetBasalElement(void){_error_("not implemented yet");};
+		int         GetElementType(void);
+		void        GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating){_error_("not implemented yet");};
+		IssmDouble  GetGroundedPortion(IssmDouble* xyz_list){_error_("not implemented yet");};
+		void		   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){_error_("not implemented yet");};
+		void        GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
+		void		   GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level){_error_("not implemented yet");};
+		void        GetLevelsetPositivePart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlynegative,IssmDouble* levelsetvalues){_error_("not implemented yet");};
+		Node*       GetNode(int node_number){_error_("Not implemented");};
 		int         GetNodeIndex(Node* node);
 		int         GetNumberOfNodes(void);
 		int         GetNumberOfNodes(int enum_type){_error_("not implemented yet");};
 		int         GetNumberOfVertices(void);
+		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type){_error_("not implemented yet");};
+		Element*    GetUpperElement(void){_error_("not implemented yet");};
+		void        GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,bool onsid){_error_("not implemented yet");};
 		void        GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
 		void        GetVerticesCoordinatesTop(IssmDouble** pxyz_list);
+		void        GradientIndexing(int* indexing,int control_index){_error_("not implemented yet");};
 		bool        HasFaceOnBase();
 		bool        HasFaceOnSurface();
+		IssmDouble  IceMass(void){_error_("not implemented yet");};
+		IssmDouble  IceVolume(void){_error_("not implemented yet");};
+		IssmDouble  IceVolumeAboveFloatation(void){_error_("not implemented yet");};
+		bool        IsFaceOnBoundary(void){_error_("not implemented yet");};
+		bool		   IsIcefront(void);
+		bool        IsNodeOnShelfFromFlags(IssmDouble* flags){_error_("not implemented yet");};
 		bool        IsOnBase();
 		bool        IsOnSurface();
-		bool        IsNodeOnShelfFromFlags(IssmDouble* flags){_error_("not implemented yet");};
+		bool        IsZeroLevelset(int levelset_enum){_error_("not implemented");};
+		void        InputControlUpdate(IssmDouble scalar,bool save_parameter){_error_("not implemented yet");};
+		void        InputDepthAverageAtBase(int enum_type,int average_enum_type){_error_("not implemented yet");};
+		void        InputExtrude(int enum_type,int start){_error_("not implemented"); /*For penta only*/};
+		void        InputScale(int enum_type,IssmDouble scale_factor){_error_("not implemented yet");};
+		void        InputUpdateFromIoModel(int index, IoModel* iomodel);
+		void        InputUpdateFromSolutionOneDof(IssmDouble* solution,int inputenum);
+		void        InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int inputenum){_error_("not implemented yet");};
+		void        InputUpdateFromVector(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
 		void        JacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void        JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
 		void        JacobianDeterminantLine(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
 		void        JacobianDeterminantSurface(IssmDouble*  pJdet, IssmDouble* xyz_list,Gauss* gauss);
-		void        JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
 		void        JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
+		IssmDouble  Masscon(IssmDouble* levelset){_error_("not implemented yet");};
+		IssmDouble  MassFlux(IssmDouble* segment){_error_("not implemented yet");};
+		IssmDouble  MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){_error_("not implemented yet");}
+		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
 		IssmDouble  MinEdgeLength(IssmDouble* xyz_list){_error_("not implemented yet");};
-		void        NodalFunctions(IssmDouble* basis,Gauss* gauss);
-		void        NodalFunctionsP1(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
-		void        NodalFunctionsP2(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
-		void        NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss);
-		void        NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss);
-		void        NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss);
-		void        NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
-		void        NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
-		void        NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
-		void        NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
-		void        NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
-		void        NormalTop(IssmDouble* normal,IssmDouble* xyz_list);
-		void        NormalBase(IssmDouble* normal,IssmDouble* xyz_list);
-		int         NumberofNodesVelocity(void);
-		int         NumberofNodesPressure(void);
-	   Element*    SpawnBasalElement(void);
-		Element*    SpawnTopElement(void);
-		Tria*       SpawnTria(int index1,int index2,int index3);
-		IssmDouble  StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){_error_("not implemented yet");};
-		int         PressureInterpolation(void);
-		void        ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
-		void        ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
-		int         VelocityInterpolation(void);
-		int         TensorInterpolation(void);
-		void        GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating){_error_("not implemented yet");};
-		IssmDouble  GetGroundedPortion(IssmDouble* xyz_list){_error_("not implemented yet");};
-		void        GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
-		Node*       GetNode(int node_number){_error_("Not implemented");};
-		int         GetElementType(void);
+		IssmDouble  Misfit(int modelenum,int observationenum,int weightsenum){_error_("not implemented yet");};
+		IssmDouble  MisfitArea(int weightsenum){_error_("not implemented yet");};
 		Gauss*      NewGauss(void);
 		Gauss*      NewGauss(int order);
@@ -123,54 +121,60 @@
 		Gauss*      NewGaussLine(int vertex1,int vertex2,int order){_error_("not implemented yet");};
 		Gauss*      NewGaussTop(int order);
+		void        NodalFunctions(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void        NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void        NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsP1(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsP2(IssmDouble* basis,Gauss* gauss){_error_("not implemented yet");};
+		void        NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss);
+		void        NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss);
+		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){_error_("not implemented yet");};
+		void        NormalBase(IssmDouble* normal,IssmDouble* xyz_list);
+		void        NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
+		void        NormalTop(IssmDouble* normal,IssmDouble* xyz_list);
+		int         NumberofNodesPressure(void);
+		int         NumberofNodesVelocity(void);
+		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm){_error_("not implemented yet");};
+		void        PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding){_error_("not implemented yet");};
+		int         PressureInterpolation(void);
+		void        ResetFSBasalBoundaryCondition(void);
+		void        ResetHooks();
+		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
+		void        SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){_error_("not implemented yet");};
+		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
+		void        SetTemporaryElementType(int element_type_in){_error_("not implemented yet");};
+	   Element*    SpawnBasalElement(void);
+		Element*    SpawnTopElement(void);
+		Tria*       SpawnTria(int index1,int index2,int index3);
+		IssmDouble  StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){_error_("not implemented yet");};
+		void        StrainRateparallel(void){_error_("not implemented yet");};
+		void        StrainRateperpendicular(void){_error_("not implemented yet");};
+		void        StressIntensityFactor(void){_error_("not implemented yet");};
+		IssmDouble  SurfaceArea(void){_error_("not implemented yet");};
+		int         TensorInterpolation(void);
+		IssmDouble  TimeAdapt(){_error_("not implemented yet");};
+		IssmDouble  TotalSmb(void){_error_("not implemented yet");};
+		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
+		void        UpdateConstraintsExtrudeFromBase(){_error_("not implemented");};
+		void        UpdateConstraintsExtrudeFromTop(){_error_("not implemented");};
+		int         UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){_error_("not implemented yet");};
+		void        ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void        ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
+		int         VelocityInterpolation(void);
 		int         VertexConnectivity(int vertexindex){_error_("not implemented yet");};
 		void        VerticalSegmentIndices(int** pindices,int* pnumseg){_error_("not implemented yet");};
 		void        ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
-		bool        IsZeroLevelset(int levelset_enum){_error_("not implemented");};
-		bool		   IsIcefront(void);
-		bool        IsFaceOnBoundary(void){_error_("not implemented yet");};
 		void        ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum);
-		void		   GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){_error_("not implemented yet");};
-		void		   GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level){_error_("not implemented yet");};
-		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type){_error_("not implemented yet");};
-		void        InputDepthAverageAtBase(int enum_type,int average_enum_type){_error_("not implemented yet");};
-		void        InputExtrude(int enum_type){_error_("not implemented"); /*For penta only*/};
-		void        InputScale(int enum_type,IssmDouble scale_factor){_error_("not implemented yet");};
-		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
-		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum){_error_("not implemented yet");};
-		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){_error_("not implemented yet");};
-		void        ResetFSBasalBoundaryCondition(void);
-		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
-		void        SetTemporaryElementType(int element_type_in){_error_("not implemented yet");};
-		IssmDouble  SurfaceArea(void){_error_("not implemented yet");};
-		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
-		IssmDouble  TimeAdapt(){_error_("not implemented yet");};
-		void UpdateConstraintsExtrudeFromBase(){_error_("not implemented");};
-		void UpdateConstraintsExtrudeFromTop(){_error_("not implemented");};
-
-		void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){_error_("not implemented yet");};
-		IssmDouble IceVolume(void){_error_("not implemented yet");};
-		IssmDouble IceVolumeAboveFloatation(void){_error_("not implemented yet");};
-		IssmDouble TotalSmb(void){_error_("not implemented yet");};
-		IssmDouble MassFlux(IssmDouble* segment){_error_("not implemented yet");};
-		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){_error_("not implemented yet");}
-		void       ElementResponse(IssmDouble* presponse,int response_enum){_error_("not implemented yet");};
-		IssmDouble Misfit(int modelenum,int observationenum,int weightsenum){_error_("not implemented yet");};
-		IssmDouble MisfitArea(int weightsenum){_error_("not implemented yet");};
 
 #ifdef _HAVE_GIA_
-		void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y){_error_("not implemented yet");};
+		void        GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y){_error_("not implemented yet");};
 #endif
 
-		IssmDouble DragCoefficientAbsGradient(void){_error_("not implemented yet");};
-		void       GradientIndexing(int* indexing,int control_index){_error_("not implemented yet");};
-		void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data){_error_("not implemented yet");};
-		void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){_error_("not implemented yet");};
-		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){_error_("not implemented yet");};
-		void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){_error_("not implemented yet");};
-		void       InputControlUpdate(IssmDouble scalar,bool save_parameter){_error_("not implemented yet");};
-
-		void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding){_error_("not implemented yet");};
-		void   MigrateGroundingLine(IssmDouble* sheet_ungrounding){_error_("not implemented yet");};
-		int    UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){_error_("not implemented yet");};
+#ifdef _HAVE_DAKOTA_
+		void        InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("not implemented yet");};
+		void        InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type){_error_("not implemented yet");};
+#endif
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Elements/TetraRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/TetraRef.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/TetraRef.cpp	(revision 19105)
@@ -20,4 +20,5 @@
 #define NUMNODESP1b 5
 #define NUMNODESP2  10
+#define NUMNODESMAX 10
 
 /*Object constructors and destructor*/
@@ -30,4 +31,141 @@
 
 /*Reference Element numerics*/
+void TetraRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement){/*{{{*/
+	/*From node values of parameter p (p_list[0], p_list[1], p_list[2],
+	 * p_list[3], p_list[4] and p_list[4]), return parameter derivative value at
+	 * gaussian point specified by gauss_coord:
+	 *   dp/dx=p_list[0]*dh1/dx+p_list[1]*dh2/dx+p_list[2]*dh3/dx+p_list[3]*dh4/dx+p_list[4]*dh5/dx+p_list[5]*dh6/dx;
+	 *   dp/dy=p_list[0]*dh1/dy+p_list[1]*dh2/dy+p_list[2]*dh3/dy+p_list[3]*dh4/dy+p_list[4]*dh5/dy+p_list[5]*dh6/dy;
+	 *   dp/dz=p_list[0]*dh1/dz+p_list[1]*dh2/dz+p_list[2]*dh3/dz+p_list[3]*dh4/dz+p_list[4]*dh5/dz+p_list[5]*dh6/dz;
+	 *
+	 *   p is a vector of size 3x1 already allocated.
+	 *
+	 * WARNING: For a significant gain in performance, it is better to use
+	 * static memory allocation instead of dynamic.
+	 */
+
+	/*Allocate derivatives of basis functions*/
+	IssmDouble  dbasis[3*NUMNODESMAX];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+	_assert_(numnodes<=NUMNODESMAX);
+
+	/*Get basis functions derivatives at this point*/
+	GetNodalFunctionsDerivatives(&dbasis[0],xyz_list,gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	IssmDouble dpx=0.;
+	IssmDouble dpy=0.;
+	IssmDouble dpz=0.;
+	for(int i=0;i<numnodes;i++) dpx += dbasis[0*numnodes+i]*plist[i];
+	for(int i=0;i<numnodes;i++) dpy += dbasis[1*numnodes+i]*plist[i];
+	for(int i=0;i<numnodes;i++) dpz += dbasis[2*numnodes+i]*plist[i];
+
+	/*Assign values*/
+	p[0]=dpx;
+	p[1]=dpy;
+	p[2]=dpz;
+}
+/*}}}*/
+void TetraRef::GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement){/*{{{*/
+	/* WARNING: For a significant gain in performance, it is better to use
+	 * static memory allocation instead of dynamic.*/
+
+	/*Allocate basis functions*/
+	IssmDouble  basis[NUMNODESMAX];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+	_assert_(numnodes<=NUMNODESMAX);
+
+	/*Get basis functions at this point*/
+	GetNodalFunctions(&basis[0],gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	IssmDouble value =0.;
+	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
+
+	/*Assign output pointer*/
+	*p = value;
+}
+/*}}}*/
+void TetraRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
+	/*The Jacobian is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size 1*/
+
+	IssmDouble x1=xyz_list[3*0+0];
+	IssmDouble x2=xyz_list[3*1+0];
+	IssmDouble x3=xyz_list[3*2+0];
+	IssmDouble x4=xyz_list[3*3+0];
+
+	IssmDouble y1=xyz_list[3*0+1];
+	IssmDouble y2=xyz_list[3*1+1];
+	IssmDouble y3=xyz_list[3*2+1];
+	IssmDouble y4=xyz_list[3*3+1];
+
+	IssmDouble z1=xyz_list[3*0+2];
+	IssmDouble z2=xyz_list[3*1+2];
+	IssmDouble z3=xyz_list[3*2+2];
+	IssmDouble z4=xyz_list[3*3+2];
+
+	J[NDOF3*0+0] = x2-x1;
+	J[NDOF3*0+1] = y2-y1;
+	J[NDOF3*0+2] = z2-z1;
+
+	J[NDOF3*1+0] = x3-x1;
+	J[NDOF3*1+1] = y3-y1;
+	J[NDOF3*1+2] = z3-z1;
+
+	J[NDOF3*2+0] = x4-x1;
+	J[NDOF3*2+1] = y4-y1;
+	J[NDOF3*2+2] = z4-z1;
+}
+/*}}}*/
+void TetraRef::GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+	IssmDouble J[3][3];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0],xyz_list, gauss);
+
+	/*Get Determinant*/
+	Matrix3x3Determinant(Jdet,&J[0][0]);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+void TetraRef::GetJacobianDeterminantFace(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
+
+	IssmDouble x1=xyz_list[3*0+0];
+	IssmDouble y1=xyz_list[3*0+1];
+	IssmDouble z1=xyz_list[3*0+2];
+	IssmDouble x2=xyz_list[3*1+0];
+	IssmDouble y2=xyz_list[3*1+1];
+	IssmDouble z2=xyz_list[3*1+2];
+	IssmDouble x3=xyz_list[3*2+0];
+	IssmDouble y3=xyz_list[3*2+1];
+	IssmDouble z3=xyz_list[3*2+2];
+
+	/*Jdet = norm( AB ^ AC ) / (2 * area of the reference triangle), with areaRef=sqrt(3) */
+	*Jdet=SQRT3/6.*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2),0.5);
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+}
+/*}}}*/
+void TetraRef::GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
+
+	/*Jacobian*/
+	IssmDouble J[3][3];
+
+	/*Call Jacobian routine to get the jacobian:*/
+	GetJacobian(&J[0][0], xyz_list, gauss);
+
+	/*Invert Jacobian matrix: */
+	Matrix3x3Invert(Jinv,&J[0][0]);
+}
+/*}}}*/
 void TetraRef::GetNodalFunctions(IssmDouble* basis,Gauss* gauss_in,int finiteelement){/*{{{*/
 	/*This routine returns the values of the nodal functions  at the gaussian point.*/
@@ -37,5 +175,5 @@
 	/*Cast gauss to GaussTetra*/
 	_assert_(gauss_in->Enum()==GaussTetraEnum);
-	GaussTetra* gauss = dynamic_cast<GaussTetra*>(gauss_in);
+	GaussTetra* gauss = xDynamicCast<GaussTetra*>(gauss_in);
 
 	switch(finiteelement){
@@ -206,136 +344,4 @@
 	}
 
-}
-/*}}}*/
-void TetraRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement){/*{{{*/
-	/*From node values of parameter p (p_list[0], p_list[1], p_list[2],
-	 * p_list[3], p_list[4] and p_list[4]), return parameter derivative value at
-	 * gaussian point specified by gauss_coord:
-	 *   dp/dx=p_list[0]*dh1/dx+p_list[1]*dh2/dx+p_list[2]*dh3/dx+p_list[3]*dh4/dx+p_list[4]*dh5/dx+p_list[5]*dh6/dx;
-	 *   dp/dy=p_list[0]*dh1/dy+p_list[1]*dh2/dy+p_list[2]*dh3/dy+p_list[3]*dh4/dy+p_list[4]*dh5/dy+p_list[5]*dh6/dy;
-	 *   dp/dz=p_list[0]*dh1/dz+p_list[1]*dh2/dz+p_list[2]*dh3/dz+p_list[3]*dh4/dz+p_list[4]*dh5/dz+p_list[5]*dh6/dz;
-	 *
-	 *   p is a vector of size 3x1 already allocated.
-	 */
-
-	/*Output*/
-	IssmDouble dpx=0.;
-	IssmDouble dpy=0.;
-	IssmDouble dpz=0.;
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes(finiteelement);
-
-	/*Get nodal functions derivatives*/
-	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
-
-	/*Calculate parameter for this Gauss point*/
-	for(int i=0;i<numnodes;i++) dpx += dbasis[0*numnodes+i]*plist[i];
-	for(int i=0;i<numnodes;i++) dpy += dbasis[1*numnodes+i]*plist[i];
-	for(int i=0;i<numnodes;i++) dpz += dbasis[2*numnodes+i]*plist[i];
-
-	/*Assign values*/
-	xDelete<IssmDouble>(dbasis);
-	p[0]=dpx;
-	p[1]=dpy;
-	p[2]=dpz;
-}
-/*}}}*/
-void TetraRef::GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement){/*{{{*/
-
-	/*Output*/
-	IssmDouble value =0.;
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes(finiteelement);
-
-	/*Get nodal functions*/
-	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	GetNodalFunctions(basis, gauss,finiteelement);
-
-	/*Calculate parameter for this Gauss point*/
-	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
-
-	/*Assign output pointer*/
-	xDelete<IssmDouble>(basis);
-	*p = value;
-}
-/*}}}*/
-void TetraRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
-	/*The Jacobian is constant over the element, discard the gaussian points. 
-	 * J is assumed to have been allocated of size 1*/
-
-	IssmDouble x1=xyz_list[3*0+0];
-	IssmDouble x2=xyz_list[3*1+0];
-	IssmDouble x3=xyz_list[3*2+0];
-	IssmDouble x4=xyz_list[3*3+0];
-
-	IssmDouble y1=xyz_list[3*0+1];
-	IssmDouble y2=xyz_list[3*1+1];
-	IssmDouble y3=xyz_list[3*2+1];
-	IssmDouble y4=xyz_list[3*3+1];
-
-	IssmDouble z1=xyz_list[3*0+2];
-	IssmDouble z2=xyz_list[3*1+2];
-	IssmDouble z3=xyz_list[3*2+2];
-	IssmDouble z4=xyz_list[3*3+2];
-
-	J[NDOF3*0+0] = x2-x1;
-	J[NDOF3*0+1] = y2-y1;
-	J[NDOF3*0+2] = z2-z1;
-
-	J[NDOF3*1+0] = x3-x1;
-	J[NDOF3*1+1] = y3-y1;
-	J[NDOF3*1+2] = z3-z1;
-
-	J[NDOF3*2+0] = x4-x1;
-	J[NDOF3*2+1] = y4-y1;
-	J[NDOF3*2+2] = z4-z1;
-}
-/*}}}*/
-void TetraRef::GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
-	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
-	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
-	IssmDouble J[3][3];
-
-	/*Call Jacobian routine to get the jacobian:*/
-	GetJacobian(&J[0][0],xyz_list, gauss);
-
-	/*Get Determinant*/
-	Matrix3x3Determinant(Jdet,&J[0][0]);
-	if(*Jdet<0) _error_("negative jacobian determinant!");
-
-}
-/*}}}*/
-void TetraRef::GetJacobianDeterminantFace(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
-	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
-	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
-
-	IssmDouble x1=xyz_list[3*0+0];
-	IssmDouble y1=xyz_list[3*0+1];
-	IssmDouble z1=xyz_list[3*0+2];
-	IssmDouble x2=xyz_list[3*1+0];
-	IssmDouble y2=xyz_list[3*1+1];
-	IssmDouble z2=xyz_list[3*1+2];
-	IssmDouble x3=xyz_list[3*2+0];
-	IssmDouble y3=xyz_list[3*2+1];
-	IssmDouble z3=xyz_list[3*2+2];
-
-	/*Jdet = norm( AB ^ AC ) / (2 * area of the reference triangle), with areaRef=sqrt(3) */
-	*Jdet=SQRT3/6.*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2),0.5);
-	if(*Jdet<0) _error_("negative jacobian determinant!");
-}
-/*}}}*/
-void TetraRef::GetJacobianInvert(IssmDouble* Jinv, IssmDouble* xyz_list,GaussTetra* gauss){/*{{{*/
-
-	/*Jacobian*/
-	IssmDouble J[3][3];
-
-	/*Call Jacobian routine to get the jacobian:*/
-	GetJacobian(&J[0][0], xyz_list, gauss);
-
-	/*Invert Jacobian matrix: */
-	Matrix3x3Invert(Jinv,&J[0][0]);
 }
 /*}}}*/
@@ -362,4 +368,28 @@
 }
 /*}}}*/
+int  TetraRef::PressureInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:          return P1Enum;
+		case P1P1GLSEnum:       return P1Enum;
+		case MINIcondensedEnum: return P1Enum;
+		case MINIEnum:          return P1Enum;
+		case TaylorHoodEnum:    return P1Enum;
+		case LATaylorHoodEnum:  return NoneEnum;
+		case XTaylorHoodEnum:   return P1Enum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}/*}}}*/
+int  TetraRef::TensorInterpolation(int fe_stokes){/*{{{*/
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	switch(fe_stokes){
+		case XTaylorHoodEnum: return P1DGEnum;
+		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+}
+/*}}}*/
 int  TetraRef::VelocityInterpolation(int fe_stokes){/*{{{*/
 
@@ -378,26 +408,2 @@
 }
 /*}}}*/
-int  TetraRef::PressureInterpolation(int fe_stokes){/*{{{*/
-
-	switch(fe_stokes){
-		case P1P1Enum:          return P1Enum;
-		case P1P1GLSEnum:       return P1Enum;
-		case MINIcondensedEnum: return P1Enum;
-		case MINIEnum:          return P1Enum;
-		case TaylorHoodEnum:    return P1Enum;
-		case LATaylorHoodEnum:  return NoneEnum;
-		case XTaylorHoodEnum:   return P1Enum;
-		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
-	}
-
-	return -1;
-}/*}}}*/
-int  TetraRef::TensorInterpolation(int fe_stokes){/*{{{*/
-	/*This routine returns the values of the nodal functions  at the gaussian point.*/
-
-	switch(fe_stokes){
-		case XTaylorHoodEnum: return P1DGEnum;
-		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
-	}
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/TetraRef.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/TetraRef.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/TetraRef.h	(revision 19105)
@@ -16,4 +16,6 @@
 		~TetraRef();
 
+		void GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement);
+		void GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement);
 		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussTetra* gauss);
 		void GetJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussTetra* gauss);
@@ -23,11 +25,8 @@
 		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement);
 		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussTetra* gauss,int finiteelement);
-		void GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussTetra* gauss,int finiteelement);
-		void GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement);
-
 		int  NumberofNodes(int finiteelement);
-		int  VelocityInterpolation(int fe_stokes);
 		int  PressureInterpolation(int fe_stokes);
 		int  TensorInterpolation(int fe_stokes);
+		int  VelocityInterpolation(int fe_stokes);
 };
 #endif
Index: /issm/trunk/src/c/classes/Elements/Tria.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 19105)
@@ -12,4 +12,5 @@
 #include <stdio.h>
 #include <string.h>
+#include <math.h>
 #include "../classes.h"
 #include "../../shared/shared.h"
@@ -155,4 +156,229 @@
 }
 /*}}}*/
+void       Tria::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){/*{{{*/
+
+	bool       already = false;
+	int        i,j;
+	int        partition[NUMVERTICES];
+	int        offsetsid[NUMVERTICES];
+	int        offsetdof[NUMVERTICES];
+	IssmDouble area;
+	IssmDouble mean;
+
+	/*First, get the area: */
+	area=this->GetArea();
+
+	/*Figure out the average for this element: */
+	this->GetVerticesSidList(&offsetsid[0]);
+	this->GetVertexPidList(&offsetdof[0]);
+	mean=0;
+	for(i=0;i<NUMVERTICES;i++){
+		partition[i]=reCast<int>(qmu_part[offsetsid[i]]);
+		mean=mean+1.0/NUMVERTICES*vertex_response[offsetdof[i]];
+	}
+
+	/*Add contribution: */
+	for(i=0;i<NUMVERTICES;i++){
+		already=false;
+		for(j=0;j<i;j++){
+			if (partition[i]==partition[j]){
+				already=true;
+				break;
+			}
+		}
+		if(!already){
+			partition_contributions->SetValue(partition[i],mean*area,ADD_VAL);
+			partition_areas->SetValue(partition[i],area,ADD_VAL);
+		};
+	}
+}
+/*}}}*/
+void       Tria::CalvingRateLevermann(){/*{{{*/
+
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	GaussTria* gauss=NULL;
+	IssmDouble  vx,vy,vel;
+	IssmDouble  strainparallel;
+	IssmDouble  propcoeff;
+	IssmDouble  strainperpendicular;
+	IssmDouble  calvingratex[NUMVERTICES];
+	IssmDouble  calvingratey[NUMVERTICES];
+	IssmDouble  calvingrate[NUMVERTICES];
+
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs and parameters we will need*/
+	Input* vx_input=inputs->GetInput(VxEnum);																		_assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);																		_assert_(vy_input);
+	Input* strainparallel_input=inputs->GetInput(StrainRateparallelEnum);								_assert_(strainparallel_input);
+	Input* strainperpendicular_input=inputs->GetInput(StrainRateperpendicularEnum);					_assert_(strainperpendicular_input);
+	Input* levermanncoeff_input=inputs->GetInput(CalvinglevermannCoeffEnum);                     _assert_(levermanncoeff_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/* Get the value we need*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel=vx*vx+vy*vy;
+		strainparallel_input->GetInputValue(&strainparallel,gauss);
+		strainperpendicular_input->GetInputValue(&strainperpendicular,gauss);
+		levermanncoeff_input->GetInputValue(&propcoeff,gauss);
+
+		/*Calving rate proportionnal to the positive product of the strain rate along the ice flow direction and the strain rate perpendicular to the ice flow */
+		calvingrate[iv]=propcoeff*strainparallel*strainperpendicular;
+		if(calvingrate[iv]<0){
+			calvingrate[iv]=0;
+		}
+		calvingratex[iv]=calvingrate[iv]*vx/(sqrt(vel)+1.e-14);
+		calvingratey[iv]=calvingrate[iv]*vy/(sqrt(vel)+1.e-14);
+	}
+
+	/*Add input*/
+	this->inputs->AddInput(new TriaInput(CalvingratexEnum,&calvingratex[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(CalvingrateyEnum,&calvingratey[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(CalvingCalvingrateEnum,&calvingrate[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+
+}
+/*}}}*/
+void       Tria::CalvingRatePi(){/*{{{*/
+
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	GaussTria* gauss=NULL;
+	IssmDouble  vx,vy,vel;
+	IssmDouble  strainparallel;
+	IssmDouble  sxx;
+	IssmDouble  sxy;
+	IssmDouble  syy;
+	IssmDouble  sigVM;
+	IssmDouble  thickness;
+	IssmDouble  base;
+	IssmDouble  hAB;
+	IssmDouble  propcoeff;
+	IssmDouble  calvingratex[NUMVERTICES];
+	IssmDouble  calvingratey[NUMVERTICES];
+	IssmDouble  calvingrate[NUMVERTICES];
+
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs and parameters we will need*/
+	Input* vx_input=inputs->GetInput(VxEnum);                                                    _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                                                    _assert_(vy_input);
+	Input* strainparallel_input=inputs->GetInput(StrainRateparallelEnum);                        _assert_(strainparallel_input);
+	Input* sxx_input=inputs->GetInput(DeviatoricStressxxEnum);                                   _assert_(sxx_input);
+	Input* sxy_input=inputs->GetInput(DeviatoricStressxyEnum);                                   _assert_(sxy_input);
+	Input* syy_input=inputs->GetInput(DeviatoricStressyyEnum);                                   _assert_(syy_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);                                      _assert_(thickness_input);
+	Input* base_input=inputs->GetInput(BaseEnum);                                                _assert_(base_input);
+	Input* picoeff_input=inputs->GetInput(CalvingpiCoeffEnum);                                   _assert_(picoeff_input);
+
+
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/* Get the value we need*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel=vx*vx+vy*vy;
+		strainparallel_input->GetInputValue(&strainparallel,gauss);
+		sxx_input->GetInputValue(&sxx,gauss);
+		sxy_input->GetInputValue(&sxy,gauss);
+		syy_input->GetInputValue(&syy,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+		base_input->GetInputValue(&base,gauss);
+		picoeff_input->GetInputValue(&propcoeff,gauss);
+
+		/* Computing sigma Von Mises*/
+		sigVM=sqrt(sxx*sxx+syy*syy+3*sxy*sxy-sxx*syy);
+
+		/* Computing heigth above buoyancy*/
+		hAB=thickness+1028/920*base;
+
+		/*Calving rate for Pi criterion proportionnal to the product of the strain rate along the ice flow direction and the Von Mises stress and the square of the glacier width (hardcoded) divided by the height above buoyancy and the max of the ice velocity power 3 and the ice density (ignored here)*/
+
+		calvingrate[iv]=propcoeff*strainparallel*sigVM*25.e6/hAB/1e9;
+		if(calvingrate[iv]<0){
+			calvingrate[iv]=0;
+		}
+		calvingrate[iv]=pow(calvingrate[iv],0.3);
+		calvingratex[iv]=calvingrate[iv]*vx/(sqrt(vel)+1.e-14);
+		calvingratey[iv]=calvingrate[iv]*vy/(sqrt(vel)+1.e-14);
+	}
+
+	/*Add input*/
+	this->inputs->AddInput(new TriaInput(CalvingratexEnum,&calvingratex[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(CalvingrateyEnum,&calvingratey[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(CalvingCalvingrateEnum,&calvingrate[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+
+}
+/*}}}*/
+void       Tria::CalvingRateDev(){/*{{{*/
+
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble  calvingratex[NUMVERTICES];
+	IssmDouble  calvingratey[NUMVERTICES];
+	IssmDouble  calvingrate[NUMVERTICES];
+	IssmDouble  lambda1,lambda2,ex,ey,vx,vy,vel;
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs and parameters we will need*/
+	Input* vx_input=inputs->GetInput(VxEnum);        _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);        _assert_(vy_input);
+
+	/* Start looping on the number of vertices: */
+	GaussTria* gauss=new GaussTria();
+	for(int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Get velocity components and thickness*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel=sqrt(vx*vx+vy*vy)+1.e-14;
+
+		/*Compute strain rate and viscosity: */
+		this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+
+		/*Get Eigen values*/
+		Matrix2x2Eigen(&lambda1,&lambda2,&ex,&ey,epsilon[0],epsilon[2],epsilon[1]);
+		_assert_(!xIsNan<IssmDouble>(lambda1));
+		_assert_(!xIsNan<IssmDouble>(lambda2));
+
+		/*Process Eigen values (only account for extension)*/
+		lambda1 = max(lambda1,0.);
+		lambda2 = max(lambda2,0.);
+
+		/*Assign values*/
+		calvingratex[iv]=vx*pow(lambda1 + lambda2,1./3.)*3.e+2;
+		calvingratey[iv]=vy*pow(lambda1 + lambda2,1./3.)*3.e+2;
+		calvingrate[iv]=sqrt(calvingratex[iv]*calvingratex[iv] + calvingratey[iv]*calvingratey[iv]);
+	}
+
+	/*Add input*/
+	this->inputs->AddInput(new TriaInput(CalvingratexEnum,&calvingratex[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(CalvingrateyEnum,&calvingratey[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(CalvingCalvingrateEnum,&calvingrate[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
 IssmDouble Tria::CharacteristicLength(void){/*{{{*/
 
@@ -164,9 +390,59 @@
 }
 /*}}}*/
+void       Tria::ComputeDeviatoricStressTensor(){/*{{{*/
+
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  viscosity;
+	IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+	IssmDouble  tau_xx[NUMVERTICES];
+	IssmDouble	tau_yy[NUMVERTICES];
+	IssmDouble	tau_zz[NUMVERTICES]={0,0,0};
+	IssmDouble  tau_xy[NUMVERTICES];
+	IssmDouble	tau_xz[NUMVERTICES]={0,0,0};
+	IssmDouble	tau_yz[NUMVERTICES]={0,0,0};
+	GaussTria*  gauss=NULL;
+	int domaintype,dim=2;
+
+	/* Get node coordinates and dof list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Retrieve all inputs we will be needing: */
+	this->FindParam(&domaintype,DomainTypeEnum);
+	if(domaintype!=Domain2DhorizontalEnum) _error_("deviatoric stress tensor calculation not implemented for mesh of type " <<EnumToStringx(domaintype));
+	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/*Compute strain rate and viscosity: */
+		this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->ViscositySSA(&viscosity,dim,&xyz_list[0][0],gauss,vx_input,vy_input);
+
+		/*Compute Stress*/
+		tau_xx[iv]=2*viscosity*epsilon[0]; // tau = nu eps
+		tau_yy[iv]=2*viscosity*epsilon[1];
+		tau_xy[iv]=2*viscosity*epsilon[2];
+	}
+
+	/*Add Stress tensor components into inputs*/
+	this->inputs->AddInput(new TriaInput(DeviatoricStressxxEnum,&tau_xx[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(DeviatoricStressxyEnum,&tau_xy[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(DeviatoricStressxzEnum,&tau_xz[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(DeviatoricStressyyEnum,&tau_yy[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(DeviatoricStressyzEnum,&tau_yz[0],P1Enum));
+	this->inputs->AddInput(new TriaInput(DeviatoricStresszzEnum,&tau_zz[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+}
+/*}}}*/
 void       Tria::ComputeSigmaNN(){/*{{{*/
 
 	if(!IsOnBase()){
-		IssmDouble sigma_nn=0;
-		this->inputs->AddInput(new TriaInput(SigmaNNEnum,&sigma_nn,P0Enum));
+		IssmDouble sigma_nn[3]={0.};
+		this->inputs->AddInput(new TriaInput(SigmaNNEnum,&sigma_nn[0],P1Enum));
 		return;
 	}
@@ -174,5 +450,6 @@
 		IssmDouble* xyz_list=NULL;
 		IssmDouble *xyz_list_base=NULL;
-		IssmDouble  pressure,viscosity,sigma_nn;
+		IssmDouble  pressure,viscosity;
+		IssmDouble  sigma_nn[3];
 		IssmDouble  sigma_xx,sigma_xy,sigma_yy;
 		IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
@@ -192,25 +469,27 @@
 
 		/* Start looping on the number of vertices: */
-		Gauss* gauss=NewGaussBase(1);
-		gauss->GaussPoint(0);
-
-		/*Compute strain rate viscosity and pressure: */
-		this->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
-		this->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,NULL);
-		pressure_input->GetInputValue(&pressure,gauss);
-
-		/*Compute Stress*/
-		sigma_xx=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
-		sigma_yy=2*viscosity*epsilon[1]-pressure;
-		sigma_xy=2*viscosity*epsilon[2];
-
-		/*Get normal vector to the bed */
-		NormalBase(&base_normal[0],xyz_list_base);
-
-		/*Compute sigma_nn*/
-		sigma_nn=sigma_xx*base_normal[0]*base_normal[0] + 2*sigma_xy*base_normal[0]*base_normal[1] + sigma_yy*base_normal[1]*base_normal[1];
+		Gauss* gauss = this->NewGauss();
+		for(int i=0;i<NUMVERTICES;i++){
+			gauss->GaussNode(P1Enum,i);
+
+			/*Compute strain rate viscosity and pressure: */
+			this->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+			this->ViscosityFS(&viscosity,dim,xyz_list,gauss,vx_input,vy_input,NULL);
+			pressure_input->GetInputValue(&pressure,gauss);
+
+			/*Compute Stress*/
+			sigma_xx=2*viscosity*epsilon[0]-pressure; // sigma = nu eps - pressure
+			sigma_yy=2*viscosity*epsilon[1]-pressure;
+			sigma_xy=2*viscosity*epsilon[2];
+
+			/*Get normal vector to the bed */
+			NormalBase(&base_normal[0],xyz_list_base);
+
+			/*Compute sigma_nn*/
+			sigma_nn[i]=sigma_xx*base_normal[0]*base_normal[0] + 2*sigma_xy*base_normal[0]*base_normal[1] + sigma_yy*base_normal[1]*base_normal[1];
+		}
 
 		/*Add Stress tensor components into inputs*/
-		this->inputs->AddInput(new TriaInput(SigmaNNEnum,&sigma_nn,P0Enum));
+		this->inputs->AddInput(new TriaInput(SigmaNNEnum,&sigma_nn[0],P1Enum));
 
 		/*Clean up and return*/
@@ -273,54 +552,4 @@
 }
 /*}}}*/
-void       Tria::ComputeDeviatoricStressTensor(){/*{{{*/
-
-	IssmDouble  xyz_list[NUMVERTICES][3];
-	IssmDouble  viscosity;
-	IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
-	IssmDouble  tau_xx[NUMVERTICES];
-	IssmDouble	tau_yy[NUMVERTICES];
-	IssmDouble	tau_zz[NUMVERTICES]={0,0,0};
-	IssmDouble  tau_xy[NUMVERTICES];
-	IssmDouble	tau_xz[NUMVERTICES]={0,0,0};
-	IssmDouble	tau_yz[NUMVERTICES]={0,0,0};
-	GaussTria*  gauss=NULL;
-	int domaintype,dim=2;
-
-	/* Get node coordinates and dof list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*Retrieve all inputs we will be needing: */
-	this->FindParam(&domaintype,DomainTypeEnum);
-	if(domaintype!=Domain2DhorizontalEnum) _error_("deviatoric stress tensor calculation not implemented for mesh of type " <<EnumToStringx(domaintype));
-	Input* vx_input=inputs->GetInput(VxEnum);             _assert_(vx_input);
-	Input* vy_input=inputs->GetInput(VyEnum);             _assert_(vy_input);
-
-	/* Start looping on the number of vertices: */
-	gauss=new GaussTria();
-	for (int iv=0;iv<NUMVERTICES;iv++){
-		gauss->GaussVertex(iv);
-
-		/*Compute strain rate and viscosity: */
-		this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
-		this->ViscositySSA(&viscosity,dim,&xyz_list[0][0],gauss,vx_input,vy_input);
-
-		/*Compute Stress*/
-		tau_xx[iv]=2*viscosity*epsilon[0]; // tau = nu eps
-		tau_yy[iv]=2*viscosity*epsilon[1];
-		tau_xy[iv]=2*viscosity*epsilon[2];
-	}
-
-	/*Add Stress tensor components into inputs*/
-	this->inputs->AddInput(new TriaInput(DeviatoricStressxxEnum,&tau_xx[0],P1Enum));
-	this->inputs->AddInput(new TriaInput(DeviatoricStressxyEnum,&tau_xy[0],P1Enum));
-	this->inputs->AddInput(new TriaInput(DeviatoricStressxzEnum,&tau_xz[0],P1Enum));
-	this->inputs->AddInput(new TriaInput(DeviatoricStressyyEnum,&tau_yy[0],P1Enum));
-	this->inputs->AddInput(new TriaInput(DeviatoricStressyzEnum,&tau_yz[0],P1Enum));
-	this->inputs->AddInput(new TriaInput(DeviatoricStresszzEnum,&tau_zz[0],P1Enum));
-
-	/*Clean up and return*/
-	delete gauss;
-}
-/*}}}*/
 void       Tria::Configure(Elements* elementsin, Loads* loadsin,Nodes* nodesin,Vertices *verticesin,Materials* materialsin, Parameters* parametersin){/*{{{*/
 
@@ -358,4 +587,52 @@
 }
 /*}}}*/
+void       Tria::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){/*{{{*/
+
+	int    vertexpidlist[NUMVERTICES];
+	IssmDouble grad_list[NUMVERTICES];
+	Input* grad_input=NULL;
+
+	Input* input=inputs->GetInput(enum_type);
+	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
+
+	GradientIndexing(&vertexpidlist[0],control_index);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
+	grad_input=new TriaInput(GradientEnum,grad_list,P1Enum);
+
+	((ControlInput*)input)->SetGradient(grad_input);
+
+}/*}}}*/
+void       Tria::ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){/*{{{*/
+
+	Input* input=inputs->GetInput(control_enum);
+	if (!input) _error_("Input " << EnumToStringx(control_enum) << " not found");
+	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(control_enum) << " is not a ControlInput");
+
+	int         sidlist[NUMVERTICES];
+	int         connectivity[NUMVERTICES];
+	IssmPDouble values[NUMVERTICES];
+	IssmPDouble gradients[NUMVERTICES]; 
+	IssmDouble  value,gradient;
+
+	this->GetVerticesConnectivityList(&connectivity[0]);
+	this->GetVerticesSidList(&sidlist[0]);
+
+	GaussTria* gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		((ControlInput*)input)->GetInputValue(&value,gauss);
+		((ControlInput*)input)->GetGradientValue(&gradient,gauss);
+
+		values[iv]    = reCast<IssmPDouble>(value)/reCast<IssmPDouble>(connectivity[iv]);
+		gradients[iv] = reCast<IssmPDouble>(gradient)/reCast<IssmPDouble>(connectivity[iv]);
+	}
+	delete gauss;
+
+	vector_control->SetValues(NUMVERTICES,&sidlist[0],&values[0],ADD_VAL);
+	vector_gradient->SetValues(NUMVERTICES,&sidlist[0],&gradients[0],ADD_VAL);
+
+}/*}}}*/
 void       Tria::Delta18oParameterization(void){/*{{{*/
 
@@ -385,5 +662,4 @@
 			input2->GetInputValue(&TemperaturesLgm[iv][month],gauss,month/12.*yts);
 			input3->GetInputValue(&PrecipitationsPresentday[iv][month],gauss,month/12.*yts);
-			PrecipitationsPresentday[iv][month]=PrecipitationsPresentday[iv][month]/yts; // converion in m/sec
 		}
 	}
@@ -428,4 +704,169 @@
 }
 /*}}}*/
+void       Tria::MungsmtpParameterization(void){/*{{{*/
+	/*Are we on the base? If not, return*/
+	if(!IsOnBase()) return;
+
+	int        i;
+	IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+	IssmDouble TemperaturesPresentday[NUMVERTICES][12],TemperaturesLgm[NUMVERTICES][12];
+	IssmDouble PrecipitationsPresentday[NUMVERTICES][12],PrecipitationsLgm[NUMVERTICES][12];
+	IssmDouble tmp[NUMVERTICES];
+	IssmDouble TdiffTime,PfacTime;
+	IssmDouble time,yts;
+	this->parameters->FindParam(&time,TimeEnum);
+	this->parameters->FindParam(&yts,ConstantsYtsEnum);
+
+	/*Recover present day temperature and precipitation*/
+	Input*     input=inputs->GetInput(SurfaceforcingsTemperaturesPresentdayEnum);    _assert_(input);
+	Input*     input2=inputs->GetInput(SurfaceforcingsTemperaturesLgmEnum);          _assert_(input2);
+	Input*     input3=inputs->GetInput(SurfaceforcingsPrecipitationsPresentdayEnum); _assert_(input3);
+	Input*     input4=inputs->GetInput(SurfaceforcingsPrecipitationsLgmEnum);        _assert_(input4);
+	GaussTria* gauss=new GaussTria();
+	for(int month=0;month<12;month++) {
+		for(int iv=0;iv<NUMVERTICES;iv++) {
+			gauss->GaussVertex(iv);
+			input->GetInputValue(&TemperaturesPresentday[iv][month],gauss,month/12.*yts);
+			input2->GetInputValue(&TemperaturesLgm[iv][month],gauss,month/12.*yts);
+			input3->GetInputValue(&PrecipitationsPresentday[iv][month],gauss,month/12.*yts);
+			input4->GetInputValue(&PrecipitationsLgm[iv][month],gauss,month/12.*yts);
+		}
+	}
+
+	/*Recover interpolation parameters at time t*/
+	this->parameters->FindParam(&TdiffTime,SurfaceforcingsTdiffEnum,time);
+	this->parameters->FindParam(&PfacTime,SurfaceforcingsPfacEnum,time);
+
+	/*Compute the temperature and precipitation*/
+	for(int iv=0;iv<NUMVERTICES;iv++){
+	  ComputeMungsmTemperaturePrecipitation(TdiffTime,PfacTime,
+					&PrecipitationsLgm[iv][0],&PrecipitationsPresentday[iv][0], 
+					&TemperaturesLgm[iv][0], &TemperaturesPresentday[iv][0], 
+					&monthlytemperatures[iv][0], &monthlyprec[iv][0]);
+	}
+
+	/*Update inputs*/ 
+	TransientInput* NewTemperatureInput = new TransientInput(SurfaceforcingsMonthlytemperaturesEnum);
+	TransientInput* NewPrecipitationInput = new TransientInput(SurfaceforcingsPrecipitationEnum);
+	for (int imonth=0;imonth<12;imonth++) {
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
+		TriaInput* newmonthinput1 = new TriaInput(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0],P1Enum);
+		NewTemperatureInput->AddTimeInput(newmonthinput1,time+imonth/12.*yts);
+
+		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlyprec[i][imonth];
+		TriaInput* newmonthinput2 = new TriaInput(SurfaceforcingsPrecipitationEnum,&tmp[0],P1Enum);
+		NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
+	}
+	NewTemperatureInput->Configure(this->parameters);
+	NewPrecipitationInput->Configure(this->parameters);
+
+	this->inputs->AddInput(NewTemperatureInput);
+	this->inputs->AddInput(NewPrecipitationInput);
+
+	/*clean-up*/
+	delete gauss;
+}
+/*}}}*/
+int        Tria::EdgeOnBaseIndex(void){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			return i;
+		}
+	}
+
+	_printf_("list of vertices on bed: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on bed");
+}
+/*}}}*/
+void       Tria::EdgeOnBaseIndices(int* pindex1,int* pindex2){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			*pindex1 = indices[i][0];
+			*pindex2 = indices[i][1];
+			return;
+		}
+	}
+
+	_printf_("list of vertices on bed: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on bed");
+}
+/*}}}*/
+int        Tria::EdgeOnSurfaceIndex(void){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			return i;
+		}
+	}
+
+	_printf_("list of vertices on surface: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on surface");
+}
+/*}}}*/
+void       Tria::EdgeOnSurfaceIndices(int* pindex1,int* pindex2){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	int        indices[3][2] = {{1,2},{2,0},{0,1}};
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+
+	for(int i=0;i<3;i++){
+		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
+			*pindex1 = indices[i][0];
+			*pindex2 = indices[i][1];
+			return;
+		}
+	}
+
+	_printf_("list of vertices on surface: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
+	_error_("Could not find 2 vertices on surface");
+}
+/*}}}*/
+void       Tria::ElementResponse(IssmDouble* presponse,int response_enum){/*{{{*/
+
+	switch(response_enum){
+		case MaterialsRheologyBbarEnum:
+			*presponse=this->material->GetBbar();
+			break;
+
+		case VelEnum:{
+
+			/*Get input:*/
+			IssmDouble vel;
+			Input* vel_input;
+
+			vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
+			vel_input->GetInputAverage(&vel);
+
+			/*Assign output pointers:*/
+			*presponse=vel;}
+			break;
+		default:  
+			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
+	}
+
+}
+/*}}}*/
 void       Tria::ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz){/*{{{*/
 
@@ -455,8 +896,88 @@
 }
 /*}}}*/
-int        Tria::ObjectEnum(void){/*{{{*/
-
-	return TriaEnum;
-
+void       Tria::FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating){/*{{{*/
+
+	if(!IsOnBase()) return;
+
+	int approximation;
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+
+	if(approximation==HOApproximationEnum || approximation==SSAApproximationEnum || approximation==SSAHOApproximationEnum){
+		for(int i=0;i<NUMVERTICES;i++){
+			vertexgrounded->SetValue(vertices[i]->Pid(),+9999.,INS_VAL);
+			vertexfloating->SetValue(vertices[i]->Pid(),+9999.,INS_VAL);
+		}
+	}
+	else{
+		/*Intermediaries*/
+		IssmDouble* xyz_list = NULL;
+		IssmDouble* xyz_list_base = NULL;
+		IssmDouble  pressure,water_pressure,sigma_nn,viscosity,bed,base;
+		IssmDouble  bed_normal[2];
+		IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+		IssmDouble  surface=0,value=0;
+		bool grounded;
+
+		/* Get node coordinates and dof list: */
+		GetVerticesCoordinates(&xyz_list);
+		GetVerticesCoordinatesBase(&xyz_list_base);
+
+		/*Retrieve all inputs we will be needing: */
+		Input* pressure_input = inputs->GetInput(PressureEnum); _assert_(pressure_input);
+		Input* base_input     = inputs->GetInput(BaseEnum);     _assert_(base_input);
+		Input* bed_input      = inputs->GetInput(BedEnum);      _assert_(bed_input);
+		Input* vx_input       = inputs->GetInput(VxEnum);       _assert_(vx_input);
+		Input* vy_input       = inputs->GetInput(VyEnum);       _assert_(vy_input);
+
+		/*Create gauss point in the middle of the basal edge*/
+		Gauss* gauss=NewGaussBase(1);
+		gauss->GaussPoint(0);
+
+		if(!IsFloating()){ 
+			/*Check for basal force only if grounded and touching GL*/
+			//		if(this->inputs->Min(MaskGroundediceLevelsetEnum)==0.){
+			this->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+			this->ViscosityFS(&viscosity,2,xyz_list,gauss,vx_input,vy_input,NULL);
+			pressure_input->GetInputValue(&pressure, gauss);
+			base_input->GetInputValue(&base, gauss); 
+
+			/*Compute Stress*/
+			IssmDouble sigma_xx=2.*viscosity*epsilon[0]-pressure;
+			IssmDouble sigma_yy=2.*viscosity*epsilon[1]-pressure;
+			IssmDouble sigma_xy=2.*viscosity*epsilon[2];
+
+			/*Get normal vector to the bed */
+			NormalBase(&bed_normal[0],xyz_list_base);
+
+			/*basalforce*/
+			sigma_nn = sigma_xx*bed_normal[0]*bed_normal[0] + sigma_yy*bed_normal[1]*bed_normal[1] + 2.*sigma_xy*bed_normal[0]*bed_normal[1];
+
+			/*Compute water pressure*/
+			IssmDouble rho_ice   = matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+			IssmDouble rho_water = matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+			IssmDouble gravity   = matpar->GetMaterialParameter(ConstantsGEnum);
+			water_pressure=gravity*rho_water*base;
+
+			/*Compare basal stress to water pressure and determine whether it should ground*/
+			if (sigma_nn<water_pressure) grounded=true;
+			else                         grounded=false;
+		}
+		else{
+			/*Check for basal elevation if floating*/
+			base_input->GetInputValue(&base, gauss);
+			bed_input->GetInputValue(&bed, gauss);
+			if(base<bed) grounded=true;
+			else         grounded=false;
+		}
+		for(int i=0;i<NUMVERTICES;i++){
+			if(grounded) vertexgrounded->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
+			else         vertexfloating->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
+		}
+
+		/*clean up*/
+		delete gauss;
+		xDelete<IssmDouble>(xyz_list);
+		xDelete<IssmDouble>(xyz_list_base);
+	}
 }
 /*}}}*/
@@ -476,4 +997,37 @@
 }
 /*}}}*/
+IssmDouble Tria::GetAreaIce(void){/*{{{*/
+
+	/*return area of element covered by ice*/
+	/*Intermediaries*/
+	int numiceverts;
+	IssmDouble area_fraction;
+	IssmDouble s[2]; // s:fraction of intersected triangle edges that lie inside ice
+	int* indices=NULL;
+
+	this->GetLevelsetIntersection(&indices, &numiceverts, s, MaskIceLevelsetEnum, 0.);
+
+	switch (numiceverts){
+		case 0: // no vertex has ice: element is ice free
+			area_fraction=0.;
+			break;
+		case 1: // one vertex has ice: get area of triangle
+			area_fraction=s[0]*s[1];
+			break;
+		case 2: // two vertices have ice: get area of quadrangle
+			area_fraction=s[0]+s[1]-s[0]*s[1];
+			break;
+		case NUMVERTICES: // all vertices have ice: return triangle area
+			area_fraction=1.;
+			break;
+		default:
+			_error_("Wrong number of ice vertices in Tria::GetAreaIce!");
+			break;
+	}
+	_assert_((area_fraction>=0.) && (area_fraction<=1.));
+
+	xDelete<int>(indices);
+	return area_fraction*this->GetArea();
+}/*}}}*/
 void       Tria::GetAreaCoordinates(IssmDouble* area_coordinates,IssmDouble* xyz_zero,IssmDouble* xyz_list,int numpoints){/*{{{*/
 	/*Computeportion of the element that is grounded*/ 
@@ -689,147 +1243,4 @@
 }
 /*}}}*/
-void       Tria::GetVerticesCoordinatesBase(IssmDouble** pxyz_list){/*{{{*/
-
-	int        indices[2];
-	IssmDouble xyz_list[NUMVERTICES][3];
-
-	/*Element XYZ list*/
-	::GetVerticesCoordinates(&xyz_list[0][0],this->vertices,NUMVERTICES);
-
-	/*Allocate Output*/
-	IssmDouble* xyz_list_edge = xNew<IssmDouble>(2*3);
-	this->EdgeOnBaseIndices(&indices[0],&indices[1]);
-	for(int i=0;i<2;i++) for(int j=0;j<2;j++) xyz_list_edge[i*3+j]=xyz_list[indices[i]][j];
-
-	/*Assign output pointer*/
-	*pxyz_list = xyz_list_edge;
-
-}/*}}}*/
-void       Tria::GetVerticesCoordinatesTop(IssmDouble** pxyz_list){/*{{{*/
-
-	int        indices[2];
-	IssmDouble xyz_list[NUMVERTICES][3];
-
-	/*Element XYZ list*/
-	::GetVerticesCoordinates(&xyz_list[0][0],this->vertices,NUMVERTICES);
-
-	/*Allocate Output*/
-	IssmDouble* xyz_list_edge = xNew<IssmDouble>(2*3);
-	this->EdgeOnSurfaceIndices(&indices[0],&indices[1]);
-	for(int i=0;i<2;i++) for(int j=0;j<2;j++) xyz_list_edge[i*3+j]=xyz_list[indices[i]][j];
-
-	/*Assign output pointer*/
-	*pxyz_list = xyz_list_edge;
-
-}/*}}}*/
-void       Tria::NormalSection(IssmDouble* normal,IssmDouble* xyz_list){/*{{{*/
-
-	/*Build unit outward pointing vector*/
-	IssmDouble vector[2];
-	IssmDouble norm;
-
-	vector[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
-	vector[1]=xyz_list[1*3+1] - xyz_list[0*3+1];
-
-	norm=sqrt(vector[0]*vector[0] + vector[1]*vector[1]);
-
-	normal[0]= + vector[1]/norm;
-	normal[1]= - vector[0]/norm;
-}
-/*}}}*/
-void       Tria::ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
-
-	int         normal_orientation=0;
-	IssmDouble  s1,s2;
-	IssmDouble  levelset[NUMVERTICES];
-
-	/*Recover parameters and values*/
-	IssmDouble* xyz_zero = xNew<IssmDouble>(2*3);
-	GetInputListOnVertices(&levelset[0],levelsetenum);
-
-	if(levelset[0]*levelset[1]>0.){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
-		/*Portion of the segments*/
-		s1=levelset[2]/(levelset[2]-levelset[1]);
-		s2=levelset[2]/(levelset[2]-levelset[0]);
-
-		if(levelset[2]<0.) normal_orientation=1; //orientation of quadrangle depending on distribution of levelsetfunction
-		/*New point 1*/
-		xyz_zero[3*normal_orientation+0]=xyz_list[2*3+0]+s1*(xyz_list[1*3+0]-xyz_list[2*3+0]);
-		xyz_zero[3*normal_orientation+1]=xyz_list[2*3+1]+s1*(xyz_list[1*3+1]-xyz_list[2*3+1]);
-		xyz_zero[3*normal_orientation+2]=xyz_list[2*3+2]+s1*(xyz_list[1*3+2]-xyz_list[2*3+2]);
-
-		/*New point 0*/
-		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[2*3+0]+s2*(xyz_list[0*3+0]-xyz_list[2*3+0]);
-		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[2*3+1]+s2*(xyz_list[0*3+1]-xyz_list[2*3+1]);
-		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[2*3+2]+s2*(xyz_list[0*3+2]-xyz_list[2*3+2]);
-	}
-	else if(levelset[1]*levelset[2]>0.){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
-		/*Portion of the segments*/
-		s1=levelset[0]/(levelset[0]-levelset[2]);
-		s2=levelset[0]/(levelset[0]-levelset[1]);
-
-		if(levelset[0]<0.) normal_orientation=1;
-		/*New point 1*/
-		xyz_zero[3*normal_orientation+0]=xyz_list[0*3+0]+s1*(xyz_list[2*3+0]-xyz_list[0*3+0]);
-		xyz_zero[3*normal_orientation+1]=xyz_list[0*3+1]+s1*(xyz_list[2*3+1]-xyz_list[0*3+1]);
-		xyz_zero[3*normal_orientation+2]=xyz_list[0*3+2]+s1*(xyz_list[2*3+2]-xyz_list[0*3+2]);
-
-		/*New point 2*/
-		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[0*3+0]+s2*(xyz_list[1*3+0]-xyz_list[0*3+0]);
-		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[0*3+1]+s2*(xyz_list[1*3+1]-xyz_list[0*3+1]);
-		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[0*3+2]+s2*(xyz_list[1*3+2]-xyz_list[0*3+2]);
-	}
-	else if(levelset[0]*levelset[2]>0.){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
-		/*Portion of the segments*/
-		s1=levelset[1]/(levelset[1]-levelset[0]);
-		s2=levelset[1]/(levelset[1]-levelset[2]);
-
-		if(levelset[1]<0.) normal_orientation=1;
-		/*New point 0*/
-		xyz_zero[3*normal_orientation+0]=xyz_list[1*3+0]+s1*(xyz_list[0*3+0]-xyz_list[1*3+0]);
-		xyz_zero[3*normal_orientation+1]=xyz_list[1*3+1]+s1*(xyz_list[0*3+1]-xyz_list[1*3+1]);
-		xyz_zero[3*normal_orientation+2]=xyz_list[1*3+2]+s1*(xyz_list[0*3+2]-xyz_list[1*3+2]);
-
-		/*New point 2*/
-		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[1*3+0]+s2*(xyz_list[2*3+0]-xyz_list[1*3+0]);
-		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[1*3+1]+s2*(xyz_list[2*3+1]-xyz_list[1*3+1]);
-		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[1*3+2]+s2*(xyz_list[2*3+2]-xyz_list[1*3+2]);
-	}
-	else if(levelset[0]==0. && levelset[1]==0.){ //front is on point 0 and 1
-		xyz_zero[3*0+0]=xyz_list[0*3+0];
-		xyz_zero[3*0+1]=xyz_list[0*3+1];
-		xyz_zero[3*0+2]=xyz_list[0*3+2];
-
-		/*New point 2*/
-		xyz_zero[3*1+0]=xyz_list[1*3+0];
-		xyz_zero[3*1+1]=xyz_list[1*3+1];
-		xyz_zero[3*1+2]=xyz_list[1*3+2];
-	}
-	else if(levelset[0]==0. && levelset[2]==0.){ //front is on point 0 and 1
-		xyz_zero[3*0+0]=xyz_list[2*3+0];
-		xyz_zero[3*0+1]=xyz_list[2*3+1];
-		xyz_zero[3*0+2]=xyz_list[2*3+2];
-
-		/*New point 2*/
-		xyz_zero[3*1+0]=xyz_list[0*3+0];
-		xyz_zero[3*1+1]=xyz_list[0*3+1];
-		xyz_zero[3*1+2]=xyz_list[0*3+2];
-	}
-	else if(levelset[1]==0. && levelset[2]==0.){ //front is on point 0 and 1
-		xyz_zero[3*0+0]=xyz_list[1*3+0];
-		xyz_zero[3*0+1]=xyz_list[1*3+1];
-		xyz_zero[3*0+2]=xyz_list[1*3+2];
-
-		/*New point 2*/
-		xyz_zero[3*1+0]=xyz_list[2*3+0];
-		xyz_zero[3*1+1]=xyz_list[2*3+1];
-		xyz_zero[3*1+2]=xyz_list[2*3+2];
-	}
-	else _error_("Case not covered");
-
-	/*Assign output pointer*/
-	*pxyz_zero= xyz_zero;
-}
-/*}}}*/
 void       Tria::GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
 	
@@ -872,4 +1283,16 @@
 	xDelete<int>(indicesfront);
 }/*}}}*/
+void       Tria::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){/*{{{*/
+
+	Input* input=inputs->GetInput(enumtype);
+	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
+
+	GaussTria* gauss=new GaussTria();
+	gauss->GaussVertex(this->GetNodeIndex(node));
+
+	input->GetInputValue(pvalue,gauss);
+	delete gauss;
+}
+/*}}}*/
 void       Tria::GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level){/*{{{*/
 
@@ -912,4 +1335,136 @@
 	xDelete<int>(indicesfront);
 }/*}}}*/
+void			Tria::GetLevelsetIntersection(int** pindices, int* pnumiceverts, IssmDouble* fraction, int levelset_enum, IssmDouble level){/*{{{*/
+	
+	/* GetLevelsetIntersection computes: 
+	 * 1. indices of element, sorted in [iceverts, noiceverts] in counterclockwise fashion,
+	 * 2. fraction of intersected triangle edges intersected by levelset, lying below level*/
+
+	/*Intermediaries*/
+	int i, numiceverts, numnoiceverts;
+	int ind0, ind1, lastindex;
+	int indices_ice[NUMVERTICES],indices_noice[NUMVERTICES];
+	IssmDouble lsf[NUMVERTICES];
+	int* indices = xNew<int>(NUMVERTICES);
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&lsf[0],levelset_enum);
+
+	/* Determine distribution of ice over element.
+	 * Exploit: ice/no-ice parts are connected, so find starting vertex of segment*/
+	lastindex=0;
+	for(i=0;i<NUMVERTICES;i++){ // go backwards along vertices, and check for sign change
+		ind0=(NUMVERTICES-i)%NUMVERTICES;
+		ind1=(ind0-1+NUMVERTICES)%NUMVERTICES;
+		if((lsf[ind0]-level)*(lsf[ind1]-level)<=0.){ // levelset has been crossed, find last index belonging to segment
+			if(lsf[ind1]==level) //if levelset intersects 2nd vertex, choose this vertex as last
+				lastindex=ind1;
+			else
+				lastindex=ind0;
+			break;
+		}
+	}
+
+	numiceverts=0;
+	numnoiceverts=0;
+	for(i=0;i<NUMVERTICES;i++){
+		ind0=(lastindex+i)%NUMVERTICES;
+		if(lsf[i]<=level){
+			indices_ice[numiceverts]=i;
+			numiceverts++;
+		}
+		else{
+			indices_noice[numnoiceverts]=i;
+			numnoiceverts++;
+		}
+	}
+	//merge indices 
+	for(i=0;i<numiceverts;i++){indices[i]=indices_ice[i];}
+	for(i=0;i<numnoiceverts;i++){indices[numiceverts+i]=indices_noice[i];}
+
+	switch (numiceverts){
+		case 0: // no vertex has ice: element is ice free, no intersection
+			for(i=0;i<2;i++)
+				fraction[i]=0.;
+			break;
+		case 1: // one vertex has ice:
+			for(i=0;i<2;i++){
+				fraction[i]=(level-lsf[indices[0]])/(lsf[indices[numiceverts+i]]-lsf[indices[0]]);
+			}
+			break;
+		case 2: // two vertices have ice: fraction is computed from first ice vertex to last in CCW fashion
+			for(i=0;i<2;i++){
+				fraction[i]=(level-lsf[indices[i]])/(lsf[indices[numiceverts]]-lsf[indices[i]]);
+			}
+			break;
+		case NUMVERTICES: // all vertices have ice: return triangle area
+			for(i=0;i<2;i++)
+				fraction[i]=1.;
+			break;
+		default:
+			_error_("Wrong number of ice vertices in Tria::GetLevelsetIntersection!");
+			break;
+	}
+
+	*pindices=indices;
+	*pnumiceverts=numiceverts;
+}
+/*}}}*/
+void       Tria::GetLevelsetPositivePart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlynegative,IssmDouble* gl){/*{{{*/
+	
+	/*Computeportion of the element that has a positive levelset*/ 
+
+	bool               negative=true;
+	int                point;
+	const IssmPDouble  epsilon= 1.e-15;
+	IssmDouble         f1,f2;
+
+	/*Be sure that values are not zero*/
+	if(gl[0]==0.) gl[0]=gl[0]+epsilon;
+	if(gl[1]==0.) gl[1]=gl[1]+epsilon;
+	if(gl[2]==0.) gl[2]=gl[2]+epsilon;
+
+	/*Check that not all nodes are positive or negative*/
+	if(gl[0]>0 && gl[1]>0 && gl[2]>0){ // All positive
+		point=0;
+		f1=1.;
+		f2=1.;
+	}
+	else if(gl[0]<0 && gl[1]<0 && gl[2]<0){ //All negative
+		point=0;
+		f1=0.;
+		f2=0.;
+	}
+	else{
+		if(gl[0]*gl[1]*gl[2]<0) negative=false;
+
+		if(gl[0]*gl[1]>0){ //Nodes 0 and 1 are similar, so points must be found on segment 0-2 and 1-2
+			point=2;
+			f1=gl[2]/(gl[2]-gl[0]);
+			f2=gl[2]/(gl[2]-gl[1]);
+		}
+		else if(gl[1]*gl[2]>0){ //Nodes 1 and 2 are similar, so points must be found on segment 0-1 and 0-2
+			point=0;
+			f1=gl[0]/(gl[0]-gl[1]);
+			f2=gl[0]/(gl[0]-gl[2]);
+		}
+		else if(gl[0]*gl[2]>0){ //Nodes 0 and 2 are similar, so points must be found on segment 1-0 and 1-2
+			point=1;
+			f1=gl[1]/(gl[1]-gl[2]);
+			f2=gl[1]/(gl[1]-gl[0]);
+		}
+	}
+	*point1=point;
+	*fraction1=f1;
+	*fraction2=f2;
+	*mainlynegative=negative;
+}
+/*}}}*/
+Node*      Tria::GetNode(int node_number){/*{{{*/
+	_assert_(node_number>=0); 
+	_assert_(node_number<this->NumberofNodes(this->element_type)); 
+	return this->nodes[node_number];
+
+}/*}}}*/
 int        Tria::GetNodeIndex(Node* node){/*{{{*/
 
@@ -935,22 +1490,274 @@
 }
 /*}}}*/
-void       Tria::GetInputValue(IssmDouble* pvalue,Node* node,int enumtype){/*{{{*/
-
-	Input* input=inputs->GetInput(enumtype);
-	if(!input) _error_("No input of type " << EnumToStringx(enumtype) << " found in tria");
-
+void       Tria::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){/*{{{*/
+
+	int        *doflist = NULL;
+	IssmDouble  value;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(this->element_type);
+
+	/*Fetch dof list and allocate solution vector*/
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values = xNew<IssmDouble>(numnodes);
+
+	/*Get inputs*/
+	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);
+
+	/*Ok, we have the values, fill in the array: */
 	GaussTria* gauss=new GaussTria();
-	gauss->GaussVertex(this->GetNodeIndex(node));
-
-	input->GetInputValue(pvalue,gauss);
+	for(int i=0;i<numnodes;i++){
+		gauss->GaussNode(this->element_type,i);
+
+		enum_input->GetInputValue(&value,gauss);
+		values[i]=value;
+	}
+
+	solution->SetValues(numnodes,doflist,values,INS_VAL);
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+	xDelete<IssmDouble>(values);
 	delete gauss;
 }
 /*}}}*/
-Node*      Tria::GetNode(int node_number){/*{{{*/
-	_assert_(node_number>=0); 
-	_assert_(node_number<this->NumberofNodes(this->element_type)); 
-	return this->nodes[node_number];
+void       Tria::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data,bool onsid){/*{{{*/
+
+	int vertexidlist[NUMVERTICES];
+	Input *input=NULL;
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexidlist[0],control_index,onsid);
+
+	/*Get input (either in element or material)*/
+	input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+
+	/*Check that it is a ControlInput*/
+	if (input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexidlist[0],data);
+}
+/*}}}*/
+void       Tria::GetVerticesCoordinatesBase(IssmDouble** pxyz_list){/*{{{*/
+
+	int        indices[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Element XYZ list*/
+	::GetVerticesCoordinates(&xyz_list[0][0],this->vertices,NUMVERTICES);
+
+	/*Allocate Output*/
+	IssmDouble* xyz_list_edge = xNew<IssmDouble>(2*3);
+	this->EdgeOnBaseIndices(&indices[0],&indices[1]);
+	for(int i=0;i<2;i++) for(int j=0;j<2;j++) xyz_list_edge[i*3+j]=xyz_list[indices[i]][j];
+
+	/*Assign output pointer*/
+	*pxyz_list = xyz_list_edge;
 
 }/*}}}*/
+void       Tria::GetVerticesCoordinatesTop(IssmDouble** pxyz_list){/*{{{*/
+
+	int        indices[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Element XYZ list*/
+	::GetVerticesCoordinates(&xyz_list[0][0],this->vertices,NUMVERTICES);
+
+	/*Allocate Output*/
+	IssmDouble* xyz_list_edge = xNew<IssmDouble>(2*3);
+	this->EdgeOnSurfaceIndices(&indices[0],&indices[1]);
+	for(int i=0;i<2;i++) for(int j=0;j<2;j++) xyz_list_edge[i*3+j]=xyz_list[indices[i]][j];
+
+	/*Assign output pointer*/
+	*pxyz_list = xyz_list_edge;
+
+}/*}}}*/
+bool       Tria::HasEdgeOnBase(){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
+	sum = values[0]+values[1]+values[2];
+
+	_assert_(sum==0. || sum==1. || sum==2.);
+
+	if(sum==3.)  _error_("Two edges on bed not supported yet...");
+
+	if(sum>1.){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
+bool       Tria::HasEdgeOnSurface(){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
+	sum = values[0]+values[1]+values[2];
+
+	_assert_(sum==0. || sum==1. || sum==2.);
+
+	if(sum==3.)  _error_("Two edges on surface not supported yet...");
+
+	if(sum>1.){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
+IssmDouble Tria::IceMass(void){/*{{{*/
+
+	IssmDouble rho_ice; 
+	
+	if(!IsIceInElement())return 0.; //do not contribute to the volume of the ice!
+
+	/*recover ice density: */
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+
+	return rho_ice*this->IceVolume();
+}
+/*}}}*/
+IssmDouble Tria::IceVolume(void){/*{{{*/
+
+	/*The volume of a truncated prism is area_base * 1/numedges sum(length of edges)*/
+
+	/*Intermediaries*/
+	int i, numiceverts;
+	IssmDouble area_base,surface,base,Haverage;
+	IssmDouble Haux[NUMVERTICES], surfaces[NUMVERTICES], bases[NUMVERTICES];
+	IssmDouble s[2]; // s:fraction of intersected triangle edges, that lies inside ice
+	int* indices=NULL;
+	IssmDouble* H=NULL;
+
+	if(!IsIceInElement())return 0.;
+
+	int domaintype;
+	parameters->FindParam(&domaintype,DomainTypeEnum);
+
+	if(false && IsIcefront()){
+		area_base=this->GetAreaIce();
+		//Assumption: linear ice thickness profile on element. 
+		//Hence ice thickness at intersection of levelset function with triangle edge is linear interpolation of ice thickness at vertices.
+		this->GetLevelsetIntersection(&indices, &numiceverts, s, MaskIceLevelsetEnum, 0.);
+		GetInputListOnVertices(&surfaces[0],SurfaceEnum);
+		GetInputListOnVertices(&bases[0],BaseEnum);
+		for(i=0;i<NUMVERTICES;i++) Haux[i]= surfaces[indices[i]]-bases[indices[i]]; //sort thicknesses in ice/noice
+		int numthk=numiceverts+2;
+		H=xNew<IssmDouble>(numthk);
+		switch(numiceverts){
+			case 1: // average over triangle 
+				H[0]=Haux[0];
+				H[1]=Haux[0]+s[0]*(Haux[1]-Haux[0]);
+				H[2]=Haux[0]+s[1]*(Haux[2]-Haux[0]);
+				break;
+			case 2: // average over quadrangle
+				H[0]=Haux[0];
+				H[1]=Haux[1];
+				H[2]=Haux[0]+s[0]*(Haux[2]-Haux[0]);
+				H[3]=Haux[1]+s[1]*(Haux[2]-Haux[1]);
+				break;
+			default:
+				_error_("Number of ice covered vertices wrong in Tria::IceVolume()");
+				break;
+		}
+		Haverage=0.;
+		for(i=0;i<numthk;i++)	Haverage+=H[i];
+		Haverage/=IssmDouble(numthk);
+	}
+	else{
+		/*First get back the area of the base*/
+		area_base=this->GetArea();
+
+		/*Now get the average height*/
+		Input* surface_input = inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+		Input* base_input     = inputs->GetInput(BaseEnum);     _assert_(base_input);
+		surface_input->GetInputAverage(&surface);
+		base_input->GetInputAverage(&base);
+		Haverage=surface-base;
+	}
+
+	/*Cleanup & return: */
+	xDelete<int>(indices);
+	xDelete<IssmDouble>(H);
+
+	if(domaintype==Domain2DverticalEnum){
+	  return area_base;
+	}
+	else{
+	  return area_base*Haverage;
+	}
+}
+/*}}}*/
+IssmDouble Tria::IceVolumeAboveFloatation(void){/*{{{*/
+
+	/*The volume above floatation: H + rho_water/rho_ice * bathymetry */
+	IssmDouble rho_ice,rho_water;
+	IssmDouble base,surface,bed,bathymetry;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	if(!IsIceInElement() || IsFloating())return 0;
+
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+	rho_water=matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Triangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
+
+	/*Now get the average height and bathymetry*/
+	Input* surface_input    = inputs->GetInput(SurfaceEnum);    _assert_(surface_input);
+	Input* base_input        = inputs->GetInput(BaseEnum);        _assert_(base_input);
+	Input* bed_input = inputs->GetInput(BedEnum); _assert_(bed_input);
+	surface_input->GetInputAverage(&surface);
+	base_input->GetInputAverage(&bed);
+	bed_input->GetInputAverage(&bathymetry);
+	
+	/*Return: */
+	return base*(surface-bed+min(rho_water/rho_ice*bathymetry,0.));
+}
+/*}}}*/
+void       Tria::InputControlUpdate(IssmDouble scalar,bool save_parameter){/*{{{*/
+
+	/*Intermediary*/
+	int    num_controls;
+	int*   control_type=NULL;
+	Input* input=NULL;
+
+	/*retrieve some parameters: */
+	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
+
+	for(int i=0;i<num_controls;i++){
+		input=(Input*)this->inputs->GetInput(control_type[i]);   _assert_(input);
+		if (input->ObjectEnum()!=ControlInputEnum){
+			_error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
+		}
+
+		((ControlInput*)input)->UpdateValue(scalar);
+		((ControlInput*)input)->Constrain();
+		if (save_parameter) ((ControlInput*)input)->SaveValue();
+
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(control_type);
+}
+/*}}}*/
 void       Tria::InputDepthAverageAtBase(int enum_type,int average_enum_type){/*{{{*/
 
@@ -1031,7 +1838,8 @@
 				/*No yts conversion*/
 				case ThicknessEnum:
+				case BalancethicknessOmegaEnum:
 				case FrictionCoefficientEnum:
-				case BalancethicknessNuxEnum:
-				case BalancethicknessNuyEnum:
+			  case FrictionAsEnum:
+			  case MaterialsRheologyBEnum:
 					if(iomodel->Data(control)){
 						for(j=0;j<NUMVERTICES;j++)nodeinputs[j]=iomodel->Data(control)[tria_vertex_ids[j]-1];
@@ -1135,5 +1943,4 @@
 
 	case NodesEnum:
-
 		/*Get number of nodes and dof list: */
 		numnodes = this->NumberofNodes(this->element_type);
@@ -1149,5 +1956,4 @@
 
 	case NodeSIdEnum:
-
 		/*Get number of nodes and dof list: */
 		numnodes = this->NumberofNodes(this->element_type);
@@ -1169,4 +1975,57 @@
 	xDelete<IssmDouble>(values);
 
+}
+/*}}}*/
+bool       Tria::IsFaceOnBoundary(void){/*{{{*/
+
+	IssmDouble values[NUMVERTICES];
+	IssmDouble sum;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&values[0],MeshVertexonboundaryEnum);
+	sum = values[0]+values[1]+values[2];
+
+	_assert_(sum==0. || sum==1. || sum==2.);
+
+	if(sum==3.)  _error_("Two edges on boundary not supported yet...");
+
+	if(sum>1.){
+		return true;
+	}
+	else{
+		return false;
+	}
+}/*}}}*/
+bool       Tria::IsIcefront(void){/*{{{*/
+
+	bool isicefront;
+	int i,nrice;
+   IssmDouble ls[NUMVERTICES];
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/* If only one vertex has ice, there is an ice front here */
+	isicefront=false;
+	if(IsIceInElement()){
+		nrice=0;       
+		for(i=0;i<NUMVERTICES;i++)
+			if(ls[i]<0.) nrice++;
+		if(nrice==1) isicefront= true;
+	}
+	return isicefront;
+}/*}}}*/
+bool       Tria::IsNodeOnShelfFromFlags(IssmDouble* flags){/*{{{*/
+
+	int  i;
+	bool shelf=false;
+
+	for(i=0;i<NUMVERTICES;i++){
+		if (flags[vertices[i]->Pid()]<0.){
+			shelf=true;
+			break;
+		}
+	}
+	return shelf;
 }
 /*}}}*/
@@ -1197,4 +2056,23 @@
 }
 /*}}}*/
+bool       Tria::IsZeroLevelset(int levelset_enum){/*{{{*/
+
+	bool iszerols;
+	IssmDouble ls[NUMVERTICES];
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],levelset_enum);
+
+	/*If the level set is awlays <0, there is no ice front here*/
+	iszerols= false;
+	if(IsIceInElement()){
+		if(ls[0]*ls[1]<0. || ls[0]*ls[2]<0. || (ls[0]*ls[1]*ls[2]==0. && ls[0]*ls[1]+ls[0]*ls[2]+ls[1]*ls[2]<=0.)){
+			iszerols = true;
+		}
+	}
+
+	return iszerols;
+}
+/*}}}*/
 void       Tria::JacobianDeterminant(IssmDouble* pJdet,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 
@@ -1225,213 +2103,265 @@
 }
 /*}}}*/
-bool       Tria::HasEdgeOnBase(){/*{{{*/
-
-	IssmDouble values[NUMVERTICES];
-	IssmDouble sum;
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
-	sum = values[0]+values[1]+values[2];
-
-	_assert_(sum==0. || sum==1. || sum==2.);
-
-	if(sum==3.)  _error_("Two edges on bed not supported yet...");
-
-	if(sum>1.){
-		return true;
-	}
-	else{
-		return false;
-	}
-}
-/*}}}*/
-bool       Tria::HasEdgeOnSurface(){/*{{{*/
-
-	IssmDouble values[NUMVERTICES];
-	IssmDouble sum;
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
-	sum = values[0]+values[1]+values[2];
-
-	_assert_(sum==0. || sum==1. || sum==2.);
-
-	if(sum==3.)  _error_("Two edges on surface not supported yet...");
-
-	if(sum>1.){
-		return true;
-	}
-	else{
-		return false;
-	}
-}
-/*}}}*/
-void       Tria::EdgeOnBaseIndices(int* pindex1,int* pindex2){/*{{{*/
-
-	IssmDouble values[NUMVERTICES];
-	int        indices[3][2] = {{1,2},{2,0},{0,1}};
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
-
-	for(int i=0;i<3;i++){
-		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
-			*pindex1 = indices[i][0];
-			*pindex2 = indices[i][1];
-			return;
-		}
-	}
-
-	_printf_("list of vertices on bed: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
-	_error_("Could not find 2 vertices on bed");
-}
-/*}}}*/
-void       Tria::EdgeOnSurfaceIndices(int* pindex1,int* pindex2){/*{{{*/
-
-	IssmDouble values[NUMVERTICES];
-	int        indices[3][2] = {{1,2},{2,0},{0,1}};
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
-
-	for(int i=0;i<3;i++){
-		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
-			*pindex1 = indices[i][0];
-			*pindex2 = indices[i][1];
-			return;
-		}
-	}
-
-	_printf_("list of vertices on surface: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
-	_error_("Could not find 2 vertices on surface");
-}
-/*}}}*/
-int        Tria::EdgeOnBaseIndex(void){/*{{{*/
-
-	IssmDouble values[NUMVERTICES];
-	int        indices[3][2] = {{1,2},{2,0},{0,1}};
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&values[0],MeshVertexonbaseEnum);
-
-	for(int i=0;i<3;i++){
-		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
-			return i;
-		}
-	}
-
-	_printf_("list of vertices on bed: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
-	_error_("Could not find 2 vertices on bed");
-}
-/*}}}*/
-int        Tria::EdgeOnSurfaceIndex(void){/*{{{*/
-
-	IssmDouble values[NUMVERTICES];
-	int        indices[3][2] = {{1,2},{2,0},{0,1}};
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&values[0],MeshVertexonsurfaceEnum);
-
-	for(int i=0;i<3;i++){
-		if(values[indices[i][0]] == 1. && values[indices[i][1]] == 1.){
-			return i;
-		}
-	}
-
-	_printf_("list of vertices on surface: "<<values[0]<<" "<<values[1]<<" "<<values[2]);
-	_error_("Could not find 2 vertices on surface");
-}
-/*}}}*/
-void       Tria::FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating){/*{{{*/
-
-	if(!IsOnBase()) return;
-
-	/*Intermediaries*/
-	IssmDouble* xyz_list = NULL;
-	IssmDouble* xyz_list_base = NULL;
-	IssmDouble  pressure,water_pressure,sigma_nn,viscosity,bed,base;
-	IssmDouble  bed_normal[2];
-	IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
-	IssmDouble  surface=0,value=0;
-	bool grounded;
+IssmDouble Tria::Masscon(IssmDouble* levelset){ /*{{{*/
+
+
+	/*intermediary: */
+	IssmDouble* values=NULL;
+	Input*      thickness_input=NULL;
+	IssmDouble  thickness;
+	IssmDouble  weight;
+	IssmDouble  Jdet;
+	IssmDouble  volume;
+	IssmDouble  rho_ice;
+	IssmDouble* xyz_list=NULL;
+	int         point1;
+	IssmDouble  fraction1,fraction2;
+	bool        mainlynegative=true;
+	
+	/*Output:*/
+	volume=0;
 
 	/* Get node coordinates and dof list: */
 	GetVerticesCoordinates(&xyz_list);
-	GetVerticesCoordinatesBase(&xyz_list_base);
+
+	/*Retrieve inputs required:*/
+	thickness_input=this->GetInput(ThicknessEnum); _assert_(thickness_input);
+	
+	/*Retrieve material parameters: */
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+
+	/*Retrieve values of the levelset defining the masscon: */
+	values = xNew<IssmDouble>(NUMVERTICES);
+	for(int i=0;i<NUMVERTICES;i++){
+		values[i]=levelset[this->vertices[i]->Sid()];
+	}
+		
+	/*Ok, use the level set values to figure out where we put our gaussian points:*/
+	this->GetLevelsetPositivePart(&point1,&fraction1,&fraction2,&mainlynegative,values);
+	Gauss* gauss = this->NewGauss(point1,fraction1,fraction2,mainlynegative,4);
+
+	volume=0;
+
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+		gauss->GaussPoint(ig);
+
+		this->JacobianDeterminant(&Jdet,xyz_list,gauss);
+		thickness_input->GetInputValue(&thickness, gauss);
+
+		volume+=thickness*gauss->weight*Jdet;
+	}
+
+	/* clean up and Return: */
+	xDelete<IssmDouble>(xyz_list);
+	xDelete<IssmDouble>(values);
+	delete gauss;
+	return rho_ice*volume;
+}
+/*}}}*/
+IssmDouble Tria::MassFlux(IssmDouble x1, IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){/*{{{*/
+
+	int        domaintype;
+	IssmDouble mass_flux=0.;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble normal[2];
+	IssmDouble length,rho_ice;
+	IssmDouble h1,h2;
+	IssmDouble vx1,vx2,vy1,vy2;
+	GaussTria* gauss_1=NULL;
+	GaussTria* gauss_2=NULL;
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+
+	/*First off, check that this segment belongs to this element: */
+	if (segment_id!=this->id)_error_("error message: segment with id " << segment_id << " does not belong to element with id:" << this->id);
+
+	/*Get xyz list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*get area coordinates of 0 and 1 locations: */
+	gauss_1=new GaussTria();
+	gauss_1->GaussFromCoords(x1,y1,&xyz_list[0][0]);
+	gauss_2=new GaussTria();
+	gauss_2->GaussFromCoords(x2,y2,&xyz_list[0][0]);
+
+	normal[0]=cos(atan2(x1-x2,y2-y1));
+	normal[1]=sin(atan2(x1-x2,y2-y1));
+
+	length=sqrt(pow(x2-x1,2)+pow(y2-y1,2));
+
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	this->parameters->FindParam(&domaintype,DomainTypeEnum);
+	Input* vx_input=NULL;
+	Input* vy_input=NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	}
+	else{
+		vx_input=inputs->GetInput(VxAverageEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyAverageEnum); _assert_(vy_input);
+	}
+
+	thickness_input->GetInputValue(&h1, gauss_1);
+	thickness_input->GetInputValue(&h2, gauss_2);
+	vx_input->GetInputValue(&vx1,gauss_1);
+	vx_input->GetInputValue(&vx2,gauss_2);
+	vy_input->GetInputValue(&vy1,gauss_1);
+	vy_input->GetInputValue(&vy2,gauss_2);
+
+	mass_flux= rho_ice*length*(  
+				(ONETHIRD*(h1-h2)*(vx1-vx2)+0.5*h2*(vx1-vx2)+0.5*(h1-h2)*vx2+h2*vx2)*normal[0]+
+				(ONETHIRD*(h1-h2)*(vy1-vy2)+0.5*h2*(vy1-vy2)+0.5*(h1-h2)*vy2+h2*vy2)*normal[1]
+				);
+
+	/*clean up and return:*/
+	delete gauss_1;
+	delete gauss_2;
+	return mass_flux;
+}
+/*}}}*/
+IssmDouble Tria::MassFlux(IssmDouble* segment){/*{{{*/
+
+	int        domaintype;
+	IssmDouble mass_flux=0.;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble normal[2];
+	IssmDouble length,rho_ice;
+	IssmDouble x1,y1,x2,y2,h1,h2;
+	IssmDouble vx1,vx2,vy1,vy2;
+	GaussTria* gauss_1=NULL;
+	GaussTria* gauss_2=NULL;
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+
+	/*First off, check that this segment belongs to this element: */
+	if (reCast<int>(*(segment+4))!=this->id)_error_("error message: segment with id " << reCast<int>(*(segment+4)) << " does not belong to element with id:" << this->id);
+
+	/*Recover segment node locations: */
+	x1=*(segment+0); y1=*(segment+1); x2=*(segment+2); y2=*(segment+3);
+
+	/*Get xyz list: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*get area coordinates of 0 and 1 locations: */
+	gauss_1=new GaussTria();
+	gauss_1->GaussFromCoords(x1,y1,&xyz_list[0][0]);
+	gauss_2=new GaussTria();
+	gauss_2->GaussFromCoords(x2,y2,&xyz_list[0][0]);
+
+	normal[0]=cos(atan2(x1-x2,y2-y1));
+	normal[1]=sin(atan2(x1-x2,y2-y1));
+
+	length=sqrt(pow(x2-x1,2)+pow(y2-y1,2));
+
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	this->parameters->FindParam(&domaintype,DomainTypeEnum);
+	Input* vx_input=NULL;
+	Input* vy_input=NULL;
+	if(domaintype==Domain2DhorizontalEnum){
+		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	}
+	else{
+		vx_input=inputs->GetInput(VxAverageEnum); _assert_(vx_input);
+		vy_input=inputs->GetInput(VyAverageEnum); _assert_(vy_input);
+	}
+
+	thickness_input->GetInputValue(&h1, gauss_1);
+	thickness_input->GetInputValue(&h2, gauss_2);
+	vx_input->GetInputValue(&vx1,gauss_1);
+	vx_input->GetInputValue(&vx2,gauss_2);
+	vy_input->GetInputValue(&vy1,gauss_1);
+	vy_input->GetInputValue(&vy2,gauss_2);
+
+	mass_flux= rho_ice*length*(  
+				(ONETHIRD*(h1-h2)*(vx1-vx2)+0.5*h2*(vx1-vx2)+0.5*(h1-h2)*vx2+h2*vx2)*normal[0]+
+				(ONETHIRD*(h1-h2)*(vy1-vy2)+0.5*h2*(vy1-vy2)+0.5*(h1-h2)*vy2+h2*vy2)*normal[1]
+				);
+
+	/*clean up and return:*/
+	delete gauss_1;
+	delete gauss_2;
+	return mass_flux;
+}
+/*}}}*/
+IssmDouble Tria::Misfit(int modelenum,int observationenum,int weightsenum){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble model,observation,weight;
+	IssmDouble Jdet;
+	IssmDouble Jelem = 0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	GaussTria *gauss = NULL;
+
+	/*If on water, return 0: */
+	if(!IsIceInElement())return 0;
 
 	/*Retrieve all inputs we will be needing: */
-	Input* pressure_input = inputs->GetInput(PressureEnum); _assert_(pressure_input);
-	Input* base_input     = inputs->GetInput(BaseEnum);     _assert_(base_input);
-	Input* bed_input      = inputs->GetInput(BedEnum);      _assert_(bed_input);
-	Input* vx_input       = inputs->GetInput(VxEnum);       _assert_(vx_input);
-	Input* vy_input       = inputs->GetInput(VyEnum);       _assert_(vy_input);
-
-	/*Create gauss point in the middle of the basal edge*/
-	Gauss* gauss=NewGaussBase(1);
-	gauss->GaussPoint(0);
-
-	if(!IsFloating()){ 
-		/*Check for basal force only if grounded and touching GL*/
-		if(this->inputs->Min(MaskGroundediceLevelsetEnum)==0.){
-			this->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
-			this->ViscosityFS(&viscosity,2,xyz_list,gauss,vx_input,vy_input,NULL);
-			pressure_input->GetInputValue(&pressure, gauss);
-			base_input->GetInputValue(&base, gauss); _assert_(base<0.);
-
-			/*Compute Stress*/
-			IssmDouble sigma_xx=2.*viscosity*epsilon[0]-pressure;
-			IssmDouble sigma_yy=2.*viscosity*epsilon[1]-pressure;
-			IssmDouble sigma_xy=2.*viscosity*epsilon[2];
-
-			/*Get normal vector to the bed */
-			NormalBase(&bed_normal[0],xyz_list_base);
-
-			/*basalforce*/
-			sigma_nn = sigma_xx*bed_normal[0]*bed_normal[0] + sigma_yy*bed_normal[1]*bed_normal[1] + 2.*sigma_xy*bed_normal[0]*bed_normal[1];
-
-			/*Compute water pressure*/
-			IssmDouble rho_ice   = matpar->GetRhoIce();
-			IssmDouble rho_water = matpar->GetRhoWater();
-			IssmDouble gravity   = matpar->GetG();
-			water_pressure=gravity*rho_water*base;
-
-			/*Compare basal stress to water pressure and determine whether it should ground*/
-			if (sigma_nn<water_pressure) grounded=true;
-			else                         grounded=false;
-		}
-		else{
-			grounded=true;
-		}
-	}
-	else{
-		/*Check for basal elevation if floating*/
-		base_input->GetInputValue(&base, gauss);
-		bed_input->GetInputValue(&bed, gauss);
-		if (base<bed) grounded=true;
-		else          grounded=false;
-	}
-	for(int i=0;i<NUMVERTICES;i++){
-		if(grounded) vertexgrounded->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
-		else         vertexfloating->SetValue(vertices[i]->Pid(),+1.,INS_VAL);
-	}
-
-	/*clean up*/
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* model_input=inputs->GetInput(modelenum);   _assert_(model_input);
+	Input* observation_input=inputs->GetInput(observationenum);_assert_(observation_input);
+	Input* weights_input     =inputs->GetInput(weightsenum);     _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get parameters at gauss point*/
+		model_input->GetInputValue(&model,gauss);
+		observation_input->GetInputValue(&observation,gauss);
+		weights_input->GetInputValue(&weight,gauss);
+
+		/*compute misfit between model and observation */
+		Jelem+=0.5*(model-observation)*(model-observation)*Jdet*weight*gauss->weight;
+	}
+
+	/* clean up and Return: */
 	delete gauss;
-	xDelete<IssmDouble>(xyz_list);
-	xDelete<IssmDouble>(xyz_list_base);
-}
-/*}}}*/
-bool       Tria::IsNodeOnShelfFromFlags(IssmDouble* flags){/*{{{*/
-
-	int  i;
-	bool shelf=false;
-
-	for(i=0;i<NUMVERTICES;i++){
-		if (flags[vertices[i]->Pid()]<0.){
-			shelf=true;
-			break;
-		}
-	}
-	return shelf;
+	return Jelem;
+}
+/*}}}*/
+IssmDouble Tria::MisfitArea(int weightsenum){/*{{{*/
+
+	/*Intermediaries*/
+	IssmDouble weight;
+	IssmDouble Jdet;
+	IssmDouble Jelem = 0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	GaussTria *gauss = NULL;
+
+	/*If on water, return 0: */
+	if(!IsIceInElement())return 0;
+
+	/*Retrieve all inputs we will be needing: */
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* weights_input     =inputs->GetInput(weightsenum);     _assert_(weights_input);
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+
+		/*Get parameters at gauss point*/
+		weights_input->GetInputValue(&weight,gauss);
+
+		/*compute misfit between model and observation */
+		Jelem+=Jdet*weight*gauss->weight;
+	}
+
+	/* clean up and Return: */
+	delete gauss;
+	return Jelem;
 }
 /*}}}*/
@@ -1484,4 +2414,25 @@
 }
 /*}}}*/
+void       Tria::NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss,this->element_type);
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss,this->VelocityInterpolation());
+
+}
+/*}}}*/
+void       Tria::NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctions(basis,(GaussTria*)gauss,this->PressureInterpolation());
+
+}
+/*}}}*/
 void       Tria::NodalFunctionsP1(IssmDouble* basis, Gauss* gauss){/*{{{*/
 
@@ -1491,4 +2442,11 @@
 }
 /*}}}*/
+void       Tria::NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+
+	_assert_(gauss->Enum()==GaussTriaEnum);
+	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss,P1Enum);
+
+}
+/*}}}*/
 void       Tria::NodalFunctionsP2(IssmDouble* basis, Gauss* gauss){/*{{{*/
 
@@ -1498,22 +2456,8 @@
 }
 /*}}}*/
-void       Tria::NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+void       Tria::NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss){/*{{{*/
 
 	_assert_(gauss->Enum()==GaussTriaEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss,this->element_type);
-
-}
-/*}}}*/
-void       Tria::NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussTriaEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss,P1Enum);
-
-}
-/*}}}*/
-void       Tria::NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussTriaEnum);
-	this->GetNodalFunctionsDerivatives(dbasis,xyz_list,(GaussTria*)gauss,this->VelocityInterpolation());
+	this->GetNodalFunctions(basis,(GaussTria*)gauss,this->TensorInterpolation());
 
 }
@@ -1523,18 +2467,4 @@
 	_assert_(gauss->Enum()==GaussTriaEnum);
 	this->GetNodalFunctions(basis,(GaussTria*)gauss,this->VelocityInterpolation());
-
-}
-/*}}}*/
-void       Tria::NodalFunctionsPressure(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussTriaEnum);
-	this->GetNodalFunctions(basis,(GaussTria*)gauss,this->PressureInterpolation());
-
-}
-/*}}}*/
-void       Tria::NodalFunctionsTensor(IssmDouble* basis, Gauss* gauss){/*{{{*/
-
-	_assert_(gauss->Enum()==GaussTriaEnum);
-	this->GetNodalFunctions(basis,(GaussTria*)gauss,this->TensorInterpolation());
 
 }
@@ -1588,4 +2518,19 @@
 }
 /*}}}*/
+void       Tria::NormalSection(IssmDouble* normal,IssmDouble* xyz_list){/*{{{*/
+
+	/*Build unit outward pointing vector*/
+	IssmDouble vector[2];
+	IssmDouble norm;
+
+	vector[0]=xyz_list[1*3+0] - xyz_list[0*3+0];
+	vector[1]=xyz_list[1*3+1] - xyz_list[0*3+1];
+
+	norm=sqrt(vector[0]*vector[0] + vector[1]*vector[1]);
+
+	normal[0]= + vector[1]/norm;
+	normal[1]= - vector[0]/norm;
+}
+/*}}}*/
 void       Tria::NormalTop(IssmDouble* top_normal,IssmDouble* xyz_list){/*{{{*/
 
@@ -1606,6 +2551,8 @@
 }
 /*}}}*/
-int        Tria::VelocityInterpolation(void){/*{{{*/
-	return TriaRef::VelocityInterpolation(this->element_type);
+int        Tria::ObjectEnum(void){/*{{{*/
+
+	return TriaEnum;
+
 }
 /*}}}*/
@@ -1614,8 +2561,4 @@
 }
 /*}}}*/
-int        Tria::TensorInterpolation(void){/*{{{*/
-	return TriaRef::TensorInterpolation(this->element_type);
-}
-/*}}}*/
 int        Tria::NumberofNodesPressure(void){/*{{{*/
 	return TriaRef::NumberofNodes(this->PressureInterpolation());
@@ -1626,12 +2569,26 @@
 }
 /*}}}*/
-void       Tria::PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm){/*{{{*/
-
+void       Tria::PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm){/*{{{*/
+ 
+   int        i;
    IssmDouble agd[NUMVERTICES];             // surface mass balance
    IssmDouble monthlytemperatures[NUMVERTICES][12],monthlyprec[NUMVERTICES][12];
+   IssmDouble tmp[NUMVERTICES];
    IssmDouble h[NUMVERTICES],s[NUMVERTICES];
-   IssmDouble rho_water,rho_ice,desfac,s0p;
-
-   /*Recover monthly temperatures and precipitation*/
+   IssmDouble rho_water,rho_ice,desfac,s0p,s0t,rlaps,rlapslgm;
+   IssmDouble PfacTime,TdiffTime,sealevTime;
+   
+   /*Get material parameters :*/
+   rho_water=matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+   rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+
+  /*Get some pdd parameters*/
+  desfac=matpar->GetMaterialParameter(SurfaceforcingsDesfacEnum);
+  s0p=matpar->GetMaterialParameter(SurfaceforcingsS0pEnum);
+  s0t=matpar->GetMaterialParameter(SurfaceforcingsS0tEnum);
+  rlaps=matpar->GetMaterialParameter(SurfaceforcingsRlapsEnum);
+  rlapslgm=matpar->GetMaterialParameter(SurfaceforcingsRlapslgmEnum);
+
+   /*Recover monthly temperatures and precipitation and Present day and LGm ones*/
    Input*     input=inputs->GetInput(SurfaceforcingsMonthlytemperaturesEnum); _assert_(input);
    Input*     input2=inputs->GetInput(SurfaceforcingsPrecipitationEnum); _assert_(input2);
@@ -1640,4 +2597,6 @@
    this->parameters->FindParam(&time,TimeEnum);
    this->parameters->FindParam(&yts,ConstantsYtsEnum);
+
+
    for(int month=0;month<12;month++) {
      for(int iv=0;iv<NUMVERTICES;iv++) {
@@ -1646,31 +2605,85 @@
        monthlytemperatures[iv][month]=monthlytemperatures[iv][month]-273.15; // conversion from Kelvin to celcius
        input2->GetInputValue(&monthlyprec[iv][month],gauss,time+month/12.*yts);
-       monthlyprec[iv][month]=monthlyprec[iv][month]*yts; // convertion in m/y
      }
    }
+
+  /*Recover Pfac, Tdiff and sealev at time t:
+    This parameters are used to interpolate the temperature 
+    and precipitaton between PD and LGM when ismungsm==1 */ 
+  if (ismungsm==1){  
+    this->parameters->FindParam(&TdiffTime,SurfaceforcingsTdiffEnum,time);
+    this->parameters->FindParam(&sealevTime,SurfaceforcingsSealevEnum,time);
+  }
+  else {
+    TdiffTime=0;
+    sealevTime=0;  
+  }
 
   /*Recover info at the vertices: */
   GetInputListOnVertices(&h[0],ThicknessEnum);
   GetInputListOnVertices(&s[0],SurfaceEnum);
-
-  /*Get material parameters :*/
-  rho_ice=matpar->GetRhoIce();
-  rho_water=matpar->GetRhoFreshwater();
-
-  /*Get desertification effect parameters*/
-  desfac=matpar->GetDesFac();
-  s0p=matpar->GetS0p();
-
+     
    /*measure the surface mass balance*/
-   for (int iv = 0; iv<NUMVERTICES; iv++){
-     agd[iv]=PddSurfaceMassBlance(&monthlytemperatures[iv][0], &monthlyprec[iv][0], pdds, pds, signorm, yts, h[iv], s[iv], rho_ice, rho_water, desfac, s0p);
+  for (int iv = 0; iv<NUMVERTICES; iv++){
+     agd[iv]=PddSurfaceMassBalance(&monthlytemperatures[iv][0], &monthlyprec[iv][0],
+				  pdds, pds, signorm, yts, h[iv], s[iv],
+				  desfac, s0t, s0p,rlaps,rlapslgm,TdiffTime,sealevTime,
+				  rho_water,rho_ice);
    }
 
    /*Update inputs*/    
+   // TransientInput* NewTemperatureInput = new TransientInput(SurfaceforcingsMonthlytemperaturesEnum);
+   // TransientInput* NewPrecipitationInput = new TransientInput(SurfaceforcingsPrecipitationEnum);
+   // for (int imonth=0;imonth<12;imonth++) {
+   //   for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
+   //   TriaInput* newmonthinput1 = new TriaInput(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0],P1Enum);
+   //   NewTemperatureInput->AddTimeInput(newmonthinput1,time+imonth/12.*yts);
+   // 
+   //   for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlyprec[i][imonth];
+   //   TriaInput* newmonthinput2 = new TriaInput(SurfaceforcingsPrecipitationEnum,&tmp[0],P1Enum);
+   //   NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
+   // }
+   // NewTemperatureInput->Configure(this->parameters);
+   // NewPrecipitationInput->Configure(this->parameters);
+
+
    this->inputs->AddInput(new TriaInput(SurfaceforcingsMassBalanceEnum,&agd[0],P1Enum));
+   // this->inputs->AddInput(NewTemperatureInput);
+   // this->inputs->AddInput(NewPrecipitationInput);
    // this->inputs->AddInput(new TriaVertexInput(ThermalSpcTemperatureEnum,&Tsurf[0]));
+
+   //this->InputExtrude(SurfaceforcingsMassBalanceEnum,-1);
+   // this->InputExtrude(SurfaceforcingsMonthlytemperaturesEnum,-1);
+   // this->InputExtrude(SurfaceforcingsPrecipitationEnum,-1);
 
 	/*clean-up*/
 	delete gauss;
+}
+/*}}}*/
+void       Tria::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){/*{{{*/
+
+	IssmDouble  h[NUMVERTICES],r[NUMVERTICES],gl[NUMVERTICES];
+	IssmDouble  bed_hydro;
+	IssmDouble  rho_water,rho_ice,density;
+
+	/*material parameters: */
+	rho_water=matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+	density=rho_ice/rho_water;
+	GetInputListOnVertices(&h[0],ThicknessEnum);
+	GetInputListOnVertices(&r[0],BedEnum);
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
+
+	/*go through vertices, and figure out which ones are grounded and want to unground: */
+	for(int i=0;i<NUMVERTICES;i++){
+		/*Find if grounded vertices want to start floating*/
+		if (gl[i]>0.){
+			bed_hydro=-density*h[i];
+			if(bed_hydro>r[i]){
+				/*Vertex that could potentially unground, flag it*/
+				potential_ungrounding->SetValue(vertices[i]->Pid(),1,INS_VAL);
+			}
+		}
+	}
 }
 /*}}}*/
@@ -1726,5 +2739,4 @@
 	if(!HasNodeOnBase() ||  approximation!=FSApproximationEnum) return;
 
-	//printf("element number %i \n",this->id);
 	/*Get inputs*/
 	Input* slope_input=inputs->GetInput(BedSlopeXEnum);                             _assert_(slope_input);
@@ -1747,4 +2759,5 @@
 			xz_plane[1]=sin(theta);       xz_plane[4]=0.;  
 			xz_plane[2]=0.;               xz_plane[5]=1.;          
+
 			if(groundedice>=0){
 				this->nodes[i]->DofInSSet(1); //vy
@@ -1785,29 +2798,60 @@
 }
 /*}}}*/
-Seg*       Tria::SpawnSeg(int index1,int index2){/*{{{*/
-
+void       Tria::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){/*{{{*/
+
+	IssmDouble  values[NUMVERTICES];
+	int         vertexpidlist[NUMVERTICES],control_init;
+
+
+	/*Get Domain type*/
+	int domaintype;
+	parameters->FindParam(&domaintype,DomainTypeEnum);
+
+	/*Specific case for depth averaged quantities*/
+	control_init=control_enum;
+	if(domaintype==Domain2DverticalEnum){
+		if(control_enum==MaterialsRheologyBbarEnum){
+			control_enum=MaterialsRheologyBEnum;
+			if(!IsOnBase()) return;
+		}
+		if(control_enum==DamageDbarEnum){
+			control_enum=DamageDEnum;
+			if(!IsOnBase()) return;
+		}
+	}
+
+	/*Get out if this is not an element input*/
+	if(!IsInput(control_enum)) return;
+
+	/*Prepare index list*/
+	GradientIndexing(&vertexpidlist[0],control_index);
+
+	/*Get values on vertices*/
+	for(int i=0;i<NUMVERTICES;i++){
+		values[i]=vector[vertexpidlist[i]];
+	}
+	Input* new_input = new TriaInput(control_enum,values,P1Enum);
+	Input* input     = (Input*)this->inputs->GetInput(control_enum);   _assert_(input);
+	if(input->ObjectEnum()!=ControlInputEnum){
+		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
+	}
+
+	((ControlInput*)input)->SetInput(new_input);
+}
+/*}}}*/
+void       Tria::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
+
+	/*go into parameters and get the analysis_counter: */
 	int analysis_counter;
-
-	/*go into parameters and get the analysis_counter: */
-	this->parameters->FindParam(&analysis_counter,AnalysisCounterEnum);
-
-	/*Create Seg*/
-	Seg* seg=new Seg();
-	seg->id=this->id;
-	seg->inputs=(Inputs*)this->inputs->SpawnSegInputs(index1,index2);
-	seg->parameters=this->parameters;
-	seg->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
-	this->SpawnSegHook(dynamic_cast<ElementHook*>(seg),index1,index2);
-
-	/*Spawn material*/
-	seg->material=(Material*)this->material->copy2(seg);
-
-	/*recover nodes, material and matpar: */
-	seg->nodes    = (Node**)seg->hnodes[analysis_counter]->deliverp();
-	seg->vertices = (Vertex**)seg->hvertices->deliverp();
-	seg->matpar   = (Matpar*)seg->hmatpar->delivers();
-
-	/*Return new Seg*/
-	return seg;
+	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Get Element type*/
+	if(this->element_type_list) this->element_type=this->element_type_list[analysis_counter];
+
+	/*Pick up nodes*/
+	if(this->hnodes && this->hnodes[analysis_counter]){
+		this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
+	}
+
 }
 /*}}}*/
@@ -1830,4 +2874,31 @@
 }
 /*}}}*/
+Seg*       Tria::SpawnSeg(int index1,int index2){/*{{{*/
+
+	int analysis_counter;
+
+	/*go into parameters and get the analysis_counter: */
+	this->parameters->FindParam(&analysis_counter,AnalysisCounterEnum);
+
+	/*Create Seg*/
+	Seg* seg=new Seg();
+	seg->id=this->id;
+	seg->inputs=(Inputs*)this->inputs->SpawnSegInputs(index1,index2);
+	seg->parameters=this->parameters;
+	seg->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
+	this->SpawnSegHook(xDynamicCast<ElementHook*>(seg),index1,index2);
+
+	/*Spawn material*/
+	seg->material=(Material*)this->material->copy2(seg);
+
+	/*recover nodes, material and matpar: */
+	seg->nodes    = (Node**)seg->hnodes[analysis_counter]->deliverp();
+	seg->vertices = (Vertex**)seg->hvertices->deliverp();
+	seg->matpar   = (Matpar*)seg->hmatpar->delivers();
+
+	/*Return new Seg*/
+	return seg;
+}
+/*}}}*/
 Element*   Tria::SpawnTopElement(void){/*{{{*/
 
@@ -1848,18 +2919,94 @@
 }
 /*}}}*/
-void       Tria::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, Nodes* nodesin, Materials* materialsin, Parameters* parametersin){/*{{{*/
-
-	/*go into parameters and get the analysis_counter: */
-	int analysis_counter;
-	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
-
-	/*Get Element type*/
-	if(this->element_type_list) this->element_type=this->element_type_list[analysis_counter];
-
-	/*Pick up nodes*/
-	if(this->hnodes && this->hnodes[analysis_counter]){
-		this->nodes=(Node**)this->hnodes[analysis_counter]->deliverp();
-	}
-
+void       Tria::StrainRateparallel(){/*{{{*/
+
+	IssmDouble *xyz_list = NULL;
+	IssmDouble  epsilon[3];
+	GaussTria* gauss=NULL;
+	IssmDouble  vx,vy,vel;
+	IssmDouble  strainxx;
+	IssmDouble  strainxy;
+	IssmDouble  strainyy;
+	IssmDouble  strainparallel[NUMVERTICES];
+
+	/* Get node coordinates and dof list: */
+	this->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will need*/
+	Input* vx_input=inputs->GetInput(VxEnum);                                  _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                                  _assert_(vy_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/* Get the value we need*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel=vx*vx+vy*vy;
+
+		/*Compute strain rate viscosity and pressure: */
+		this->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		strainxx=epsilon[0];
+		strainyy=epsilon[1];
+		strainxy=epsilon[2];
+
+		/*strainparallel= Strain rate along the ice flow direction */
+		strainparallel[iv]=(vx*vx*(strainxx)+vy*vy*(strainyy)+2*vy*vx*strainxy)/(vel+1.e-14);
+	}
+
+	/*Add input*/
+	this->inputs->AddInput(new TriaInput(StrainRateparallelEnum,&strainparallel[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
+}
+/*}}}*/
+void       Tria::StrainRateperpendicular(){/*{{{*/
+
+	IssmDouble *xyz_list = NULL;
+	GaussTria* gauss=NULL;
+	IssmDouble  epsilon[3];
+	IssmDouble  vx,vy,vel;
+	IssmDouble  strainxx;
+	IssmDouble  strainxy;
+	IssmDouble  strainyy;
+	IssmDouble  strainperpendicular[NUMVERTICES];
+
+	/* Get node coordinates and dof list: */
+	this->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will need*/
+	Input* vx_input=inputs->GetInput(VxEnum);                                  _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum);                                  _assert_(vy_input);
+
+	/* Start looping on the number of vertices: */
+	gauss=new GaussTria();
+	for (int iv=0;iv<NUMVERTICES;iv++){
+		gauss->GaussVertex(iv);
+
+		/* Get the value we need*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vel=vx*vx+vy*vy;
+
+		/*Compute strain rate viscosity and pressure: */
+		this->StrainRateSSA(&epsilon[0],xyz_list,gauss,vx_input,vy_input);
+		strainxx=epsilon[0];
+		strainyy=epsilon[1];
+		strainxy=epsilon[2];
+
+		/*strainperpendicular= Strain rate perpendicular to the ice flow direction */
+		strainperpendicular[iv]=(vx*vx*(strainyy)+vy*vy*(strainxx)-2*vy*vx*strainxy)/(vel+1.e-14);
+	}
+
+	/*Add input*/
+	this->inputs->AddInput(new TriaInput(StrainRateperpendicularEnum,&strainperpendicular[0],P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+	xDelete<IssmDouble>(xyz_list);
 }
 /*}}}*/
@@ -1889,4 +3036,8 @@
 	/*Return: */
 	return S;
+}
+/*}}}*/
+int        Tria::TensorInterpolation(void){/*{{{*/
+	return TriaRef::TensorInterpolation(this->element_type);
 }
 /*}}}*/
@@ -1930,4 +3081,32 @@
 
 	return dt;
+}
+/*}}}*/
+IssmDouble Tria::TotalSmb(void){/*{{{*/
+
+	/*The smb[kg yr-1] of one element is area[m2] * smb [kg m^-2 yr^-1]*/
+	IssmDouble base,smb,rho_ice;
+	IssmDouble Total_Smb=0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Get material parameters :*/
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+
+   if(!IsIceInElement())return 0;
+
+	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*First calculate the area of the base (cross section triangle)
+	 * http://en.wikipedia.org/wiki/Triangle
+	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
+	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));	// area of element in m2
+
+	/*Now get the average SMB over the element*/
+	Input* smb_input = inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(smb_input);
+	smb_input->GetInputAverage(&smb);																								// average smb on element in m ice s-1
+   Total_Smb=rho_ice*base*smb;																											// smb on element in kg s-1
+
+	/*Return: */
+	return Total_Smb;
 }
 /*}}}*/
@@ -2052,4 +3231,15 @@
 			tria_node_ids[9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->numberofelements+3*index+3;
 			break;
+		case LACrouzeixRaviartEnum:
+			numnodes        = 7;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+iomodel->elements[3*index+0];
+			tria_node_ids[1]=iomodel->nodecounter+iomodel->elements[3*index+1];
+			tria_node_ids[2]=iomodel->nodecounter+iomodel->elements[3*index+2];
+			tria_node_ids[3]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+0]+1;
+			tria_node_ids[4]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+1]+1;
+			tria_node_ids[5]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[3*index+2]+1;
+			tria_node_ids[6]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+index+1;
+			break;
 		default:
 			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
@@ -2110,10 +3300,33 @@
 }
 /*}}}*/
+int        Tria::UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){/*{{{*/
+
+	int i;
+	int nflipped=0;
+
+	/*Go through nodes, and whoever is on the potential_ungrounding, ends up in nodes_on_iceshelf: */
+	for(i=0;i<3;i++){
+		if (reCast<bool>(vertices_potentially_ungrounding[vertices[i]->Pid()])){
+			vec_nodes_on_iceshelf->SetValue(vertices[i]->Pid(),-1.,INS_VAL);
+
+			/*If node was not on ice shelf, we flipped*/
+			if(nodes_on_iceshelf[vertices[i]->Pid()]>=0.){
+				nflipped++;
+			}
+		}
+	}
+	return nflipped;
+}
+/*}}}*/
+void       Tria::ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	TriaRef::GetInputDerivativeValue(dvalue,values,xyz_list,gauss,P1Enum);
+}
+/*}}}*/
 void       Tria::ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss){/*{{{*/
 	TriaRef::GetInputValue(pvalue,values,gauss,P1Enum);
 }
 /*}}}*/
-void       Tria::ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	TriaRef::GetInputDerivativeValue(dvalue,values,xyz_list,gauss,P1Enum);
+int        Tria::VelocityInterpolation(void){/*{{{*/
+	return TriaRef::VelocityInterpolation(this->element_type);
 }
 /*}}}*/
@@ -2123,416 +3336,52 @@
 }
 /*}}}*/
-bool       Tria::IsZeroLevelset(int levelset_enum){/*{{{*/
-
-	bool iszerols;
-	IssmDouble ls[NUMVERTICES];
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&ls[0],levelset_enum);
-
-	/*If the level set is awlays <0, there is no ice front here*/
-	iszerols= false;
-	if(IsIceInElement()){
-		if(ls[0]*ls[1]<0. || ls[0]*ls[2]<0. || (ls[0]*ls[1]*ls[2]==0. && ls[0]*ls[1]+ls[0]*ls[2]+ls[1]*ls[2]<=0.)){
-			iszerols = true;
-		}
-	}
-
-	return iszerols;
-}
-/*}}}*/
-bool       Tria::IsIcefront(void){/*{{{*/
-
-	bool isicefront;
-	int i,nrice;
-   IssmDouble ls[NUMVERTICES];
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
-
-	/* If only one vertex has ice, there is an ice front here */
-	isicefront=false;
-	if(IsIceInElement()){
-		nrice=0;       
-		for(i=0;i<NUMVERTICES;i++)
-			if(ls[i]<0.) nrice++;
-		if(nrice==1) isicefront= true;
-	}
-	return isicefront;
-}/*}}}*/
-bool       Tria::IsFaceOnBoundary(void){/*{{{*/
-
-	IssmDouble values[NUMVERTICES];
-	IssmDouble sum;
-
-	/*Retrieve all inputs and parameters*/
-	GetInputListOnVertices(&values[0],MeshVertexonboundaryEnum);
-	sum = values[0]+values[1]+values[2];
-
-	_assert_(sum==0. || sum==1. || sum==2.);
-
-	if(sum==3.)  _error_("Two edges on boundary not supported yet...");
-
-	if(sum>1.){
-		return true;
-	}
-	else{
-		return false;
-	}
-}/*}}}*/
-void       Tria::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){/*{{{*/
-
-	bool       already = false;
-	int        i,j;
-	int        partition[NUMVERTICES];
-	int        offsetsid[NUMVERTICES];
-	int        offsetdof[NUMVERTICES];
-	IssmDouble area;
-	IssmDouble mean;
-
-	/*First, get the area: */
-	area=this->GetArea();
-
-	/*Figure out the average for this element: */
-	this->GetVerticesSidList(&offsetsid[0]);
-	this->GetVertexPidList(&offsetdof[0]);
-	mean=0;
-	for(i=0;i<NUMVERTICES;i++){
-		partition[i]=reCast<int>(qmu_part[offsetsid[i]]);
-		mean=mean+1.0/NUMVERTICES*vertex_response[offsetdof[i]];
-	}
-
-	/*Add contribution: */
-	for(i=0;i<NUMVERTICES;i++){
-		already=false;
-		for(j=0;j<i;j++){
-			if (partition[i]==partition[j]){
-				already=true;
-				break;
+void       Tria::ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum){/*{{{*/
+	/* Return coordinates where levelset intersects element edges.
+	 * Attention: In case that no intersection exists, NULL pointer is returned.*/
+
+	/*Intermediaries*/
+	const int dim=3;
+	int numiceverts;
+	int i, n, e, counter;
+	IssmDouble s[2];
+	int* indices=NULL;
+	IssmDouble* xyz_zero=NULL;
+
+	this->GetLevelsetIntersection(&indices, &numiceverts, s, MaskIceLevelsetEnum, 0.);
+	
+	//TODO: check if for 2 iceverts front segment is oriented in CCW way
+	
+	if(numiceverts>0) xyz_zero=xNew<IssmDouble>(2*dim);
+	if((numiceverts>0)&&(numiceverts<NUMVERTICES)){
+		counter=0;
+		for(i=0;i<numiceverts;i++){	// iterate over ice vertices
+			for(n=numiceverts;n<NUMVERTICES;n++){ // iterate over no-ice vertices
+				for(e=0;e<dim;e++){ // spatial direction
+					int ind_ice		=dim*indices[i]+e;
+					int ind_noice	=dim*indices[n]+e;
+					int ind			=dim*counter+e;
+					xyz_zero[ind]=xyz_list[ind_ice]+s[counter]*(xyz_list[ind_noice]-xyz_list[ind_ice]);
+				}
+				counter++;
 			}
 		}
-		if(!already){
-			partition_contributions->SetValue(partition[i],mean*area,ADD_VAL);
-			partition_areas->SetValue(partition[i],area,ADD_VAL);
-		};
-	}
-}
-/*}}}*/
-IssmDouble Tria::IceVolume(void){/*{{{*/
-
-	/*The volume of a troncated prism is base * 1/3 sum(length of edges)*/
-	IssmDouble base,surface,bed;
-	IssmDouble xyz_list[NUMVERTICES][3];
-
-	if(!IsIceInElement())return 0;
-
-	/*First get back the area of the base*/
-	base=this->GetArea();
-
-	/*Now get the average height*/
-	Input* surface_input = inputs->GetInput(SurfaceEnum); _assert_(surface_input);
-	Input* base_input     = inputs->GetInput(BaseEnum);     _assert_(base_input);
-	surface_input->GetInputAverage(&surface);
-	base_input->GetInputAverage(&bed);
-
-	/*Return: */
-	int domaintype;
-	parameters->FindParam(&domaintype,DomainTypeEnum);
-	if(domaintype==Domain2DverticalEnum){
-	  return base;
-	}
-	else{
-	  return base*(surface-bed);
-	}
-}
-/*}}}*/
-IssmDouble Tria::IceVolumeAboveFloatation(void){/*{{{*/
-
-	/*The volume above floatation: H + rho_water/rho_ice * bathymetry */
-	IssmDouble rho_ice,rho_water;
-	IssmDouble base,surface,bed,bathymetry;
-	IssmDouble xyz_list[NUMVERTICES][3];
-
-	if(!IsIceInElement() || IsFloating())return 0;
-
-	rho_ice=matpar->GetRhoIce();
-	rho_water=matpar->GetRhoWater();
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*First calculate the area of the base (cross section triangle)
-	 * http://en.wikipedia.org/wiki/Triangle
-	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
-	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));
-
-	/*Now get the average height and bathymetry*/
-	Input* surface_input    = inputs->GetInput(SurfaceEnum);    _assert_(surface_input);
-	Input* base_input        = inputs->GetInput(BaseEnum);        _assert_(base_input);
-	Input* bed_input = inputs->GetInput(BedEnum); _assert_(bed_input);
-	surface_input->GetInputAverage(&surface);
-	base_input->GetInputAverage(&bed);
-	bed_input->GetInputAverage(&bathymetry);
-	
-	/*Return: */
-	return base*(surface-bed+min(rho_water/rho_ice*bathymetry,0.));
-}
-/*}}}*/
-IssmDouble Tria::MassFlux( IssmDouble x1, IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id){/*{{{*/
-
-	int        domaintype;
-	IssmDouble mass_flux=0.;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble normal[2];
-	IssmDouble length,rho_ice;
-	IssmDouble h1,h2;
-	IssmDouble vx1,vx2,vy1,vy2;
-	GaussTria* gauss_1=NULL;
-	GaussTria* gauss_2=NULL;
-
-	/*Get material parameters :*/
-	rho_ice=matpar->GetRhoIce();
-
-	/*First off, check that this segment belongs to this element: */
-	if (segment_id!=this->id)_error_("error message: segment with id " << segment_id << " does not belong to element with id:" << this->id);
-
-	/*Get xyz list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*get area coordinates of 0 and 1 locations: */
-	gauss_1=new GaussTria();
-	gauss_1->GaussFromCoords(x1,y1,&xyz_list[0][0]);
-	gauss_2=new GaussTria();
-	gauss_2->GaussFromCoords(x2,y2,&xyz_list[0][0]);
-
-	normal[0]=cos(atan2(x1-x2,y2-y1));
-	normal[1]=sin(atan2(x1-x2,y2-y1));
-
-	length=sqrt(pow(x2-x1,2)+pow(y2-y1,2));
-
-	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
-	this->parameters->FindParam(&domaintype,DomainTypeEnum);
-	Input* vx_input=NULL;
-	Input* vy_input=NULL;
-	if(domaintype==Domain2DhorizontalEnum){
-		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
-		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
-	}
-	else{
-		vx_input=inputs->GetInput(VxAverageEnum); _assert_(vx_input);
-		vy_input=inputs->GetInput(VyAverageEnum); _assert_(vy_input);
-	}
-
-	thickness_input->GetInputValue(&h1, gauss_1);
-	thickness_input->GetInputValue(&h2, gauss_2);
-	vx_input->GetInputValue(&vx1,gauss_1);
-	vx_input->GetInputValue(&vx2,gauss_2);
-	vy_input->GetInputValue(&vy1,gauss_1);
-	vy_input->GetInputValue(&vy2,gauss_2);
-
-	mass_flux= rho_ice*length*(  
-				(ONETHIRD*(h1-h2)*(vx1-vx2)+0.5*h2*(vx1-vx2)+0.5*(h1-h2)*vx2+h2*vx2)*normal[0]+
-				(ONETHIRD*(h1-h2)*(vy1-vy2)+0.5*h2*(vy1-vy2)+0.5*(h1-h2)*vy2+h2*vy2)*normal[1]
-				);
-
-	/*clean up and return:*/
-	delete gauss_1;
-	delete gauss_2;
-	return mass_flux;
-}
-/*}}}*/
-IssmDouble Tria::MassFlux( IssmDouble* segment){/*{{{*/
-
-	int        domaintype;
-	IssmDouble mass_flux=0.;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble normal[2];
-	IssmDouble length,rho_ice;
-	IssmDouble x1,y1,x2,y2,h1,h2;
-	IssmDouble vx1,vx2,vy1,vy2;
-	GaussTria* gauss_1=NULL;
-	GaussTria* gauss_2=NULL;
-
-	/*Get material parameters :*/
-	rho_ice=matpar->GetRhoIce();
-
-	/*First off, check that this segment belongs to this element: */
-	if (reCast<int>(*(segment+4))!=this->id)_error_("error message: segment with id " << reCast<int>(*(segment+4)) << " does not belong to element with id:" << this->id);
-
-	/*Recover segment node locations: */
-	x1=*(segment+0); y1=*(segment+1); x2=*(segment+2); y2=*(segment+3);
-
-	/*Get xyz list: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*get area coordinates of 0 and 1 locations: */
-	gauss_1=new GaussTria();
-	gauss_1->GaussFromCoords(x1,y1,&xyz_list[0][0]);
-	gauss_2=new GaussTria();
-	gauss_2->GaussFromCoords(x2,y2,&xyz_list[0][0]);
-
-	normal[0]=cos(atan2(x1-x2,y2-y1));
-	normal[1]=sin(atan2(x1-x2,y2-y1));
-
-	length=sqrt(pow(x2-x1,2)+pow(y2-y1,2));
-
-	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
-	this->parameters->FindParam(&domaintype,DomainTypeEnum);
-	Input* vx_input=NULL;
-	Input* vy_input=NULL;
-	if(domaintype==Domain2DhorizontalEnum){
-		vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
-		vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
-	}
-	else{
-		vx_input=inputs->GetInput(VxAverageEnum); _assert_(vx_input);
-		vy_input=inputs->GetInput(VyAverageEnum); _assert_(vy_input);
-	}
-
-	thickness_input->GetInputValue(&h1, gauss_1);
-	thickness_input->GetInputValue(&h2, gauss_2);
-	vx_input->GetInputValue(&vx1,gauss_1);
-	vx_input->GetInputValue(&vx2,gauss_2);
-	vy_input->GetInputValue(&vy1,gauss_1);
-	vy_input->GetInputValue(&vy2,gauss_2);
-
-	mass_flux= rho_ice*length*(  
-				(ONETHIRD*(h1-h2)*(vx1-vx2)+0.5*h2*(vx1-vx2)+0.5*(h1-h2)*vx2+h2*vx2)*normal[0]+
-				(ONETHIRD*(h1-h2)*(vy1-vy2)+0.5*h2*(vy1-vy2)+0.5*(h1-h2)*vy2+h2*vy2)*normal[1]
-				);
-
-	/*clean up and return:*/
-	delete gauss_1;
-	delete gauss_2;
-	return mass_flux;
-}
-/*}}}*/
-void       Tria::ElementResponse(IssmDouble* presponse,int response_enum){/*{{{*/
-
-	switch(response_enum){
-		case MaterialsRheologyBbarEnum:
-			*presponse=this->material->GetBbar();
-			break;
-
-		case VelEnum:{
-
-			/*Get input:*/
-			IssmDouble vel;
-			Input* vel_input;
-
-			vel_input=this->inputs->GetInput(VelEnum); _assert_(vel_input);
-			vel_input->GetInputAverage(&vel);
-
-			/*Assign output pointers:*/
-			*presponse=vel;}
-			break;
-		default:  
-			_error_("Response type " << EnumToStringx(response_enum) << " not supported yet!");
-	}
-
-}
-/*}}}*/
-IssmDouble Tria::TotalSmb(void){/*{{{*/
-
-	/*The smb[kg yr-1] of one element is area[m2] * smb [kg m^-2 yr^-1]*/
-	IssmDouble base,smb,rho_ice;
-	IssmDouble Total_Smb=0;
-	IssmDouble xyz_list[NUMVERTICES][3];
-
-	/*Get material parameters :*/
-	rho_ice=matpar->GetRhoIce();
-
-   if(!IsIceInElement())return 0;
-
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*First calculate the area of the base (cross section triangle)
-	 * http://en.wikipedia.org/wiki/Triangle
-	 * base = 1/2 abs((xA-xC)(yB-yA)-(xA-xB)(yC-yA))*/
-	base = 1./2. * fabs((xyz_list[0][0]-xyz_list[2][0])*(xyz_list[1][1]-xyz_list[0][1]) - (xyz_list[0][0]-xyz_list[1][0])*(xyz_list[2][1]-xyz_list[0][1]));	// area of element in m2
-
-	/*Now get the average SMB over the element*/
-	Input* smb_input = inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(smb_input);
-	smb_input->GetInputAverage(&smb);																								// average smb on element in m ice s-1
-   Total_Smb=rho_ice*base*smb;																											// smb on element in kg s-1
-
-	/*Return: */
-	return Total_Smb;
-}
-/*}}}*/
-IssmDouble Tria::MisfitArea(int weightsenum){/*{{{*/
-
-	/*Intermediaries*/
-	IssmDouble weight;
-	IssmDouble Jdet;
-	IssmDouble Jelem = 0;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	GaussTria *gauss = NULL;
-
-	/*If on water, return 0: */
-	if(!IsIceInElement())return 0;
-
-	/*Retrieve all inputs we will be needing: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	Input* weights_input     =inputs->GetInput(weightsenum);     _assert_(weights_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		/* Get Jacobian determinant: */
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-
-		/*Get parameters at gauss point*/
-		weights_input->GetInputValue(&weight,gauss);
-
-		/*compute misfit between model and observation */
-		Jelem+=Jdet*weight*gauss->weight;
-	}
-
-	/* clean up and Return: */
-	delete gauss;
-	return Jelem;
-}
-/*}}}*/
-IssmDouble Tria::Misfit(int modelenum,int observationenum,int weightsenum){/*{{{*/
-
-	/*Intermediaries*/
-	IssmDouble model,observation,weight;
-	IssmDouble Jdet;
-	IssmDouble Jelem = 0;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	GaussTria *gauss = NULL;
-
-	/*If on water, return 0: */
-	if(!IsIceInElement())return 0;
-
-	/*Retrieve all inputs we will be needing: */
-	::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	Input* model_input=inputs->GetInput(modelenum);   _assert_(model_input);
-	Input* observation_input=inputs->GetInput(observationenum);_assert_(observation_input);
-	Input* weights_input     =inputs->GetInput(weightsenum);     _assert_(weights_input);
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		/* Get Jacobian determinant: */
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-
-		/*Get parameters at gauss point*/
-		model_input->GetInputValue(&model,gauss);
-		observation_input->GetInputValue(&observation,gauss);
-		weights_input->GetInputValue(&weight,gauss);
-
-		/*compute misfit between model and observation */
-		Jelem+=0.5*(model-observation)*(model-observation)*Jdet*weight*gauss->weight;
-	}
-
-	/* clean up and Return: */
-	delete gauss;
-	return Jelem;
+	}
+	else if(numiceverts==NUMVERTICES){ //NUMVERTICES ice vertices: calving front lies on element edge
+		IssmDouble lsf[NUMVERTICES];
+		this->GetInputListOnVertices(&lsf[0],MaskIceLevelsetEnum);
+		counter=0;
+		for(i=0;i<NUMVERTICES;i++){
+			if(lsf[indices[i]]==0.){
+				for(e=0;e<dim;e++)	xyz_zero[dim*counter+e]=xyz_list[dim*indices[i]+e];
+				counter++;
+			}
+			if(counter==2) break;
+		}
+	}
+	_assert_(counter==2);
+
+	/*Cleanup & return*/
+	xDelete<int>(indices);
+	*pxyz_zero=xyz_zero;
 }
 /*}}}*/
@@ -2591,9 +3440,9 @@
 
 	/*recover material parameters: */
-	lithosphere_shear_modulus=matpar->GetLithosphereShearModulus();
-	lithosphere_density=matpar->GetLithosphereDensity();
-	mantle_shear_modulus=matpar->GetMantleShearModulus();
-	mantle_density=matpar->GetMantleDensity();
-	rho_ice=matpar->GetRhoIce();
+	lithosphere_shear_modulus=matpar->GetMaterialParameter(MaterialsLithosphereShearModulusEnum);
+	lithosphere_density=matpar->GetMaterialParameter(MaterialsLithosphereDensityEnum);
+	mantle_shear_modulus=matpar->GetMaterialParameter(MaterialsMantleShearModulusEnum);
+	mantle_density=matpar->GetMaterialParameter(MaterialsMantleDensityEnum);
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
 
 	/*pull thickness averages: */
@@ -2666,177 +3515,43 @@
 #endif
 
-void       Tria::InputControlUpdate(IssmDouble scalar,bool save_parameter){/*{{{*/
-
-	/*Intermediary*/
-	int    num_controls;
-	int*   control_type=NULL;
-	Input* input=NULL;
-
-	/*retrieve some parameters: */
-	this->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
-	this->parameters->FindParam(&control_type,NULL,InversionControlParametersEnum);
-
-	for(int i=0;i<num_controls;i++){
-		input=(Input*)this->inputs->GetInput(control_type[i]);   _assert_(input);
-		if (input->ObjectEnum()!=ControlInputEnum){
-			_error_("input " << EnumToStringx(control_type[i]) << " is not a ControlInput");
-		}
-
-		((ControlInput*)input)->UpdateValue(scalar);
-		((ControlInput*)input)->Constrain();
-		if (save_parameter) ((ControlInput*)input)->SaveValue();
-
-	}
-
-	/*Clean up and return*/
-	xDelete<int>(control_type);
-}
-/*}}}*/
-void       Tria::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){/*{{{*/
-
-	int    vertexpidlist[NUMVERTICES];
-	IssmDouble grad_list[NUMVERTICES];
-	Input* grad_input=NULL;
-
-	Input* input=inputs->GetInput(enum_type);
-	if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found");
-	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
-
-	GradientIndexing(&vertexpidlist[0],control_index);
-	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
-	grad_input=new TriaInput(GradientEnum,grad_list,P1Enum);
-
-	((ControlInput*)input)->SetGradient(grad_input);
-
-}/*}}}*/
-void       Tria::ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum){/*{{{*/
-
-	Input* input=inputs->GetInput(control_enum);
-	if (!input) _error_("Input " << EnumToStringx(control_enum) << " not found");
-	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(control_enum) << " is not a ControlInput");
-
-	int         sidlist[NUMVERTICES];
-	int         connectivity[NUMVERTICES];
-	IssmPDouble values[NUMVERTICES];
-	IssmPDouble gradients[NUMVERTICES]; 
-	IssmDouble  value,gradient;
-
-	this->GetVerticesConnectivityList(&connectivity[0]);
-	this->GetVerticesSidList(&sidlist[0]);
-
-	GaussTria* gauss=new GaussTria();
-	for (int iv=0;iv<NUMVERTICES;iv++){
-		gauss->GaussVertex(iv);
-
-		((ControlInput*)input)->GetInputValue(&value,gauss);
-		((ControlInput*)input)->GetGradientValue(&gradient,gauss);
-
-		values[iv]    = reCast<IssmPDouble>(value)/reCast<IssmPDouble>(connectivity[iv]);
-		gradients[iv] = reCast<IssmPDouble>(gradient)/reCast<IssmPDouble>(connectivity[iv]);
-	}
-	delete gauss;
-
-	vector_control->SetValues(NUMVERTICES,&sidlist[0],&values[0],ADD_VAL);
-	vector_gradient->SetValues(NUMVERTICES,&sidlist[0],&gradients[0],ADD_VAL);
-
-}/*}}}*/
-void       Tria::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){/*{{{*/
-
-	int vertexpidlist[NUMVERTICES];
-	Input *input=NULL;
-
-	/*Get out if this is not an element input*/
-	if(!IsInput(control_enum)) return;
-
-	/*Prepare index list*/
-	GradientIndexing(&vertexpidlist[0],control_index);
-
-	/*Get input (either in element or material)*/
-	input=(Input*)this->inputs->GetInput(control_enum);   _assert_(input);
-
-	/*Check that it is a ControlInput*/
-	if (input->ObjectEnum()!=ControlInputEnum){
-		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
-	}
-
-	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexpidlist[0],data);
-}
-/*}}}*/
-void       Tria::SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index){/*{{{*/
-
-	IssmDouble  values[NUMVERTICES];
-	int         vertexpidlist[NUMVERTICES],control_init;
-
-
-	/*Get Domain type*/
-	int domaintype;
-	parameters->FindParam(&domaintype,DomainTypeEnum);
-
-	/*Specific case for depth averaged quantities*/
-	control_init=control_enum;
-	if(domaintype==Domain2DverticalEnum){
-		if(control_enum==MaterialsRheologyBbarEnum){
-			control_enum=MaterialsRheologyBEnum;
-			if(!IsOnBase()) return;
-		}
-		if(control_enum==DamageDbarEnum){
-			control_enum=DamageDEnum;
-			if(!IsOnBase()) return;
-		}
-	}
-
-	/*Get out if this is not an element input*/
-	if(!IsInput(control_enum)) return;
-
-	/*Prepare index list*/
-	GradientIndexing(&vertexpidlist[0],control_index);
-
-	/*Get values on vertices*/
-	for(int i=0;i<NUMVERTICES;i++){
-		values[i]=vector[vertexpidlist[i]];
-	}
-	Input* new_input = new TriaInput(control_enum,values,P1Enum);
-	Input* input     = (Input*)this->inputs->GetInput(control_enum);   _assert_(input);
-	if(input->ObjectEnum()!=ControlInputEnum){
-		_error_("input " << EnumToStringx(control_enum) << " is not a ControlInput");
-	}
-
-	((ControlInput*)input)->SetInput(new_input);
-}
-/*}}}*/
-void       Tria::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){/*{{{*/
-
-	int        *doflist = NULL;
-	IssmDouble  value;
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes(this->element_type);
-
-	/*Fetch dof list and allocate solution vector*/
-	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	IssmDouble* values = xNew<IssmDouble>(numnodes);
-
-	/*Get inputs*/
-	Input* enum_input=inputs->GetInput(enum_type); _assert_(enum_input);
-
-	/*Ok, we have the values, fill in the array: */
-	GaussTria* gauss=new GaussTria();
-	for(int i=0;i<numnodes;i++){
-		gauss->GaussNode(this->element_type,i);
-
-		enum_input->GetInputValue(&value,gauss);
-		values[i]=value;
-	}
-
-	solution->SetValues(numnodes,doflist,values,INS_VAL);
-
-	/*Free ressources:*/
-	xDelete<int>(doflist);
-	xDelete<IssmDouble>(values);
-	delete gauss;
-}
-/*}}}*/
-
 #ifdef _HAVE_DAKOTA_
+void       Tria::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*{{{*/
+
+	int             i,t,row;
+	IssmDouble      time;
+	TransientInput *transientinput = NULL;
+	IssmDouble      values[3];
+
+	/*Check that name is an element input*/
+	if (!IsInput(name)) return;
+
+	switch(type){
+
+		case VertexEnum:
+			/*Create transient input: */
+			for(t=0;t<ncols;t++){ //ncols is the number of times
+
+				/*create input values: */
+				for(i=0;i<3;i++){
+					row=this->vertices[i]->Sid();
+					values[i]=matrix[ncols*row+t];
+				}
+
+				/*time:*/
+				time=matrix[(nrows-1)*ncols+t];
+
+				if(t==0) transientinput=new TransientInput(name);
+				transientinput->AddTimeInput(new TriaInput(name,values,P1Enum),time);
+				transientinput->Configure(parameters);
+			}
+			this->inputs->AddInput(transientinput);
+			break;
+
+		default:
+			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
+	}
+
+}
+/*}}}*/
 void       Tria::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
 
@@ -2877,6 +3592,6 @@
 						/*hydrostatic equilibrium: */
 						IssmDouble rho_ice,rho_water,di;
-						rho_ice   = this->matpar->GetRhoIce();
-						rho_water = this->matpar->GetRhoWater();
+						rho_ice   = this->matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+						rho_water = this->matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
 						di        = rho_ice/rho_water;
 
@@ -2930,176 +3645,3 @@
 }
 /*}}}*/
-void       Tria::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*{{{*/
-
-	int             i,t,row;
-	IssmDouble      time;
-	TransientInput *transientinput = NULL;
-	IssmDouble      values[3];
-
-	/*Check that name is an element input*/
-	if (!IsInput(name)) return;
-
-	switch(type){
-
-		case VertexEnum:
-			/*Create transient input: */
-			for(t=0;t<ncols;t++){ //ncols is the number of times
-
-				/*create input values: */
-				for(i=0;i<3;i++){
-					row=this->vertices[i]->Sid();
-					values[i]=matrix[ncols*row+t];
-				}
-
-				/*time:*/
-				time=matrix[(nrows-1)*ncols+t];
-
-				if(t==0) transientinput=new TransientInput(name);
-				transientinput->AddTimeInput(new TriaInput(name,values,P1Enum),time);
-				transientinput->Configure(parameters);
-			}
-			this->inputs->AddInput(transientinput);
-			break;
-
-		default:
-			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
-	}
-
-}
-/*}}}*/
 #endif
-
-void       Tria::MigrateGroundingLine(IssmDouble* phi_ungrounding){/*{{{*/
-
-	int        i,migration_style;
-	bool       groundedelement = false;
-	IssmDouble bed_hydro,yts;
-	IssmDouble rho_water,rho_ice,density;
-	IssmDouble melting[NUMVERTICES],phi[NUMVERTICES];;
-	IssmDouble h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],r[NUMVERTICES];
-
-	/*Recover info at the vertices: */
-	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
-	parameters->FindParam(&yts,ConstantsYtsEnum);
-	GetInputListOnVertices(&h[0],ThicknessEnum);
-	GetInputListOnVertices(&s[0],SurfaceEnum);
-	GetInputListOnVertices(&b[0],BaseEnum);
-	GetInputListOnVertices(&r[0],BedEnum);
-	GetInputListOnVertices(&phi[0],MaskGroundediceLevelsetEnum);
-	rho_water   = matpar->GetRhoWater();
-	rho_ice     = matpar->GetRhoIce();
-	density     = rho_ice/rho_water;
-
-	if(migration_style == ContactEnum){
-		for(i = 0;i < NUMVERTICES;i++) phi[i] = phi_ungrounding[vertices[i]->Pid()];
-		this->inputs->AddInput(new TriaInput(MaskGroundediceLevelsetEnum,&phi[0],P1Enum));
-
-		/*go through vertices, and update inputs, considering them to be TriaVertex type: */
-		for(i = 0;i < NUMVERTICES;i++){
-			/*Ice shelf: if bed below bathymetry, impose it at the bathymetry and update surface, elso do nothing */
-			if(phi[i] >= 0.){
-					b[i]  = r[i];
-			}
-		}
-
-		/*Update inputs*/
-		this->inputs->AddInput(new TriaInput(BaseEnum,&b[0],P1Enum));
-		return;
-	}
-
-	this->inputs->AddInput(new TriaInput(MaskGroundediceLevelsetEnum,&phi[0],P1Enum));
-
-	/*go through vertices, and update inputs, considering them to be TriaVertex type: */
-	for(i=0;i<NUMVERTICES;i++){
-		/*Ice shelf: if bed below bathymetry, impose it at the bathymetry and update surface, elso do nothing */
-		if(phi[i]<=0.){
-			if(b[i]<=r[i]){ 
-				b[i]        = r[i];
-				s[i]        = b[i]+h[i];
-			}
-		}
-		/*Ice sheet: if hydrostatic bed above bathymetry, ice sheet starts to unground, elso do nothing */
-		/*Change only if AggressiveMigration or if the ice sheet is in contact with the ocean*/
-		else{ // phi>0
-			bed_hydro=-density*h[i];
-			if (bed_hydro>r[i]){
-				/*Unground only if the element is connected to the ice shelf*/
-				if(migration_style==AggressiveMigrationEnum || migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
-					s[i]        = (1-density)*h[i];
-					b[i]        = -density*h[i];
-				}
-				else if(migration_style==SoftMigrationEnum && phi_ungrounding[vertices[i]->Pid()]<0.){
-					s[i]        = (1-density)*h[i];
-					b[i]        = -density*h[i];
-				}
-				else{
-					if(migration_style!=SoftMigrationEnum) _error_("Error: migration should be Aggressive, Soft or Subelement");
-				}
-			}
-		}
-	}
-
-	/*Recalculate phi*/
-	for(i=0;i<NUMVERTICES;i++){
-		if(migration_style==SoftMigrationEnum){
-			bed_hydro=-density*h[i];
-			if(phi[i]<0. || bed_hydro<=r[i] || phi_ungrounding[vertices[i]->Pid()]<0.){
-				phi[i]=h[i]+r[i]/density;
-			}
-		}
-		else phi[i]=h[i]+r[i]/density;
-	}
-	this->inputs->AddInput(new TriaInput(MaskGroundediceLevelsetEnum,&phi[0],P1Enum));
-
-	/*Update inputs*/
-	this->inputs->AddInput(new TriaInput(SurfaceEnum,&s[0],P1Enum));
-	this->inputs->AddInput(new TriaInput(BaseEnum,&b[0],P1Enum));
-
-}
-/*}}}*/
-void       Tria::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){/*{{{*/
-
-	IssmDouble  h[NUMVERTICES],r[NUMVERTICES],gl[NUMVERTICES];
-	IssmDouble  bed_hydro;
-	IssmDouble  rho_water,rho_ice,density;
-
-	/*material parameters: */
-	rho_water=matpar->GetRhoWater();
-	rho_ice=matpar->GetRhoIce();
-	density=rho_ice/rho_water;
-	GetInputListOnVertices(&h[0],ThicknessEnum);
-	GetInputListOnVertices(&r[0],BedEnum);
-	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
-
-	/*go through vertices, and figure out which ones are grounded and want to unground: */
-	for(int i=0;i<NUMVERTICES;i++){
-		/*Find if grounded vertices want to start floating*/
-		if (gl[i]>0.){
-			bed_hydro=-density*h[i];
-			if(bed_hydro>r[i]){
-				/*Vertex that could potentially unground, flag it*/
-				potential_ungrounding->SetValue(vertices[i]->Pid(),1,INS_VAL);
-			}
-		}
-	}
-}
-/*}}}*/
-int        Tria::UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf){/*{{{*/
-
-	int i;
-	int nflipped=0;
-
-	/*Go through nodes, and whoever is on the potential_ungrounding, ends up in nodes_on_iceshelf: */
-	for(i=0;i<3;i++){
-		if (reCast<bool>(vertices_potentially_ungrounding[vertices[i]->Pid()])){
-			vec_nodes_on_iceshelf->SetValue(vertices[i]->Pid(),-1.,INS_VAL);
-
-			/*If node was not on ice shelf, we flipped*/
-			if(nodes_on_iceshelf[vertices[i]->Pid()]>=0.){
-				nflipped++;
-			}
-		}
-	}
-	return nflipped;
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/Tria.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tria.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/Tria.h	(revision 19105)
@@ -42,98 +42,103 @@
 		/*}}}*/
 		/*Update virtual functions resolution: {{{*/
-		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
 		#ifdef _HAVE_DAKOTA_
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type);
 		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type);
 		#endif
 		void  InputUpdateFromIoModel(int index, IoModel* iomodel);
+		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
 		/*}}}*/
 		/*Element virtual functions definitions: {{{*/
+		void        AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
+		void			CalvingRateLevermann();
+		void			CalvingRatePi();
+		void			CalvingRateDev();
 		IssmDouble  CharacteristicLength(void);
 		void        ComputeBasalStress(Vector<IssmDouble>* sigma_b);
+		void        ComputeDeviatoricStressTensor();
 		void        ComputeSigmaNN();
 		void        ComputeStressTensor();
-		void        ComputeDeviatoricStressTensor();
 		void        ComputeSurfaceNormalVelocity();
 		void        Configure(Elements* elements,Loads* loads,Nodes* nodesin,Vertices* verticesin,Materials* materials,Parameters* parameters);
-		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
-		void        ResetHooks();
+		void        ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
+		void        ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
 		void        Delta18oParameterization(void);
+		void        MungsmtpParameterization(void);
+		int         EdgeOnBaseIndex();
+		void        EdgeOnBaseIndices(int* pindex1,int* pindex);
+		int         EdgeOnSurfaceIndex();
+		void        EdgeOnSurfaceIndices(int* pindex1,int* pindex);
+		void        ElementResponse(IssmDouble* presponse,int response_enum);
 		void        ElementSizes(IssmDouble* hx,IssmDouble* hy,IssmDouble* hz);
+		int         FiniteElement(void);
 		void        FSContactMigration(Vector<IssmDouble>* vertexgrounded,Vector<IssmDouble>* vertexfloating);
-		int         FiniteElement(void);
-		Element*    GetUpperElement(void){_error_("not implemented yet");};
 		Element*    GetBasalElement(void){_error_("not implemented yet");};
+		void        GetLevelsetPositivePart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlynegative,IssmDouble* levelsetvalues);
 		void        GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating);
 		IssmDouble  GetGroundedPortion(IssmDouble* xyz_list);
+		void	      GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum);
+		void	      GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level);
 		int         GetNodeIndex(Node* node);
 		int         GetNumberOfNodes(void);
 		int         GetNumberOfNodes(int enum_type);
 		int         GetNumberOfVertices(void);
+		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type);
+		Element*    GetUpperElement(void){_error_("not implemented yet");};
+		void        GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data,bool onsid);
+		void        GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
+		void        GetVerticesCoordinatesTop(IssmDouble** pxyz_list);
+		bool        HasEdgeOnBase();
+		bool        HasEdgeOnSurface();
+		IssmDouble  IceMass(void);
+		IssmDouble  IceVolume(void);
+		IssmDouble  IceVolumeAboveFloatation(void);
+		void        InputControlUpdate(IssmDouble scalar,bool save_parameter);
+		void        InputDepthAverageAtBase(int enum_type,int average_enum_type);
+		void        InputExtrude(int enum_type,int start){_error_("not implemented"); /*For penta only*/};
+		void        InputScale(int enum_type,IssmDouble scale_factor);
+		bool	   	IsFaceOnBoundary(void);
+		bool	   	IsIcefront(void);
+		bool        IsNodeOnShelfFromFlags(IssmDouble* flags);
 		bool        IsOnBase();
 		bool        IsOnSurface();
-		bool        HasEdgeOnBase();
-		bool        HasEdgeOnSurface();
-		void        EdgeOnSurfaceIndices(int* pindex1,int* pindex);
-		void        EdgeOnBaseIndices(int* pindex1,int* pindex);
-		int         EdgeOnBaseIndex();
-		int         EdgeOnSurfaceIndex();
-		bool        IsNodeOnShelfFromFlags(IssmDouble* flags);
+		bool        IsZeroLevelset(int levelset_enum);
+		IssmDouble  Masscon(IssmDouble* levelset);
+		IssmDouble  MassFlux(IssmDouble* segment);
+		IssmDouble  MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id);
+		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
+		IssmDouble  Misfit(int modelenum,int observationenum,int weightsenum);
+		IssmDouble  MisfitArea(int weightsenum);
+		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum);
+		int         NumberofNodesPressure(void);
 		int         NumberofNodesVelocity(void);
-		int         NumberofNodesPressure(void);
-		void        GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution,int enum_type);
-		void        GetVerticesCoordinatesBase(IssmDouble** pxyz_list);
-		void        GetVerticesCoordinatesTop(IssmDouble** pxyz_list);
-		void        InputDepthAverageAtBase(int enum_type,int average_enum_type);
-		void        InputExtrude(int enum_type){_error_("not implemented"); /*For penta only*/};
-		void        InputScale(int enum_type,IssmDouble scale_factor);
-		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
-		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum);
-		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm);
+		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm,bool ismungsm);
+		void        PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding);
+		int         PressureInterpolation();
 		void        ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
 		void        ResetFSBasalBoundaryCondition(void);
+		void        ResetHooks();
+		void        SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
+		void        SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
 	   Element*    SpawnBasalElement(void);
 		Element*    SpawnTopElement(void);
+		void			StrainRateparallel();
+		void			StrainRateperpendicular();
+		void        StressIntensityFactor(void){_error_("not implemented yet");};
+		IssmDouble  SurfaceArea(void);
+		int         TensorInterpolation();
+		IssmDouble  TimeAdapt();
+		IssmDouble  TotalSmb(void);
+		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
+		int         UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
+		void        ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss);
+		void        ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
 		int         VelocityInterpolation();
-		int         PressureInterpolation();
-		int         TensorInterpolation();
-		IssmDouble  SurfaceArea(void);
-		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
-		IssmDouble  TimeAdapt();
-		void        ValueP1OnGauss(IssmDouble* pvalue,IssmDouble* values,Gauss* gauss);
-		void        ValueP1DerivativesOnGauss(IssmDouble* dvalue,IssmDouble* values,IssmDouble* xyz_list,Gauss* gauss);
 		int         VertexConnectivity(int vertexindex);
 		void        VerticalSegmentIndices(int** pindices,int* pnumseg){_error_("not implemented yet");};
 		void        ZeroLevelsetCoordinates(IssmDouble** pxyz_zero,IssmDouble* xyz_list,int levelsetenum);
-		void	      GetIcefrontCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum);
-		void	      GetLevelCoordinates(IssmDouble** pxyz_front,IssmDouble* xyz_list,int levelsetenum,IssmDouble level);
-		bool        IsZeroLevelset(int levelset_enum);
-		bool	   	IsIcefront(void);
-		bool	   	IsFaceOnBoundary(void);
-
-		void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
-		IssmDouble IceVolume(void);
-		IssmDouble IceVolumeAboveFloatation(void);
-		IssmDouble TotalSmb(void);
-		IssmDouble MassFlux(IssmDouble* segment);
-		IssmDouble MassFlux(IssmDouble x1,IssmDouble y1, IssmDouble x2, IssmDouble y2,int segment_id);
-		void       ElementResponse(IssmDouble* presponse,int response_enum);
-		IssmDouble Misfit(int modelenum,int observationenum,int weightsenum);
-		IssmDouble MisfitArea(int weightsenum);
 
 		#ifdef _HAVE_GIA_
 		void   GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,IssmDouble* x,IssmDouble* y);
 		#endif
-
-		void       GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data);
-		void       SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
-		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
-		void       ControlToVectors(Vector<IssmPDouble>* vector_control, Vector<IssmPDouble>* vector_gradient,int control_enum);
-		void       InputControlUpdate(IssmDouble scalar,bool save_parameter);
-
-		void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding);
-		void   MigrateGroundingLine(IssmDouble* sheet_ungrounding);
-		int    UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
-
 		/*}}}*/
 		/*Tria specific routines:{{{*/
@@ -141,9 +146,8 @@
 		void           AddInput(int input_enum, IssmDouble* values, int interpolation_enum);
 		IssmDouble     GetArea(void);
+		IssmDouble 	GetAreaIce(void);
 		void           GetAreaCoordinates(IssmDouble *area_coordinates,IssmDouble* xyz_zero,IssmDouble* xyz_list,int numpoints);
+		void		GetLevelsetIntersection(int** pindices, int* pnumiceverts, IssmDouble* fraction, int levelset_enum, IssmDouble level);
 		int            GetElementType(void);
-		void           NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
-		void           NormalTop(IssmDouble* normal,IssmDouble* xyz_list);
-		void           NormalBase(IssmDouble* normal,IssmDouble* xyz_list);
 		void           GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
 		void           GetMaterialInputValue(IssmDouble* pvalue,Node* node,int enumtype);
@@ -152,7 +156,7 @@
 		void	         InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solution,int enum_type){_error_("not implemented yet");};
 		void           JacobianDeterminant(IssmDouble*  pJdet, IssmDouble* xyz_list,Gauss* gauss);
+		void           JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
 		void           JacobianDeterminantLine(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
 		void           JacobianDeterminantSurface(IssmDouble*  pJdet, IssmDouble* xyz_list,Gauss* gauss);
-		void           JacobianDeterminantBase(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
 		void           JacobianDeterminantTop(IssmDouble* pJdet,IssmDouble* xyz_list_base,Gauss* gauss);
 		IssmDouble     MinEdgeLength(IssmDouble* xyz_list){_error_("not implemented yet");};
@@ -166,21 +170,23 @@
 		Gauss*         NewGaussTop(int order);
 		void           NodalFunctions(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
+		void           NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss);
 		void           NodalFunctionsP1(IssmDouble* basis,Gauss* gauss);
+		void           NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
 		void           NodalFunctionsP2(IssmDouble* basis,Gauss* gauss);
-		void           NodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
-		void           NodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
-		void           NodalFunctionsMINIDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss){_error_("not implemented yet");};
-		void           NodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,Gauss* gauss);
+		void           NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss);
 		void           NodalFunctionsVelocity(IssmDouble* basis,Gauss* gauss);
-		void           NodalFunctionsPressure(IssmDouble* basis,Gauss* gauss);
-		void           NodalFunctionsTensor(IssmDouble* basis,Gauss* gauss);
+		void           NormalBase(IssmDouble* normal,IssmDouble* xyz_list);
+		void           NormalSection(IssmDouble* normal,IssmDouble* xyz_list);
+		void           NormalTop(IssmDouble* normal,IssmDouble* xyz_list);
 		void	         SetClone(int* minranks);
 		void           SetTemporaryElementType(int element_type_in){_error_("not implemented yet");};
 		Seg*	         SpawnSeg(int index1,int index2);
 		IssmDouble     StabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa){_error_("not implemented yet");};
+		void           UpdateConstraintsExtrudeFromBase(void);
+		void           UpdateConstraintsExtrudeFromTop(void);
 		void           ViscousHeating(IssmDouble* pphi,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){_error_("not implemented yet");};
-
-		void UpdateConstraintsExtrudeFromBase(void);
-		void UpdateConstraintsExtrudeFromTop(void);
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/Elements/TriaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/TriaRef.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/TriaRef.cpp	(revision 19105)
@@ -21,4 +21,5 @@
 #define NUMNODESP2  6
 #define NUMNODESP2b 7
+#define NUMNODESMAX 7
 
 /*Object constructors and destructor*/
@@ -31,52 +32,58 @@
 
 /*Reference Element numerics*/
-void TriaRef::GetSegmentBFlux(IssmDouble* B,Gauss* gauss, int index1,int index2,int finiteelement){/*{{{*/
-	/*Compute B  matrix. B=[phi1 phi2 -phi3 -phi4]
+void TriaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
+	/*From node values of parameter p (plist[0],plist[1],plist[2]), return parameter derivative value at gaussian 
+	 * point specified by gauss_basis:
+	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx+plist[2]*dh3/dx
+	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx+plist[2]*dh3/dx
 	 *
-	 * and phi1=phi3 phi2=phi4
+	 * p is a vector already allocated.
 	 *
-	 * We assume B has been allocated already, of size: 1x4
+	 * WARNING: For a significant gain in performance, it is better to use
+	 * static memory allocation instead of dynamic.
 	 */
+
+	/*Allocate derivatives of basis functions*/
+	IssmDouble  dbasis[2*NUMNODESMAX];
 
 	/*Fetch number of nodes for this finite element*/
 	int numnodes = this->NumberofNodes(finiteelement);
-
-	/*Get nodal functions*/
-	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	GetNodalFunctions(basis,gauss,finiteelement);
-
-	/*Build B for this segment*/
-	B[0] = +basis[index1];
-	B[1] = +basis[index2];
-	B[2] = -basis[index1];
-	B[3] = -basis[index2];
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(basis);
-}
-/*}}}*/
-void TriaRef::GetSegmentBprimeFlux(IssmDouble* Bprime,Gauss* gauss, int index1,int index2,int finiteelement){/*{{{*/
-	/*Compute Bprime  matrix. Bprime=[phi1 phi2 phi3 phi4]
-	 *
-	 * and phi1=phi3 phi2=phi4
-	 *
-	 * We assume Bprime has been allocated already, of size: 1x4
-	 */
+	_assert_(numnodes<=NUMNODESMAX);
+
+	/*Get basis functions derivatives at this point*/
+	GetNodalFunctionsDerivatives(&dbasis[0],xyz_list,gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	IssmDouble dpx=0.;
+	IssmDouble dpy=0.;
+	for(int i=0;i<numnodes;i++) dpx += dbasis[0*numnodes+i]*plist[i];
+	for(int i=0;i<numnodes;i++) dpy += dbasis[1*numnodes+i]*plist[i];
+
+	/*Assign values*/
+	p[0]=dpx;
+	p[1]=dpy;
+
+}
+/*}}}*/
+void TriaRef::GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement){/*{{{*/
+	/* WARNING: For a significant gain in performance, it is better to use
+	 * static memory allocation instead of dynamic.*/
+
+	/*Allocate basis functions*/
+	IssmDouble  basis[NUMNODESMAX];
 
 	/*Fetch number of nodes for this finite element*/
 	int numnodes = this->NumberofNodes(finiteelement);
-
-	/*Get nodal functions*/
-	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	GetNodalFunctions(basis,gauss,finiteelement);
-
-	/*Build B'*/
-	Bprime[0] = basis[index1];
-	Bprime[1] = basis[index2];
-	Bprime[2] = basis[index1];
-	Bprime[3] = basis[index2];
-
-	/*Clean-up*/
-	xDelete<IssmDouble>(basis);
+	_assert_(numnodes<=NUMNODESMAX);
+
+	/*Get basis functions at this point*/
+	GetNodalFunctions(&basis[0],gauss,finiteelement);
+
+	/*Calculate parameter for this Gauss point*/
+	IssmDouble value =0.;
+	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
+
+	/*Assign output pointer*/
+	*p = value;
 }
 /*}}}*/
@@ -98,18 +105,4 @@
 }
 /*}}}*/
-void TriaRef::GetSegmentJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
-	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
-	 * J is assumed to have been allocated*/
-
-	IssmDouble x1 = xyz_list[3*0+0];
-	IssmDouble y1 = xyz_list[3*0+1];
-	IssmDouble x2 = xyz_list[3*1+0];
-	IssmDouble y2 = xyz_list[3*1+1];
-
-	*Jdet = .5*sqrt(pow(x2-x1,2) + pow(y2-y1,2));
-	if(*Jdet<0) _error_("negative jacobian determinant!");
-
-}
-/*}}}*/
 void TriaRef::GetJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
 	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
@@ -146,5 +139,5 @@
 	/*Cast gauss to GaussTria*/
 	_assert_(gauss_in->Enum()==GaussTriaEnum);
-	GaussTria* gauss = dynamic_cast<GaussTria*>(gauss_in);
+	GaussTria* gauss = xDynamicCast<GaussTria*>(gauss_in);
 
 	switch(finiteelement){
@@ -194,43 +187,4 @@
 }
 /*}}}*/
-void TriaRef::GetSegmentNodalFunctions(IssmDouble* basis,Gauss* gauss,int index1,int index2,int finiteelement){/*{{{*/
-	/*This routine returns the values of the nodal functions  at the gaussian point.*/
-
-	_assert_(index1>=0 && index1<3);
-	_assert_(index2>=0 && index2<3);
-
-	/*Fetch number of nodes for this finite element*/
-	int numnodes = this->NumberofNodes(finiteelement);
-
-	/*Get nodal functions*/
-	IssmDouble* triabasis=xNew<IssmDouble>(numnodes);
-	GetNodalFunctions(triabasis,gauss,finiteelement);
-
-	switch(finiteelement){
-		case P1Enum: case P1DGEnum:
-			basis[0]=triabasis[index1];
-			basis[1]=triabasis[index2];
-			xDelete<IssmDouble>(triabasis);
-			return;
-		case P1bubbleEnum: case P1bubblecondensedEnum:
-			basis[0]=triabasis[index1];
-			basis[1]=triabasis[index2];
-			xDelete<IssmDouble>(triabasis);
-			return;
-		case P2Enum:
-			_assert_(index2<index1);
-			basis[0]=triabasis[index1];
-			basis[1]=triabasis[index2];
-			basis[2]=triabasis[3+index2-1];
-			xDelete<IssmDouble>(triabasis);
-			return;
-		default:
-			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
-	}
-
-	/*Clean up*/
-	xDelete<IssmDouble>(triabasis);
-}
-/*}}}*/
 void TriaRef::GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
 
@@ -271,5 +225,5 @@
 	/*Cast gauss to GaussTria*/
 	_assert_(gauss_in->Enum()==GaussTriaEnum);
-	GaussTria* gauss = dynamic_cast<GaussTria*>(gauss_in);
+	GaussTria* gauss = xDynamicCast<GaussTria*>(gauss_in);
 
 	switch(finiteelement){
@@ -353,40 +307,36 @@
 }
 /*}}}*/
-void TriaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement){/*{{{*/
-
-	/*From node values of parameter p (plist[0],plist[1],plist[2]), return parameter derivative value at gaussian 
-	 * point specified by gauss_basis:
-	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx+plist[2]*dh3/dx
-	 *   dp/dx=plist[0]*dh1/dx+plist[1]*dh2/dx+plist[2]*dh3/dx
+void TriaRef::GetSegmentBFlux(IssmDouble* B,Gauss* gauss, int index1,int index2,int finiteelement){/*{{{*/
+	/*Compute B  matrix. B=[phi1 phi2 -phi3 -phi4]
 	 *
-	 * p is a vector already allocated.
+	 * and phi1=phi3 phi2=phi4
+	 *
+	 * We assume B has been allocated already, of size: 1x4
 	 */
-
-	/*Output*/
-	IssmDouble dpx=0.;
-	IssmDouble dpy=0.;
 
 	/*Fetch number of nodes for this finite element*/
 	int numnodes = this->NumberofNodes(finiteelement);
 
-	/*Get nodal functions derivatives*/
-	IssmDouble* dbasis=xNew<IssmDouble>(2*numnodes);
-	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss,finiteelement);
-
-	/*Calculate parameter for this Gauss point*/
-	for(int i=0;i<numnodes;i++) dpx += dbasis[0*numnodes+i]*plist[i];
-	for(int i=0;i<numnodes;i++) dpy += dbasis[1*numnodes+i]*plist[i];
-
-	/*Assign values*/
-	xDelete<IssmDouble>(dbasis);
-	p[0]=dpx;
-	p[1]=dpy;
-
-}
-/*}}}*/
-void TriaRef::GetInputValue(IssmDouble* p, IssmDouble* plist, Gauss* gauss,int finiteelement){/*{{{*/
-
-	/*Output*/
-	IssmDouble value =0.;
+	/*Get nodal functions*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis,gauss,finiteelement);
+
+	/*Build B for this segment*/
+	B[0] = +basis[index1];
+	B[1] = +basis[index2];
+	B[2] = -basis[index1];
+	B[3] = -basis[index2];
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
+}
+/*}}}*/
+void TriaRef::GetSegmentBprimeFlux(IssmDouble* Bprime,Gauss* gauss, int index1,int index2,int finiteelement){/*{{{*/
+	/*Compute Bprime  matrix. Bprime=[phi1 phi2 phi3 phi4]
+	 *
+	 * and phi1=phi3 phi2=phi4
+	 *
+	 * We assume Bprime has been allocated already, of size: 1x4
+	 */
 
 	/*Fetch number of nodes for this finite element*/
@@ -395,81 +345,67 @@
 	/*Get nodal functions*/
 	IssmDouble* basis=xNew<IssmDouble>(numnodes);
-	GetNodalFunctions(basis, gauss,finiteelement);
-
-	/*Calculate parameter for this Gauss point*/
-	for(int i=0;i<numnodes;i++) value += basis[i]*plist[i];
-
-	/*Assign output pointer*/
+	GetNodalFunctions(basis,gauss,finiteelement);
+
+	/*Build B'*/
+	Bprime[0] = basis[index1];
+	Bprime[1] = basis[index2];
+	Bprime[2] = basis[index1];
+	Bprime[3] = basis[index2];
+
+	/*Clean-up*/
 	xDelete<IssmDouble>(basis);
-	*p = value;
-}
-/*}}}*/
-int  TriaRef::NumberofNodes(int finiteelement){/*{{{*/
+}
+/*}}}*/
+void TriaRef::GetSegmentJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss){/*{{{*/
+	/*The Jacobian determinant is constant over the element, discard the gaussian points. 
+	 * J is assumed to have been allocated*/
+
+	IssmDouble x1 = xyz_list[3*0+0];
+	IssmDouble y1 = xyz_list[3*0+1];
+	IssmDouble x2 = xyz_list[3*1+0];
+	IssmDouble y2 = xyz_list[3*1+1];
+
+	*Jdet = .5*sqrt(pow(x2-x1,2) + pow(y2-y1,2));
+	if(*Jdet<0) _error_("negative jacobian determinant!");
+
+}
+/*}}}*/
+void TriaRef::GetSegmentNodalFunctions(IssmDouble* basis,Gauss* gauss,int index1,int index2,int finiteelement){/*{{{*/
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	_assert_(index1>=0 && index1<3);
+	_assert_(index2>=0 && index2<3);
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes(finiteelement);
+
+	/*Get nodal functions*/
+	IssmDouble* triabasis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(triabasis,gauss,finiteelement);
 
 	switch(finiteelement){
-		case NoneEnum:              return 0;
-		case P0Enum:                return NUMNODESP0;
-		case P1Enum:                return NUMNODESP1;
-		case P1DGEnum:              return NUMNODESP1;
-		case P1bubbleEnum:          return NUMNODESP1b;
-		case P1bubblecondensedEnum: return NUMNODESP1b;
-		case P2Enum:                return NUMNODESP2;
-		case P2bubbleEnum:          return NUMNODESP2b;
-		case P2bubblecondensedEnum: return NUMNODESP2b;
-		case P1P1Enum:              return NUMNODESP1*2;
-		case P1P1GLSEnum:           return NUMNODESP1*2;
-		case MINIcondensedEnum:     return NUMNODESP1b+NUMNODESP1;
-		case MINIEnum:              return NUMNODESP1b+NUMNODESP1;
-		case TaylorHoodEnum:        return NUMNODESP2+NUMNODESP1;
-		case LATaylorHoodEnum:      return NUMNODESP2;
-		case XTaylorHoodEnum:       return NUMNODESP2+NUMNODESP1;
-		case CrouzeixRaviartEnum:   return NUMNODESP2b+NUMNODESP1;
-		default: _error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
-	}
-
-	return -1;
-}
-/*}}}*/
-int  TriaRef::VelocityInterpolation(int fe_stokes){/*{{{*/
-
-	switch(fe_stokes){
-		case P1P1Enum:           return P1Enum;
-		case P1P1GLSEnum:        return P1Enum;
-		case MINIcondensedEnum:  return P1bubbleEnum;
-		case MINIEnum:           return P1bubbleEnum;
-		case TaylorHoodEnum:     return P2Enum;
-		case LATaylorHoodEnum:   return P2Enum;
-		case XTaylorHoodEnum:    return P2Enum;
-		case CrouzeixRaviartEnum:return P2bubbleEnum;
-		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
-	}
-
-	return -1;
-}
-/*}}}*/
-int  TriaRef::PressureInterpolation(int fe_stokes){/*{{{*/
-
-	switch(fe_stokes){
-		case P1P1Enum:            return P1Enum;
-		case P1P1GLSEnum:         return P1Enum;
-		case MINIcondensedEnum:   return P1Enum;
-		case MINIEnum:            return P1Enum;
-		case TaylorHoodEnum:      return P1Enum;
-		case LATaylorHoodEnum:    return NoneEnum;
-		case XTaylorHoodEnum:     return P1Enum;
-		case CrouzeixRaviartEnum: return P1DGEnum;
-		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
-	}
-
-	return -1;
-}
-/*}}}*/
-int  TriaRef::TensorInterpolation(int fe_stokes){/*{{{*/
-	/*This routine returns the values of the nodal functions  at the gaussian point.*/
-
-	switch(fe_stokes){
-		case XTaylorHoodEnum: return P1DGEnum;
-		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
-	}
+		case P1Enum: case P1DGEnum:
+			basis[0]=triabasis[index1];
+			basis[1]=triabasis[index2];
+			xDelete<IssmDouble>(triabasis);
+			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			basis[0]=triabasis[index1];
+			basis[1]=triabasis[index2];
+			xDelete<IssmDouble>(triabasis);
+			return;
+		case P2Enum:
+			_assert_(index2<index1);
+			basis[0]=triabasis[index1];
+			basis[1]=triabasis[index2];
+			basis[2]=triabasis[3+index2-1];
+			xDelete<IssmDouble>(triabasis);
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(triabasis);
 }
 /*}}}*/
@@ -533,2 +469,74 @@
 }
 /*}}}*/
+int  TriaRef::NumberofNodes(int finiteelement){/*{{{*/
+
+	switch(finiteelement){
+		case NoneEnum:                return 0;
+		case P0Enum:                  return NUMNODESP0;
+		case P1Enum:                  return NUMNODESP1;
+		case P1DGEnum:                return NUMNODESP1;
+		case P1bubbleEnum:            return NUMNODESP1b;
+		case P1bubblecondensedEnum:   return NUMNODESP1b;
+		case P2Enum:                  return NUMNODESP2;
+		case P2bubbleEnum:            return NUMNODESP2b;
+		case P2bubblecondensedEnum:   return NUMNODESP2b;
+		case P1P1Enum:                return NUMNODESP1*2;
+		case P1P1GLSEnum:             return NUMNODESP1*2;
+		case MINIcondensedEnum:       return NUMNODESP1b+NUMNODESP1;
+		case MINIEnum:                return NUMNODESP1b+NUMNODESP1;
+		case TaylorHoodEnum:          return NUMNODESP2+NUMNODESP1;
+		case LATaylorHoodEnum:        return NUMNODESP2;
+		case XTaylorHoodEnum:         return NUMNODESP2+NUMNODESP1;
+		case CrouzeixRaviartEnum:     return NUMNODESP2b+NUMNODESP1;
+		case LACrouzeixRaviartEnum:   return NUMNODESP2b;
+		default: _error_("Element type "<<EnumToStringx(finiteelement)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+int  TriaRef::PressureInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:              return P1Enum;
+		case P1P1GLSEnum:           return P1Enum;
+		case MINIcondensedEnum:     return P1Enum;
+		case MINIEnum:              return P1Enum;
+		case TaylorHoodEnum:        return P1Enum;
+		case LATaylorHoodEnum:      return NoneEnum;
+		case XTaylorHoodEnum:       return P1Enum;
+		case CrouzeixRaviartEnum:   return P1DGEnum;
+		case LACrouzeixRaviartEnum: return NoneEnum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+int  TriaRef::TensorInterpolation(int fe_stokes){/*{{{*/
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	switch(fe_stokes){
+		case XTaylorHoodEnum: return P1DGEnum;
+		default: _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+}
+/*}}}*/
+int  TriaRef::VelocityInterpolation(int fe_stokes){/*{{{*/
+
+	switch(fe_stokes){
+		case P1P1Enum:              return P1Enum;
+		case P1P1GLSEnum:           return P1Enum;
+		case MINIcondensedEnum:     return P1bubbleEnum;
+		case MINIEnum:              return P1bubbleEnum;
+		case TaylorHoodEnum:        return P2Enum;
+		case LATaylorHoodEnum:      return P2Enum;
+		case XTaylorHoodEnum:       return P2Enum;
+		case CrouzeixRaviartEnum:   return P2bubbleEnum;
+		case LACrouzeixRaviartEnum: return P2bubbleEnum;
+		default:       _error_("Element type "<<EnumToStringx(fe_stokes)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/TriaRef.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/TriaRef.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Elements/TriaRef.h	(revision 19105)
@@ -16,22 +16,21 @@
 
 		/*Numerics*/
+		void GetInputDerivativeValue(IssmDouble* pp, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
+		void GetInputValue(IssmDouble* pp, IssmDouble* plist, Gauss* gauss,int finiteelement);
 		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,Gauss* gauss);
-		void GetSegmentJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss);
 		void GetJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss);
 		void GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,Gauss* gauss);
 		void GetNodalFunctions(IssmDouble* basis,Gauss* gauss,int finiteelement);
-		void GetSegmentNodalFunctions(IssmDouble* basis,Gauss* gauss, int index1,int index2,int finiteelement);
+		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
+		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss,int finiteelement);
 		void GetSegmentBFlux(IssmDouble* B,Gauss* gauss, int index1,int index2,int finiteelement);
 		void GetSegmentBprimeFlux(IssmDouble* Bprime,Gauss* gauss, int index1,int index2,int finiteelement);
-		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
-		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,Gauss* gauss,int finiteelement);
-		void GetInputValue(IssmDouble* pp, IssmDouble* plist, Gauss* gauss,int finiteelement);
-		void GetInputDerivativeValue(IssmDouble* pp, IssmDouble* plist,IssmDouble* xyz_list, Gauss* gauss,int finiteelement);
-
+		void GetSegmentJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,Gauss* gauss);
+		void GetSegmentNodalFunctions(IssmDouble* basis,Gauss* gauss, int index1,int index2,int finiteelement);
 		void NodeOnEdgeIndices(int* pnumindices,int** pindices,int index,int finiteelement);
 		int  NumberofNodes(int finiteelement);
-		int  VelocityInterpolation(int fe_stokes);
 		int  PressureInterpolation(int fe_stokes);
 		int  TensorInterpolation(int fe_stokes);
+		int  VelocityInterpolation(int fe_stokes);
 };
 #endif
Index: /issm/trunk/src/c/classes/ExternalResults/ExternalResult.h
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/ExternalResult.h	(revision 19104)
+++ /issm/trunk/src/c/classes/ExternalResults/ExternalResult.h	(revision 19105)
@@ -28,4 +28,5 @@
 		virtual int    GetStep(void)=0;
 		virtual double GetValue(void)=0;
+		virtual int    GetResultEnum(void)=0;
 };
 #endif
Index: /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h	(revision 19104)
+++ /issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h	(revision 19105)
@@ -160,11 +160,17 @@
 		return name;
 } /*}}}*/
+int GetResultEnum(void){ /*{{{*/
+		return StringToEnumx(this->result_name,false);
+} /*}}}*/
 int   GetStep(void){ /*{{{*/
 	return this->step;
 } /*}}}*/
-IssmPDouble GetValue(void){ /*{{{*/
+double GetValue(void){ /*{{{*/
 	/*Only supported by IssmPDouble result, error out by default*/
 	_error_("not supported for this type of result");
-	return 0.;
+} /*}}}*/
+double* GetValues(void){ /*{{{*/
+	/*Only supported by IssmPDouble* result, error out by default*/
+	_error_("not supported for this type of result");
 } /*}}}*/
 };
@@ -367,4 +373,7 @@
 	return DoubleMatExternalResultEnum;
 } /*}}}*/
+template <> inline double* GenericExternalResult<IssmPDouble*>::GetValues(void){ /*{{{*/
+	return value;
+} /*}}}*/
 
 /*Specific instantiations for IssmDouble*: */
Index: /issm/trunk/src/c/classes/ExternalResults/Results.cpp
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/Results.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/ExternalResults/Results.cpp	(revision 19105)
@@ -41,5 +41,5 @@
 
 	for(int i=0;i<this->Size();i++){
-		ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
+		ExternalResult* result=xDynamicCast<ExternalResult*>(this->GetObjectByOffset(i));
 		result->WriteData(fid,io_gather);
 	}
@@ -57,5 +57,5 @@
 
 	for(int i=0;i<this->Size();i++){
-		ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
+		ExternalResult* result=xDynamicCast<ExternalResult*>(this->GetObjectByOffset(i));
 
 		if(result->GetStep()==in_result->GetStep()){
@@ -81,5 +81,5 @@
 
 	for(int i=0;i<this->Size();i++){
-		ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
+		ExternalResult* result=xDynamicCast<ExternalResult*>(this->GetObjectByOffset(i));
 
 		if(result->GetStep()==result_step){
@@ -94,2 +94,14 @@
 }
 /*}}}*/
+ExternalResult* Results::FindResult(int result_enum){/*{{{*/
+
+	for(int i=0;i<this->Size();i++){
+		ExternalResult* result=xDynamicCast<ExternalResult*>(this->GetObjectByOffset(i));
+
+		if(result->GetResultEnum()==result_enum){
+			return result;
+		}
+	}
+	return NULL;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/ExternalResults/Results.h
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/Results.h	(revision 19104)
+++ /issm/trunk/src/c/classes/ExternalResults/Results.h	(revision 19105)
@@ -22,4 +22,5 @@
 		/*Mehthos*/
 		int AddResult(ExternalResult* result);
+		ExternalResult* FindResult(int result_enum);
 		int DeleteResult(int result_enum,int result_step);
 		void Write(Parameters* parameters);
Index: /issm/trunk/src/c/classes/FemModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/FemModel.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/FemModel.cpp	(revision 19105)
@@ -43,9 +43,7 @@
 
 /*Object constructors and destructor*/
-FemModel::FemModel(int argc,char** argv,ISSM_MPI_Comm incomm){/*{{{*/
+FemModel::FemModel(int argc,char** argv,ISSM_MPI_Comm incomm,bool trace){/*{{{*/
 
 	/*configuration: */
-	int* analyses=NULL;
-	int  numanalyses;
 	int  solution_type;
 	int  ierr;
@@ -75,14 +73,10 @@
 	ProcessArguments(&solution_type,&binfilename,&outbinfilename,&petscfilename,&lockfilename,&rootpath,argc,argv);
 
-	/*out of solution_type, figure out types of analyses needed in the femmodel: */
-	AnalysisConfiguration(&analyses,&numanalyses,solution_type);
-
 	/*Create femmodel from input files: */
 	profiler->Tag(StartInit);
-	this->InitFromFiles(rootpath,binfilename,outbinfilename,petscfilename,lockfilename,solution_type,analyses,numanalyses);
+	this->InitFromFiles(rootpath,binfilename,outbinfilename,petscfilename,lockfilename,solution_type,trace,NULL);
 	profiler->Tag(FinishInit);
 
 	/*Free resources */
-	xDelete<int>(analyses);
 	xDelete<char>(lockfilename);
 	xDelete<char>(binfilename);
@@ -93,8 +87,16 @@
 }
 /*}}}*/
-FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){/*{{{*/
-
-	/*Call InitFromFiles. This constructor is just a wrapper: */
-	this->InitFromFiles(rootpath, inputfilename, outputfilename, toolkitsfilename, lockfilename, in_solution_type,analyses,nummodels);
+FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, ISSM_MPI_Comm incomm, int solution_type,IssmPDouble* X){ /*{{{*/
+
+	bool traceon=true;
+	this->profiler=NULL; /*avoid leak, as we are not using the profiler ever in ad control run. */
+	
+	/*Store the communicator, but do not set it as a global variable, as this has already 
+	 * been done by the FemModel that called this copy constructor: */
+	this->comm=incomm;
+	this->SetStaticComm();
+
+	/*Create femmodel from input files, with trace activated: */
+	this->InitFromFiles(rootpath,inputfilename,outputfilename,toolkitsfilename,lockfilename,solution_type,traceon,X);
 
 }
@@ -111,19 +113,18 @@
 
 	/*Delete all the datasets: */
-	xDelete<int>(analysis_type_list);
-	xDelete<char>(outbinfilename);
-	xDelete<char>(lockfilename);
-	delete elements;
-	delete nodes;
-	delete vertices;
-	delete constraints;
-	delete loads;
-	delete materials;
-	delete parameters;
-	delete results;
+	if(analysis_type_list)xDelete<int>(analysis_type_list);
+	if(outbinfilename)xDelete<char>(outbinfilename);
+	if(lockfilename)xDelete<char>(lockfilename);
+	if(elements)delete elements;
+	if(nodes)delete nodes;
+	if(vertices)delete vertices;
+	if(constraints)delete constraints;
+	if(loads)delete loads;
+	if(materials)delete materials;
+	if(parameters)delete parameters;
+	if(results)delete results;
 
 	/*Now delete: */
-	delete profiler;
-
+	if(profiler)delete profiler;
 }
 /*}}}*/
@@ -141,5 +142,5 @@
 }
 /*}}}*/
-void FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){/*{{{*/
+void FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, const int in_solution_type,bool trace,IssmPDouble* X){/*{{{*/
 
 	/*intermediary*/
@@ -154,24 +155,20 @@
 	my_rank=IssmComm::GetRank();
 
-	/*Open input file on cpu 0: */
-	if(my_rank==0) IOMODEL = pfopen0(inputfilename ,"rb");
-
-	/*Open toolkits file: */
-	toolkitsoptionsfid=pfopen(toolkitsfilename,"r");
-
 	/*Initialize internal data: */
-	this->nummodels        = nummodels;
 	this->solution_type    = in_solution_type;
 	this->analysis_counter = nummodels-1;   //point to last analysis_type carried out.
 	this->results          = new Results(); //not initialized by CreateDataSets
-
-	/*Dynamically allocate whatever is a list of length nummodels: */
-	analysis_type_list=xNew<int>(nummodels);
-
-	/*Initialize: */
-	for(i=0;i<nummodels;i++)analysis_type_list[i]=analyses[i];
+	/*Open input file on cpu 0 and create IoModel */
+	if(my_rank==0) IOMODEL = pfopen0(inputfilename ,"rb");
+	IoModel* iomodel = new IoModel(IOMODEL,trace,X);
+
+	/*Figure out what analyses are activated for this solution*/
+	SolutionAnalysesList(&this->analysis_type_list,&this->nummodels,iomodel,this->solution_type);
+
+	/*Open toolkits file: */
+	toolkitsoptionsfid=pfopen(toolkitsfilename,"r");
 
 	/*create datasets for all analyses*/
-	ModelProcessorx(&this->elements,&this->nodes,&this->vertices,&this->materials,&this->constraints,&this->loads,&this->parameters,IOMODEL,toolkitsoptionsfid,rootpath,this->solution_type,nummodels,analyses);
+	ModelProcessorx(&this->elements,&this->nodes,&this->vertices,&this->materials,&this->constraints,&this->loads,&this->parameters,iomodel,toolkitsoptionsfid,rootpath,this->solution_type,this->nummodels,this->analysis_type_list);
 
 	/*do the post-processing of the datasets to get an FemModel that can actually run analyses: */
@@ -201,14 +198,18 @@
 	pfclose(toolkitsoptionsfid,toolkitsfilename);
 
-	/*Open output file once for all and add output file name and file descriptor to parameters*/
+	/*Open output file once for all and add output file descriptor to parameters*/
 	output_fid=pfopen(outputfilename,"wb");
+	this->parameters->SetParam(output_fid,OutputFilePointerEnum);
+	
+	/*Now save all of these file names into parameters, you never know when you might need them: */
+	this->parameters->AddObject(new StringParam(ToolkitsFileNameEnum,toolkitsfilename));
+	this->parameters->AddObject(new StringParam(RootPathEnum,rootpath));
+	this->parameters->AddObject(new StringParam(InputFileNameEnum,inputfilename));
 	this->parameters->AddObject(new StringParam(OutputFileNameEnum,outputfilename));
-	this->parameters->SetParam(output_fid,OutputFilePointerEnum);
-
-	/*Save lock file name for later: */
 	this->parameters->AddObject(new StringParam(LockFileNameEnum,lockfilename));
 
-	}
-/*}}}*/
+	/*Clean up*/
+	delete iomodel;
+}/*}}}*/
 void FemModel::CleanUp(void){/*{{{*/
 
@@ -238,5 +239,5 @@
 	_printf0_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<profiler->DeltaTime(StartCore,FinishCore) << "\n");
 	_printf0_("\n");
-	_printf0_("   Total elapsed time:"
+	_printf0_("   Total elapsed time: "
 				<<profiler->DeltaTimeModHour(Start,Finish)<<" hrs "
 				<<profiler->DeltaTimeModMin(Start,Finish)<<" min "
@@ -324,5 +325,5 @@
 	WrapperCorePointerFromSolutionEnum(&solutioncore,this->parameters,solution_type);
 
-	/*run solutoin core: */
+	/*run solution core: */
 	profiler->Tag(StartCore);   
 	solutioncore(this); 
@@ -412,4 +413,194 @@
 }
 /*}}}*/
+void  FemModel::SolutionAnalysesList(int** panalyses,int* pnumanalyses,IoModel* iomodel,int solutiontype){/*{{{*/
+
+	/*output: */
+	int  numanalyses = 0;
+	int* analyses=NULL;
+
+	/*Intermediaries*/
+	const int MAXANALYSES = 30;
+	int   analyses_temp[MAXANALYSES];
+
+	/*Analyses lists*/
+	switch(solutiontype){
+
+		case StressbalanceSolutionEnum:{
+			bool isSIA,isFS;
+			int  fe_FS;
+			iomodel->Constant(&fe_FS,FlowequationFeFSEnum);
+			iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+			iomodel->Constant(&isFS,FlowequationIsFSEnum);
+			analyses_temp[numanalyses++]=StressbalanceAnalysisEnum;
+			analyses_temp[numanalyses++]=StressbalanceVerticalAnalysisEnum;
+			if(isSIA){
+				analyses_temp[numanalyses++]=StressbalanceSIAAnalysisEnum;
+			}
+			analyses_temp[numanalyses++]=L2ProjectionBaseAnalysisEnum;
+			analyses_temp[numanalyses++]=ExtrudeFromBaseAnalysisEnum;
+			analyses_temp[numanalyses++]=DepthAverageAnalysisEnum;
+			if(fe_FS==LATaylorHoodEnum || fe_FS==LACrouzeixRaviartEnum){
+				analyses_temp[numanalyses++]=UzawaPressureAnalysisEnum;
+			}
+			}
+			break;
+
+		case SteadystateSolutionEnum:{
+			bool isSIA,isenthalpy;
+			iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+			iomodel->Constant(&isenthalpy,ThermalIsenthalpyEnum);
+			analyses_temp[numanalyses++]=StressbalanceAnalysisEnum;
+			analyses_temp[numanalyses++]=StressbalanceVerticalAnalysisEnum;
+			if(isSIA){
+				analyses_temp[numanalyses++]=StressbalanceSIAAnalysisEnum;
+			}
+			if(isenthalpy){
+				analyses_temp[numanalyses++]=EnthalpyAnalysisEnum;
+			}
+			else{
+				analyses_temp[numanalyses++]=ThermalAnalysisEnum;
+				analyses_temp[numanalyses++]=MeltingAnalysisEnum;
+			}
+			analyses_temp[numanalyses++]=L2ProjectionBaseAnalysisEnum;
+			}
+			break;
+
+		case ThermalSolutionEnum:{
+			bool isenthalpy;
+			iomodel->Constant(&isenthalpy,ThermalIsenthalpyEnum);
+			if(isenthalpy){
+				analyses_temp[numanalyses++]=EnthalpyAnalysisEnum;
+			}
+			else{
+				analyses_temp[numanalyses++]=ThermalAnalysisEnum;
+				analyses_temp[numanalyses++]=MeltingAnalysisEnum;
+			}
+			}
+			break;
+
+		case HydrologySolutionEnum:
+			analyses_temp[numanalyses++]=HydrologyShreveAnalysisEnum;
+			analyses_temp[numanalyses++]=HydrologyDCInefficientAnalysisEnum;
+			analyses_temp[numanalyses++]=HydrologyDCEfficientAnalysisEnum;
+			analyses_temp[numanalyses++]=L2ProjectionBaseAnalysisEnum;
+			analyses_temp[numanalyses++]=L2ProjectionEPLAnalysisEnum;
+			break;
+
+		case MasstransportSolutionEnum:
+			analyses_temp[numanalyses++]=MasstransportAnalysisEnum;
+			break;
+
+		case BalancethicknessSolutionEnum:
+			analyses_temp[numanalyses++]=BalancethicknessAnalysisEnum;
+			break;
+
+		case Balancethickness2SolutionEnum:
+			analyses_temp[numanalyses++]=L2ProjectionBaseAnalysisEnum;
+			analyses_temp[numanalyses++]=SmoothAnalysisEnum;
+			analyses_temp[numanalyses++]=Balancethickness2AnalysisEnum;
+			break;
+
+		case BalancethicknessSoftSolutionEnum:
+			analyses_temp[numanalyses++]=BalancethicknessAnalysisEnum;
+			break;
+
+		case BalancevelocitySolutionEnum:
+			analyses_temp[numanalyses++]=BalancevelocityAnalysisEnum;
+			analyses_temp[numanalyses++]=SmoothAnalysisEnum;
+			break;
+
+		case SurfaceSlopeSolutionEnum:
+			analyses_temp[numanalyses++]=L2ProjectionBaseAnalysisEnum;
+			break;
+
+		case BedSlopeSolutionEnum:
+			analyses_temp[numanalyses++]=L2ProjectionBaseAnalysisEnum;
+			break;
+
+		case GiaSolutionEnum:
+			analyses_temp[numanalyses++]=GiaAnalysisEnum;
+			break;
+		
+		case DamageEvolutionSolutionEnum:
+			analyses_temp[numanalyses++]=DamageEvolutionAnalysisEnum;
+			break;
+
+		case TransientSolutionEnum:{
+			bool isSIA,isFS,isthermal,isenthalpy,ismasstransport,isgroundingline,isstressbalance,islevelset,ishydrology,isdamage;
+			iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+			iomodel->Constant(&isFS,FlowequationIsFSEnum);
+			iomodel->Constant(&isthermal,TransientIsthermalEnum);
+			iomodel->Constant(&isenthalpy,ThermalIsenthalpyEnum);
+			iomodel->Constant(&islevelset,TransientIslevelsetEnum);
+			iomodel->Constant(&ismasstransport,TransientIsmasstransportEnum);
+			iomodel->Constant(&isstressbalance,TransientIsstressbalanceEnum);
+			iomodel->Constant(&isgroundingline,TransientIsgroundinglineEnum);
+			iomodel->Constant(&isdamage,TransientIsdamageevolutionEnum);
+			iomodel->Constant(&ishydrology,TransientIshydrologyEnum);
+			if(isstressbalance){
+				int  fe_FS;
+				iomodel->Constant(&fe_FS,FlowequationFeFSEnum);
+				analyses_temp[numanalyses++]=StressbalanceAnalysisEnum;
+				analyses_temp[numanalyses++]=StressbalanceVerticalAnalysisEnum;
+				if(isSIA){
+					analyses_temp[numanalyses++]=StressbalanceSIAAnalysisEnum;
+				}
+				analyses_temp[numanalyses++]=DepthAverageAnalysisEnum;
+				if(fe_FS==LATaylorHoodEnum || fe_FS==LACrouzeixRaviartEnum){
+					analyses_temp[numanalyses++]=UzawaPressureAnalysisEnum;
+				}
+			}
+			if(isthermal && iomodel->domaintype==Domain3DEnum){
+				if(isenthalpy){
+					analyses_temp[numanalyses++]=EnthalpyAnalysisEnum;
+				}
+				else{
+					analyses_temp[numanalyses++]=ThermalAnalysisEnum;
+					analyses_temp[numanalyses++]=MeltingAnalysisEnum;
+				}
+			}
+			if(ismasstransport || isgroundingline){
+				analyses_temp[numanalyses++]=MasstransportAnalysisEnum;
+			}
+			if(islevelset){
+				analyses_temp[numanalyses++]=LevelsetAnalysisEnum;
+				analyses_temp[numanalyses++]=ExtrapolationAnalysisEnum;
+				analyses_temp[numanalyses++]=LsfReinitializationAnalysisEnum;
+			}
+			if(ishydrology){
+				analyses_temp[numanalyses++]=HydrologyShreveAnalysisEnum;
+				analyses_temp[numanalyses++]=HydrologyDCInefficientAnalysisEnum;
+				analyses_temp[numanalyses++]=HydrologyDCEfficientAnalysisEnum;
+				analyses_temp[numanalyses++]=L2ProjectionEPLAnalysisEnum;
+			}
+			if(isdamage){
+				analyses_temp[numanalyses++]=DamageEvolutionAnalysisEnum;
+			}
+
+			if(iomodel->domaintype==Domain2DverticalEnum || iomodel->domaintype==Domain3DEnum){
+				analyses_temp[numanalyses++]=ExtrudeFromBaseAnalysisEnum;
+				analyses_temp[numanalyses++]=ExtrudeFromTopAnalysisEnum;
+				analyses_temp[numanalyses++]=FreeSurfaceBaseAnalysisEnum;
+				analyses_temp[numanalyses++]=FreeSurfaceTopAnalysisEnum;
+			}
+			analyses_temp[numanalyses++]=L2ProjectionBaseAnalysisEnum;
+			}
+			break;
+
+		default:
+			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
+			break;
+	}
+
+	/*Copy analyses from temp to output*/
+	_assert_(numanalyses<MAXANALYSES);
+	analyses=xNew<int>(numanalyses);
+	for(int i=0;i<numanalyses;i++) analyses[i]=analyses_temp[i];
+
+	/*Assign output pointers:*/
+	if(pnumanalyses) *pnumanalyses=numanalyses;
+	if(panalyses)    *panalyses=analyses;
+	else              xDelete<int>(analyses);
+}/*}}}*/
 
 /*Modules:*/
@@ -420,6 +611,6 @@
 
 	/*get vertex vectors for bed and thickness: */
-	GetVectorFromInputsx(&surface  ,this, SurfaceEnum,VertexEnum);
-	GetVectorFromInputsx(&bed      ,this, BaseEnum,    VertexEnum);
+	GetVectorFromInputsx(&surface  ,this, SurfaceEnum,VertexPIdEnum);
+	GetVectorFromInputsx(&bed      ,this, BaseEnum,   VertexPIdEnum);
 
 	/*Allocate vector*/
@@ -477,4 +668,13 @@
 }
 /*}}}*/
+void FemModel::ElementOperationx(void (Element::*function)(void)){ /*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		(element->*function)();
+	}
+
+}
+/*}}}*/
 void FemModel::Responsex(IssmDouble* responses,const char* response_descriptor){/*{{{*/
 
@@ -489,4 +689,6 @@
 
 		case DivergenceEnum:               this->Divergencex(responses); break;
+		case MaxDivergenceEnum:            this->MaxDivergencex(responses); break;
+		case IceMassEnum:                  this->IceMassx(responses); break;
 		case IceVolumeEnum:                this->IceVolumex(responses); break;
 		case IceVolumeAboveFloatationEnum: this->IceVolumeAboveFloatationx(responses); break;
@@ -515,5 +717,4 @@
 		case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters); break;
 		case BalancethicknessMisfitEnum:   BalancethicknessMisfitx(responses); break;
-		case Balancethickness2MisfitEnum:  Balancethickness2Misfitx(responses); break;
 		case TotalSmbEnum:					  this->TotalSmbx(responses); break;
 		case MaterialsRheologyBbarEnum:    this->ElementResponsex(responses,MaterialsRheologyBbarEnum); break;
@@ -559,23 +760,34 @@
 		}
 		else{
-			switch(output_enum){
-
-				/*Scalar output*/
-				case DivergenceEnum:               this->Divergencex(&double_result);               break;
-				case IceVolumeEnum:                this->IceVolumex(&double_result);                break;
-				case IceVolumeAboveFloatationEnum: this->IceVolumeAboveFloatationx(&double_result); break;
-				case MinVelEnum:                   this->MinVelx(&double_result);                   break;
-				case MaxVelEnum:                   this->MaxVelx(&double_result);                   break;
-				case MinVxEnum:                    this->MinVxx(&double_result);                    break;
-				case MaxVxEnum:                    this->MaxVxx(&double_result);                    break;
-				case MaxAbsVxEnum:                 this->MaxAbsVxx(&double_result);                 break;
-				case MinVyEnum:                    this->MinVyx(&double_result);                    break;
-				case MaxVyEnum:                    this->MaxVyx(&double_result);                    break;
-				case MaxAbsVyEnum:                 this->MaxAbsVyx(&double_result);                 break;
-				case MinVzEnum:                    this->MinVzx(&double_result);                    break;
-				case MaxVzEnum:                    this->MaxVzx(&double_result);                    break;
-				case MaxAbsVzEnum:                 this->MaxAbsVzx(&double_result);                 break;
-				case MassFluxEnum:                 this->MassFluxx(&double_result);                 break;
-				case TotalSmbEnum:                 this->TotalSmbx(&double_result);                 break;
+			/*last chance for the output definition, if the enum is one of Outputdefinition[1-10]Enum:*/
+			if(output_enum>=Outputdefinition1Enum && output_enum <=Outputdefinition10Enum){
+				double_result = OutputDefinitionsResponsex(this,output_enum);
+				if(save_results){
+					results->AddResult(new GenericExternalResult<IssmPDouble>(results->Size()+1,output_string,reCast<IssmPDouble>(double_result),step,time));
+					continue;
+				}
+			}
+			else{
+				switch(output_enum){
+
+					/*Scalar output*/
+					case DivergenceEnum:               this->Divergencex(&double_result);               break;
+					case MaxDivergenceEnum:            this->MaxDivergencex(&double_result);            break;
+					case IceMassEnum:                this->IceMassx(&double_result);                break;
+					case IceVolumeEnum:                this->IceVolumex(&double_result);                break;
+					case IceVolumeAboveFloatationEnum: this->IceVolumeAboveFloatationx(&double_result); break;
+					case MinVelEnum:                   this->MinVelx(&double_result);                   break;
+					case MaxVelEnum:                   this->MaxVelx(&double_result);                   break;
+					case MinVxEnum:                    this->MinVxx(&double_result);                    break;
+					case MaxVxEnum:                    this->MaxVxx(&double_result);                    break;
+					case MaxAbsVxEnum:                 this->MaxAbsVxx(&double_result);                 break;
+					case MinVyEnum:                    this->MinVyx(&double_result);                    break;
+					case MaxVyEnum:                    this->MaxVyx(&double_result);                    break;
+					case MaxAbsVyEnum:                 this->MaxAbsVyx(&double_result);                 break;
+					case MinVzEnum:                    this->MinVzx(&double_result);                    break;
+					case MaxVzEnum:                    this->MaxVzx(&double_result);                    break;
+					case MaxAbsVzEnum:                 this->MaxAbsVzx(&double_result);                 break;
+					case MassFluxEnum:                 this->MassFluxx(&double_result);                 break;
+					case TotalSmbEnum:                 this->TotalSmbx(&double_result);                 break;
 
 			   /*Scalar control output*/
@@ -590,71 +802,74 @@
 				case ThicknessAcrossGradientEnum:   ThicknessAcrossGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters);    break;
 				case RheologyBbarAbsGradientEnum:   RheologyBbarAbsGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters);    break;
+				case RheologyBAbsGradientEnum:      RheologyBAbsGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters);  break;
 				case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(&double_result,elements,nodes,vertices,loads,materials,parameters); break;
 				case BalancethicknessMisfitEnum:    BalancethicknessMisfitx(&double_result);                                                        break;
-				case Balancethickness2MisfitEnum:  Balancethickness2Misfitx(&double_result); break;
-
-			   /*Vector */
-				default:
-
-					/*Vector layout*/
-					int interpolation,nodesperelement,size;
-					int rank_interpolation=-1,rank_nodesperelement=-1;
-
-					/*Get interpolation (and compute input if necessary)*/
-					for(int j=0;j<elements->Size();j++){
-						Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(j));
-						element->ResultInterpolation(&rank_interpolation,&rank_nodesperelement,output_enum);
-					}
-
-					/*Broadcast for cpus that do not have any elements*/
-					ISSM_MPI_Reduce(&rank_interpolation,&interpolation,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
-					ISSM_MPI_Reduce(&rank_nodesperelement,&nodesperelement,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
-					ISSM_MPI_Bcast(&interpolation,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-					ISSM_MPI_Bcast(&nodesperelement,1,ISSM_MPI_INT,0,IssmComm::GetComm());
-
-					if(results_on_nodes){
-
-						/*Allocate matrices*/
-						int         nbe       = this->elements->NumberOfElements();
-						IssmDouble* values    = xNewZeroInit<IssmDouble>(nbe*nodesperelement);
-						IssmDouble* allvalues = xNew<IssmDouble>(nbe*nodesperelement);
-
-						/*Fill-in matrix*/
+				case SurfaceAbsMisfitEnum:          SurfaceAbsMisfitx(&double_result); break;
+
+				   /*Vector */
+					default:
+
+						/*Vector layout*/
+						int interpolation,nodesperelement,size;
+						int rank_interpolation=-1,rank_nodesperelement=-1;
+
+						/*Get interpolation (and compute input if necessary)*/
 						for(int j=0;j<elements->Size();j++){
-							Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(j));
-							element->ResultToPatch(values,nodesperelement,output_enum);
+							Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(j));
+							element->ResultInterpolation(&rank_interpolation,&rank_nodesperelement,output_enum);
 						}
 
-						/*Gather from all cpus*/
-						ISSM_MPI_Allreduce((void*)values,(void*)allvalues,nbe*nodesperelement,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
-						xDelete<IssmDouble>(values);
-
-						if(save_results)results->AddResult(new GenericExternalResult<IssmDouble*>(results->Size()+1,output_enum,allvalues,nbe,nodesperelement,step,time));
-						xDelete<IssmDouble>(allvalues);
-
-					}
-					else{
-
-						/*Allocate vector depending on interpolation*/
-						switch(interpolation){
-							case P0Enum: size = this->elements->NumberOfElements(); break;
-							case P1Enum: size = this->vertices->NumberOfVertices(); break;
-							default:     _error_("Interpolation "<<EnumToStringx(interpolation)<<" not supported yet");
+						/*Broadcast for cpus that do not have any elements*/
+						ISSM_MPI_Reduce(&rank_interpolation,&interpolation,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
+						ISSM_MPI_Reduce(&rank_nodesperelement,&nodesperelement,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm());
+						ISSM_MPI_Bcast(&interpolation,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+						ISSM_MPI_Bcast(&nodesperelement,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+
+						if(results_on_nodes){
+
+							/*Allocate matrices*/
+							int         nbe       = this->elements->NumberOfElements();
+							IssmDouble* values    = xNewZeroInit<IssmDouble>(nbe*nodesperelement);
+							IssmDouble* allvalues = xNew<IssmDouble>(nbe*nodesperelement);
+
+							/*Fill-in matrix*/
+							for(int j=0;j<elements->Size();j++){
+								Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(j));
+								element->ResultToPatch(values,nodesperelement,output_enum);
+							}
+
+							/*Gather from all cpus*/
+							ISSM_MPI_Allreduce((void*)values,(void*)allvalues,nbe*nodesperelement,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+							xDelete<IssmDouble>(values);
+
+							if(save_results)results->AddResult(new GenericExternalResult<IssmDouble*>(results->Size()+1,output_enum,allvalues,nbe,nodesperelement,step,time));
+							xDelete<IssmDouble>(allvalues);
 
 						}
-						Vector<IssmDouble> *vector_result = new Vector<IssmDouble>(size);
-
-						/*Fill in vector*/
-						for(int j=0;j<elements->Size();j++){
-							Element* element=(Element*)elements->GetObjectByOffset(j);
-							element->ResultToVector(vector_result,output_enum);
+						else{
+
+							/*Allocate vector depending on interpolation*/
+							switch(interpolation){
+								case P0Enum: size = this->elements->NumberOfElements(); break;
+								case P1Enum: size = this->vertices->NumberOfVertices(); break;
+								default:     _error_("Interpolation "<<EnumToStringx(interpolation)<<" not supported yet");
+
+							}
+							Vector<IssmDouble> *vector_result = new Vector<IssmDouble>(size);
+
+							/*Fill in vector*/
+							for(int j=0;j<elements->Size();j++){
+								Element* element=(Element*)elements->GetObjectByOffset(j);
+								element->ResultToVector(vector_result,output_enum);
+							}
+							vector_result->Assemble();
+
+							if(save_results)results->AddResult(new GenericExternalResult<Vector<IssmDouble>*>(results->Size()+1,output_enum,vector_result,step,time));
 						}
-						vector_result->Assemble();
-
-						if(save_results)results->AddResult(new GenericExternalResult<Vector<IssmDouble>*>(results->Size()+1,output_enum,vector_result,step,time));
-					}
-					isvec = true;
-					break;
-			}
+						isvec = true;
+						break;
+				}
+			}
+
 		}
 
@@ -739,5 +954,5 @@
 
 	for (i=1;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		dt=element->TimeAdapt();
 		if(dt<min_dt)min_dt=dt;
@@ -756,5 +971,5 @@
 
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->UpdateConstraintsExtrudeFromBase();
 	}
@@ -765,5 +980,5 @@
 
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->UpdateConstraintsExtrudeFromTop();
 	}
@@ -839,5 +1054,5 @@
 	maxabsvx=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		element_maxabsvx=element->inputs->MaxAbs(VxEnum);
 		if(element_maxabsvx>maxabsvx) maxabsvx=element_maxabsvx;
@@ -863,5 +1078,5 @@
 	maxabsvy=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		element_maxabsvy=element->inputs->MaxAbs(VyEnum);
 		if(element_maxabsvy>maxabsvy) maxabsvy=element_maxabsvy;
@@ -887,5 +1102,5 @@
 	maxabsvz=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		element_maxabsvz=element->inputs->MaxAbs(VzEnum);
 		if(element_maxabsvz>maxabsvz) maxabsvz=element_maxabsvz;
@@ -911,5 +1126,5 @@
 	maxvel=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		element_maxvel = element->inputs->Max(VelEnum);
 		if(element_maxvel>maxvel) maxvel=element_maxvel;
@@ -935,5 +1150,5 @@
 	maxvx=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		element_maxvx = element->inputs->Max(VxEnum);
 		if(element_maxvx>maxvx) maxvx=element_maxvx;
@@ -959,5 +1174,5 @@
 	maxvy=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		element_maxvy = element->inputs->Max(VyEnum);
 		if(element_maxvy>maxvy) maxvy=element_maxvy;
@@ -983,5 +1198,5 @@
 	maxvz=-INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		element_maxvz = element->inputs->Max(VzEnum);
 		if(element_maxvz>maxvz) maxvz=element_maxvz;
@@ -1007,5 +1222,5 @@
 	minvel=INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		element_minvel = element->inputs->Min(VelEnum);
 		if(element_minvel<minvel) minvel=element_minvel;
@@ -1031,5 +1246,5 @@
 	minvx=INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		element_minvx = element->inputs->Min(VxEnum);
 		if(element_minvx<minvx) minvx=element_minvx;
@@ -1055,5 +1270,5 @@
 	minvy=INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		element_minvy = element->inputs->Min(VyEnum);
 		if(element_minvy<minvy) minvy=element_minvy;
@@ -1079,5 +1294,5 @@
 	minvz=INFINITY;
 	for(i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		element_minvz = element->inputs->Min(VzEnum);
 		if(element_minvz<minvz) minvz=element_minvz;
@@ -1099,5 +1314,5 @@
 
 	for(int i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		local_smb+=element->TotalSmb();
 	}
@@ -1115,5 +1330,5 @@
 
 	for(int i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		local_divergence+=element->Divergence();
 	}
@@ -1125,4 +1340,72 @@
 
 }/*}}}*/
+void FemModel::MaxDivergencex(IssmDouble* pdiv){/*{{{*/
+
+	IssmDouble local_divergence;
+	IssmDouble node_max_divergence;
+	IssmDouble max_divergence = -INFINITY;
+
+	for(int i=0;i<this->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+		local_divergence=element->Divergence();
+		if(fabs(local_divergence)>max_divergence) max_divergence=fabs(local_divergence);
+	}
+	ISSM_MPI_Reduce(&max_divergence,&node_max_divergence,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_max_divergence,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	max_divergence=node_max_divergence;
+
+	/*Assign output pointers: */
+	*pdiv=max_divergence;
+
+}/*}}}*/
+void FemModel::GetInputLocalMinMaxOnNodesx(IssmDouble** pmin,IssmDouble** pmax,IssmDouble* ug){/*{{{*/
+
+	/*Get vector sizes for current configuration*/
+	int configuration_type;
+	this->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	int numnodes = this->nodes->NumberOfNodes(configuration_type);
+
+	/*Initialize output vectors*/
+	IssmDouble* uLmin_local = xNew<IssmDouble>(numnodes);
+	IssmDouble* uLmax_local = xNew<IssmDouble>(numnodes);
+	IssmDouble* uLmin = xNew<IssmDouble>(numnodes);
+	IssmDouble* uLmax = xNew<IssmDouble>(numnodes);
+	for(int i=0;i<numnodes;i++){
+		uLmin_local[i] = +1.e+50;
+		uLmax_local[i] = -1.e+50;
+	}
+
+	for(int i=0;i<this->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+		element->GetInputLocalMinMaxOnNodes(uLmin_local,uLmax_local,ug);
+	}
+
+	/*Synchronize all CPUs*/
+	ISSM_MPI_Allreduce((void*)uLmin_local,(void*)uLmin,numnodes,ISSM_MPI_DOUBLE,ISSM_MPI_MIN,IssmComm::GetComm());
+	ISSM_MPI_Allreduce((void*)uLmax_local,(void*)uLmax,numnodes,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,IssmComm::GetComm());
+	xDelete<IssmDouble>(uLmin_local);
+	xDelete<IssmDouble>(uLmax_local);
+
+	/*Assign output pointers: */
+	*pmin=uLmin;
+	*pmax=uLmax;
+
+}/*}}}*/
+void FemModel::IceMassx(IssmDouble* pM){/*{{{*/
+
+	IssmDouble local_ice_mass = 0;
+	IssmDouble total_ice_mass;
+
+	for(int i=0;i<this->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
+		local_ice_mass+=element->IceMass();
+	}
+	ISSM_MPI_Reduce(&local_ice_mass,&total_ice_mass,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&total_ice_mass,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+
+	/*Assign output pointers: */
+	*pM=total_ice_mass;
+
+}/*}}}*/
 void FemModel::IceVolumex(IssmDouble* pV){/*{{{*/
 
@@ -1131,5 +1414,5 @@
 
 	for(int i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		local_ice_volume+=element->IceVolume();
 	}
@@ -1147,5 +1430,5 @@
 
 	for(int i=0;i<this->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		local_ice_volume_af+=element->IceVolumeAboveFloatation();
 	}
@@ -1172,5 +1455,5 @@
 	/*now, go through our elements, and retrieve the one with this id: index: */
 	for(int i=0;i<this->elements->Size();i++){
-		element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element=xDynamicCast<Element*>(this->elements->GetObjectByOffset(i));
 		if (element->Id()==index){
 			found=1;
@@ -1210,5 +1493,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 
 		/*If on water, return 0: */
@@ -1265,5 +1548,5 @@
 
 }/*}}}*/
-void FemModel::Balancethickness2Misfitx(IssmDouble* presponse){/*{{{*/
+void FemModel::SurfaceAbsMisfitx(IssmDouble* presponse){/*{{{*/
 
 	/*output: */
@@ -1271,6 +1554,5 @@
 	IssmDouble J_sum;
 
-	IssmDouble  weight,thicknessobs,thickness,potential;
-	IssmDouble  vx,vy,vxbar,vybar,vxobs,vyobs,vxbarobs,vybarobs,nux,nuy;
+	IssmDouble  surface,surfaceobs,weight;
 	IssmDouble  Jdet;
 	IssmDouble* xyz_list = NULL;
@@ -1278,5 +1560,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 
 		/*If on water, return 0: */
@@ -1285,50 +1567,29 @@
 		/* Get node coordinates*/
 		element->GetVerticesCoordinates(&xyz_list);
-		Input* weights_input     =element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
-		Input* thickness_input   =element->GetInput(ThicknessEnum);                          _assert_(thickness_input);
-		Input* thicknessobs_input=element->GetInput(InversionThicknessObsEnum);              _assert_(thicknessobs_input);
-		Input* potential_input   =element->GetInput(PotentialEnum);                          _assert_(potential_input);
-		Input* vxobs_input       =element->GetInput(BalancethicknessVxObsEnum); _assert_(vxobs_input);
-		Input* vyobs_input       =element->GetInput(BalancethicknessVyObsEnum); _assert_(vyobs_input);
-		Input* vx_input          =element->GetInput(VxEnum); _assert_(vx_input);
-		Input* vy_input          =element->GetInput(VyEnum); _assert_(vy_input);
-		Input* nux_input       = element->GetInput(BalancethicknessNuxEnum);   _assert_(nux_input);
-		Input* nuy_input       = element->GetInput(BalancethicknessNuyEnum);   _assert_(nuy_input);
-
-		/* Start  looping on the number of gaussian points: */
-		Gauss* gauss=element->NewGauss(2);
-		for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-			gauss->GaussPoint(ig);
-
-			/* Get Jacobian determinant: */
-			element->JacobianDeterminant(&Jdet,xyz_list,gauss);
-
-			/*Get all parameters at gaussian point*/
-			weights_input->GetInputValue(&weight,gauss,Balancethickness2MisfitEnum);
-			thickness_input->GetInputValue(&thickness,gauss);
-			thicknessobs_input->GetInputValue(&thicknessobs,gauss);
-			potential_input->GetInputValue(&potential,gauss);
-			vxobs_input->GetInputValue(&vxobs,gauss);
-			vyobs_input->GetInputValue(&vyobs,gauss);
-			vx_input->GetInputValue(&vxbar,gauss);
-			vy_input->GetInputValue(&vybar,gauss);
-			nux_input->GetInputValue(&nux,gauss);
-			nuy_input->GetInputValue(&nuy,gauss);
-
-			vxbarobs = nux*vxobs;
-			vybarobs = nuy*vyobs;
-
-			/*J = (H^2 - Hobs^2)^2*/
-			//J +=0.5*(thickness*thickness - thicknessobs*thicknessobs)*(thickness*thickness - thicknessobs*thicknessobs)*weight*Jdet*gauss->weight;
-			/*J = phi^2*/
-			//J +=.5*potential*potential*weight*Jdet*gauss->weight; OK
-			/*J = (ubar - nux*uobs)^2*/
-			J +=0.5*((vxbarobs - vxbar)*(vxbarobs - vxbar) + (vybarobs - vybar)*(vybarobs - vybar))*weight*Jdet*gauss->weight;
-		}
-
-		/*clean up and Return: */
-		xDelete<IssmDouble>(xyz_list);
-		delete gauss;
+
+		 /*Retrieve all inputs we will be needing: */
+		 Input* weights_input   =element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+		 Input* surface_input   =element->GetInput(SurfaceEnum);                            _assert_(surface_input);
+		 Input* surfaceobs_input=element->GetInput(InversionSurfaceObsEnum);                _assert_(surfaceobs_input);
+
+		 /* Start  looping on the number of gaussian points: */
+		 Gauss* gauss=element->NewGauss(2);
+		 for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+			 gauss->GaussPoint(ig);
+
+			 /* Get Jacobian determinant: */
+			 element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+			 /*Get all parameters at gaussian point*/
+			 weights_input->GetInputValue(&weight,gauss,SurfaceAbsMisfitEnum);
+			 surface_input->GetInputValue(&surface,gauss);
+			 surfaceobs_input->GetInputValue(&surfaceobs,gauss);
+
+			 /*Compute SurfaceAbsMisfitEnum*/
+			 J+=0.5*(surface-surfaceobs)*(surface-surfaceobs)*weight*Jdet*gauss->weight;
+		 }
+		 delete gauss;
+		 xDelete<IssmDouble>(xyz_list);
 	}
 
@@ -1355,5 +1616,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 
 		/*If on water, return 0: */
@@ -1377,5 +1638,5 @@
 
 			/*Get all parameters at gaussian point*/
-			weights_input->GetInputValue(&weight,gauss,ThicknessAbsMisfitEnum);
+			weights_input->GetInputValue(&weight,gauss,ThicknessAbsGradientEnum);
 			thickness_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
 
@@ -1478,4 +1739,61 @@
 	/*Clean up and return*/
 	xDelete<int>(control_type);
+}
+/*}}}*/
+void FemModel::StressIntensityFactorx(){/*{{{*/
+
+	/*Update input for basal element only*/
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element->StressIntensityFactor();
+	}
+}
+	/*}}}*/
+void FemModel::CalvingRateLevermannx(){/*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element->CalvingRateLevermann();
+	}
+}
+/*}}}*/
+void FemModel::CalvingRatePix(){/*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element->CalvingRatePi();
+	}
+}
+/*}}}*/
+void FemModel::CalvingRateDevx(){/*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element->CalvingRateDev();
+	}
+}
+/*}}}*/
+void FemModel::StrainRateparallelx(){/*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element->StrainRateparallel();
+	}
+}
+/*}}}*/
+void FemModel::StrainRateperpendicularx(){/*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element->StrainRateperpendicular();
+	}
+}
+/*}}}*/
+void FemModel::DeviatoricStressx(){/*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element->ComputeDeviatoricStressTensor();
+	}
 }
 /*}}}*/
@@ -1513,5 +1831,5 @@
 
 			/*this response was scaled. pick up the response from the inputs: */
-			GetVectorFromInputsx(&vertex_response,this, StringToEnumx(root),VertexEnum);
+			GetVectorFromInputsx(&vertex_response,this, StringToEnumx(root),VertexPIdEnum);
 
 			/*Now, average it onto the partition nodes: */
@@ -1586,5 +1904,5 @@
 	/*Go through elements, and add contribution from each element to the deflection vector wg:*/
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->GiaDeflection(wg,dwgdt, x,y);
 	}
@@ -1592,33 +1910,61 @@
 /*}}}*/
 #endif
-void FemModel::HydrologyEPLupdateDomainx(void){ /*{{{*/
-
-	Vector<IssmDouble>* mask          = NULL;
-	IssmDouble*         serial_mask   = NULL;
-	Vector<IssmDouble>* active        = NULL;
-	IssmDouble*         serial_active = NULL;
+void FemModel::HydrologyEPLupdateDomainx(IssmDouble* pEplcount){ /*{{{*/
+
+	Vector<IssmDouble>* mask							= NULL;
+	Vector<IssmDouble>* recurence  				= NULL;
+	Vector<IssmDouble>* active						= NULL;
+	IssmDouble*         serial_mask				= NULL;
+	IssmDouble*         serial_rec  			= NULL;
+	IssmDouble*         serial_active			= NULL;
+	IssmDouble*         old_active        = NULL;
+	int*                eplzigzag_counter =	NULL;
+	int                 eplflip_lock;
 	
 	HydrologyDCEfficientAnalysis* effanalysis =  new HydrologyDCEfficientAnalysis();
+	HydrologyDCInefficientAnalysis* inefanalysis =  new HydrologyDCInefficientAnalysis();
+
 	/*Step 1: update mask, the mask might be extended by residual and/or using downstream sediment head*/
-	mask=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
-
+	mask=new Vector<IssmDouble>(this->nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
+	recurence=new Vector<IssmDouble>(this->nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
+	this->parameters->FindParam(&eplzigzag_counter,NULL,EplZigZagCounterEnum); 
+	this->parameters->FindParam(&eplflip_lock,HydrologydcEplflipLockEnum); 
+	GetVectorFromInputsx(&old_active,this,HydrologydcMaskEplactiveNodeEnum,NodeSIdEnum);
+	
 	for (int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		effanalysis->HydrologyEPLGetMask(mask,element);
-	}
-
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		effanalysis->HydrologyEPLGetMask(mask,recurence,eplzigzag_counter,element);
+	}
+	/*check for changes and increment zigzag counter, change the mask if necessary*/
+	recurence->Assemble();
+	serial_rec=recurence->ToMPISerial();
+	for (int i=0;i<nodes->Size();i++){
+		Node* node=xDynamicCast<Node*>(nodes->GetObjectByOffset(i));
+		if(serial_rec[node->Sid()]==1.)eplzigzag_counter[node->Lid()] ++;
+		if(eplzigzag_counter[node->Lid()]>eplflip_lock & eplflip_lock!=0){
+			mask->SetValue(node->Sid(),old_active[node->Sid()],INS_VAL);
+		}
+	}
+
+	
+	this->parameters->SetParam(eplzigzag_counter,this->nodes->Size(),EplZigZagCounterEnum);
 	/*Assemble and serialize*/
 	mask->Assemble();
-	serial_mask=mask->ToMPISerial();
+	serial_mask=mask->ToMPISerial();	
+	
+	xDelete<int>(eplzigzag_counter);
+	xDelete<IssmDouble>(serial_rec);
+	xDelete<IssmDouble>(old_active);
 	delete mask;
+	delete recurence;
 
 	/*Update Mask*/
 	InputUpdateFromVectorx(this,serial_mask,HydrologydcMaskEplactiveNodeEnum,NodeSIdEnum);
 	xDelete<IssmDouble>(serial_mask);
-
+	inefanalysis->ElementizeEplMask(this);
 	/*Step 2: update node activity. If one element is connected to mask=1, all nodes are active*/
 	active=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
 	for (int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		effanalysis->HydrologyEPLGetActive(active,element);
 	}
@@ -1632,9 +1978,9 @@
 	int counter =0;
 	for (int i=0;i<nodes->Size();i++){
-		Node* node=dynamic_cast<Node*>(nodes->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(nodes->GetObjectByOffset(i));
 		if(node->InAnalysis(HydrologyDCEfficientAnalysisEnum)){
 			if(serial_active[node->Sid()]==1.){
 				node->Activate();
-				counter++;
+				if(!node->IsClone()) counter++;
 			}
 			else{
@@ -1645,8 +1991,10 @@
 	xDelete<IssmDouble>(serial_active);
 	delete effanalysis;
+	delete inefanalysis;
 	int sum_counter;
 	ISSM_MPI_Reduce(&counter,&sum_counter,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
 	ISSM_MPI_Bcast(&sum_counter,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
 	counter=sum_counter;
+	*pEplcount = counter;
 	if(VerboseSolution()) _printf0_("   Number of active nodes in EPL layer: "<< counter <<"\n");
 
@@ -1656,5 +2004,5 @@
 }
 /*}}}*/
-void FemModel::UpdateConstraintsL2ProjectionEPLx(void){ /*{{{*/
+void FemModel::UpdateConstraintsL2ProjectionEPLx(IssmDouble* pL2count){ /*{{{*/
 
 	Vector<IssmDouble>* active        = NULL;
@@ -1665,5 +2013,5 @@
 	active=new Vector<IssmDouble>(nodes->NumberOfNodes(HydrologyDCEfficientAnalysisEnum));
 	for (int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		effanalysis->HydrologyEPLGetActive(active,element);
 	}
@@ -1678,9 +2026,9 @@
 	int counter =0;
 	for (int i=0;i<nodes->Size();i++){
-		Node* node=dynamic_cast<Node*>(nodes->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(nodes->GetObjectByOffset(i));
 		if(node->InAnalysis(L2ProjectionEPLAnalysisEnum)){
 			if(serial_active[node->Sid()]==1.){
 				node->Activate();
-				counter++;
+				if(!node->IsClone()) counter++;
 			}
 			else{
@@ -1694,8 +2042,6 @@
 	ISSM_MPI_Bcast(&sum_counter,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
 	counter=sum_counter;
+	*pL2count = counter;
 	if(VerboseSolution()) _printf0_("   Number of active nodes L2 Projection: "<< counter <<"\n");
-
-	/*Update dof indexings*/
-	this->UpdateConstraintsx();
-}
-/*}}}*/
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/FemModel.h
===================================================================
--- /issm/trunk/src/c/classes/FemModel.h	(revision 19104)
+++ /issm/trunk/src/c/classes/FemModel.h	(revision 19105)
@@ -46,6 +46,6 @@
 
 		/*constructors, destructors: */
-		FemModel(int argc,char** argv,ISSM_MPI_Comm comm_init);
-		FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int solution_type,const int* analyses,const int nummodels);
+		FemModel(int argc,char** argv,ISSM_MPI_Comm comm_init,bool trace=false);
+		FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* toolkitsfilename, char* lockfilename, ISSM_MPI_Comm incomm, int solution_type,IssmPDouble* X);
 		~FemModel();
 
@@ -53,5 +53,6 @@
 		void Echo();
 		FemModel* copy();
-		void InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int solution_type,const int* analyses,const int nummodels);
+		void InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int solution_type,bool trace,IssmPDouble* X=NULL);
+		void SolutionAnalysesList(int** panalyses,int* pnumanalyses,IoModel* iomodel,int solutiontype);
 		void CleanUp(void);
 		void Solve(void);
@@ -61,4 +62,6 @@
 
 		/*Modules*/ 
+		void ElementOperationx(void (Element::*function)(void));
+		void GetInputLocalMinMaxOnNodesx(IssmDouble** pmin,IssmDouble** pmax,IssmDouble* ug);
 		void MassFluxx(IssmDouble* presponse);
 		void MaxAbsVxx(IssmDouble* presponse);
@@ -75,9 +78,17 @@
 		void TotalSmbx(IssmDouble* pSmb);
 		void Divergencex(IssmDouble* pdiv);
+		void MaxDivergencex(IssmDouble* pdiv);
+		void IceMassx(IssmDouble* pV);
 		void IceVolumex(IssmDouble* pV);
 		void IceVolumeAboveFloatationx(IssmDouble* pV);
 		void ElementResponsex(IssmDouble* presponse,int response_enum);
 		void BalancethicknessMisfitx(IssmDouble* pV);
-		void Balancethickness2Misfitx(IssmDouble* pV);
+		void StressIntensityFactorx();
+		void StrainRateparallelx();
+		void StrainRateperpendicularx();
+		void DeviatoricStressx();
+		void CalvingRateLevermannx();
+		void CalvingRatePix();
+		void CalvingRateDevx();
 		#ifdef  _HAVE_DAKOTA_
 		void DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses);
@@ -91,4 +102,5 @@
 		void CostFunctionx(IssmDouble* pJ,IssmDouble** pJlist,int* pn);
 		void ThicknessAbsGradientx( IssmDouble* pJ);
+		void SurfaceAbsMisfitx( IssmDouble* pJ);
 		#ifdef _HAVE_GIA_
 		void Deflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt, IssmDouble* x, IssmDouble* y);
@@ -99,7 +111,6 @@
 		void UpdateConstraintsExtrudeFromBasex();
 		void UpdateConstraintsExtrudeFromTopx();
-		void HydrologyEPLupdateDomainx(void);
-		//		void HydrologyEPLThicknessx(void);
-		void UpdateConstraintsL2ProjectionEPLx(void);
+		void HydrologyEPLupdateDomainx(IssmDouble* pEplcount);
+		void UpdateConstraintsL2ProjectionEPLx(IssmDouble* pL2count);
 };
 
Index: /issm/trunk/src/c/classes/Hook.cpp
===================================================================
--- /issm/trunk/src/c/classes/Hook.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Hook.cpp	(revision 19105)
@@ -168,5 +168,5 @@
 		/*Now, for this->objects that did not get resolved, and for which we have no offset, chase them in the dataset, by id: */
 		if(this->objects[i]==NULL){
-			this->objects[i]=dynamic_cast<Object*>(dataset->GetObjectById(this->offsets+i,this->ids[i])); //remember the offset for later on.
+			this->objects[i]=xDynamicCast<Object*>(dataset->GetObjectById(this->offsets+i,this->ids[i])); //remember the offset for later on.
 			/*check the id is correct!: */
 			if (this->objects[i]->Id()!=this->ids[i]) _error_("wrong id: " << this->objects[i]->Id() << " vs " << this->ids[i] << "  in resolved pointer!");
Index: /issm/trunk/src/c/classes/IndependentObject.cpp
===================================================================
--- /issm/trunk/src/c/classes/IndependentObject.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/IndependentObject.cpp	(revision 19105)
@@ -70,11 +70,15 @@
 
 /*IndependentObject methods: */
-void IndependentObject::FetchIndependent(IoModel* iomodel){/*{{{*/
+void IndependentObject::FetchIndependent(IoModel* iomodel,int* pXcount,IssmPDouble* X){ /*{{{*/
 
 	int my_rank;
 	FILE* fid=NULL;
+	int Xcount=0;
 
 	/*recover my_rank:*/
 	my_rank=IssmComm::GetRank();
+
+	/*recover Xcount if X is not NULL:*/
+	if(X)Xcount=*pXcount;
 
 	#ifdef _HAVE_ADOLC_ //cannot come here unless you are running AD mode, from DeclaredIndependents:
@@ -98,6 +102,12 @@
 			if(fread(&pscalar,sizeof(IssmPDouble),1,fid)!=1)_error_("could not read scalar ");
 
-			/*Now, before we even broadcast this to other nodes, declare the scalar  as an independent variable!: */
-			scalar<<=pscalar;
+			/*Now, before we even broadcast this to other nodes, declare the scalar  as an independent variable!. If we 
+			 *have been supplied an X vector, use it instead of what we just read: */
+			if(X){
+				scalar<<=X[Xcount];
+			}
+			else{
+				scalar<<=pscalar;
+			}
 		}
 
@@ -113,4 +123,7 @@
 		iomodel->independents[name]=true;
 
+		/*increment offset into X vector, now that we have read 1 value:*/
+		Xcount++; *pXcount=Xcount;
+
 		//finally, record the number of independents:
 		this->numberofindependents=1;
@@ -150,6 +163,12 @@
 				if(fread(buffer,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
 
-				/*Now, before we even broadcast this to other nodes, declare the whole matrix as a independent variable!: */
-				for (int i=0;i<M*N;++i) matrix[i]<<=buffer[i];  /*we use the <<= ADOLC overloaded operator to declare the independency*/
+				/*Now, before we even broadcast this to other nodes, declare the whole matrix as a independent variable!
+				 If we have been supplied an X vector, use it instead of what we just read: */
+				if(X){
+					for (int i=0;i<M*N;i++) matrix[i]<<=X[Xcount+i];  /*<<= ADOLC overloaded operator to declare independent*/
+				}
+				else{
+					for (int i=0;i<M*N;i++) matrix[i]<<=buffer[i];
+				}
 			}
 			ISSM_MPI_Bcast(matrix,M*N,ISSM_MPI_DOUBLE,0,IssmComm::GetComm()); 
@@ -165,4 +184,8 @@
 		iomodel->independents[name]=true;
 
+			
+		/*increment offset into X vector, now that we have read M*N values:*/
+		Xcount+=M*N; *pXcount=Xcount;
+		
 		//Finally, record the number of independents created: 
 		this->numberofindependents=M*N;
@@ -180,6 +203,4 @@
 /*}}}*/
 void IndependentObject::FillIndependents(IssmDouble** data, IssmDouble* xp){/*{{{*/
-
-	int i;
 
 	/*Branch according to the type of variable: */
@@ -189,7 +210,5 @@
 	else if(type==1){ /* vector:*/
 		IssmDouble* values=data[name];
-		for(i=0;i<this->numberofindependents;i++){
-			xp[i]=values[i];
-		}
+		for(int i=0;i<this->numberofindependents;i++) xp[i]=values[i];
 	}
 	else _error_("should not have a type of " << type);
Index: /issm/trunk/src/c/classes/IndependentObject.h
===================================================================
--- /issm/trunk/src/c/classes/IndependentObject.h	(revision 19104)
+++ /issm/trunk/src/c/classes/IndependentObject.h	(revision 19105)
@@ -33,5 +33,5 @@
 		/*}}}*/
 		/*IndependentObject methods: {{{*/
-		void FetchIndependent(IoModel* iomodel);
+		void FetchIndependent(IoModel* iomodel,int* pXcount,IssmPDouble* X);
 		int  NumIndependents(void);
 		void FillIndependents(IssmDouble** data, IssmDouble* xp);
Index: /issm/trunk/src/c/classes/Inputs/BoolInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 19105)
@@ -133,5 +133,5 @@
 }
 /*}}}*/
-void BoolInput::Extrude(void){/*{{{*/
+void BoolInput::Extrude(int start){/*{{{*/
 
 	/*do nothing*/
Index: /issm/trunk/src/c/classes/Inputs/BoolInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/BoolInput.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/BoolInput.h	(revision 19105)
@@ -64,5 +64,5 @@
 		void AXPY(Input* xinput,IssmDouble scalar);
 		void Constrain(IssmDouble cm_min, IssmDouble cm_max){_error_("Constrain not implemented for booleans");};
-		void Extrude(void);
+		void Extrude(int start);
 		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
Index: /issm/trunk/src/c/classes/Inputs/ControlInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/ControlInput.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/ControlInput.cpp	(revision 19105)
@@ -87,9 +87,9 @@
 	output->control_id=this->control_id;
 
-	if(values)      output->values      = dynamic_cast<Input*>(this->values->copy());
-	if(savedvalues) output->savedvalues = dynamic_cast<Input*>(this->savedvalues->copy());
-	if(minvalues)   output->minvalues   = dynamic_cast<Input*>(this->minvalues->copy());
-	if(maxvalues)   output->maxvalues   = dynamic_cast<Input*>(this->maxvalues->copy());
-	if(gradient)    output->gradient    = dynamic_cast<Input*>(this->gradient->copy());
+	if(values)      output->values      = xDynamicCast<Input*>(this->values->copy());
+	if(savedvalues) output->savedvalues = xDynamicCast<Input*>(this->savedvalues->copy());
+	if(minvalues)   output->minvalues   = xDynamicCast<Input*>(this->minvalues->copy());
+	if(maxvalues)   output->maxvalues   = xDynamicCast<Input*>(this->maxvalues->copy());
+	if(gradient)    output->gradient    = xDynamicCast<Input*>(this->gradient->copy());
 
 	return output;
@@ -121,7 +121,7 @@
 	   values->Constrain(min,max);
 }/*}}}*/
-void ControlInput::Extrude(void){/*{{{*/
-	values->Extrude();
-	savedvalues->Extrude();
+void ControlInput::Extrude(int start){/*{{{*/
+	values->Extrude(start);
+	savedvalues->Extrude(start);
 	//gradient->Extrude();
 }/*}}}*/
@@ -234,5 +234,5 @@
 
 	if(savedvalues) delete this->savedvalues;
-	this->savedvalues=dynamic_cast<Input*>(this->values->copy());
+	this->savedvalues=xDynamicCast<Input*>(this->values->copy());
 }/*}}}*/
 void ControlInput::UpdateValue(IssmDouble scalar){/*{{{*/
@@ -241,5 +241,5 @@
 
 	if(values) delete this->values;
-	this->values=dynamic_cast<Input*>(this->savedvalues->copy());
+	this->values=xDynamicCast<Input*>(this->savedvalues->copy());
 	this->values->AXPY(gradient,scalar);
 }/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/ControlInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 19105)
@@ -72,5 +72,5 @@
 		IssmDouble Min(void);
 		IssmDouble MinAbs(void){_error_("not implemented yet");};
-		void Extrude(void);
+		void Extrude(int start);
 		void VerticallyIntegrate(Input* thickness_input);
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist,const char* data);
Index: /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 19105)
@@ -81,5 +81,5 @@
 	outinput=new DatasetInput();
 	outinput->enum_type=this->enum_type;
-	outinput->inputs=dynamic_cast<Inputs*>(this->inputs->SpawnTriaInputs(index1,index2,index3));
+	outinput->inputs=xDynamicCast<Inputs*>(this->inputs->SpawnTriaInputs(index1,index2,index3));
 	outinput->numids=this->numids;
 	outinput->ids=xNew<int>(this->numids);
@@ -98,5 +98,5 @@
 	outinput=new DatasetInput();
 	outinput->enum_type=this->enum_type;
-	outinput->inputs=dynamic_cast<Inputs*>(this->inputs->SpawnSegInputs(index1,index2));
+	outinput->inputs=xDynamicCast<Inputs*>(this->inputs->SpawnSegInputs(index1,index2));
 	outinput->numids=this->numids;
 	outinput->ids=xNew<int>(this->numids);
@@ -157,5 +157,5 @@
 	if(offset<0) _error_("Could not find input of id "<<id );
 
-	Input* input=dynamic_cast<Input*>(this->inputs->GetObjectByOffset(offset));
+	Input* input=xDynamicCast<Input*>(this->inputs->GetObjectByOffset(offset));
 	input->GetInputValue(pvalue,gauss);
 }
Index: /issm/trunk/src/c/classes/Inputs/DatasetInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DatasetInput.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/DatasetInput.h	(revision 19105)
@@ -68,5 +68,5 @@
 		IssmDouble Min(void){_error_("not implemented yet");};
 		IssmDouble MinAbs(void){_error_("not implemented yet");};
-		void Extrude(void){_error_("not implemented yet");};
+		void Extrude(int start){_error_("not implemented yet");};
 		void VerticallyIntegrate(Input* thickness_input){_error_("not implemented yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){_error_("not implemented yet");};
Index: /issm/trunk/src/c/classes/Inputs/DoubleInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DoubleInput.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/DoubleInput.h	(revision 19105)
@@ -67,5 +67,5 @@
 		IssmDouble Min(void);
 		IssmDouble MinAbs(void);
-		void Extrude(void){_error_("not supported yet");};
+		void Extrude(int start){_error_("not supported yet");};
 		void VerticallyIntegrate(Input* thickness_input);
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
Index: /issm/trunk/src/c/classes/Inputs/Input.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Input.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/Input.h	(revision 19105)
@@ -51,5 +51,5 @@
 		virtual void   Constrain(IssmDouble cm_min, IssmDouble cm_max)=0;
 		virtual void   VerticallyIntegrate(Input* thickness_input)=0;
-		virtual void   Extrude()=0;
+		virtual void   Extrude(int start)=0;
 		virtual void   GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist)=0;
 
Index: /issm/trunk/src/c/classes/Inputs/Inputs.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 19105)
@@ -38,5 +38,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=dynamic_cast<Input*>(*object);
+		input=xDynamicCast<Input*>(*object);
 		if (input->InstanceEnum()==enum_type){
 			found=true;
@@ -65,5 +65,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=dynamic_cast<Input*>(*object);
+		input=xDynamicCast<Input*>(*object);
 		if (input->InstanceEnum()==enum_type){
 			found=true;
@@ -92,5 +92,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=dynamic_cast<Input*>(*object); 
+		input=xDynamicCast<Input*>(*object); 
 		if (input->InstanceEnum()==enum_type){
 			found=true;
@@ -119,5 +119,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=dynamic_cast<Input*>(*object);
+		input=xDynamicCast<Input*>(*object);
 		if (input->InstanceEnum()==enum_type){
 			found=true;
@@ -150,5 +150,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=dynamic_cast<Input*>(*object);
+		input=xDynamicCast<Input*>(*object);
 
 		if (input->InstanceEnum()==in_input->InstanceEnum()){
@@ -171,5 +171,5 @@
 	/*Delete existing input of newenumtype if it exists*/
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
-		input=dynamic_cast<Input*>(*object);
+		input=xDynamicCast<Input*>(*object);
 
 		if (input->InstanceEnum()==newenumtype){
@@ -182,5 +182,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=dynamic_cast<Input*>(*object);
+		input=xDynamicCast<Input*>(*object);
 
 		if (input->InstanceEnum()==oldenumtype){
@@ -194,5 +194,5 @@
 
 	/*Find x and y inputs: */
-	Input* constrain_input=dynamic_cast<Input*>(this->GetInput(constrain_enum));
+	Input* constrain_input=xDynamicCast<Input*>(this->GetInput(constrain_enum));
 
 	/*some checks: */
@@ -209,5 +209,5 @@
 
 	/*Get input*/
-	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+	Input* input=xDynamicCast<Input*>(this->GetInput(enumtype));
 
 	/*Apply ContrainMin: */
@@ -229,5 +229,5 @@
 
 	/*Get input*/
-	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+	Input* input=xDynamicCast<Input*>(this->GetInput(enumtype));
 
 	/*Apply ContrainMin: */
@@ -249,5 +249,5 @@
 
 	/*Get input*/
-	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+	Input* input=xDynamicCast<Input*>(this->GetInput(enumtype));
 
 	/*Apply ContrainMin: */
@@ -269,5 +269,5 @@
 
 	/*Get input*/
-	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+	Input* input=xDynamicCast<Input*>(this->GetInput(enumtype));
 
 	/*Apply ContrainMin: */
@@ -289,5 +289,5 @@
 
 	/*Get input*/
-	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
+	Input* input=xDynamicCast<Input*>(this->GetInput(enumtype));
 
 	/*Apply ContrainMin: */
@@ -310,5 +310,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=dynamic_cast<Input*>(*object);
+		input=xDynamicCast<Input*>(*object);
 
 		if (input->InstanceEnum()==enum_name){
@@ -326,5 +326,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=dynamic_cast<Input*>(*object);
+		input=xDynamicCast<Input*>(*object);
 
 		if (input->InstanceEnum()==enum_type){
@@ -341,7 +341,7 @@
 
 	/*Make a copy of the original input: */
-	Input* original=dynamic_cast<Input*>(this->GetInput(original_enum));
+	Input* original=xDynamicCast<Input*>(this->GetInput(original_enum));
 	if(!original)_error_("could not find input with enum: " << EnumToStringx(original_enum)); 
-	Input* copy=dynamic_cast<Input*>(original->copy());
+	Input* copy=xDynamicCast<Input*>(original->copy());
 
 	/*Change copy enum to reinitialized_enum: */
@@ -349,5 +349,5 @@
 
 	/*Add copy into inputs, it will wipe off the one already there: */
-	this->AddInput(dynamic_cast<Input*>(copy));
+	this->AddInput(xDynamicCast<Input*>(copy));
 }
 /*}}}*/
@@ -366,5 +366,5 @@
 
 		/*Create new input*/
-		inputin=dynamic_cast<Input*>(*object);
+		inputin=xDynamicCast<Input*>(*object);
 		inputout=inputin->SpawnTriaInput(index1,index2,index3);
 
@@ -391,5 +391,5 @@
 
 		/*Create new input*/
-		inputin=dynamic_cast<Input*>(*object);
+		inputin=xDynamicCast<Input*>(*object);
 		inputout=inputin->SpawnSegInput(index1,index2);
 
@@ -405,6 +405,6 @@
 
 	/*Find x and y inputs: */
-	Input* xinput=dynamic_cast<Input*>(this->GetInput(inputx_enum));
-	Input* yinput=dynamic_cast<Input*>(this->GetInput(inputy_enum));
+	Input* xinput=xDynamicCast<Input*>(this->GetInput(inputx_enum));
+	Input* yinput=xDynamicCast<Input*>(this->GetInput(inputy_enum));
 
 	/*some checks: */
@@ -423,5 +423,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=dynamic_cast<Input*>(*object);
+		input=xDynamicCast<Input*>(*object);
 		input->Configure(parameters);
 
Index: /issm/trunk/src/c/classes/Inputs/IntInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/IntInput.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/IntInput.h	(revision 19105)
@@ -68,5 +68,5 @@
 		IssmDouble Min(void){_error_("Min not implemented for integers");};
 		IssmDouble MinAbs(void){_error_("Min not implemented for integers");};
-		void Extrude(void){_error_("not supported yet");};
+		void Extrude(int start){_error_("not supported yet");};
 		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
Index: /issm/trunk/src/c/classes/Inputs/PentaInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaInput.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/PentaInput.cpp	(revision 19105)
@@ -291,9 +291,14 @@
 }
 /*}}}*/
-void PentaInput::Extrude(void){/*{{{*/
+void PentaInput::Extrude(int start){/*{{{*/
 
 	switch(this->interpolation_type){
 		case P1Enum:
-			for(int i=0;i<3;i++) this->values[3+i]=this->values[i];
+			if(start==-1){
+				for(int i=0;i<3;i++) this->values[3+i]=this->values[i];
+			}
+			else{
+				for(int i=0;i<3;i++) this->values[i]  =this->values[3+i];
+			}
 			break;
 		default:
Index: /issm/trunk/src/c/classes/Inputs/PentaInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaInput.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/PentaInput.h	(revision 19105)
@@ -68,5 +68,5 @@
 		IssmDouble Min(void);
 		IssmDouble MinAbs(void);
-		void Extrude(void);
+		void Extrude(int start);
 		void VerticallyIntegrate(Input* thickness_input);
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
Index: /issm/trunk/src/c/classes/Inputs/SegInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/SegInput.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/SegInput.h	(revision 19105)
@@ -69,5 +69,5 @@
 		IssmDouble Min(void);
 		IssmDouble MinAbs(void){_error_("not implemented yet");};
-		void Extrude(void){_error_("not supported yet");};
+		void Extrude(int start){_error_("not supported yet");};
 		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){_error_("not implemented yet");};
Index: /issm/trunk/src/c/classes/Inputs/TetraInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TetraInput.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/TetraInput.h	(revision 19105)
@@ -69,5 +69,5 @@
 		IssmDouble Min(void);
 		IssmDouble MinAbs(void);
-		void Extrude(void){_error_("not supported yet");};
+		void Extrude(int start){_error_("not supported yet");};
 		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
Index: /issm/trunk/src/c/classes/Inputs/TransientInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 19105)
@@ -345,8 +345,8 @@
 }
 /*}}}*/
-void TransientInput::Extrude(void){/*{{{*/
+void TransientInput::Extrude(int start){/*{{{*/
 
 	for(int i=0;i<this->numtimesteps;i++){
-		((Input*)this->inputs->GetObjectByOffset(i))->Extrude();
+		((Input*)this->inputs->GetObjectByOffset(i))->Extrude(start);
 	}
 }
Index: /issm/trunk/src/c/classes/Inputs/TransientInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TransientInput.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/TransientInput.h	(revision 19105)
@@ -42,7 +42,7 @@
 		Input* SpawnTriaInput(int index1,int index2,int index3);
 		Input* SpawnSegInput(int index1,int index2);
-		Input* PointwiseDivide(Input* forcingB){_error_("not implemented yet");};
-		Input* PointwiseMin(Input* forcingB){_error_("not implemented yet");};
-		Input* PointwiseMax(Input* forcingB){_error_("not implemented yet");};
+		Input* PointwiseDivide(Input* input_in){_error_("not implemented yet");};
+		Input* PointwiseMin(Input* input_in){_error_("not implemented yet");};
+		Input* PointwiseMax(Input* input_in){_error_("not implemented yet");};
 		int  GetResultInterpolation(void);
 		int  GetResultNumberOfNodes(void);
@@ -73,5 +73,5 @@
 		IssmDouble Min(void);
 		IssmDouble MinAbs(void);
-		void Extrude(void);
+		void Extrude(int start);
 		void VerticallyIntegrate(Input* thickness_forcing){_error_("not supported yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
Index: /issm/trunk/src/c/classes/Inputs/TriaInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 19105)
@@ -49,5 +49,5 @@
 		void GetInputValue(bool* pvalue){_error_("not implemented yet");}
 		void GetInputValue(int* pvalue){_error_("not implemented yet");}
-		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet");}
+		void GetInputValue(IssmDouble* pvalue){_error_("not implemented yet (Input is "<<EnumToStringx(this->enum_type)<<")");}//{_error_("not implemented yet");}
 		void GetInputValue(IssmDouble* pvalue,Gauss* gauss);
 		void GetInputValue(IssmDouble* pvalue,Gauss* gauss,IssmDouble time){_error_("not implemented yet");};
@@ -69,5 +69,5 @@
 		IssmDouble Min(void);
 		IssmDouble MinAbs(void);
-		void Extrude(void){_error_("not supported yet");};
+		void Extrude(int start){_error_("not supported yet");};
 		void VerticallyIntegrate(Input* thickness_input){_error_("not supported yet");};
 		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
Index: /issm/trunk/src/c/classes/IoModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/IoModel.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/IoModel.cpp	(revision 19105)
@@ -50,6 +50,9 @@
 }
 /*}}}*/
-IoModel::IoModel(FILE* iomodel_handle){/*{{{*/
-
+IoModel::IoModel(FILE* iomodel_handle,bool trace,IssmPDouble* X){/*{{{*/
+
+	bool autodiff=false;
+	bool iscontrol=false;
+	
 	/*First, keep track of the file handle: */
 	this->fid=iomodel_handle;
@@ -65,10 +68,25 @@
 	 *and prevent them from being erased during successive calls to iomodel->FetchConstants, iomodel->FetchData and 
 	 iomodel->DeleteData:*/
-	this->StartTrace();
-	this->DeclareIndependents();
+	this->StartTrace(trace);
+	this->DeclareIndependents(trace,X);
 
 	/*Initialize and read constants:*/
 	this->constants=new Parameters();
 	this->FetchConstants(); /*this routine goes through the input file, and fetches bools, ints, IssmDoubles and strings only, nothing memory intensive*/
+
+	/*Now some very specific piece of logic. We want to know whether we are going to carry out an autodiff run. There are 
+	 *several cases: either trace is true (which bypasses the isautodiff choice), or trace is false but isautodiff is on, in which 
+	 *case two cases are possible: are we running a control method or not? To make things simpler, we are going to pin down everyting 
+	 *on isautodiff. By the way, we could not do this before we had the constants dataset initialized! {{{*/
+	this->constants->FindParam(&autodiff,AutodiffIsautodiffEnum);
+	this->constants->FindParam(&iscontrol,InversionIscontrolEnum);
+
+	if(trace)autodiff=true;
+	else{
+		if(autodiff && !iscontrol) autodiff=true;
+		else autodiff=false;
+	}
+	this->constants->SetParam(autodiff,AutodiffIsautodiffEnum);
+	/*}}}*/
 
 	/*Initialize permanent data: */
@@ -108,5 +126,5 @@
 
 	/*checks in debugging mode*/
-	#ifdef _ISSM_DEBUG_
+	#if defined(_ISSM_DEBUG_) && !defined(_HAVE_ADOLC_)
 	if(this->data){
 		for(int i=0;i<MaximumNumberOfDefinitionsEnum;i++){
@@ -259,8 +277,8 @@
 
 	/*Find constant*/
-	Param* param=dynamic_cast<Param*>(this->constants->FindParamObject(constant_enum));
+	Param* param=xDynamicCast<Param*>(this->constants->FindParamObject(constant_enum));
 	if(!param) _error_("Constant " << EnumToStringx(constant_enum) << " not found in iomodel");
 
-	return dynamic_cast<Param*>(param->copy());
+	return xDynamicCast<Param*>(param->copy());
 }
 /*}}}*/
@@ -273,7 +291,8 @@
 }
 /*}}}*/
-void IoModel::StartTrace(void){/*{{{*/
+void IoModel::StartTrace(bool trace){/*{{{*/
 
 	bool autodiff = false;
+	bool iscontrol = false;
 	bool keep=false;
 	IssmDouble gcTriggerRatio;
@@ -287,6 +306,7 @@
 
 	this->FetchData(&autodiff,AutodiffIsautodiffEnum);
-	if(autodiff){
-
+	this->FetchData(&iscontrol,InversionIscontrolEnum);
+
+	if(trace || (autodiff && !iscontrol)){
 		#ifdef _HAVE_ADOLC_
 		/*Retrieve parameters: */
@@ -311,9 +331,11 @@
 }
 /*}}}*/
-void IoModel::DeclareIndependents(void){/*{{{*/
+void IoModel::DeclareIndependents(bool trace,IssmPDouble* X){/*{{{*/
 
 	int  i;
 	bool autodiff = false;
+	bool iscontrol = false;
 	int  num_independent_objects;
+	int  Xcount=0;
 
 	int *names = NULL;
@@ -327,5 +349,7 @@
 
 	this->FetchData(&autodiff,AutodiffIsautodiffEnum);
-	if(autodiff){
+	this->FetchData(&iscontrol,InversionIscontrolEnum);
+	
+	if(trace || (autodiff && !iscontrol)){
 
 		#ifdef _HAVE_ADOLC_
@@ -348,5 +372,5 @@
 
 				/*now go fetch the independent variable: */
-				independent_object->FetchIndependent(this); //supply the pointer to iomodel.
+				independent_object->FetchIndependent(this,&Xcount,X); //supply the pointer to iomodel.
 			}
 			xDelete<int>(names);
@@ -1229,4 +1253,57 @@
 }
 /*}}}*/
+void  IoModel::FetchMultipleData(IssmDouble** pvector, int* pnum_instances,int data_enum){/*{{{*/
+
+	int     num_instances;
+	fpos_t* file_positions=NULL;
+
+	/*output: */
+	IssmDouble* vector=NULL;
+
+	/*intermediary: */
+	IssmPDouble          scalar;
+	int         *codes   = NULL;
+	int          code;
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+	
+	/*Get file pointers to beginning of the data (multiple instances of it): */
+	file_positions=this->SetFilePointersToData(&codes,NULL,&num_instances,data_enum);
+
+	if(num_instances){
+
+		/*Allocate vector :*/
+		vector=xNew<IssmDouble>(num_instances);
+
+		for(int i=0;i<num_instances;i++){
+
+			if(my_rank==0){
+				code=codes[i];
+
+				if(code!=3)_error_("expecting a double for enum " << EnumToStringx(data_enum));
+				
+				/*We have to read a double from disk: */
+				fsetpos(fid,file_positions+i);
+				if(my_rank==0){  
+					if(fread(&scalar,sizeof(IssmPDouble),1,fid)!=1) _error_("could not read scalar ");
+				}
+			}
+			ISSM_MPI_Bcast(&scalar,1,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
+
+			/*Assign: */
+			vector[i]=scalar;
+		}
+	}
+			
+	/*Free ressources:*/
+	xDelete<fpos_t>(file_positions);
+	xDelete<int>(codes);
+
+	/*Assign output pointers: */
+	*pvector=vector;
+	*pnum_instances=num_instances;
+}
+/*}}}*/
 void  IoModel::FetchMultipleData(IssmDouble*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum){/*{{{*/
 
@@ -1455,5 +1532,5 @@
 
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		if(!doublearray) element->AddInput(vector_enum,&default_value,P0Enum); 
 		else             element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
@@ -1485,5 +1562,5 @@
 			this->FetchData(&boolean,vector_enum);
 			for(i=0;i<elements->Size();i++){
-				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 				element->InputUpdateFromConstant(boolean,vector_enum);
 			}
@@ -1492,5 +1569,5 @@
 			this->FetchData(&integer,vector_enum);
 			for(i=0;i<elements->Size();i++){
-				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 				element->InputUpdateFromConstant(integer,vector_enum);
 			}
@@ -1499,5 +1576,5 @@
 			this->FetchData(&scalar,vector_enum);
 			for(i=0;i<elements->Size();i++){
-				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 				element->InputUpdateFromConstant(scalar,vector_enum);
 			}
@@ -1507,5 +1584,5 @@
 			if(!doublearray) _error_(EnumToStringx(vector_enum)<<" not found in binary file");
 			for(i=0;i<elements->Size();i++){
-				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 				element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
 			}
@@ -1515,5 +1592,5 @@
 			if(!doublearray) _error_(EnumToStringx(vector_enum)<<" not found in binary file");
 			for(i=0;i<elements->Size();i++){
-				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 				element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
 			}
@@ -1523,5 +1600,5 @@
 			if(!doublearray) _error_(EnumToStringx(vector_enum)<<" not found in binary file");
 			for(i=0;i<elements->Size();i++){
-				Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+				Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 				element->InputCreate(doublearray,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
 			}
Index: /issm/trunk/src/c/classes/IoModel.h
===================================================================
--- /issm/trunk/src/c/classes/IoModel.h	(revision 19104)
+++ /issm/trunk/src/c/classes/IoModel.h	(revision 19105)
@@ -59,5 +59,5 @@
 		~IoModel();
 		IoModel();
-		IoModel(FILE* iomodel_handle);
+		IoModel(FILE* iomodel_handle,bool trace,IssmPDouble* X);
 
 		/*Input/Output*/
@@ -85,4 +85,5 @@
 		void        FetchMultipleData(int*** pmatrices,int** pmdims,int** pndims, int* pnumrecords,int data_enum);
 		void        FetchMultipleData(int** pvector, int* pnum_instances,int data_enum);
+		void        FetchMultipleData(IssmDouble** pvector, int* pnum_instances,int data_enum);
 		void        FetchData(Option **poption,int data_enum);
 		void        FetchData(int num,...);
@@ -92,6 +93,6 @@
 		FILE*       SetFilePointerToData(int* pcode,int* pvector_type, int data_enum);
 		fpos_t*     SetFilePointersToData(int** pcodes,int** pvector_types, int* pnum_instances, int data_enum);
-		void        DeclareIndependents(void);
-		void        StartTrace(void);
+		void        DeclareIndependents(bool trace,IssmPDouble* X);
+		void        StartTrace(bool trace);
 		void        FetchIndependent(int dependent_enum);
 };
Index: /issm/trunk/src/c/classes/Loads/Friction.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Friction.cpp	(revision 19105)
@@ -40,31 +40,33 @@
 }
 /*}}}*/
-void Friction::GetAlpha2(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+void Friction::GetAlphaComplement(IssmDouble* palpha_complement, Gauss* gauss){/*{{{*/
 
 	switch(this->law){
 		case 1:
-			GetAlpha2Viscous(palpha2,gauss);
-			break;
-		case 2:
-			GetAlpha2Weertman(palpha2,gauss);
-			break;
-		default:
-			_error_("not supported");
-	}
-
-}/*}}}*/
-void Friction::GetAlpha2Viscous(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
-
-	/*This routine calculates the basal friction coefficient 
-	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p**/
+			GetAlphaViscousComplement(palpha_complement,gauss);
+			break;
+		case 3:
+			GetAlphaHydroComplement(palpha_complement,gauss);
+			break;
+	  default:
+			_error_("not supported");
+	}
+
+}/*}}}*/
+
+void Friction::GetAlphaViscousComplement(IssmDouble* palpha_complement, Gauss* gauss){/*{{{*/
+
+	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p. 
+	 * FrictionGetAlphaComplement is used in control methods on drag, and it computes: 
+	 * alpha_complement= Neff ^r * vel ^s*/
 
 	/*diverse: */
 	IssmDouble  r,s;
-	IssmDouble  drag_p, drag_q;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  drag_p,drag_q;
 	IssmDouble  Neff;
-	IssmDouble  thickness,bed;
-	IssmDouble  vx,vy,vz,vmag;
 	IssmDouble  drag_coefficient;
-	IssmDouble  alpha2;
+	IssmDouble  bed,thickness;
+	IssmDouble  alpha_complement;
 
 	/*Recover parameters: */
@@ -86,89 +88,236 @@
 	if(Neff<0)Neff=0;
 
-	switch(dim){
-		case 1:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			vmag=sqrt(vx*vx);
-			break;
-		case 2:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			element->GetInputValue(&vy,gauss,VyEnum);
-			vmag=sqrt(vx*vx+vy*vy);
-			break;
-		case 3:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			element->GetInputValue(&vy,gauss,VyEnum);
-			element->GetInputValue(&vz,gauss,VzEnum);
-			vmag=sqrt(vx*vx+vy*vy+vz*vz);
-			break;
-		default:
-			_error_("not supported");
-	}
-
-	/*Check to prevent dividing by zero if vmag==0*/
-	if(vmag==0. && (s-1.)<0.) alpha2=0.;
-	else alpha2=drag_coefficient*drag_coefficient*pow(Neff,r)*pow(vmag,(s-1.));
+	//We need the velocity magnitude to evaluate the basal stress:
+	switch(dim){
+		case 1:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			vmag=sqrt(vx*vx);
+			break;
+		case 2:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			vmag=sqrt(vx*vx+vy*vy);
+			break;
+		case 3:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			element->GetInputValue(&vz,gauss,VzEnum);
+			vmag=sqrt(vx*vx+vy*vy+vz*vz);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+	/*Check to prevent dividing by zero if vmag==0*/
+	if(vmag==0. && (s-1.)<0.) alpha_complement=0.;
+	else alpha_complement=pow(Neff,r)*pow(vmag,(s-1));_assert_(!xIsNan<IssmDouble>(alpha_complement));
+
+	/*Assign output pointers:*/
+	*palpha_complement=alpha_complement;
+}
+/*}}}*/
+void Friction::GetAlphaHydroComplement(IssmDouble* palpha_complement, Gauss* gauss){/*{{{*/
+
+	/*diverse: */
+	IssmDouble  q_exp;
+	IssmDouble  C_param;
+	IssmDouble  As;
+	IssmDouble  Neff;
+	IssmDouble  n;
+	IssmDouble  alpha;
+	IssmDouble  Chi,Gamma;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  alpha_complement;
+
+	/*Recover parameters: */
+	element->GetInputValue(&q_exp,FrictionQEnum);
+	element->GetInputValue(&C_param,FrictionCEnum);
+
+	element->GetInputValue(&As,gauss,FrictionAsEnum);
+	element->GetInputValue(&Neff,gauss,FrictionEffectivePressureEnum);
+	element->GetInputValue(&n,gauss,MaterialsRheologyNEnum);
+
+	if(Neff<0)Neff=0;
+
+	//We need the velocity magnitude to evaluate the basal stress:
+	switch(dim){
+		case 1:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			vmag=sqrt(vx*vx);
+			break;
+		case 2:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			vmag=sqrt(vx*vx+vy*vy);
+			break;
+		case 3:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			element->GetInputValue(&vz,gauss,VzEnum);
+			vmag=sqrt(vx*vx+vy*vy+vz*vz);
+			break;
+		default:
+			_error_("not supported");
+	}
+	//	vmag=100./(3600.*24.*365.);
+
+	if (q_exp==1){
+		alpha=1;
+	}
+	else{
+		alpha=(pow(q_exp-1,q_exp-1))/pow(q_exp,q_exp);
+	}
+	Chi   = vmag/(pow(C_param,n)*pow(Neff,n)*As);
+	Gamma = (Chi/(1.+alpha*pow(Chi,q_exp)));
+	/*Check to prevent dividing by zero if vmag==0*/
+	if(vmag==0.) alpha_complement=0.;
+	else	if(Neff==0.) alpha_complement=0.;
+	else	alpha_complement=-(C_param*Neff/(n*vmag)) *
+					pow(Gamma,((1.-n)/n)) *
+					(Gamma/As - (alpha*q_exp*pow(Chi,q_exp-1.)* Gamma * Gamma/As));
+
+	_assert_(!xIsNan<IssmDouble>(alpha_complement));
+	/*Assign output pointers:*/
+	*palpha_complement=alpha_complement;
+}
+/*}}}*/
+void Friction::GetAlpha2(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+
+	switch(this->law){
+		case 1:
+			GetAlpha2Viscous(palpha2,gauss);
+			break;
+		case 2:
+			GetAlpha2Weertman(palpha2,gauss);
+			break;
+		case 3:
+			GetAlpha2Hydro(palpha2,gauss);
+			break;
+		case 4:
+			GetAlpha2Temp(palpha2,gauss);
+			break;
+		case 5:
+			GetAlpha2WaterLayer(palpha2,gauss);
+			break;
+		case 6:
+			GetAlpha2WeertmanTemp(palpha2,gauss);
+			break;
+	  default:
+			_error_("not supported");
+	}
+
+}/*}}}*/
+void Friction::GetAlpha2Hydro(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+
+	/*This routine calculates the basal friction coefficient 
+		Based on Gagliardini 2007, needs a good effective pressure computation
+		Not tested so far so use at your own risks
+	  alpha2= NeffC[Chi/(1+alpha*Chi^q)]^(1/n)*1/vel  with
+		-Chi=|vel|/(C^n*Neff^n*As)
+		-alpha=(q-1)^(q-1)/q^q  **/
+
+	/*diverse: */
+	IssmDouble  q_exp;
+	IssmDouble  C_param;
+	IssmDouble  As;
+
+	IssmDouble  Neff;
+	IssmDouble  n;
+
+	IssmDouble  alpha;
+	IssmDouble  Chi,Gamma;
+
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  alpha2;
+
+	/*Recover parameters: */
+	element->GetInputValue(&q_exp,FrictionQEnum);
+	element->GetInputValue(&C_param,FrictionCEnum);
+	element->GetInputValue(&As,gauss,FrictionAsEnum);
+
+	element->GetInputValue(&Neff,gauss,FrictionEffectivePressureEnum);
+	element->GetInputValue(&n,gauss,MaterialsRheologyNEnum);
+	
+	if(Neff<0)Neff=0;
+
+	switch(dim){
+		case 1:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			vmag=sqrt(vx*vx);
+			break;
+		case 2:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			vmag=sqrt(vx*vx+vy*vy);
+			break;
+		case 3:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			element->GetInputValue(&vz,gauss,VzEnum);
+			vmag=sqrt(vx*vx+vy*vy+vz*vz);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+	//	vmag=100./(3600.*24.*365.);
+	//compute alpha and Chi coefficients: */
+	if (q_exp==1){
+		alpha=1;
+	}
+	else{
+		alpha=(pow(q_exp-1,q_exp-1))/pow(q_exp,q_exp);
+	}
+	Chi=vmag/(pow(C_param,n)*pow(Neff,n)*As);
+	Gamma=(Chi/(1. + alpha * pow(Chi,q_exp)));
+	/*Check to prevent dividing by zero if vmag==0*/
+	if(vmag==0.) alpha2=0.; 
+	else	if (Neff==0) alpha2=0.0;
+	else	alpha2=Neff * C_param * pow(Gamma,1./n) * 1/vmag;
+
 	_assert_(!xIsNan<IssmDouble>(alpha2));
-
-	/*Assign output pointers:*/
-	*palpha2=alpha2;
-}/*}}}*/
-void Friction::GetAlpha2Weertman(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
-
-	/*This routine calculates the basal friction coefficient alpha2= C^-1/m |v|^(1/m-1) */
-
-	/*diverse: */
-	IssmDouble  C,m;
-	IssmDouble  vx,vy,vz,vmag;
-	IssmDouble  alpha2;
-
-	/*Recover parameters: */
-	element->GetInputValue(&C,gauss,FrictionCEnum);
-	element->GetInputValue(&m,FrictionMEnum);
-
-	switch(dim){
-		case 1:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			vmag=sqrt(vx*vx);
-			break;
-		case 2:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			element->GetInputValue(&vy,gauss,VyEnum);
-			vmag=sqrt(vx*vx+vy*vy);
-			break;
-		case 3:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			element->GetInputValue(&vy,gauss,VyEnum);
-			element->GetInputValue(&vz,gauss,VzEnum);
-			vmag=sqrt(vx*vx+vy*vy+vz*vz);
-			break;
-		default:
-			_error_("not supported");
-	}
-
-	/*Check to prevent dividing by zero if vmag==0*/
-	if(vmag==0. && (1./m-1.)<0.) alpha2=0.;
-	else alpha2=pow(C,-1./m)*pow(vmag,(1./m-1.));
-	_assert_(!xIsNan<IssmDouble>(alpha2));
-
-	/*Assign output pointers:*/
-	*palpha2=alpha2;
-}/*}}}*/
-void Friction::GetAlphaComplement(IssmDouble* palpha_complement, Gauss* gauss){/*{{{*/
-
-	/* FrictionGetAlpha2 computes alpha2= drag^2 * Neff ^r * vel ^s, with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p. 
-	 * FrictionGetAlphaComplement is used in control methods on drag, and it computes: 
-	 * alpha_complement= Neff ^r * vel ^s*/
-
-	if(this->law!=1)_error_("not supported");
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}/*}}}*/
+void Friction::GetAlpha2Temp(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+	/*Here, we want to parameterize the friction as a function of temperature
+	 *
+	 * alpha2 = alpha2_viscous * 1/f(T)
+	 *
+	 * where f(T) = exp((T-Tpmp)/gamma)
+	 */
+
+	/*Intermediaries: */
+	IssmDouble  f,T,pressure,Tpmp,gamma;
+	IssmDouble  alpha2;
+
+	/*Get viscous part*/
+	this->GetAlpha2Viscous(&alpha2,gauss);
+
+	/*Get pressure melting point (Tpmp) for local pressure and get current temperature*/
+	element->GetInputValue(&T,gauss,TemperatureEnum);
+	element->GetInputValue(&pressure,gauss,PressureEnum);
+	Tpmp = element->TMeltingPoint(pressure);
+
+	/*Compute scaling parameter*/
+	element->parameters->FindParam(&gamma,FrictionGammaEnum);
+	alpha2 = alpha2 / exp((T-Tpmp)/gamma);
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}/*}}}*/
+void Friction::GetAlpha2Viscous(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+
+	/*This routine calculates the basal friction coefficient 
+	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p**/
 
 	/*diverse: */
 	IssmDouble  r,s;
-	IssmDouble  vx,vy,vz,vmag;
-	IssmDouble  drag_p,drag_q;
+	IssmDouble  drag_p, drag_q;
 	IssmDouble  Neff;
+	IssmDouble  thickness,bed;
+	IssmDouble  vx,vy,vz,vmag;
 	IssmDouble  drag_coefficient;
-	IssmDouble  bed,thickness;
-	IssmDouble  alpha_complement;
+	IssmDouble  alpha2;
 
 	/*Recover parameters: */
@@ -190,31 +339,160 @@
 	if(Neff<0)Neff=0;
 
-	//We need the velocity magnitude to evaluate the basal stress:
-	switch(dim){
-		case 1:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			vmag=sqrt(vx*vx);
-			break;
-		case 2:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			element->GetInputValue(&vy,gauss,VyEnum);
-			vmag=sqrt(vx*vx+vy*vy);
-			break;
-		case 3:
-			element->GetInputValue(&vx,gauss,VxEnum);
-			element->GetInputValue(&vy,gauss,VyEnum);
-			element->GetInputValue(&vz,gauss,VzEnum);
-			vmag=sqrt(vx*vx+vy*vy+vz*vz);
-			break;
-		default:
-			_error_("not supported");
-	}
-
-	/*Check to prevent dividing by zero if vmag==0*/
-	if(vmag==0. && (s-1.)<0.) alpha_complement=0.;
-	else alpha_complement=pow(Neff,r)*pow(vmag,(s-1));_assert_(!xIsNan<IssmDouble>(alpha_complement));
-
-	/*Assign output pointers:*/
-	*palpha_complement=alpha_complement;
-}
-/*}}}*/
+	switch(dim){
+		case 1:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			vmag=sqrt(vx*vx);
+			break;
+		case 2:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			vmag=sqrt(vx*vx+vy*vy);
+			break;
+		case 3:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			element->GetInputValue(&vz,gauss,VzEnum);
+			vmag=sqrt(vx*vx+vy*vy+vz*vz);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+	/*Check to prevent dividing by zero if vmag==0*/
+	if(vmag==0. && (s-1.)<0.) alpha2=0.;
+	else alpha2=drag_coefficient*drag_coefficient*pow(Neff,r)*pow(vmag,(s-1.));
+	_assert_(!xIsNan<IssmDouble>(alpha2));
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}/*}}}*/
+void Friction::GetAlpha2WaterLayer(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+
+	/*This routine calculates the basal friction coefficient 
+	  alpha2= drag^2 * Neff ^r * | vel | ^(s-1), with Neff=rho_ice*g*thickness+rho_ice*g*bed, r=q/p and s=1/p**/
+
+	/*diverse: */
+	IssmDouble  r,s;
+	IssmDouble  drag_p, drag_q;
+	IssmDouble  Neff;
+	IssmDouble  thickness,bed;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  drag_coefficient,water_layer;
+	IssmDouble  alpha2;
+
+	/*Recover parameters: */
+	element->GetInputValue(&drag_p,FrictionPEnum);
+	element->GetInputValue(&drag_q,FrictionQEnum);
+	element->GetInputValue(&thickness, gauss,ThicknessEnum);
+	element->GetInputValue(&bed, gauss,BaseEnum);
+	element->GetInputValue(&drag_coefficient, gauss,FrictionCoefficientEnum);
+	element->GetInputValue(&water_layer, gauss,FrictionWaterLayerEnum);
+	IssmDouble rho_water   = element->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	IssmDouble rho_ice     = element->GetMaterialParameter(MaterialsRhoIceEnum);
+	IssmDouble gravity     = element->GetMaterialParameter(ConstantsGEnum);
+
+	//compute r and q coefficients: */
+	r=drag_q/drag_p;
+	s=1./drag_p;
+
+	//From bed and thickness, compute effective pressure when drag is viscous:
+	if(bed>0) bed=0;
+	Neff=gravity*(rho_ice*thickness+rho_water*(bed-water_layer));
+	if(Neff<0) Neff=0;
+
+	switch(dim){
+		case 1:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			vmag=sqrt(vx*vx);
+			break;
+		case 2:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			vmag=sqrt(vx*vx+vy*vy);
+			break;
+		case 3:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			element->GetInputValue(&vz,gauss,VzEnum);
+			vmag=sqrt(vx*vx+vy*vy+vz*vz);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+	/*Check to prevent dividing by zero if vmag==0*/
+	if(vmag==0. && (s-1.)<0.) alpha2=0.;
+	else alpha2=drag_coefficient*drag_coefficient*pow(Neff,r)*pow(vmag,(s-1.));
+	_assert_(!xIsNan<IssmDouble>(alpha2));
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}/*}}}*/
+void Friction::GetAlpha2Weertman(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+
+	/*This routine calculates the basal friction coefficient alpha2= C^-1/m |v|^(1/m-1) */
+
+	/*diverse: */
+	IssmDouble  C,m;
+	IssmDouble  vx,vy,vz,vmag;
+	IssmDouble  alpha2;
+
+	/*Recover parameters: */
+	element->GetInputValue(&C,gauss,FrictionCEnum);
+	element->GetInputValue(&m,FrictionMEnum);
+
+	switch(dim){
+		case 1:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			vmag=sqrt(vx*vx);
+			break;
+		case 2:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			vmag=sqrt(vx*vx+vy*vy);
+			break;
+		case 3:
+			element->GetInputValue(&vx,gauss,VxEnum);
+			element->GetInputValue(&vy,gauss,VyEnum);
+			element->GetInputValue(&vz,gauss,VzEnum);
+			vmag=sqrt(vx*vx+vy*vy+vz*vz);
+			break;
+		default:
+			_error_("not supported");
+	}
+
+	/*Check to prevent dividing by zero if vmag==0*/
+	if(vmag==0. && (1./m-1.)<0.) alpha2=0.;
+	else alpha2=pow(C,-1./m)*pow(vmag,(1./m-1.));
+	_assert_(!xIsNan<IssmDouble>(alpha2));
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}/*}}}*/
+void Friction::GetAlpha2WeertmanTemp(IssmDouble* palpha2, Gauss* gauss){/*{{{*/
+	/*Here, we want to parameterize the friction as a function of temperature
+	 *
+	 * alpha2 = alpha2_weertman * 1/f(T)
+	 *
+	 * where f(T) = exp((T-Tpmp)/gamma)
+	 */
+
+	/*Intermediaries: */
+	IssmDouble  f,T,pressure,Tpmp,gamma;
+	IssmDouble  alpha2;
+
+	/*Get viscous part*/
+	this->GetAlpha2Weertman(&alpha2,gauss);
+
+	/*Get pressure melting point (Tpmp) for local pressure and get current temperature*/
+	element->GetInputValue(&T,gauss,TemperatureEnum);
+	element->GetInputValue(&pressure,gauss,PressureEnum);
+	Tpmp = element->TMeltingPoint(pressure);
+
+	/*Compute scaling parameter*/
+	element->parameters->FindParam(&gamma,FrictionGammaEnum);
+	alpha2 = alpha2 / exp((T-Tpmp)/gamma);
+
+	/*Assign output pointers:*/
+	*palpha2=alpha2;
+}/*}}}*/
Index: /issm/trunk/src/c/classes/Loads/Friction.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Friction.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Friction.h	(revision 19105)
@@ -29,8 +29,14 @@
 
 		void  Echo(void);
+		void  GetAlphaComplement(IssmDouble* alpha_complement,Gauss* gauss);
+		void  GetAlphaViscousComplement(IssmDouble* alpha_complement,Gauss* gauss);
+		void  GetAlphaHydroComplement(IssmDouble* alpha_complement,Gauss* gauss);
 		void  GetAlpha2(IssmDouble* palpha2,Gauss* gauss);
+		void  GetAlpha2Hydro(IssmDouble* palpha2,Gauss* gauss);
+		void  GetAlpha2Temp(IssmDouble* palpha2,Gauss* gauss);
 		void  GetAlpha2Viscous(IssmDouble* palpha2,Gauss* gauss);
+		void  GetAlpha2WaterLayer(IssmDouble* palpha2,Gauss* gauss);
 		void  GetAlpha2Weertman(IssmDouble* palpha2,Gauss* gauss);
-		void  GetAlphaComplement(IssmDouble* alpha_complement,Gauss* gauss);
+		void  GetAlpha2WeertmanTemp(IssmDouble* palpha2,Gauss* gauss);
 };
 
Index: /issm/trunk/src/c/classes/Loads/Load.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Load.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Load.h	(revision 19105)
@@ -26,17 +26,17 @@
 		virtual       ~Load(){};
 		virtual void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
-		virtual void  ResetHooks()=0;
-		virtual bool  IsPenalty(void)=0;
-		virtual int   GetNumberOfNodes(void)=0;
-		virtual void  GetNodesSidList(int* sidlist)=0;
-		virtual void  GetNodesLidList(int* lidlist)=0;
-		virtual void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff)=0;
 		virtual void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs)=0;
 		virtual void  CreatePVector(Vector<IssmDouble>* pf)=0;
-		virtual void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff)=0;
+		virtual void  GetNodesLidList(int* lidlist)=0;
+		virtual void  GetNodesSidList(int* sidlist)=0;
+		virtual int   GetNumberOfNodes(void)=0;
+		virtual bool  InAnalysis(int analysis_type)=0;
+		virtual bool  IsPenalty(void)=0;
 		virtual void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax)=0;
 		virtual void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs, IssmDouble kmax)=0;
 		virtual void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax)=0;
-		virtual bool  InAnalysis(int analysis_type)=0;
+		virtual void  ResetHooks()=0;
+		virtual void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
 		virtual void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum)=0;
 };
Index: /issm/trunk/src/c/classes/Loads/Loads.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Loads.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Loads.cpp	(revision 19105)
@@ -41,20 +41,6 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		load=dynamic_cast<Load*>(*object);
+		load=xDynamicCast<Load*>(*object);
 		load->Configure(elements,loads,nodes,vertices,materials,parameters);
-
-	}
-
-}
-/*}}}*/
-void Loads::ResetHooks(){/*{{{*/
-
-	vector<Object*>::iterator object;
-	Load* load=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		load=dynamic_cast<Load*>((*object));
-		load->ResetHooks();
 
 	}
@@ -70,5 +56,5 @@
 	for(int i=0;i<this->Size();i++){
 
-		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
+		Load* load=xDynamicCast<Load*>(this->GetObjectByOffset(i));
 		if (load->InAnalysis(analysis_type)){
 			if(load->IsPenalty()) ispenalty++;
@@ -86,5 +72,5 @@
 }
 /*}}}*/
-int Loads::MaxNumNodes(int analysis_type){/*{{{*/
+int  Loads::MaxNumNodes(int analysis_type){/*{{{*/
 
 	int max=0;
@@ -95,5 +81,5 @@
 	for(int i=0;i<this->Size();i++){
 
-		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
+		Load* load=xDynamicCast<Load*>(this->GetObjectByOffset(i));
 		if (load->InAnalysis(analysis_type)){
 			numnodes=load->GetNumberOfNodes();
@@ -109,5 +95,5 @@
 }
 /*}}}*/
-int Loads::NumberOfLoads(void){/*{{{*/
+int  Loads::NumberOfLoads(void){/*{{{*/
 
 	int localloads;
@@ -124,5 +110,5 @@
 }
 /*}}}*/
-int Loads::NumberOfLoads(int analysis_type){/*{{{*/
+int  Loads::NumberOfLoads(int analysis_type){/*{{{*/
 
 	int localloads = 0;
@@ -132,5 +118,5 @@
 	for(int i=0;i<this->Size();i++){
 
-		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
+		Load* load=xDynamicCast<Load*>(this->GetObjectByOffset(i));
 
 		/*Check that this load corresponds to our analysis currently being carried out: */
@@ -145,23 +131,16 @@
 }
 /*}}}*/
-int Loads::Size(void){/*{{{*/
+void Loads::ResetHooks(){/*{{{*/
 
-	return this->DataSet::Size();
-}
-/*}}}*/
-int Loads::Size(int analysis_type){/*{{{*/
+	vector<Object*>::iterator object;
+	Load* load=NULL;
 
-	int localloads = 0;
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-	/*Get number of local loads*/
-	for(int i=0;i<this->Size();i++){
+		load=xDynamicCast<Load*>((*object));
+		load->ResetHooks();
 
-		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
-
-		/*Check that this load corresponds to our analysis currently being carried out: */
-		if (load->InAnalysis(analysis_type)) localloads++;
 	}
 
-	return localloads;
 }
 /*}}}*/
@@ -173,5 +152,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		load=dynamic_cast<Load*>(*object);
+		load=xDynamicCast<Load*>(*object);
 		load->SetCurrentConfiguration(elements,loads,nodes,vertices,materials,parameters);
 
@@ -180,2 +159,23 @@
 }
 /*}}}*/
+int  Loads::Size(void){/*{{{*/
+
+	return this->DataSet::Size();
+}
+/*}}}*/
+int  Loads::Size(int analysis_type){/*{{{*/
+
+	int localloads = 0;
+
+	/*Get number of local loads*/
+	for(int i=0;i<this->Size();i++){
+
+		Load* load=xDynamicCast<Load*>(this->GetObjectByOffset(i));
+
+		/*Check that this load corresponds to our analysis currently being carried out: */
+		if (load->InAnalysis(analysis_type)) localloads++;
+	}
+
+	return localloads;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Loads/Loads.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Loads.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Loads.h	(revision 19105)
@@ -24,9 +24,9 @@
 		/*numerics*/
 		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
-		void  ResetHooks();
 		bool  IsPenalty(int analysis);
 		int   MaxNumNodes(int analysis);
 		int   NumberOfLoads(void);
 		int   NumberOfLoads(int analysis);
+		void  ResetHooks();
 		void  SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
 		int   Size(int analysis);
Index: /issm/trunk/src/c/classes/Loads/Numericalflux.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Numericalflux.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Numericalflux.cpp	(revision 19105)
@@ -131,16 +131,32 @@
 
 /*Object virtual functions definitions:*/
-void Numericalflux::Echo(void){/*{{{*/
-	_printf_("Numericalflux:\n");
-	_printf_("   id: " << id << "\n");
-	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
-	_printf_("   flux_type: " << this->flux_type<< "\n");
-	hnodes->Echo();
-	hvertices->Echo();
-	helement->Echo();
-	_printf_("   parameters: " << parameters << "\n");
-}
-/*}}}*/
-void Numericalflux::DeepEcho(void){/*{{{*/
+Object* Numericalflux::copy() {/*{{{*/
+
+	Numericalflux* numericalflux=NULL;
+
+	numericalflux=new Numericalflux();
+
+	/*copy fields: */
+	numericalflux->id=this->id;
+	numericalflux->analysis_type=this->analysis_type;
+	numericalflux->flux_type=this->flux_type;
+
+	/*point parameters: */
+	numericalflux->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	numericalflux->hnodes    = (Hook*)this->hnodes->copy();
+	numericalflux->hvertices = (Hook*)this->hvertices->copy();
+	numericalflux->helement  = (Hook*)this->helement->copy();
+
+	/*corresponding fields*/
+	numericalflux->nodes    = (Node**)numericalflux->hnodes->deliverp();
+	numericalflux->vertices = (Vertex**)numericalflux->hvertices->deliverp();
+	numericalflux->element  = (Element*)numericalflux->helement->delivers();
+
+	return numericalflux;
+}
+/*}}}*/
+void    Numericalflux::DeepEcho(void){/*{{{*/
 
 	_printf_("Numericalflux:\n");
@@ -158,39 +174,23 @@
 }		
 /*}}}*/
-int Numericalflux::Id(void){/*{{{*/
+void    Numericalflux::Echo(void){/*{{{*/
+	_printf_("Numericalflux:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   flux_type: " << this->flux_type<< "\n");
+	hnodes->Echo();
+	hvertices->Echo();
+	helement->Echo();
+	_printf_("   parameters: " << parameters << "\n");
+}
+/*}}}*/
+int     Numericalflux::Id(void){/*{{{*/
 	return id;
 }
 /*}}}*/
-int Numericalflux::ObjectEnum(void){/*{{{*/
+int     Numericalflux::ObjectEnum(void){/*{{{*/
 
 	return NumericalfluxEnum;
 
-}
-/*}}}*/
-Object* Numericalflux::copy() {/*{{{*/
-
-	Numericalflux* numericalflux=NULL;
-
-	numericalflux=new Numericalflux();
-
-	/*copy fields: */
-	numericalflux->id=this->id;
-	numericalflux->analysis_type=this->analysis_type;
-	numericalflux->flux_type=this->flux_type;
-
-	/*point parameters: */
-	numericalflux->parameters=this->parameters;
-
-	/*now deal with hooks and objects: */
-	numericalflux->hnodes    = (Hook*)this->hnodes->copy();
-	numericalflux->hvertices = (Hook*)this->hvertices->copy();
-	numericalflux->helement  = (Hook*)this->helement->copy();
-
-	/*corresponding fields*/
-	numericalflux->nodes    = (Node**)numericalflux->hnodes->deliverp();
-	numericalflux->vertices = (Vertex**)numericalflux->hvertices->deliverp();
-	numericalflux->element  = (Element*)numericalflux->helement->delivers();
-
-	return numericalflux;
 }
 /*}}}*/
@@ -212,22 +212,4 @@
 	/*point parameters to real dataset: */
 	this->parameters=parametersin;
-}
-/*}}}*/
-void  Numericalflux::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
-
-}
-/*}}}*/
-void  Numericalflux::ResetHooks(){/*{{{*/
-
-	this->nodes=NULL;
-	this->vertices=NULL;
-	this->element=NULL;
-	this->parameters=NULL;
-
-	/*Get Element type*/
-	this->hnodes->reset();
-	this->hvertices->reset();
-	this->helement->reset();
-
 }
 /*}}}*/
@@ -291,4 +273,21 @@
 }
 /*}}}*/
+void  Numericalflux::GetNodesLidList(int* lidlist){/*{{{*/
+
+	_assert_(lidlist);
+	_assert_(nodes);
+
+	switch(this->flux_type){
+		case InternalEnum:
+			for(int i=0;i<NUMNODES_INTERNAL;i++) lidlist[i]=nodes[i]->Lid();
+			return;
+		case BoundaryEnum:
+			for(int i=0;i<NUMNODES_BOUNDARY;i++) lidlist[i]=nodes[i]->Lid();
+			return;
+		default:
+			_error_("Numericalflux type " << EnumToStringx(this->flux_type) << " not supported yet");
+	}
+}
+/*}}}*/
 void  Numericalflux::GetNodesSidList(int* sidlist){/*{{{*/
 
@@ -308,21 +307,4 @@
 }
 /*}}}*/
-void  Numericalflux::GetNodesLidList(int* lidlist){/*{{{*/
-
-	_assert_(lidlist);
-	_assert_(nodes);
-
-	switch(this->flux_type){
-		case InternalEnum:
-			for(int i=0;i<NUMNODES_INTERNAL;i++) lidlist[i]=nodes[i]->Lid();
-			return;
-		case BoundaryEnum:
-			for(int i=0;i<NUMNODES_BOUNDARY;i++) lidlist[i]=nodes[i]->Lid();
-			return;
-		default:
-			_error_("Numericalflux type " << EnumToStringx(this->flux_type) << " not supported yet");
-	}
-}
-/*}}}*/
 int   Numericalflux::GetNumberOfNodes(void){/*{{{*/
 
@@ -338,25 +320,43 @@
 }
 /*}}}*/
-bool  Numericalflux::IsPenalty(void){/*{{{*/
-	return false;
-}
-/*}}}*/
-void  Numericalflux::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){/*{{{*/
-
-	/*No stiffness loads applied, do nothing: */
-	return;
-
-}
-/*}}}*/
-void  Numericalflux::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){/*{{{*/
-
-	/*No penalty loads applied, do nothing: */
-	return;
-
-}
-/*}}}*/
 bool  Numericalflux::InAnalysis(int in_analysis_type){/*{{{*/
 	if (in_analysis_type==this->analysis_type) return true;
 	else return false;
+}
+/*}}}*/
+bool  Numericalflux::IsPenalty(void){/*{{{*/
+	return false;
+}
+/*}}}*/
+void  Numericalflux::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){/*{{{*/
+
+	/*No stiffness loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+void  Numericalflux::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){/*{{{*/
+
+	/*No penalty loads applied, do nothing: */
+	return;
+
+}
+/*}}}*/
+void  Numericalflux::ResetHooks(){/*{{{*/
+
+	this->nodes=NULL;
+	this->vertices=NULL;
+	this->element=NULL;
+	this->parameters=NULL;
+
+	/*Get Element type*/
+	this->hnodes->reset();
+	this->hvertices->reset();
+	this->helement->reset();
+
+}
+/*}}}*/
+void  Numericalflux::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
 }
 /*}}}*/
@@ -417,4 +417,175 @@
 
 /*Numericalflux management*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethickness(void){/*{{{*/
+
+	switch(this->flux_type){
+		case InternalEnum:
+			return CreateKMatrixAdjointBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreateKMatrixAdjointBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary(void){/*{{{*/
+
+	ElementMatrix* Ke=CreateKMatrixBalancethicknessBoundary();
+	if(Ke) Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessInternal(void){/*{{{*/
+
+	ElementMatrix* Ke=CreateKMatrixBalancethicknessInternal();
+	if (Ke) Ke->Transpose();
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethickness(void){/*{{{*/
+
+	switch(this->flux_type){
+		case InternalEnum:
+			return CreateKMatrixBalancethicknessInternal();
+		case BoundaryEnum:
+			return CreateKMatrixBalancethicknessBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessBoundary(void){/*{{{*/
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     L[numdof];
+	IssmDouble     Ke_g[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke = NULL;
+	Tria*  tria=(Tria*)element;
+	if(!tria->IsIceInElement()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN<=0){
+		return NULL; /*(u,n)<0 -> inflow, PenaltyCreatePVector will take care of it*/
+	}
+	else{
+		Ke=new ElementMatrix(nodes,NUMNODES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL=gauss->weight*Jdet*UdotN;
+
+		TripleMultiply(&L[0],1,numdof,1,
+					&DL,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke_g[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g[i][j];
+	} 
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessInternal(void){/*{{{*/
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_INTERNAL;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL1,DL2,Jdet,vx,vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     B[numdof];
+	IssmDouble     Bprime[numdof];
+	IssmDouble     Ke_g1[numdof][numdof];
+	IssmDouble     Ke_g2[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	Tria*  tria=(Tria*)element;
+	if(!tria->IsIceInElement()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMNODES_INTERNAL,this->parameters);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
+	GetNormal(&normal[0],xyz_list);
+
+	/* Start  looping on the number of gaussian points: */
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentBFlux(&B[0],gauss,index1,index2,tria->FiniteElement());
+		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2,tria->FiniteElement());
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL1=gauss->weight*Jdet*UdotN/2;
+		DL2=gauss->weight*Jdet*fabs(UdotN)/2;
+
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL1,1,1,0,
+					&Bprime[0],1,numdof,0,
+					&Ke_g1[0][0],0);
+		TripleMultiply(&B[0],1,numdof,1,
+					&DL2,1,1,0,
+					&B[0],1,numdof,0,
+					&Ke_g2[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g1[i][j];
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g2[i][j];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
 ElementMatrix* Numericalflux::CreateKMatrixMasstransport(void){/*{{{*/
 
@@ -427,4 +598,75 @@
 			_error_("type not supported yet");
 	}
+}
+/*}}}*/
+ElementMatrix* Numericalflux::CreateKMatrixMasstransportBoundary(void){/*{{{*/
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,j,ig,index1,index2;
+	IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     L[numdof];
+	IssmDouble     Ke_g[numdof][numdof];
+	GaussTria *gauss;
+
+	/*Initialize Element matrix and return if necessary*/
+	ElementMatrix* Ke = NULL;
+	Tria*  tria=(Tria*)element;
+	if(!tria->IsIceInElement()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vxaverage_input=tria->inputs->GetInput(VxEnum); _assert_(vxaverage_input);
+	Input* vyaverage_input=tria->inputs->GetInput(VyEnum); _assert_(vyaverage_input);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN<=0){
+		return NULL; /*(u,n)<0 -> inflow, PenaltyCreatePVector will take care of it*/
+	}
+	else{
+		Ke=new ElementMatrix(nodes,NUMNODES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL=gauss->weight*Jdet*dt*UdotN;
+
+		TripleMultiply(&L[0],1,numdof,1,
+					&DL,1,1,0,
+					&L[0],1,numdof,0,
+					&Ke_g[0][0],0);
+
+		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g[i][j];
+	} 
+
+	/*Clean up and return*/
+	delete gauss;
+	return Ke;
 }
 /*}}}*/
@@ -493,332 +735,8 @@
 }
 /*}}}*/
-ElementMatrix* Numericalflux::CreateKMatrixMasstransportBoundary(void){/*{{{*/
-
-	/* constants*/
-	const int numdof=NDOF1*NUMNODES_BOUNDARY;
-
-	/* Intermediaries*/
-	int        i,j,ig,index1,index2;
-	IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     normal[2];
-	IssmDouble     L[numdof];
-	IssmDouble     Ke_g[numdof][numdof];
-	GaussTria *gauss;
-
-	/*Initialize Element matrix and return if necessary*/
-	ElementMatrix* Ke = NULL;
-	Tria*  tria=(Tria*)element;
-	if(!tria->IsIceInElement()) return NULL;
-
-	/*Retrieve all inputs and parameters*/
-	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
-	Input* vxaverage_input=tria->inputs->GetInput(VxEnum); _assert_(vxaverage_input);
-	Input* vyaverage_input=tria->inputs->GetInput(VyEnum); _assert_(vyaverage_input);
-	GetNormal(&normal[0],xyz_list);
-
-	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
-	index1=tria->GetNodeIndex(nodes[0]);
-	index2=tria->GetNodeIndex(nodes[1]);
-
-	gauss=new GaussTria();
-	gauss->GaussEdgeCenter(index1,index2);
-	vxaverage_input->GetInputValue(&mean_vx,gauss);
-	vyaverage_input->GetInputValue(&mean_vy,gauss);
-	delete gauss;
-
-	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
-	if (UdotN<=0){
-		return NULL; /*(u,n)<0 -> inflow, PenaltyCreatePVector will take care of it*/
-	}
-	else{
-		Ke=new ElementMatrix(nodes,NUMNODES_BOUNDARY,this->parameters);
-	}
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(index1,index2,2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
-
-		vxaverage_input->GetInputValue(&vx,gauss);
-		vyaverage_input->GetInputValue(&vy,gauss);
-		UdotN=vx*normal[0]+vy*normal[1];
-		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
-		DL=gauss->weight*Jdet*dt*UdotN;
-
-		TripleMultiply(&L[0],1,numdof,1,
-					&DL,1,1,0,
-					&L[0],1,numdof,0,
-					&Ke_g[0][0],0);
-
-		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g[i][j];
-	} 
-
-	/*Clean up and return*/
-	delete gauss;
-	return Ke;
-}
-/*}}}*/
-ElementMatrix* Numericalflux::CreateKMatrixBalancethickness(void){/*{{{*/
-
-	switch(this->flux_type){
-		case InternalEnum:
-			return CreateKMatrixBalancethicknessInternal();
-		case BoundaryEnum:
-			return CreateKMatrixBalancethicknessBoundary();
-		default:
-			_error_("type not supported yet");
-	}
-}
-/*}}}*/
-ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessInternal(void){/*{{{*/
-
-	/* constants*/
-	const int numdof=NDOF1*NUMNODES_INTERNAL;
-
-	/* Intermediaries*/
-	int        i,j,ig,index1,index2;
-	IssmDouble     DL1,DL2,Jdet,vx,vy,UdotN;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     normal[2];
-	IssmDouble     B[numdof];
-	IssmDouble     Bprime[numdof];
-	IssmDouble     Ke_g1[numdof][numdof];
-	IssmDouble     Ke_g2[numdof][numdof];
-	GaussTria *gauss;
-
-	/*Initialize Element matrix and return if necessary*/
-	Tria*  tria=(Tria*)element;
-	if(!tria->IsIceInElement()) return NULL;
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMNODES_INTERNAL,this->parameters);
-
-	/*Retrieve all inputs and parameters*/
-	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
-	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
-	GetNormal(&normal[0],xyz_list);
-
-	/* Start  looping on the number of gaussian points: */
-	index1=tria->GetNodeIndex(nodes[0]);
-	index2=tria->GetNodeIndex(nodes[1]);
-	gauss=new GaussTria(index1,index2,2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		tria->GetSegmentBFlux(&B[0],gauss,index1,index2,tria->FiniteElement());
-		tria->GetSegmentBprimeFlux(&Bprime[0],gauss,index1,index2,tria->FiniteElement());
-
-		vxaverage_input->GetInputValue(&vx,gauss);
-		vyaverage_input->GetInputValue(&vy,gauss);
-		UdotN=vx*normal[0]+vy*normal[1];
-		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
-		DL1=gauss->weight*Jdet*UdotN/2;
-		DL2=gauss->weight*Jdet*fabs(UdotN)/2;
-
-		TripleMultiply(&B[0],1,numdof,1,
-					&DL1,1,1,0,
-					&Bprime[0],1,numdof,0,
-					&Ke_g1[0][0],0);
-		TripleMultiply(&B[0],1,numdof,1,
-					&DL2,1,1,0,
-					&B[0],1,numdof,0,
-					&Ke_g2[0][0],0);
-
-		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g1[i][j];
-		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g2[i][j];
-	}
-
-	/*Clean up and return*/
-	delete gauss;
-	return Ke;
-}
-/*}}}*/
-ElementMatrix* Numericalflux::CreateKMatrixBalancethicknessBoundary(void){/*{{{*/
-
-	/* constants*/
-	const int numdof=NDOF1*NUMNODES_BOUNDARY;
-
-	/* Intermediaries*/
-	int        i,j,ig,index1,index2;
-	IssmDouble     DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     normal[2];
-	IssmDouble     L[numdof];
-	IssmDouble     Ke_g[numdof][numdof];
-	GaussTria *gauss;
-
-	/*Initialize Element matrix and return if necessary*/
-	ElementMatrix* Ke = NULL;
-	Tria*  tria=(Tria*)element;
-	if(!tria->IsIceInElement()) return NULL;
-
-	/*Retrieve all inputs and parameters*/
-	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	Input* vxaverage_input=tria->inputs->GetInput(VxEnum);
-	Input* vyaverage_input=tria->inputs->GetInput(VyEnum);
-	GetNormal(&normal[0],xyz_list);
-
-	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
-	index1=tria->GetNodeIndex(nodes[0]);
-	index2=tria->GetNodeIndex(nodes[1]);
-
-	gauss=new GaussTria();
-	gauss->GaussEdgeCenter(index1,index2);
-	vxaverage_input->GetInputValue(&mean_vx,gauss);
-	vyaverage_input->GetInputValue(&mean_vy,gauss);
-	delete gauss;
-
-	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
-	if (UdotN<=0){
-		return NULL; /*(u,n)<0 -> inflow, PenaltyCreatePVector will take care of it*/
-	}
-	else{
-		Ke=new ElementMatrix(nodes,NUMNODES_BOUNDARY,this->parameters);
-	}
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(index1,index2,2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
-
-		vxaverage_input->GetInputValue(&vx,gauss);
-		vyaverage_input->GetInputValue(&vy,gauss);
-		UdotN=vx*normal[0]+vy*normal[1];
-		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
-		DL=gauss->weight*Jdet*UdotN;
-
-		TripleMultiply(&L[0],1,numdof,1,
-					&DL,1,1,0,
-					&L[0],1,numdof,0,
-					&Ke_g[0][0],0);
-
-		for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g[i][j];
-	} 
-
-	/*Clean up and return*/
-	delete gauss;
-	return Ke;
-}
-/*}}}*/
-ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethickness(void){/*{{{*/
-
-	switch(this->flux_type){
-		case InternalEnum:
-			return CreateKMatrixAdjointBalancethicknessInternal();
-		case BoundaryEnum:
-			return CreateKMatrixAdjointBalancethicknessBoundary();
-		default:
-			_error_("type not supported yet");
-	}
-}
-/*}}}*/
-ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessInternal(void){/*{{{*/
-
-	ElementMatrix* Ke=CreateKMatrixBalancethicknessInternal();
-	if (Ke) Ke->Transpose();
-	return Ke;
-}
-/*}}}*/
-ElementMatrix* Numericalflux::CreateKMatrixAdjointBalancethicknessBoundary(void){/*{{{*/
-
-	ElementMatrix* Ke=CreateKMatrixBalancethicknessBoundary();
-	if(Ke) Ke->Transpose();
-	return Ke;
-}
-/*}}}*/
-ElementVector* Numericalflux::CreatePVectorMasstransport(void){/*{{{*/
-
-	switch(this->flux_type){
-		case InternalEnum:
-			return CreatePVectorMasstransportInternal();
-		case BoundaryEnum:
-			return CreatePVectorMasstransportBoundary();
-		default:
-			_error_("type not supported yet");
-	}
-}
-/*}}}*/
-ElementVector* Numericalflux::CreatePVectorMasstransportInternal(void){/*{{{*/
-
-	/*Nothing added to PVector*/
+ElementVector* Numericalflux::CreatePVectorAdjointBalancethickness(void){/*{{{*/
+
+	/*No PVector for the Adjoint*/
 	return NULL;
-
-}
-/*}}}*/
-ElementVector* Numericalflux::CreatePVectorMasstransportBoundary(void){/*{{{*/
-
-	/* constants*/
-	const int numdof=NDOF1*NUMNODES_BOUNDARY;
-
-	/* Intermediaries*/
-	int        i,ig,index1,index2;
-	IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN,thickness;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     normal[2];
-	IssmDouble     L[numdof];
-	GaussTria *gauss;
-
-	/*Initialize Load Vector and return if necessary*/
-	ElementVector* pe = NULL;
-	Tria*  tria=(Tria*)element;
-	if(!tria->IsIceInElement()) return NULL;
-
-	/*Retrieve all inputs and parameters*/
-	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
-	Input* vxaverage_input   =tria->inputs->GetInput(VxEnum);                     _assert_(vxaverage_input); 
-	Input* vyaverage_input   =tria->inputs->GetInput(VyEnum);                     _assert_(vyaverage_input);
-	Input* spcthickness_input=tria->inputs->GetInput(MasstransportSpcthicknessEnum); _assert_(spcthickness_input);
-	GetNormal(&normal[0],xyz_list);
-
-	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
-	index1=tria->GetNodeIndex(nodes[0]);
-	index2=tria->GetNodeIndex(nodes[1]);
-
-	gauss=new GaussTria();
-	gauss->GaussEdgeCenter(index1,index2);
-	vxaverage_input->GetInputValue(&mean_vx,gauss);
-	vyaverage_input->GetInputValue(&mean_vy,gauss);
-	delete gauss;
-
-	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
-	if (UdotN>0){
-		return NULL; /*(u,n)>0 -> outflow, PenaltyCreateKMatrix will take care of it*/
-	}
-	else{
-		pe=new ElementVector(nodes,NUMNODES_BOUNDARY,this->parameters);
-	}
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(index1,index2,2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
-
-		vxaverage_input->GetInputValue(&vx,gauss);
-		vyaverage_input->GetInputValue(&vy,gauss);
-		spcthickness_input->GetInputValue(&thickness,gauss);
-		if(xIsNan<IssmDouble>(thickness)) _error_("Cannot weakly apply constraint because NaN was provided");
-
-		UdotN=vx*normal[0]+vy*normal[1];
-		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
-		DL= - gauss->weight*Jdet*dt*UdotN*thickness;
-
-		for(i=0;i<numdof;i++) pe->values[i] += DL*L[i];
-	}
-
-	/*Clean up and return*/
-	delete gauss;
-	return pe;
 }
 /*}}}*/
@@ -833,11 +751,4 @@
 			_error_("type not supported yet");
 	}
-}
-/*}}}*/
-ElementVector* Numericalflux::CreatePVectorBalancethicknessInternal(void){/*{{{*/
-
-	/*Nothing added to PVector*/
-	return NULL;
-
 }
 /*}}}*/
@@ -908,11 +819,100 @@
 }
 /*}}}*/
-ElementVector* Numericalflux::CreatePVectorAdjointBalancethickness(void){/*{{{*/
-
-	/*No PVector for the Adjoint*/
+ElementVector* Numericalflux::CreatePVectorBalancethicknessInternal(void){/*{{{*/
+
+	/*Nothing added to PVector*/
 	return NULL;
-}
-/*}}}*/
-void Numericalflux:: GetNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]){/*{{{*/
+
+}
+/*}}}*/
+ElementVector* Numericalflux::CreatePVectorMasstransport(void){/*{{{*/
+
+	switch(this->flux_type){
+		case InternalEnum:
+			return CreatePVectorMasstransportInternal();
+		case BoundaryEnum:
+			return CreatePVectorMasstransportBoundary();
+		default:
+			_error_("type not supported yet");
+	}
+}
+/*}}}*/
+ElementVector* Numericalflux::CreatePVectorMasstransportBoundary(void){/*{{{*/
+
+	/* constants*/
+	const int numdof=NDOF1*NUMNODES_BOUNDARY;
+
+	/* Intermediaries*/
+	int        i,ig,index1,index2;
+	IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN,thickness;
+	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble     normal[2];
+	IssmDouble     L[numdof];
+	GaussTria *gauss;
+
+	/*Initialize Load Vector and return if necessary*/
+	ElementVector* pe = NULL;
+	Tria*  tria=(Tria*)element;
+	if(!tria->IsIceInElement()) return NULL;
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vxaverage_input   =tria->inputs->GetInput(VxEnum);                     _assert_(vxaverage_input); 
+	Input* vyaverage_input   =tria->inputs->GetInput(VyEnum);                     _assert_(vyaverage_input);
+	Input* spcthickness_input=tria->inputs->GetInput(MasstransportSpcthicknessEnum); _assert_(spcthickness_input);
+	GetNormal(&normal[0],xyz_list);
+
+	/*Check wether it is an inflow or outflow BC (0 is the middle of the segment)*/
+	index1=tria->GetNodeIndex(nodes[0]);
+	index2=tria->GetNodeIndex(nodes[1]);
+
+	gauss=new GaussTria();
+	gauss->GaussEdgeCenter(index1,index2);
+	vxaverage_input->GetInputValue(&mean_vx,gauss);
+	vyaverage_input->GetInputValue(&mean_vy,gauss);
+	delete gauss;
+
+	UdotN=mean_vx*normal[0]+mean_vy*normal[1];
+	if (UdotN>0){
+		return NULL; /*(u,n)>0 -> outflow, PenaltyCreateKMatrix will take care of it*/
+	}
+	else{
+		pe=new ElementVector(nodes,NUMNODES_BOUNDARY,this->parameters);
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussTria(index1,index2,2);
+	for(ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		tria->GetSegmentNodalFunctions(&L[0],gauss,index1,index2,tria->FiniteElement());
+
+		vxaverage_input->GetInputValue(&vx,gauss);
+		vyaverage_input->GetInputValue(&vy,gauss);
+		spcthickness_input->GetInputValue(&thickness,gauss);
+		if(xIsNan<IssmDouble>(thickness)) _error_("Cannot weakly apply constraint because NaN was provided");
+
+		UdotN=vx*normal[0]+vy*normal[1];
+		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		DL= - gauss->weight*Jdet*dt*UdotN*thickness;
+
+		for(i=0;i<numdof;i++) pe->values[i] += DL*L[i];
+	}
+
+	/*Clean up and return*/
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+ElementVector* Numericalflux::CreatePVectorMasstransportInternal(void){/*{{{*/
+
+	/*Nothing added to PVector*/
+	return NULL;
+
+}
+/*}}}*/
+void           Numericalflux::GetNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]){/*{{{*/
 
 	/*Build unit outward pointing vector*/
Index: /issm/trunk/src/c/classes/Loads/Numericalflux.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Numericalflux.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Numericalflux.h	(revision 19105)
@@ -40,54 +40,54 @@
 		/*}}}*/
 		/*Object virtual functions definitions:{{{ */
+		Object *copy();
+		void    DeepEcho();
 		void    Echo();
-		void    DeepEcho();
 		int     Id();
 		int     ObjectEnum();
-		Object *copy();
 		/*}}}*/
 		/*Update virtual functions resolution: {{{*/
-		void InputUpdateFromVector(IssmDouble* vector, int name, int type){/*Do nothing*/}
-		void InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*Do nothing*/}
-		void InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*Do nothing*/}
 		void InputUpdateFromConstant(IssmDouble constant, int name){/*Do nothing*/};
 		void InputUpdateFromConstant(int constant, int name){/*Do nothing*/};
 		void InputUpdateFromConstant(bool constant, int name){_error_("Not implemented yet!");}
 		void InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		void InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*Do nothing*/}
+		void InputUpdateFromVector(IssmDouble* vector, int name, int type){/*Do nothing*/}
+		void InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*Do nothing*/}
 		/*}}}*/
 		/*Load virtual functions definitions: {{{*/
 		void Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
-		void SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
-		void ResetHooks();
+		void CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
 		void CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
 		void CreatePVector(Vector<IssmDouble>* pf);
+		void GetNodesLidList(int* lidlist);
 		void GetNodesSidList(int* sidlist);
-		void GetNodesLidList(int* lidlist);
 		int  GetNumberOfNodes(void);
-		void CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
+		bool InAnalysis(int analysis_type);
 		bool IsPenalty(void);
 		void PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
 		void PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
 		void PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		void ResetHooks();
 		void SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum);
-		bool InAnalysis(int analysis_type);
+		void SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
 		/*}}}*/
 		/*Numericalflux management:{{{*/
+		ElementMatrix* CreateKMatrixAdjointBalancethickness(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethicknessBoundary(void);
+		ElementMatrix* CreateKMatrixAdjointBalancethicknessInternal(void);
+		ElementMatrix* CreateKMatrixBalancethickness(void);
+		ElementMatrix* CreateKMatrixBalancethicknessBoundary(void);
+		ElementMatrix* CreateKMatrixBalancethicknessInternal(void);
+		ElementMatrix* CreateKMatrixMasstransport(void);
+		ElementMatrix* CreateKMatrixMasstransportBoundary(void);
+		ElementMatrix* CreateKMatrixMasstransportInternal(void);
+		ElementVector* CreatePVectorAdjointBalancethickness(void);
+		ElementVector* CreatePVectorBalancethickness(void);
+		ElementVector* CreatePVectorBalancethicknessBoundary(void);
+		ElementVector* CreatePVectorBalancethicknessInternal(void);
+		ElementVector* CreatePVectorMasstransport(void);
+		ElementVector* CreatePVectorMasstransportBoundary(void);
+		ElementVector* CreatePVectorMasstransportInternal(void);
 		void           GetNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]);
-		ElementMatrix* CreateKMatrixMasstransport(void);
-		ElementMatrix* CreateKMatrixMasstransportInternal(void);
-		ElementMatrix* CreateKMatrixMasstransportBoundary(void);
-		ElementMatrix* CreateKMatrixBalancethickness(void);
-		ElementMatrix* CreateKMatrixBalancethicknessInternal(void);
-		ElementMatrix* CreateKMatrixBalancethicknessBoundary(void);
-		ElementMatrix* CreateKMatrixAdjointBalancethickness(void);
-		ElementMatrix* CreateKMatrixAdjointBalancethicknessInternal(void);
-		ElementMatrix* CreateKMatrixAdjointBalancethicknessBoundary(void);
-		ElementVector* CreatePVectorMasstransport(void);
-		ElementVector* CreatePVectorMasstransportInternal(void);
-		ElementVector* CreatePVectorMasstransportBoundary(void);
-		ElementVector* CreatePVectorBalancethickness(void);
-		ElementVector* CreatePVectorBalancethicknessInternal(void);
-		ElementVector* CreatePVectorBalancethicknessBoundary(void);
-		ElementVector* CreatePVectorAdjointBalancethickness(void);
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/Loads/Pengrid.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Pengrid.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Pengrid.cpp	(revision 19105)
@@ -81,9 +81,36 @@
 
 /*Object virtual functions definitions:*/
-void Pengrid::Echo(void){/*{{{*/
-	this->DeepEcho();
-}
-/*}}}*/
-void Pengrid::DeepEcho(void){/*{{{*/
+Object* Pengrid::copy() {/*{{{*/
+
+	Pengrid* pengrid=NULL;
+
+	pengrid=new Pengrid();
+
+	/*copy fields: */
+	pengrid->id=this->id;
+	pengrid->analysis_type=this->analysis_type;
+
+	/*point parameters: */
+	pengrid->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	pengrid->hnode=(Hook*)this->hnode->copy();
+	pengrid->hmatpar=(Hook*)this->hmatpar->copy();
+	pengrid->helement=(Hook*)this->helement->copy();
+
+	/*corresponding fields*/
+	pengrid->node  =(Node*)pengrid->hnode->delivers();
+	pengrid->matpar =(Matpar*)pengrid->hmatpar->delivers();
+	pengrid->element=(Element*)pengrid->helement->delivers();
+
+	//let's not forget internals
+	pengrid->active=this->active=0;
+	pengrid->zigzag_counter=this->zigzag_counter=0;
+
+	return pengrid;
+
+}
+/*}}}*/
+void    Pengrid::DeepEcho(void){/*{{{*/
 
 	_printf_("Pengrid:\n");
@@ -99,40 +126,13 @@
 }
 /*}}}*/
-int    Pengrid::Id(void){ return id; }/*{{{*/
-/*}}}*/
-int Pengrid::ObjectEnum(void){/*{{{*/
+void    Pengrid::Echo(void){/*{{{*/
+	this->DeepEcho();
+}
+/*}}}*/
+int     Pengrid::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int     Pengrid::ObjectEnum(void){/*{{{*/
 
 	return PengridEnum;
-}
-/*}}}*/
-Object* Pengrid::copy() {/*{{{*/
-
-	Pengrid* pengrid=NULL;
-
-	pengrid=new Pengrid();
-
-	/*copy fields: */
-	pengrid->id=this->id;
-	pengrid->analysis_type=this->analysis_type;
-
-	/*point parameters: */
-	pengrid->parameters=this->parameters;
-
-	/*now deal with hooks and objects: */
-	pengrid->hnode=(Hook*)this->hnode->copy();
-	pengrid->hmatpar=(Hook*)this->hmatpar->copy();
-	pengrid->helement=(Hook*)this->helement->copy();
-
-	/*corresponding fields*/
-	pengrid->node  =(Node*)pengrid->hnode->delivers();
-	pengrid->matpar =(Matpar*)pengrid->hmatpar->delivers();
-	pengrid->element=(Element*)pengrid->helement->delivers();
-
-	//let's not forget internals
-	pengrid->active=this->active=0;
-	pengrid->zigzag_counter=this->zigzag_counter=0;
-
-	return pengrid;
-
 }
 /*}}}*/
@@ -154,22 +154,4 @@
 	/*point parameters to real dataset: */
 	this->parameters=parametersin;
-}
-/*}}}*/
-void  Pengrid::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
-
-}
-/*}}}*/
-void  Pengrid::ResetHooks(){/*{{{*/
-
-	this->node=NULL;
-	this->element=NULL;
-	this->matpar=NULL;
-	this->parameters=NULL;
-
-	/*Get Element type*/
-	this->hnode->reset();
-	this->helement->reset();
-	this->hmatpar->reset();
-
 }
 /*}}}*/
@@ -203,4 +185,12 @@
 }
 /*}}}*/
+void  Pengrid::GetNodesLidList(int* lidlist){/*{{{*/
+
+	_assert_(lidlist);
+	_assert_(node);
+
+	lidlist[0]=node->Lid();
+}
+/*}}}*/
 void  Pengrid::GetNodesSidList(int* sidlist){/*{{{*/
 
@@ -211,15 +201,16 @@
 }
 /*}}}*/
-void  Pengrid::GetNodesLidList(int* lidlist){/*{{{*/
-
-	_assert_(lidlist);
-	_assert_(node);
-
-	lidlist[0]=node->Lid();
-}
-/*}}}*/
 int   Pengrid::GetNumberOfNodes(void){/*{{{*/
 
 	return NUMVERTICES;
+}
+/*}}}*/
+bool  Pengrid::InAnalysis(int in_analysis_type){/*{{{*/
+	if (in_analysis_type==this->analysis_type)return true;
+	else return false;
+}
+/*}}}*/
+bool  Pengrid::IsPenalty(void){/*{{{*/
+	return true;
 }
 /*}}}*/
@@ -282,11 +273,20 @@
 }
 /*}}}*/
-bool  Pengrid::InAnalysis(int in_analysis_type){/*{{{*/
-	if (in_analysis_type==this->analysis_type)return true;
-	else return false;
-}
-/*}}}*/
-bool  Pengrid::IsPenalty(void){/*{{{*/
-	return true;
+void  Pengrid::ResetHooks(){/*{{{*/
+
+	this->node=NULL;
+	this->element=NULL;
+	this->matpar=NULL;
+	this->parameters=NULL;
+
+	/*Get Element type*/
+	this->hnode->reset();
+	this->helement->reset();
+	this->hmatpar->reset();
+
+}
+/*}}}*/
+void  Pengrid::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
 }
 /*}}}*/
@@ -343,16 +343,4 @@
 
 /*Update virtual functions definitions:*/
-void  Pengrid::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
-	/*Nothing updated yet*/
-}
-/*}}}*/
-void  Pengrid::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*{{{*/
-	/*Nothing updated yet*/
-}
-/*}}}*/
-void  Pengrid::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
-	/*Nothing updated yet*/
-}
-/*}}}*/
 void  Pengrid::InputUpdateFromConstant(IssmDouble constant, int name){/*{{{*/
 	/*Nothing*/
@@ -374,7 +362,19 @@
 }
 /*}}}*/
+void  Pengrid::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Pengrid::InputUpdateFromVector(IssmDouble* vector, int name, int type){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
+void  Pengrid::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){/*{{{*/
+	/*Nothing updated yet*/
+}
+/*}}}*/
 
 /*Pengrid management:*/
-void  Pengrid::ConstraintActivate(int* punstable){/*{{{*/
+void           Pengrid::ConstraintActivate(int* punstable){/*{{{*/
 
 	int analysis_type;
@@ -404,179 +404,5 @@
 }
 /*}}}*/
-void  Pengrid::ConstraintActivateThermal(int* punstable){/*{{{*/
-
-	//   The penalty is stable if it doesn't change during to successive iterations.   
-	IssmDouble pressure;
-	IssmDouble temperature;
-	IssmDouble t_pmp;
-	int        new_active;
-	int        unstable=0;
-	int        penalty_lock;
-
-	/*recover pointers: */
-	Penta* penta=(Penta*)element;
-
-	/*check that pengrid is not a clone (penalty to be added only once)*/
-	if (node->IsClone()){
-		unstable=0;
-		*punstable=unstable;
-		return;
-	}
-
-	//First recover pressure and temperature values, using the element: */
-	penta->GetInputValue(&pressure,node,PressureEnum);
-	penta->GetInputValue(&temperature,node,TemperaturePicardEnum);
-
-	//Recover our data:
-	parameters->FindParam(&penalty_lock,ThermalPenaltyLockEnum);
-
-	//Compute pressure melting point
-	t_pmp=matpar->TMeltingPoint(pressure);
-
-	//Figure out if temperature is over melting_point, in which case, this penalty needs to be activated.
-
-	if (temperature>t_pmp){
-		new_active=1;
-	}
-	else{
-		new_active=0;
-	}
-
-	//Figure out stability of this penalty
-	if (active==new_active){
-		unstable=0;
-	}
-	else{
-		unstable=1;
-		if(penalty_lock)zigzag_counter++;
-	}
-
-	/*If penalty keeps zigzagging more than 5 times: */
-	if(penalty_lock){
-		if(zigzag_counter>penalty_lock){
-			unstable=0;
-			active=1;
-		}
-	}
-
-	//Set penalty flag
-	active=new_active;
-
-	//*Assign output pointers:*/
-	*punstable=unstable;
-}
-/*}}}*/
-ElementMatrix* Pengrid::PenaltyCreateKMatrixMelting(IssmDouble kmax){/*{{{*/
-
-	IssmDouble pressure,temperature,t_pmp;
-	IssmDouble penalty_factor;
-
-	Penta* penta=(Penta*)element;
-
-	/*check that pengrid is not a clone (penalty to be added only once)*/
-	if (node->IsClone()) return NULL;
-	ElementMatrix* Ke=new ElementMatrix(&node,1,this->parameters);
-
-	/*Retrieve all parameters*/
-	penta->GetInputValue(&pressure,node,PressureEnum);
-	penta->GetInputValue(&temperature,node,TemperatureEnum);
-	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
-
-	/*Compute pressure melting point*/
-	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
-
-	/*Add penalty load*/
-	if (temperature<t_pmp){ //If T<Tpmp, there must be no melting. Therefore, melting should be  constrained to 0 when T<Tpmp, instead of using spcs, use penalties
-		Ke->values[0]=kmax*pow(10.,penalty_factor);
-	}
-
-	/*Clean up and return*/
-	return Ke;
-}
-/*}}}*/
-ElementMatrix* Pengrid::PenaltyCreateKMatrixThermal(IssmDouble kmax){/*{{{*/
-
-	IssmDouble    penalty_factor;
-
-	/*Initialize Element matrix and return if necessary*/
-	if(!this->active) return NULL;
-	ElementMatrix* Ke=new ElementMatrix(&node,NUMVERTICES,this->parameters);
-
-	/*recover parameters: */
-	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
-
-	Ke->values[0]=kmax*pow(10.,penalty_factor);
-
-	/*Clean up and return*/
-	return Ke;
-}
-/*}}}*/
-ElementVector* Pengrid::PenaltyCreatePVectorMelting(IssmDouble kmax){/*{{{*/
-
-	IssmDouble pressure;
-	IssmDouble temperature;
-	IssmDouble melting_offset;
-	IssmDouble t_pmp;
-	IssmDouble dt,penalty_factor;
-
-	/*recover pointers: */
-	Penta* penta=(Penta*)element;
-
-	/*check that pengrid is not a clone (penalty to be added only once)*/
-	if (node->IsClone()) return NULL;
-	ElementVector* pe=new ElementVector(&node,NUMVERTICES,this->parameters);
-
-	/*Retrieve all parameters*/
-	penta->GetInputValue(&pressure,node,PressureEnum);
-	penta->GetInputValue(&temperature,node,TemperatureEnum);
-	parameters->FindParam(&melting_offset,MeltingOffsetEnum);
-	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
-	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
-
-	/*Compute pressure melting point*/
-	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
-
-	/*Add penalty load
-	  This time, the penalty must have the same value as the one used for the thermal computation
-	  so that the corresponding melting can be computed correctly
-	  In the thermal computation, we used kmax=melting_offset, and the same penalty_factor*/
-	if (temperature<t_pmp){ //%no melting
-		pe->values[0]=0;
-	}
-	else{
-		if (reCast<bool>(dt)) pe->values[0]=melting_offset*pow(10.,penalty_factor)*(temperature-t_pmp)/dt;
-		else    pe->values[0]=melting_offset*pow(10.,penalty_factor)*(temperature-t_pmp);
-	}
-
-	/*Clean up and return*/
-	return pe;
-}
-/*}}}*/
-ElementVector* Pengrid::PenaltyCreatePVectorThermal(IssmDouble kmax){/*{{{*/
-
-	IssmDouble pressure;
-	IssmDouble t_pmp;
-	IssmDouble penalty_factor;
-
-	Penta* penta=(Penta*)element;
-
-	/*Initialize Element matrix and return if necessary*/
-	if(!this->active) return NULL;
-	ElementVector* pe=new ElementVector(&node,1,this->parameters);
-
-	/*Retrieve all parameters*/
-	penta->GetInputValue(&pressure,node,PressureEnum);
-	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
-
-	/*Compute pressure melting point*/
-	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
-
-	pe->values[0]=kmax*pow(10.,penalty_factor)*t_pmp;
-
-	/*Clean up and return*/
-	return pe;
-}
-/*}}}*/
-void  Pengrid::ConstraintActivateHydrologyDCInefficient(int* punstable){/*{{{*/
+void           Pengrid::ConstraintActivateHydrologyDCInefficient(int* punstable){/*{{{*/
 
 	//   The penalty is stable if it doesn't change during two consecutive iterations.   
@@ -638,4 +464,83 @@
 }
 /*}}}*/
+void           Pengrid::ConstraintActivateThermal(int* punstable){/*{{{*/
+
+	//   The penalty is stable if it doesn't change during to successive iterations.   
+	IssmDouble pressure;
+	IssmDouble temperature;
+	IssmDouble t_pmp;
+	int        new_active;
+	int        unstable=0;
+	int        penalty_lock;
+
+	/*recover pointers: */
+	Penta* penta=(Penta*)element;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()){
+		unstable=0;
+		*punstable=unstable;
+		return;
+	}
+
+	//First recover pressure and temperature values, using the element: */
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperaturePicardEnum);
+
+	//Recover our data:
+	parameters->FindParam(&penalty_lock,ThermalPenaltyLockEnum);
+
+	//Compute pressure melting point
+	t_pmp=matpar->TMeltingPoint(pressure);
+
+	//Figure out if temperature is over melting_point, in which case, this penalty needs to be activated.
+
+	if (temperature>t_pmp){
+		new_active=1;
+	}
+	else{
+		new_active=0;
+	}
+
+	//Figure out stability of this penalty
+	if (active==new_active){
+		unstable=0;
+	}
+	else{
+		unstable=1;
+		if(penalty_lock)zigzag_counter++;
+	}
+
+	/*If penalty keeps zigzagging more than 5 times: */
+	if(penalty_lock){
+		if(zigzag_counter>penalty_lock){
+			unstable=0;
+			active=1;
+		}
+	}
+
+	//Set penalty flag
+	active=new_active;
+
+	//*Assign output pointers:*/
+	*punstable=unstable;
+}
+/*}}}*/
+ElementVector* Pengrid::CreatePVectorHydrologyDCInefficient(void){/*{{{*/
+
+	IssmDouble moulin_load,dt;
+
+	/*Initialize Element matrix*/
+	ElementVector* pe=new ElementVector(&node,1,this->parameters);
+
+	this->element->GetInputValue(&moulin_load,node,HydrologydcBasalMoulinInputEnum);
+	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+
+	if(dt!=0.0) pe->values[0]=moulin_load*dt;
+
+	/*Clean up and return*/
+	return pe;
+ }
+/*}}}*/
 ElementMatrix* Pengrid::PenaltyCreateKMatrixHydrologyDCInefficient(IssmDouble kmax){/*{{{*/
 	IssmDouble    penalty_factor;
@@ -647,4 +552,49 @@
 	if(!this->active) return NULL;
 	ElementMatrix* Ke=new ElementMatrix(&node,NUMVERTICES,this->parameters);
+
+	Ke->values[0]=kmax*pow(10.,penalty_factor);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixMelting(IssmDouble kmax){/*{{{*/
+
+	IssmDouble pressure,temperature,t_pmp;
+	IssmDouble penalty_factor;
+
+	Penta* penta=(Penta*)element;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(&node,1,this->parameters);
+
+	/*Retrieve all parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperatureEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMaterialParameter(MaterialsMeltingpointEnum)-matpar->GetMaterialParameter(MaterialsBetaEnum)*pressure;
+
+	/*Add penalty load*/
+	if (temperature<t_pmp){ //If T<Tpmp, there must be no melting. Therefore, melting should be  constrained to 0 when T<Tpmp, instead of using spcs, use penalties
+		Ke->values[0]=kmax*pow(10.,penalty_factor);
+	}
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Pengrid::PenaltyCreateKMatrixThermal(IssmDouble kmax){/*{{{*/
+
+	IssmDouble    penalty_factor;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementMatrix* Ke=new ElementMatrix(&node,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
 
 	Ke->values[0]=kmax*pow(10.,penalty_factor);
@@ -678,21 +628,71 @@
 }
 /*}}}*/
-ElementVector* Pengrid::CreatePVectorHydrologyDCInefficient(void){/*{{{*/
-
-	IssmDouble moulin_load,dt;
-
-	/*Initialize Element matrix*/
-	ElementVector* pe=new ElementVector(&node,1,this->parameters);
-
-	this->element->GetInputValue(&moulin_load,node,HydrologydcBasalMoulinInputEnum);
+ElementVector* Pengrid::PenaltyCreatePVectorMelting(IssmDouble kmax){/*{{{*/
+
+	IssmDouble pressure;
+	IssmDouble temperature;
+	IssmDouble melting_offset;
+	IssmDouble t_pmp;
+	IssmDouble dt,penalty_factor;
+
+	/*recover pointers: */
+	Penta* penta=(Penta*)element;
+
+	/*check that pengrid is not a clone (penalty to be added only once)*/
+	if (node->IsClone()) return NULL;
+	ElementVector* pe=new ElementVector(&node,NUMVERTICES,this->parameters);
+
+	/*Retrieve all parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	penta->GetInputValue(&temperature,node,TemperatureEnum);
+	parameters->FindParam(&melting_offset,MeltingOffsetEnum);
 	parameters->FindParam(&dt,TimesteppingTimeStepEnum);
-
-	if(dt!=0.0) pe->values[0]=moulin_load*dt;
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMaterialParameter(MaterialsMeltingpointEnum)-matpar->GetMaterialParameter(MaterialsBetaEnum)*pressure;
+
+	/*Add penalty load
+	  This time, the penalty must have the same value as the one used for the thermal computation
+	  so that the corresponding melting can be computed correctly
+	  In the thermal computation, we used kmax=melting_offset, and the same penalty_factor*/
+	if (temperature<t_pmp){ //%no melting
+		pe->values[0]=0;
+	}
+	else{
+		if (reCast<bool>(dt)) pe->values[0]=melting_offset*pow(10.,penalty_factor)*(temperature-t_pmp)/dt;
+		else    pe->values[0]=melting_offset*pow(10.,penalty_factor)*(temperature-t_pmp);
+	}
 
 	/*Clean up and return*/
 	return pe;
- }
-/*}}}*/
-void  Pengrid::ResetConstraint(void){/*{{{*/
+}
+/*}}}*/
+ElementVector* Pengrid::PenaltyCreatePVectorThermal(IssmDouble kmax){/*{{{*/
+
+	IssmDouble pressure;
+	IssmDouble t_pmp;
+	IssmDouble penalty_factor;
+
+	Penta* penta=(Penta*)element;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(!this->active) return NULL;
+	ElementVector* pe=new ElementVector(&node,1,this->parameters);
+
+	/*Retrieve all parameters*/
+	penta->GetInputValue(&pressure,node,PressureEnum);
+	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
+
+	/*Compute pressure melting point*/
+	t_pmp=matpar->GetMaterialParameter(MaterialsMeltingpointEnum)-matpar->GetMaterialParameter(MaterialsBetaEnum)*pressure;
+
+	pe->values[0]=kmax*pow(10.,penalty_factor)*t_pmp;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+void           Pengrid::ResetConstraint(void){/*{{{*/
 	active         = 0;
 	zigzag_counter = 0;
Index: /issm/trunk/src/c/classes/Loads/Penpair.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Penpair.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Penpair.cpp	(revision 19105)
@@ -45,5 +45,36 @@
 
 /*Object virtual functions definitions:*/
-void Penpair::Echo(void){/*{{{*/
+Object* Penpair::copy() {/*{{{*/
+
+	Penpair* penpair=NULL;
+
+	penpair=new Penpair();
+
+	/*copy fields: */
+	penpair->id=this->id;
+	penpair->analysis_type=this->analysis_type;
+
+	/*now deal with hooks and objects: */
+	penpair->hnodes=(Hook*)this->hnodes->copy();
+	penpair->nodes =(Node**)penpair->hnodes->deliverp();
+
+	/*point parameters: */
+	penpair->parameters=this->parameters;
+
+	return penpair;
+
+}
+/*}}}*/
+void    Penpair::DeepEcho(void){/*{{{*/
+
+	_printf_("Penpair:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnodes->DeepEcho();
+
+	return;
+}		
+/*}}}*/
+void    Penpair::Echo(void){/*{{{*/
 
 	_printf_("Penpair:\n");
@@ -55,40 +86,9 @@
 }
 /*}}}*/
-void Penpair::DeepEcho(void){/*{{{*/
-
-	_printf_("Penpair:\n");
-	_printf_("   id: " << id << "\n");
-	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
-	hnodes->DeepEcho();
-
-	return;
-}		
-/*}}}*/
-int  Penpair::Id(void){ return id; }/*{{{*/
-/*}}}*/
-int  Penpair::ObjectEnum(void){/*{{{*/
+int     Penpair::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int     Penpair::ObjectEnum(void){/*{{{*/
 
 	return PenpairEnum;
-}
-/*}}}*/
-Object* Penpair::copy() {/*{{{*/
-
-	Penpair* penpair=NULL;
-
-	penpair=new Penpair();
-
-	/*copy fields: */
-	penpair->id=this->id;
-	penpair->analysis_type=this->analysis_type;
-
-	/*now deal with hooks and objects: */
-	penpair->hnodes=(Hook*)this->hnodes->copy();
-	penpair->nodes =(Node**)penpair->hnodes->deliverp();
-
-	/*point parameters: */
-	penpair->parameters=this->parameters;
-
-	return penpair;
-
 }
 /*}}}*/
@@ -109,16 +109,6 @@
 }
 /*}}}*/
-void  Penpair::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
-
-}
-/*}}}*/
-void  Penpair::ResetHooks(){/*{{{*/
-
-	this->nodes=NULL;
-	this->parameters=NULL;
-
-	/*Get Element type*/
-	this->hnodes->reset();
-
+void  Penpair::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){/*{{{*/
+	this->CreateKMatrix(Jff,NULL);
 }
 /*}}}*/
@@ -137,8 +127,4 @@
 }
 /*}}}*/
-void  Penpair::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){/*{{{*/
-	this->CreateKMatrix(Jff,NULL);
-}
-/*}}}*/
 void  Penpair::GetNodesSidList(int* sidlist){/*{{{*/
 
@@ -162,6 +148,15 @@
 }
 /*}}}*/
+bool  Penpair::InAnalysis(int in_analysis_type){/*{{{*/
+	if (in_analysis_type==this->analysis_type)return true;
+	else return false;
+}
+/*}}}*/
 bool  Penpair::IsPenalty(void){/*{{{*/
 	return true;
+}
+/*}}}*/
+void  Penpair::PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){/*{{{*/
+	this->PenaltyCreateKMatrix(Jff,NULL,kmax);
 }
 /*}}}*/
@@ -196,11 +191,16 @@
 }
 /*}}}*/
-void  Penpair::PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){/*{{{*/
-	this->PenaltyCreateKMatrix(Jff,NULL,kmax);
-}
-/*}}}*/
-bool  Penpair::InAnalysis(int in_analysis_type){/*{{{*/
-	if (in_analysis_type==this->analysis_type)return true;
-	else return false;
+void  Penpair::ResetHooks(){/*{{{*/
+
+	this->nodes=NULL;
+	this->parameters=NULL;
+
+	/*Get Element type*/
+	this->hnodes->reset();
+
+}
+/*}}}*/
+void  Penpair::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
 }
 /*}}}*/
@@ -279,4 +279,56 @@
 
 /*Penpair management:*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixMasstransport(IssmDouble kmax){/*{{{*/
+
+	const int numdof=NUMVERTICES*NDOF1;
+	IssmDouble penalty_factor;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_factor,MasstransportPenaltyFactorEnum);
+
+	//Create elementary matrix: add penalty to 
+	Ke->values[0*numdof+0]=+kmax*pow(10.,penalty_factor);
+	Ke->values[0*numdof+1]=-kmax*pow(10.,penalty_factor);
+	Ke->values[1*numdof+0]=-kmax*pow(10.,penalty_factor);
+	Ke->values[1*numdof+1]=+kmax*pow(10.,penalty_factor);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceFS(IssmDouble kmax){/*{{{*/
+
+	const int  numdof=NUMVERTICES*NDOF3;
+	IssmDouble penalty_offset;
+
+	/*Initialize Element vector and return if necessary*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
+
+	/*recover parameters: */
+	parameters->FindParam(&penalty_offset,StressbalancePenaltyFactorEnum);
+
+	//Create elementary matrix: add penalty to 
+	Ke->values[0*numdof+0]=+kmax*pow(10.,penalty_offset);
+	Ke->values[0*numdof+3]=-kmax*pow(10.,penalty_offset);
+	Ke->values[3*numdof+0]=-kmax*pow(10.,penalty_offset);
+	Ke->values[3*numdof+3]=+kmax*pow(10.,penalty_offset);
+
+	Ke->values[1*numdof+1]=+kmax*pow(10.,penalty_offset);
+	Ke->values[1*numdof+4]=-kmax*pow(10.,penalty_offset);
+	Ke->values[4*numdof+1]=-kmax*pow(10.,penalty_offset);
+	Ke->values[4*numdof+4]=+kmax*pow(10.,penalty_offset);
+
+	Ke->values[2*numdof+2]=+kmax*pow(10.,penalty_offset);
+	Ke->values[2*numdof+5]=-kmax*pow(10.,penalty_offset);
+	Ke->values[5*numdof+2]=-kmax*pow(10.,penalty_offset);
+	Ke->values[5*numdof+5]=+kmax*pow(10.,penalty_offset);
+
+	/*Clean up and return*/
+	return Ke;
+}
+/*}}}*/
 ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax){/*{{{*/
 
@@ -338,54 +390,2 @@
 }
 /*}}}*/
-ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceFS(IssmDouble kmax){/*{{{*/
-
-	const int  numdof=NUMVERTICES*NDOF3;
-	IssmDouble penalty_offset;
-
-	/*Initialize Element vector and return if necessary*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
-
-	/*recover parameters: */
-	parameters->FindParam(&penalty_offset,StressbalancePenaltyFactorEnum);
-
-	//Create elementary matrix: add penalty to 
-	Ke->values[0*numdof+0]=+kmax*pow(10.,penalty_offset);
-	Ke->values[0*numdof+3]=-kmax*pow(10.,penalty_offset);
-	Ke->values[3*numdof+0]=-kmax*pow(10.,penalty_offset);
-	Ke->values[3*numdof+3]=+kmax*pow(10.,penalty_offset);
-
-	Ke->values[1*numdof+1]=+kmax*pow(10.,penalty_offset);
-	Ke->values[1*numdof+4]=-kmax*pow(10.,penalty_offset);
-	Ke->values[4*numdof+1]=-kmax*pow(10.,penalty_offset);
-	Ke->values[4*numdof+4]=+kmax*pow(10.,penalty_offset);
-
-	Ke->values[2*numdof+2]=+kmax*pow(10.,penalty_offset);
-	Ke->values[2*numdof+5]=-kmax*pow(10.,penalty_offset);
-	Ke->values[5*numdof+2]=-kmax*pow(10.,penalty_offset);
-	Ke->values[5*numdof+5]=+kmax*pow(10.,penalty_offset);
-
-	/*Clean up and return*/
-	return Ke;
-}
-/*}}}*/
-ElementMatrix* Penpair::PenaltyCreateKMatrixMasstransport(IssmDouble kmax){/*{{{*/
-
-	const int numdof=NUMVERTICES*NDOF1;
-	IssmDouble penalty_factor;
-
-	/*Initialize Element vector and return if necessary*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters);
-
-	/*recover parameters: */
-	parameters->FindParam(&penalty_factor,MasstransportPenaltyFactorEnum);
-
-	//Create elementary matrix: add penalty to 
-	Ke->values[0*numdof+0]=+kmax*pow(10.,penalty_factor);
-	Ke->values[0*numdof+1]=-kmax*pow(10.,penalty_factor);
-	Ke->values[1*numdof+0]=-kmax*pow(10.,penalty_factor);
-	Ke->values[1*numdof+1]=+kmax*pow(10.,penalty_factor);
-
-	/*Clean up and return*/
-	return Ke;
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Loads/Penpair.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Penpair.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Penpair.h	(revision 19105)
@@ -31,41 +31,41 @@
 		/*}}}*/
 		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   ObjectEnum();
 		Object* copy();
+		void     DeepEcho();
+		void     Echo();
+		int      Id(); 
+		int      ObjectEnum();
 		/*}}}*/
 		/*Update virtual functions resolution: {{{*/
-		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrow, int ncols,int name, int type){_error_("Not implemented yet!");}
-		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("Not implemented yet!");}
 		void  InputUpdateFromConstant(IssmDouble constant, int name);
 		void  InputUpdateFromConstant(int constant, int name);
 		void  InputUpdateFromConstant(bool constant, int name);
 		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrow, int ncols,int name, int type){_error_("Not implemented yet!");}
+		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("Not implemented yet!");}
 		/*}}}*/
 			/*Load virtual functions definitions: {{{*/
 		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
+		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void  CreatePVector(Vector<IssmDouble>* pf);
+		void  GetNodesLidList(int* lidlist);
+		void  GetNodesSidList(int* sidlist);
+		int   GetNumberOfNodes(void);
+		bool  InAnalysis(int analysis_type);
+		bool  IsPenalty(void);
+		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax);
+		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff,Matrix<IssmDouble>* Kfs,IssmDouble kmax);
+		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
 		void  ResetHooks();
 		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
-		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
-		void  CreatePVector(Vector<IssmDouble>* pf);
-		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
-		void  GetNodesSidList(int* sidlist);
-		void  GetNodesLidList(int* lidlist);
-		int   GetNumberOfNodes(void);
-		bool  IsPenalty(void);
-		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff,Matrix<IssmDouble>* Kfs,IssmDouble kmax);
-		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
-		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax);
 		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum);
-		bool  InAnalysis(int analysis_type);
 		/*}}}*/
 			/*Penpair management: {{{*/
+		ElementMatrix* PenaltyCreateKMatrixMasstransport(IssmDouble kmax);
+		ElementMatrix* PenaltyCreateKMatrixStressbalanceFS(IssmDouble kmax);
 		ElementMatrix* PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax);
 		ElementMatrix* PenaltyCreateKMatrixStressbalanceSSAHO(IssmDouble kmax);
-		ElementMatrix* PenaltyCreateKMatrixStressbalanceFS(IssmDouble kmax);
-		ElementMatrix* PenaltyCreateKMatrixMasstransport(IssmDouble kmax);
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Loads/Riftfront.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Riftfront.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Riftfront.cpp	(revision 19105)
@@ -108,5 +108,62 @@
 
 /*Object virtual functions definitions:*/
-void Riftfront::Echo(void){/*{{{*/
+Object* Riftfront::copy() {/*{{{*/
+
+	Riftfront* riftfront=NULL;
+
+	riftfront=new Riftfront();
+
+	/*copy fields: */
+	riftfront->id=this->id;
+	riftfront->analysis_type=this->analysis_type;
+	riftfront->type=this->type;
+	riftfront->fill=this->fill;
+	riftfront->friction=this->friction;
+	riftfront->fractionincrement=this->fractionincrement;
+	riftfront->shelf=this->shelf;
+
+	/*point parameters: */
+	riftfront->parameters=this->parameters;
+
+	/*now deal with hooks and objects: */
+	riftfront->hnodes=(Hook*)this->hnodes->copy();
+	riftfront->helements=(Hook*)this->helements->copy();
+	riftfront->hmatpar=(Hook*)this->hmatpar->copy();
+
+	/*corresponding fields*/
+	riftfront->nodes   =(Node**)riftfront->hnodes->deliverp();
+	riftfront->elements=(Element**)riftfront->helements->deliverp();
+	riftfront->matpar  =(Matpar*)riftfront->hmatpar->delivers();
+
+	/*internal data: */
+	riftfront->penalty_lock=this->penalty_lock;
+	riftfront->active=this->active;
+	riftfront->frozen=this->frozen;
+	riftfront->state=this->state;
+	riftfront->counter=this->counter;
+	riftfront->prestable=this->prestable;
+	riftfront->material_converged=this->material_converged;
+	riftfront->normal[0]=this->normal[0];
+	riftfront->normal[1]=this->normal[1];
+	riftfront->length=this->length;
+	riftfront->fraction=this->fraction;
+
+	return riftfront;
+
+}
+/*}}}*/
+void    Riftfront::DeepEcho(void){/*{{{*/
+
+	_printf_("Riftfront:\n");
+	_printf_("   id: " << id << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	hnodes->DeepEcho();
+	helements->DeepEcho();
+	hmatpar->DeepEcho();
+	_printf_("   parameters\n");
+	if(parameters)parameters->DeepEcho();
+}
+/*}}}*/
+void    Riftfront::Echo(void){/*{{{*/
 
 	_printf_("Riftfront:\n");
@@ -134,66 +191,9 @@
 }
 /*}}}*/
-void Riftfront::DeepEcho(void){/*{{{*/
-
-	_printf_("Riftfront:\n");
-	_printf_("   id: " << id << "\n");
-	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
-	hnodes->DeepEcho();
-	helements->DeepEcho();
-	hmatpar->DeepEcho();
-	_printf_("   parameters\n");
-	if(parameters)parameters->DeepEcho();
-}
-/*}}}*/
-int    Riftfront::Id(void){ return id; }/*{{{*/
-/*}}}*/
-int Riftfront::ObjectEnum(void){/*{{{*/
+int     Riftfront::Id(void){ return id; }/*{{{*/
+/*}}}*/
+int     Riftfront::ObjectEnum(void){/*{{{*/
 
 	return RiftfrontEnum;
-
-}
-/*}}}*/
-Object* Riftfront::copy() {/*{{{*/
-
-	Riftfront* riftfront=NULL;
-
-	riftfront=new Riftfront();
-
-	/*copy fields: */
-	riftfront->id=this->id;
-	riftfront->analysis_type=this->analysis_type;
-	riftfront->type=this->type;
-	riftfront->fill=this->fill;
-	riftfront->friction=this->friction;
-	riftfront->fractionincrement=this->fractionincrement;
-	riftfront->shelf=this->shelf;
-
-	/*point parameters: */
-	riftfront->parameters=this->parameters;
-
-	/*now deal with hooks and objects: */
-	riftfront->hnodes=(Hook*)this->hnodes->copy();
-	riftfront->helements=(Hook*)this->helements->copy();
-	riftfront->hmatpar=(Hook*)this->hmatpar->copy();
-
-	/*corresponding fields*/
-	riftfront->nodes   =(Node**)riftfront->hnodes->deliverp();
-	riftfront->elements=(Element**)riftfront->helements->deliverp();
-	riftfront->matpar  =(Matpar*)riftfront->hmatpar->delivers();
-
-	/*internal data: */
-	riftfront->penalty_lock=this->penalty_lock;
-	riftfront->active=this->active;
-	riftfront->frozen=this->frozen;
-	riftfront->state=this->state;
-	riftfront->counter=this->counter;
-	riftfront->prestable=this->prestable;
-	riftfront->material_converged=this->material_converged;
-	riftfront->normal[0]=this->normal[0];
-	riftfront->normal[1]=this->normal[1];
-	riftfront->length=this->length;
-	riftfront->fraction=this->fraction;
-
-	return riftfront;
 
 }
@@ -234,24 +234,42 @@
 }
 /*}}}*/
-void  Riftfront::ResetHooks(){/*{{{*/
-
-	this->nodes=NULL;
-	this->elements=NULL;
-	this->matpar=NULL;
-	this->parameters=NULL;
-
-	/*Get Element type*/
-	this->hnodes->reset();
-	this->helements->reset();
-	this->hmatpar->reset();
-
+void  Riftfront::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+void  Riftfront::CreatePVector(Vector<IssmDouble>* pf){/*{{{*/
+	/*do nothing: */
+	return;
+}
+/*}}}*/
+void  Riftfront::GetNodesLidList(int* lidlist){/*{{{*/
+
+	_assert_(lidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) lidlist[i]=nodes[i]->Lid();
+}
+/*}}}*/
+void  Riftfront::GetNodesSidList(int* sidlist){/*{{{*/
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->Sid();
+}
+/*}}}*/
+int   Riftfront::GetNumberOfNodes(void){/*{{{*/
+
+	return NUMVERTICES;
+}
+/*}}}*/
+bool  Riftfront::InAnalysis(int in_analysis_type){/*{{{*/
+	if (in_analysis_type==this->analysis_type) return true;
+	else return false;
 }
 /*}}}*/
 bool  Riftfront::IsPenalty(void){/*{{{*/
 	return true;
-}
-/*}}}*/
-void  Riftfront::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
-
 }
 /*}}}*/
@@ -306,38 +324,20 @@
 }
 /*}}}*/
-void  Riftfront::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){/*{{{*/
-	/*do nothing: */
-	return;
-}
-/*}}}*/
-void  Riftfront::CreatePVector(Vector<IssmDouble>* pf){/*{{{*/
-	/*do nothing: */
-	return;
-}
-/*}}}*/
-void  Riftfront::GetNodesSidList(int* sidlist){/*{{{*/
-
-	_assert_(sidlist);
-	_assert_(nodes);
-
-	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->Sid();
-}
-/*}}}*/
-void  Riftfront::GetNodesLidList(int* lidlist){/*{{{*/
-
-	_assert_(lidlist);
-	_assert_(nodes);
-
-	for(int i=0;i<NUMVERTICES;i++) lidlist[i]=nodes[i]->Lid();
-}
-/*}}}*/
-int   Riftfront::GetNumberOfNodes(void){/*{{{*/
-
-	return NUMVERTICES;
-}
-/*}}}*/
-bool  Riftfront::InAnalysis(int in_analysis_type){/*{{{*/
-	if (in_analysis_type==this->analysis_type) return true;
-	else return false;
+void  Riftfront::ResetHooks(){/*{{{*/
+
+	this->nodes=NULL;
+	this->elements=NULL;
+	this->matpar=NULL;
+	this->parameters=NULL;
+
+	/*Get Element type*/
+	this->hnodes->reset();
+	this->helements->reset();
+	this->hmatpar->reset();
+
+}
+/*}}}*/
+void  Riftfront::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){/*{{{*/
+
 }
 /*}}}*/
@@ -505,7 +505,7 @@
 
 	/*Get some inputs: */
-	rho_ice=matpar->GetRhoIce();
-	rho_water=matpar->GetRhoWater();
-	gravity=matpar->GetG();
+	rho_ice=matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+	rho_water=matpar->GetMaterialParameter(MaterialsRhoSeawaterEnum);
+	gravity=matpar->GetMaterialParameter(ConstantsGEnum);
 	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
 	tria2->GetInputValue(&h[1],nodes[1],ThicknessEnum);
Index: /issm/trunk/src/c/classes/Loads/Riftfront.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Riftfront.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Loads/Riftfront.h	(revision 19105)
@@ -57,42 +57,42 @@
 		/*}}}*/
 		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   ObjectEnum();
-		Object* copy();
+		Object*  copy();
+		void     DeepEcho();
+		void     Echo();
+		int      Id(); 
+		int      ObjectEnum();
 		/*}}}*/
 		/*Update virtual functions resolution: {{{*/
-		void    InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void    InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows,int ncols, int name, int type){_error_("Not implemented yet!");}
-		void    InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("Not implemented yet!");}
 		void    InputUpdateFromConstant(IssmDouble constant, int name);
 		void    InputUpdateFromConstant(int constant, int name){_error_("Not implemented yet!");}
 		void    InputUpdateFromConstant(bool constant, int name);
 		void    InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
+		void    InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows,int ncols, int name, int type){_error_("Not implemented yet!");}
+		void    InputUpdateFromVector(IssmDouble* vector, int name, int type);
+		void    InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){_error_("Not implemented yet!");}
 		/*}}}*/
 		/*Load virtual functions definitions: {{{*/
 		void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
-		void  ResetHooks();
-		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
+		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
 		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
 		void  CreatePVector(Vector<IssmDouble>* pf);
-		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
+		void  GetNodesLidList(int* lidlist);
 		void  GetNodesSidList(int* sidlist);
-		void  GetNodesLidList(int* lidlist);
 		int   GetNumberOfNodes(void);
+		bool  InAnalysis(int analysis_type);
 		bool  IsPenalty(void);
 		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
 		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
 		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		void  ResetHooks();
+		void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
 		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum);
-		bool  InAnalysis(int analysis_type);
 		/*}}}*/
 		/*Riftfront specific routines: {{{*/
+		int            Constrain(int* punstable);
+		void           FreezeConstraints(void);
+		bool           IsFrozen(void);
 		ElementMatrix* PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax);
 		ElementVector* PenaltyCreatePVectorStressbalanceHoriz(IssmDouble kmax);
-		int   Constrain(int* punstable);
-		void  FreezeConstraints(void);
-		bool  IsFrozen(void);
 		/*}}}*/
 };
Index: /issm/trunk/src/c/classes/Masscon.h
===================================================================
--- /issm/trunk/src/c/classes/Masscon.h	(revision 19105)
+++ /issm/trunk/src/c/classes/Masscon.h	(revision 19105)
@@ -0,0 +1,113 @@
+/*!\file Masscon.h
+ * \brief: header file for Masscon object
+ */
+
+#ifndef _MASSCON_H_
+#define _MASSCON_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Definition.h"
+#include "../datastructures/datastructures.h"
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+#include "../classes/Params/Parameters.h"
+/*}}}*/
+
+class Masscon: public Object, public Definition{
+
+	public: 
+
+		int         definitionenum;
+		char*       name;
+		IssmDouble* levelset;
+		int         M;
+		
+		/*Masscon constructors, destructors :*/
+		Masscon(){/*{{{*/
+
+			this->definitionenum = -1;
+			this->name = NULL;
+			this->levelset=NULL;
+			this->M=0;
+
+		}
+		/*}}}*/
+		Masscon(char* in_name, int in_definitionenum, IssmDouble* levelsetin, int Min){ /*{{{*/
+
+			this->definitionenum=in_definitionenum;
+			this->name   = xNew<char>(strlen(in_name)+1);
+			xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+			this->levelset   = xNew<IssmDouble>(Min);
+			xMemCpy<IssmDouble>(this->levelset, levelsetin, Min);
+
+			this->M=Min;
+
+		}
+		/*}}}*/
+		~Masscon(){/*{{{*/
+			if(this->name)xDelete(this->name); 
+			if(this->levelset)xDelete(this->levelset);
+		}
+		/*}}}*/
+		/*Object virtual function resolutoin: */
+		void Echo(void){/*{{{*/
+			_printf_(" Masscon: " << this->name << " " << this->definitionenum << "\n");
+			_printf_("    levelset: " << this->levelset << "\n");
+			_printf_("    M: " << this->M << "\n");
+		}
+		/*}}}*/
+		void DeepEcho(void){/*{{{*/
+			this->Echo();
+		}
+		/*}}}*/
+		int Id(void){/*{{{*/
+			return -1;
+		}
+		/*}}}*/
+		int ObjectEnum(void){/*{{{*/
+			return MassconEnum;
+		}
+		/*}}}*/
+		Object* copy() {/*{{{*/
+			Masscon* mf = new Masscon(this->name,this->definitionenum,this->levelset,this->M);
+			return (Object*) mf;
+		}
+		/*}}}*/
+		/*Definition virtual function resolutoin: */
+		char* Name(){/*{{{*/
+
+			char* name2=xNew<char>(strlen(this->name)+1);
+			xMemCpy(name2,this->name,strlen(this->name)+1);
+
+			return name2;
+		}
+		/*}}}*/
+		int DefinitionEnum(){/*{{{*/
+
+			return this->definitionenum;
+		}
+		/*}}}*/
+		 IssmDouble Response(FemModel* femmodel){/*{{{*/
+
+			 int i;
+			 IssmDouble mass_t=0.;
+			 IssmDouble all_mass_t=0.;
+
+
+			 for(i=0;i<femmodel->elements->Size();i++){
+				 Element* element=(Element*)femmodel->elements->GetObjectByOffset(i);
+				 mass_t+=element->Masscon(this->levelset);
+			 }
+
+			 ISSM_MPI_Allreduce ( (void*)&mass_t,(void*)&all_mass_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+			 mass_t=all_mass_t;
+			 
+			 return mass_t;
+		 }
+			/*}}}*/
+};
+
+#endif  /* _MASSCON_H_ */
Index: /issm/trunk/src/c/classes/Massconaxpby.h
===================================================================
--- /issm/trunk/src/c/classes/Massconaxpby.h	(revision 19105)
+++ /issm/trunk/src/c/classes/Massconaxpby.h	(revision 19105)
@@ -0,0 +1,117 @@
+/*!\file Massconaxpby.h
+ * \brief: header file for Massconaxpby object
+ */
+
+#ifndef _MASSCON_AXPBY_H_
+#define _MASSCON_AXPBY_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Definition.h"
+#include "../datastructures/datastructures.h"
+#include "./Elements/Element.h"
+#include "./Elements/Elements.h"
+#include "./FemModel.h"
+#include "../classes/Params/Parameters.h"
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,const char* output_string);
+/*}}}*/
+class Massconaxpby: public Object, public Definition{
+
+	public: 
+
+		int         definitionenum;
+		char*       name;
+		char*       namex;
+		char*       namey;
+		IssmDouble  alpha;
+		IssmDouble  beta;
+		
+		/*Massconaxpby constructors, destructors :*/
+		Massconaxpby(){/*{{{*/
+
+			this->definitionenum = -1;
+			this->name = NULL;
+			this->namex = NULL;
+			this->namey = NULL;
+			this->alpha=UNDEF;
+			this->beta=UNDEF;
+
+		}
+		/*}}}*/
+		Massconaxpby(char* in_name,int in_definitionenum, char* in_namex, char* in_namey, IssmDouble in_alpha,IssmDouble in_beta){ /*{{{*/
+
+			this->definitionenum = in_definitionenum;
+			this->name   = xNew<char>(strlen(in_name)+1);
+			xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
+
+			this->namex   = xNew<char>(strlen(in_namex)+1);
+			xMemCpy<char>(this->namex,in_namex,strlen(in_namex)+1);
+			
+			this->namey   = xNew<char>(strlen(in_namey)+1);
+			xMemCpy<char>(this->namey,in_namey,strlen(in_namey)+1);
+
+			this->alpha=in_alpha;
+			this->beta=in_beta;
+
+		}
+		/*}}}*/
+		~Massconaxpby(){/*{{{*/
+			if(this->name)xDelete(this->name); 
+			if(this->namex)xDelete(this->namex); 
+			if(this->namey)xDelete(this->namey); 
+		}
+		/*}}}*/
+		/*Object virtual function resolutoin: */
+		void Echo(void){/*{{{*/
+			_printf_(" Massconaxpby: " << this->name << " " << this->definitionenum << "\n");
+			_printf_("    namex: " << this->namex << "\n");
+			_printf_("    namey: " << this->namey << "\n");
+			_printf_("    alpha: " << this->alpha << "\n");
+			_printf_("    beta: " << this->beta << "\n");
+		}
+		/*}}}*/
+		void DeepEcho(void){/*{{{*/
+			this->Echo();
+		}
+		/*}}}*/
+		int Id(void){/*{{{*/
+			return -1;
+		}
+		/*}}}*/
+		int ObjectEnum(void){/*{{{*/
+			return MassconaxpbyEnum;
+		}
+		/*}}}*/
+		Object* copy() {/*{{{*/
+			Massconaxpby* mf = new Massconaxpby(this->name,this->definitionenum,this->namex,this->namey, this->alpha, this->beta);
+			return (Object*) mf;
+		}
+		/*}}}*/
+		/*Definition virtual function resolutoin: */
+		char* Name(){/*{{{*/
+
+			char* name2=xNew<char>(strlen(this->name)+1);
+			xMemCpy(name2,this->name,strlen(this->name)+1);
+
+			return name2;
+		}
+		/*}}}*/
+		int DefinitionEnum(){/*{{{*/
+
+			return this->definitionenum;
+		}
+		/*}}}*/
+		 IssmDouble Response(FemModel* femmodel){/*{{{*/
+
+			 IssmDouble xresponse,yresponse;
+
+			 /*Get response from both masscons: */
+			 xresponse=OutputDefinitionsResponsex(femmodel,this->namex);
+			 yresponse=OutputDefinitionsResponsex(femmodel,this->namey);
+
+			 return this->alpha*xresponse+this->beta*yresponse;
+		 }
+			/*}}}*/
+};
+
+#endif  /* _MASSCON_H_ */
Index: /issm/trunk/src/c/classes/Massfluxatgate.h
===================================================================
--- /issm/trunk/src/c/classes/Massfluxatgate.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Massfluxatgate.h	(revision 19105)
@@ -20,4 +20,5 @@
 	public: 
 
+		int         definitionenum;
 		char*       name;
 		int         numsegments;
@@ -30,4 +31,5 @@
 		/*Massfluxatgate constructors, destructors :*/
 		Massfluxatgate(){/*{{{*/
+			this->definitionenum        = -1;
 			this->name        = 0;
 			this->numsegments = 0;
@@ -35,7 +37,9 @@
 		}
 		/*}}}*/
-		Massfluxatgate(char* in_name, int in_numsegments, doubletype* in_segments) {/*{{{*/
+		Massfluxatgate(char* in_name, int in_definitionenum, int in_numsegments, doubletype* in_segments) {/*{{{*/
 			
 			int i;
+
+			this->definitionenum=in_definitionenum;
 
 			this->name   = xNew<char>(strlen(in_name)+1);
@@ -61,6 +65,7 @@
 		}
 		/*}}}*/
-		Massfluxatgate(char* in_name, int in_numsegments, doubletype* in_x1, doubletype* in_y1, doubletype* in_x2, doubletype* in_y2,int* in_elements){/*{{{*/
+		Massfluxatgate(char* in_name, int in_definitionenum, int in_numsegments, doubletype* in_x1, doubletype* in_y1, doubletype* in_x2, doubletype* in_y2,int* in_elements){/*{{{*/
 
+			this->definitionenum=in_definitionenum;
 			this->name   = xNew<char>(strlen(in_name)+1);
 			xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
@@ -90,5 +95,5 @@
 		/*Object virtual function resolutoin: */
 		void Echo(void){/*{{{*/
-			_printf_(" Massfluxatgate: " << name << "\n");
+			_printf_(" Massfluxatgate: " << name << " " << this->definitionenum << "\n");
 			_printf_("    numsegments: " << numsegments << "\n");
 			if(numsegments){
@@ -113,5 +118,5 @@
 		/*}}}*/
 		Object* copy() {/*{{{*/
-			return new Massfluxatgate(this->name,this->numsegments,this->x1,this->y1,this->x2,this->y2,this->elements); 
+			return new Massfluxatgate(this->name,this->definitionenum,this->numsegments,this->x1,this->y1,this->x2,this->y2,this->elements); 
 		}
 		/*}}}*/
@@ -123,4 +128,9 @@
 
 			return name2;
+		}
+		/*}}}*/
+		int DefinitionEnum(){/*{{{*/
+
+			return this->definitionenum;
 		}
 		/*}}}*/
Index: /issm/trunk/src/c/classes/Materials/Material.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Material.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Materials/Material.h	(revision 19105)
@@ -25,19 +25,19 @@
 		virtual Material*  copy2(Element* element)=0;
 		virtual void       Configure(Elements* elements)=0;
+		virtual IssmDouble GetA()=0;
+		virtual IssmDouble GetAbar()=0;
+		virtual IssmDouble GetB()=0;
+		virtual IssmDouble GetBbar()=0;
+		virtual IssmDouble GetD()=0;
+		virtual IssmDouble GetDbar()=0;
+		virtual IssmDouble GetN()=0;
 		virtual void       GetViscosity(IssmDouble* pviscosity,IssmDouble epseff)=0;
-		virtual void       GetViscosity_B(IssmDouble* pviscosity,IssmDouble epseff)=0;
-		virtual void       GetViscosity_D(IssmDouble* pviscosity,IssmDouble epseff)=0;
 		virtual void       GetViscosityBar(IssmDouble* pviscosity,IssmDouble epseff)=0;
 		virtual void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
 		virtual void       GetViscosityDComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
 		virtual void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosity_B(IssmDouble* pviscosity,IssmDouble epseff)=0;
+		virtual void       GetViscosity_D(IssmDouble* pviscosity,IssmDouble epseff)=0;
 		virtual void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
-		virtual IssmDouble GetA()=0;
-		virtual IssmDouble GetAbar()=0;
-		virtual IssmDouble GetB()=0;
-		virtual IssmDouble GetBbar()=0;
-		virtual IssmDouble GetN()=0;
-		virtual IssmDouble GetD()=0;
-		virtual IssmDouble GetDbar()=0;
 		virtual bool       IsDamage()=0;
 		virtual void       ResetHooks()=0;
Index: /issm/trunk/src/c/classes/Materials/Materials.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Materials.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Materials/Materials.cpp	(revision 19105)
@@ -37,5 +37,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		material=dynamic_cast<Material*>(*object);
+		material=xDynamicCast<Material*>(*object);
 		material->Configure(elements);
 
@@ -51,5 +51,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		material=dynamic_cast<Material*>((*object));
+		material=xDynamicCast<Material*>((*object));
 		material->ResetHooks();
 
Index: /issm/trunk/src/c/classes/Materials/Matice.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 19105)
@@ -64,13 +64,39 @@
 
 /*Object virtual functions definitions:*/
-void Matice::Echo(void){/*{{{*/
-
-	_printf_("Matice:\n");
-	_printf_("   mid: " << mid << "\n");
-	_printf_("   element:\n");
-	helement->Echo();
-}
-/*}}}*/
-void Matice::DeepEcho(void){/*{{{*/
+Object*   Matice::copy() {/*{{{*/
+
+	/*Output*/
+	Matice* matice=NULL;
+
+	/*Initialize output*/
+	matice=new Matice();
+
+	/*copy fields: */
+	matice->mid=this->mid;
+	matice->helement=(Hook*)this->helement->copy();
+	matice->element =(Element*)this->helement->delivers();
+	matice->isdamaged = this->isdamaged;
+
+	return matice;
+}
+/*}}}*/
+Material* Matice::copy2(Element* element_in) {/*{{{*/
+
+	/*Output*/
+	Matice* matice=NULL;
+
+	/*Initialize output*/
+	matice=new Matice();
+
+	/*copy fields: */
+	matice->mid=this->mid;
+	matice->helement=(Hook*)this->helement->copy();
+	matice->element =element_in;
+	matice->isdamaged = this->isdamaged;
+
+	return matice;
+}
+/*}}}*/
+void      Matice::DeepEcho(void){/*{{{*/
 
 	_printf_("Matice:\n");
@@ -80,44 +106,18 @@
 }		
 /*}}}*/
-int    Matice::Id(void){ return mid; }/*{{{*/
-/*}}}*/
-int Matice::ObjectEnum(void){/*{{{*/
+void      Matice::Echo(void){/*{{{*/
+
+	_printf_("Matice:\n");
+	_printf_("   mid: " << mid << "\n");
+	_printf_("   element:\n");
+	helement->Echo();
+}
+/*}}}*/
+int       Matice::Id(void){ return mid; }/*{{{*/
+/*}}}*/
+int       Matice::ObjectEnum(void){/*{{{*/
 
 	return MaticeEnum;
 
-}
-/*}}}*/
-Object* Matice::copy() {/*{{{*/
-
-	/*Output*/
-	Matice* matice=NULL;
-
-	/*Initialize output*/
-	matice=new Matice();
-
-	/*copy fields: */
-	matice->mid=this->mid;
-	matice->helement=(Hook*)this->helement->copy();
-	matice->element =(Element*)this->helement->delivers();
-	matice->isdamaged = this->isdamaged;
-
-	return matice;
-}
-/*}}}*/
-Material* Matice::copy2(Element* element_in) {/*{{{*/
-
-	/*Output*/
-	Matice* matice=NULL;
-
-	/*Initialize output*/
-	matice=new Matice();
-
-	/*copy fields: */
-	matice->mid=this->mid;
-	matice->helement=(Hook*)this->helement->copy();
-	matice->element =element_in;
-	matice->isdamaged = this->isdamaged;
-
-	return matice;
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/Materials/Matpar.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 19105)
@@ -20,74 +20,87 @@
 
 	bool isefficientlayer;
-	int  hydrology_model,smb_model;
+	int  hydrology_model,smb_model,materials_type;
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
 	iomodel->Constant(&smb_model,SurfaceforcingsEnum);
+	iomodel->Constant(&materials_type,MaterialsEnum);
 
 	this->mid = matpar_mid;
-	iomodel->Constant(&this->rho_ice,MaterialsRhoIceEnum);
-	iomodel->Constant(&this->rho_water,MaterialsRhoSeawaterEnum);
-	iomodel->Constant(&this->rho_freshwater,MaterialsRhoFreshwaterEnum);
-	iomodel->Constant(&this->mu_water,MaterialsMuWaterEnum);
-	iomodel->Constant(&this->heatcapacity,MaterialsHeatcapacityEnum);
-	iomodel->Constant(&this->thermalconductivity,MaterialsThermalconductivityEnum);
-	iomodel->Constant(&this->temperateiceconductivity,MaterialsTemperateiceconductivityEnum);
-	iomodel->Constant(&this->latentheat,MaterialsLatentheatEnum);
-	iomodel->Constant(&this->beta,MaterialsBetaEnum);
-	iomodel->Constant(&this->meltingpoint,MaterialsMeltingpointEnum);
-	iomodel->Constant(&this->referencetemperature,ConstantsReferencetemperatureEnum);
-	iomodel->Constant(&this->mixed_layer_capacity,MaterialsMixedLayerCapacityEnum);
-	iomodel->Constant(&this->thermal_exchange_velocity,MaterialsThermalExchangeVelocityEnum);
-	iomodel->Constant(&this->g,ConstantsGEnum);
-
-	switch(smb_model){
-		case SMBEnum:
-			/*Nothing to add*/
-			break;
-		case SMBpddEnum:
-			iomodel->Constant(&this->desfac,SurfaceforcingsDesfacEnum);
-			iomodel->Constant(&this->s0p,SurfaceforcingsS0pEnum);
-			break;
-		case SMBgradientsEnum:
-			/*Nothing to add*/
-			break;
-		case SMBhenningEnum:
-			/*Nothing to add*/
-			break;
-		case SMBcomponentsEnum:
-			/*Nothing to add*/
-			break;
-		case SMBmeltcomponentsEnum:
-			/*Nothing to add*/
+
+	switch(materials_type){
+		case MaticeEnum:
+		case MatdamageiceEnum:
+			iomodel->Constant(&this->rho_ice,MaterialsRhoIceEnum);
+			iomodel->Constant(&this->rho_water,MaterialsRhoSeawaterEnum);
+			iomodel->Constant(&this->rho_freshwater,MaterialsRhoFreshwaterEnum);
+			iomodel->Constant(&this->mu_water,MaterialsMuWaterEnum);
+			iomodel->Constant(&this->heatcapacity,MaterialsHeatcapacityEnum);
+			iomodel->Constant(&this->thermalconductivity,MaterialsThermalconductivityEnum);
+			iomodel->Constant(&this->temperateiceconductivity,MaterialsTemperateiceconductivityEnum);
+			iomodel->Constant(&this->latentheat,MaterialsLatentheatEnum);
+			iomodel->Constant(&this->beta,MaterialsBetaEnum);
+			iomodel->Constant(&this->meltingpoint,MaterialsMeltingpointEnum);
+			iomodel->Constant(&this->referencetemperature,ConstantsReferencetemperatureEnum);
+			iomodel->Constant(&this->mixed_layer_capacity,MaterialsMixedLayerCapacityEnum);
+			iomodel->Constant(&this->thermal_exchange_velocity,MaterialsThermalExchangeVelocityEnum);
+			iomodel->Constant(&this->g,ConstantsGEnum);
+
+			switch(smb_model){
+				case SMBEnum:
+					/*Nothing to add*/
+					break;
+				case SMBpddEnum:
+					iomodel->Constant(&this->desfac,SurfaceforcingsDesfacEnum);
+					iomodel->Constant(&this->s0p,SurfaceforcingsS0pEnum);
+					iomodel->Constant(&this->s0t,SurfaceforcingsS0tEnum);
+					iomodel->Constant(&this->rlaps,SurfaceforcingsRlapsEnum);
+					iomodel->Constant(&this->rlapslgm,SurfaceforcingsRlapslgmEnum);
+					break;
+				case SMBgradientsEnum:
+					/*Nothing to add*/
+					break;
+				case SMBhenningEnum:
+					/*Nothing to add*/
+					break;
+				case SMBcomponentsEnum:
+					/*Nothing to add*/
+					break;
+				case SMBmeltcomponentsEnum:
+					/*Nothing to add*/
+					break;
+				default:
+					_error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
+			}
+			if(hydrology_model==HydrologydcEnum){
+				iomodel->Constant(&this->sediment_compressibility,HydrologydcSedimentCompressibilityEnum);
+				iomodel->Constant(&this->sediment_porosity,HydrologydcSedimentPorosityEnum);
+				iomodel->Constant(&this->sediment_thickness,HydrologydcSedimentThicknessEnum);
+				iomodel->Constant(&this->water_compressibility,HydrologydcWaterCompressibilityEnum);
+				iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
+
+				if(isefficientlayer){
+					iomodel->Constant(&this->epl_compressibility,HydrologydcEplCompressibilityEnum);
+					iomodel->Constant(&this->epl_porosity,HydrologydcEplPorosityEnum);
+					iomodel->Constant(&this->epl_init_thickness,HydrologydcEplInitialThicknessEnum);
+					iomodel->Constant(&this->epl_colapse_thickness,HydrologydcEplColapseThicknessEnum);
+					iomodel->Constant(&this->epl_max_thickness,HydrologydcEplMaxThicknessEnum);
+					iomodel->Constant(&this->epl_conductivity,HydrologydcEplConductivityEnum);
+				}
+			}
+			else if(hydrology_model==HydrologyshreveEnum){
+				/*Nothing to add*/
+			}
+			else{
+				_error_("Hydrology model "<<EnumToStringx(hydrology_model)<<" not supported yet");
+			}
+
+			/*gia: */
+			iomodel->Constant(&this->lithosphere_shear_modulus,MaterialsLithosphereShearModulusEnum);
+			iomodel->Constant(&this->lithosphere_density,MaterialsLithosphereDensityEnum);
+			iomodel->Constant(&this->mantle_shear_modulus,MaterialsMantleShearModulusEnum);
+			iomodel->Constant(&this->mantle_density,MaterialsMantleDensityEnum);
 			break;
 		default:
-			_error_("Surface mass balance model "<<EnumToStringx(smb_model)<<" not supported yet");
-	}
-	if(hydrology_model==HydrologydcEnum){
-		iomodel->Constant(&this->sediment_compressibility,HydrologydcSedimentCompressibilityEnum);
-		iomodel->Constant(&this->sediment_porosity,HydrologydcSedimentPorosityEnum);
-		iomodel->Constant(&this->sediment_thickness,HydrologydcSedimentThicknessEnum);
-		iomodel->Constant(&this->water_compressibility,HydrologydcWaterCompressibilityEnum);
-		iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
-
-		if(isefficientlayer){
-				iomodel->Constant(&this->epl_compressibility,HydrologydcEplCompressibilityEnum);
-				iomodel->Constant(&this->epl_porosity,HydrologydcEplPorosityEnum);
-				iomodel->Constant(&this->epl_init_thickness,HydrologydcEplInitialThicknessEnum);
-				iomodel->Constant(&this->epl_max_thickness,HydrologydcEplMaxThicknessEnum);
-				iomodel->Constant(&this->epl_conductivity,HydrologydcEplConductivityEnum);
-		}
-	}
-	else if(hydrology_model==HydrologyshreveEnum){
-		/*Nothing to add*/
-	}
-	else{
-		_error_("Hydrology model "<<EnumToStringx(hydrology_model)<<" not supported yet");
-	}
-
-	/*gia: */
-	iomodel->Constant(&this->lithosphere_shear_modulus,MaterialsLithosphereShearModulusEnum);
-	iomodel->Constant(&this->lithosphere_density,MaterialsLithosphereDensityEnum);
-	iomodel->Constant(&this->mantle_shear_modulus,MaterialsMantleShearModulusEnum);
-	iomodel->Constant(&this->mantle_density,MaterialsMantleDensityEnum);
+			_error_("Material "<< EnumToStringx(materials_type) <<" not supported yet");
+	}
 }
 /*}}}*/
@@ -118,4 +131,7 @@
 	_printf_("   desfac: " << desfac << "\n");
 	_printf_("   s0p: " << s0p << "\n");
+	_printf_("   s0t: " << s0t << "\n");
+	_printf_("   rlaps: " << rlaps << "\n");
+	_printf_("   rlapslgm: " << rlapslgm << "\n");
 	return;
 }
@@ -160,4 +176,7 @@
 	matpar->desfac=this->desfac;
 	matpar->s0p=this->s0p;
+	matpar->s0t=this->s0t;
+	matpar->rlaps=this->rlaps;
+	matpar->rlapslgm=this->rlapslgm;
 
 	matpar->sediment_compressibility=this->sediment_compressibility;
@@ -169,4 +188,5 @@
 	matpar->epl_porosity=this->epl_porosity;
 	matpar->epl_init_thickness=this->epl_init_thickness;
+	matpar->epl_colapse_thickness=this->epl_colapse_thickness;
 	matpar->epl_max_thickness=this->epl_max_thickness;
 	matpar->epl_conductivity=this->epl_conductivity;
@@ -245,4 +265,13 @@
 			this->s0p=constant;
 			break;
+		case SurfaceforcingsS0tEnum:
+			this->s0t=constant;
+			break;
+		case SurfaceforcingsRlapsEnum:
+			this->rlaps=constant;
+			break;
+		case SurfaceforcingsRlapslgmEnum:
+			this->rlapslgm=constant;
+			break;
 		default: 
 			break;
@@ -261,8 +290,80 @@
 
 /*Matpar management: */
-void  Matpar::Configure(Elements* elementsin){/*{{{*/
+void       Matpar::Configure(Elements* elementsin){/*{{{*/
 
 	/*nothing done yet!*/
 
+}
+/*}}}*/
+void       Matpar::EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
+
+	/*Ouput*/
+	IssmDouble temperature,waterfraction;
+
+	if(enthalpy<PureIceEnthalpy(pressure)){
+		temperature=referencetemperature+enthalpy/heatcapacity;
+		waterfraction=0.;
+	}
+	else{
+		temperature=TMeltingPoint(pressure);
+		waterfraction=(enthalpy-PureIceEnthalpy(pressure))/latentheat;
+	}
+
+	/*Assign output pointers:*/
+	*pwaterfraction=waterfraction;
+	*ptemperature=temperature;
+}
+/*}}}*/
+IssmDouble Matpar::GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
+	if (enthalpy<PureIceEnthalpy(pressure))
+		return thermalconductivity/heatcapacity;
+	else
+		return temperateiceconductivity/heatcapacity;
+}
+/*}}}*/
+IssmDouble Matpar::GetEnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure){/*{{{*/
+
+	int         iv;
+	IssmDouble  lambda;                 // fraction of cold ice
+	IssmDouble  kappa,kappa_c,kappa_t;  //enthalpy conductivities
+	IssmDouble  Hc,Ht;
+	IssmDouble* PIE   = xNew<IssmDouble>(numvertices);
+	IssmDouble* dHpmp = xNew<IssmDouble>(numvertices);
+
+	for(iv=0; iv<numvertices; iv++){
+		PIE[iv]=PureIceEnthalpy(pressure[iv]);
+		dHpmp[iv]=enthalpy[iv]-PIE[iv];
+	}
+
+	bool allequalsign=true;
+	if(dHpmp[0]<0)
+		for(iv=1; iv<numvertices;iv++) allequalsign=(allequalsign && (dHpmp[iv]<0));
+	else
+		for(iv=1; iv<numvertices;iv++) allequalsign=(allequalsign && (dHpmp[iv]>=0));
+
+	if(allequalsign){
+		kappa=GetEnthalpyDiffusionParameter(enthalpy[0], pressure[0]);
+	}
+	else {
+		/* return harmonic mean of thermal conductivities, weighted by fraction of cold/temperate ice,
+		 cf Patankar 1980, pp44 */
+		kappa_c=GetEnthalpyDiffusionParameter(PureIceEnthalpy(0.)-1.,0.);
+		kappa_t=GetEnthalpyDiffusionParameter(PureIceEnthalpy(0.)+1.,0.);
+		Hc=0.; Ht=0.;
+		for(iv=0; iv<numvertices;iv++){
+			if(enthalpy[iv]<PIE[iv])
+			 Hc+=(PIE[iv]-enthalpy[iv]);
+			else
+			 Ht+=(enthalpy[iv]-PIE[iv]);
+		}
+		_assert_((Hc+Ht)>0.);
+		lambda = Hc/(Hc+Ht);
+		kappa  = 1./(lambda/kappa_c + (1.-lambda)/kappa_t);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(PIE);
+	xDelete<IssmDouble>(dHpmp);
+	return kappa;
 }
 /*}}}*/
@@ -271,5 +372,5 @@
 	switch(enum_in){
 		case MaterialsRhoIceEnum:                    return this->rho_ice;
-		case MaterialsRhoSeawaterEnum:                  return this->rho_water;
+		case MaterialsRhoSeawaterEnum:               return this->rho_water;
 		case MaterialsRhoFreshwaterEnum:             return this->rho_freshwater;
 		case MaterialsMuWaterEnum:                   return this->mu_water;
@@ -290,7 +391,17 @@
 		case HydrologydcEplConductivityEnum:         return this->epl_conductivity;
 		case HydrologydcEplInitialThicknessEnum:     return this->epl_init_thickness;
+		case HydrologydcEplColapseThicknessEnum:     return this->epl_colapse_thickness;
 		case HydrologydcEplMaxThicknessEnum:         return this->epl_max_thickness;
 		case HydrologydcWaterCompressibilityEnum:    return this->water_compressibility;
 		case ConstantsGEnum:                         return this->g;
+		case SurfaceforcingsDesfacEnum:              return this->desfac;
+		case SurfaceforcingsS0pEnum:                 return this->s0p;
+		case SurfaceforcingsS0tEnum:                 return this->s0t;
+		case SurfaceforcingsRlapsEnum:               return this->rlaps;
+		case SurfaceforcingsRlapslgmEnum:            return this->rlapslgm;
+		case MaterialsLithosphereShearModulusEnum:   return this->lithosphere_shear_modulus;
+		case MaterialsLithosphereDensityEnum:        return this->lithosphere_density;
+		case MaterialsMantleDensityEnum:             return this->mantle_density;
+		case MaterialsMantleShearModulusEnum:        return this->mantle_shear_modulus;
 		default: _error_("Enum "<<EnumToStringx(enum_in)<<" not supported yet");
 	}
@@ -298,35 +409,28 @@
 }
 /*}}}*/
-IssmDouble Matpar::GetBeta(){/*{{{*/
-	return beta;
-}
-/*}}}*/
-IssmDouble Matpar::GetG(){/*{{{*/
-	return g;
-}
-/*}}}*/
-IssmDouble Matpar::GetMeltingPoint(){/*{{{*/
-	return meltingpoint;
-}
-/*}}}*/
-IssmDouble Matpar::GetRhoIce(){/*{{{*/
-
-	return rho_ice;
-}
-/*}}}*/
-IssmDouble Matpar::GetRhoWater(){/*{{{*/
-	return rho_water;
-}
-/*}}}*/
-IssmDouble Matpar::GetRhoFreshwater(){/*{{{*/
-	return rho_freshwater;
-}
-/*}}}*/
-IssmDouble Matpar::GetDesFac(){/*{{{*/
-	return desfac;
-}
-/*}}}*/
-IssmDouble Matpar::GetS0p(){/*{{{*/
-	return s0p;
+IssmDouble Matpar::PureIceEnthalpy(IssmDouble pressure){/*{{{*/
+	return heatcapacity*(TMeltingPoint(pressure)-referencetemperature);
+}
+/*}}}*/
+void       Matpar::ResetHooks(){/*{{{*/
+
+	//Nothing to be done
+	return;
+}
+/*}}}*/
+void       Matpar::ThermalToEnthalpy(IssmDouble * penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){/*{{{*/
+
+	/*Ouput*/
+	IssmDouble enthalpy;
+
+	if(temperature<TMeltingPoint(pressure)){
+		enthalpy=heatcapacity*(temperature-referencetemperature);
+	}
+	else{
+		enthalpy=PureIceEnthalpy(pressure)+latentheat*waterfraction;
+	}
+
+	/*Assign output pointers:*/
+	*penthalpy=enthalpy;
 }
 /*}}}*/
@@ -335,116 +439,2 @@
 }
 /*}}}*/
-IssmDouble Matpar::PureIceEnthalpy(IssmDouble pressure){/*{{{*/
-	return heatcapacity*(TMeltingPoint(pressure)-referencetemperature);
-}
-/*}}}*/
-IssmDouble Matpar::GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
-	if (enthalpy<PureIceEnthalpy(pressure))
-		return thermalconductivity/heatcapacity;
-	else
-		return temperateiceconductivity/heatcapacity;
-}
-/*}}}*/
-IssmDouble Matpar::GetEnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure){/*{{{*/
-
-	int         iv;
-	IssmDouble  lambda;                 // fraction of cold ice
-	IssmDouble  kappa,kappa_c,kappa_t;  //enthalpy conductivities
-	IssmDouble  Hc,Ht;
-	IssmDouble* PIE   = xNew<IssmDouble>(numvertices);
-	IssmDouble* dHpmp = xNew<IssmDouble>(numvertices);
-
-	for(iv=0; iv<numvertices; iv++){
-		PIE[iv]=PureIceEnthalpy(pressure[iv]);
-		dHpmp[iv]=enthalpy[iv]-PIE[iv];
-	}
-
-	bool allequalsign=true;
-	if(dHpmp[0]<0)
-		for(iv=1; iv<numvertices;iv++) allequalsign=(allequalsign && (dHpmp[iv]<0));
-	else
-		for(iv=1; iv<numvertices;iv++) allequalsign=(allequalsign && (dHpmp[iv]>=0));
-
-	if(allequalsign){
-		kappa=GetEnthalpyDiffusionParameter(enthalpy[0], pressure[0]);
-	}
-	else {
-		/* return harmonic mean of thermal conductivities, weighted by fraction of cold/temperate ice,
-		 cf Patankar 1980, pp44 */
-		kappa_c=GetEnthalpyDiffusionParameter(PureIceEnthalpy(0.)-1.,0.);
-		kappa_t=GetEnthalpyDiffusionParameter(PureIceEnthalpy(0.)+1.,0.);
-		Hc=0.; Ht=0.;
-		for(iv=0; iv<numvertices;iv++){
-			if(enthalpy[iv]<PIE[iv])
-			 Hc+=(PIE[iv]-enthalpy[iv]);
-			else
-			 Ht+=(enthalpy[iv]-PIE[iv]);
-		}
-		_assert_((Hc+Ht)>0.);
-		lambda = Hc/(Hc+Ht);
-		kappa  = 1./(lambda/kappa_c + (1.-lambda)/kappa_t);
-	}
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(PIE);
-	xDelete<IssmDouble>(dHpmp);
-	return kappa;
-}
-/*}}}*/
-void Matpar::EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure){/*{{{*/
-
-	/*Ouput*/
-	IssmDouble temperature,waterfraction;
-
-	if(enthalpy<PureIceEnthalpy(pressure)){
-		temperature=referencetemperature+enthalpy/heatcapacity;
-		waterfraction=0.;
-	}
-	else{
-		temperature=TMeltingPoint(pressure);
-		waterfraction=(enthalpy-PureIceEnthalpy(pressure))/latentheat;
-	}
-
-	/*Assign output pointers:*/
-	*pwaterfraction=waterfraction;
-	*ptemperature=temperature;
-}
-/*}}}*/
-void Matpar::ThermalToEnthalpy(IssmDouble * penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure){/*{{{*/
-
-	/*Ouput*/
-	IssmDouble enthalpy;
-
-	if(temperature<TMeltingPoint(pressure)){
-		enthalpy=heatcapacity*(temperature-referencetemperature);
-	}
-	else{
-		enthalpy=PureIceEnthalpy(pressure)+latentheat*waterfraction;
-	}
-
-	/*Assign output pointers:*/
-	*penthalpy=enthalpy;
-}
-/*}}}*/
-IssmDouble Matpar::GetLithosphereShearModulus(){		 /*{{{*/
-	return lithosphere_shear_modulus;			 
-}		 
-/*}}}*/ 
-IssmDouble Matpar::GetLithosphereDensity(){		 /*{{{*/
-	return lithosphere_density;			 
-}		 
-/*}}}*/ 
-IssmDouble Matpar::GetMantleDensity(){		 /*{{{*/
-	return mantle_density;			 
-}		 
-/*}}}*/ 
-IssmDouble Matpar::GetMantleShearModulus(){		 /*{{{*/
-	return mantle_shear_modulus;			 
-}		 
-/*}}}*/ 
-void  Matpar::ResetHooks(){/*{{{*/
-
-	//Nothing to be done
-	return;
-}
-/*}}}*/
Index: /issm/trunk/src/c/classes/Materials/Matpar.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matpar.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Materials/Matpar.h	(revision 19105)
@@ -30,6 +30,10 @@
 		IssmDouble  thermal_exchange_velocity;
 		IssmDouble  g;
+		IssmDouble  omega;
 		IssmDouble  desfac;
 		IssmDouble  s0p;
+		IssmDouble  s0t;
+		IssmDouble  rlaps;
+		IssmDouble  rlapslgm;
 
 		/*hydrology Dual Porous Continuum: */	 
@@ -42,4 +46,5 @@
 		IssmDouble  epl_porosity;
 		IssmDouble  epl_init_thickness;
+		IssmDouble  epl_colapse_thickness;
 		IssmDouble  epl_max_thickness;
 		IssmDouble  epl_conductivity;	 
@@ -50,4 +55,15 @@
 		IssmDouble mantle_shear_modulus;
 		IssmDouble mantle_density;
+
+		/*Sea ice*/
+		IssmDouble poisson;
+		IssmDouble young_modulus;
+		IssmDouble ridging_exponent;
+		IssmDouble cohesion;
+		IssmDouble internal_friction_coef;
+		IssmDouble compression_coef;
+		IssmDouble traction_coef;
+		IssmDouble time_relaxation_stress;
+		IssmDouble time_relaxation_damage;
 
 	public:
@@ -94,23 +110,11 @@
 		/*}}}*/
 		/*Numerics: {{{*/
-		IssmDouble GetG();
-		IssmDouble GetRhoIce();
-		IssmDouble GetRhoWater();
-		IssmDouble GetRhoFreshwater();
-		IssmDouble GetBeta();
-		IssmDouble GetMeltingPoint();
-		IssmDouble TMeltingPoint(IssmDouble pressure);
-		IssmDouble PureIceEnthalpy(IssmDouble pressure);
+		void       EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure);
 		IssmDouble GetEnthalpyDiffusionParameter(IssmDouble enthalpy,IssmDouble pressure);
 		IssmDouble GetEnthalpyDiffusionParameterVolume(int numvertices,IssmDouble* enthalpy,IssmDouble* pressure);
-		IssmDouble GetLithosphereShearModulus();
-		IssmDouble GetLithosphereDensity();
-		IssmDouble GetMantleShearModulus();
-		IssmDouble GetMantleDensity();
-		void       EnthalpyToThermal(IssmDouble* ptemperature,IssmDouble* pwaterfraction,IssmDouble enthalpy,IssmDouble pressure);
+		IssmDouble GetMaterialParameter(int in_enum); 
+		IssmDouble PureIceEnthalpy(IssmDouble pressure);
 		void       ThermalToEnthalpy(IssmDouble* penthalpy,IssmDouble temperature,IssmDouble waterfraction,IssmDouble pressure);
-		IssmDouble GetDesFac();
-		IssmDouble GetS0p(); 
-		IssmDouble GetMaterialParameter(int in_enum); 
+		IssmDouble TMeltingPoint(IssmDouble pressure);
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/Misfit.h
===================================================================
--- /issm/trunk/src/c/classes/Misfit.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Misfit.h	(revision 19105)
@@ -15,5 +15,8 @@
 #include "../modules/SurfaceAreax/SurfaceAreax.h"
 #include "../classes/Params/Parameters.h"
+#include "../classes/Inputs/Input.h"
+#include "../classes/gauss/Gauss.h"
 /*}}}*/
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
 
 class Misfit: public Object, public Definition{
@@ -21,4 +24,5 @@
 	public: 
 
+		int         definitionenum;
 		char*       name;
 		int         model_enum;
@@ -26,4 +30,5 @@
 		int         weights_enum;
 		char*       timeinterpolation;
+		bool        local;     
 		
 		IssmDouble  misfit; //value carried over in time.
@@ -33,4 +38,5 @@
 		Misfit(){/*{{{*/
 
+			this->definitionenum = -1;
 			this->name = NULL;
 			this->model_enum = UNDEF;
@@ -38,4 +44,5 @@
 			this->weights_enum = UNDEF;
 			this->timeinterpolation=NULL;
+			this->local=true;
 			this->misfit=0;
 			this->lock=0;
@@ -43,6 +50,7 @@
 		}
 		/*}}}*/
-		Misfit(char* in_name, int in_model_enum, int in_observation_enum, char* in_timeinterpolation, int in_weights_enum){/*{{{*/
+		Misfit(char* in_name, int in_definitionenum, int in_model_enum, int in_observation_enum, char* in_timeinterpolation, bool in_local, int in_weights_enum){/*{{{*/
 
+			this->definitionenum=in_definitionenum;
 			this->name   = xNew<char>(strlen(in_name)+1);
 			xMemCpy<char>(this->name,in_name,strlen(in_name)+1);
@@ -54,4 +62,5 @@
 			this->observation_enum=in_observation_enum;
 			this->weights_enum=in_weights_enum;
+			this->local=in_local;
 			
 			this->misfit=0;
@@ -68,9 +77,10 @@
 		/*Object virtual function resolutoin: */
 		void Echo(void){/*{{{*/
-			_printf_(" Misfit: " << name << "\n");
+			_printf_(" Misfit: " << name << " " << this->definitionenum << "\n");
 			_printf_("    model_enum: " << model_enum << " " << EnumToStringx(model_enum) << "\n");
 			_printf_("    observation_enum: " << observation_enum << " " << EnumToStringx(observation_enum) << "\n");
 			_printf_("    weights_enum: " << weights_enum << " " << EnumToStringx(weights_enum) << "\n");
 			_printf_("    timeinterpolation: " << timeinterpolation << "\n");
+			_printf_("    local: " << local << "\n");
 		}
 		/*}}}*/
@@ -88,5 +98,5 @@
 		/*}}}*/
 		Object* copy() {/*{{{*/
-			Misfit* mf = new Misfit(this->name,this->model_enum,this->observation_enum,this->timeinterpolation,this->weights_enum);
+			Misfit* mf = new Misfit(this->name,this->definitionenum, this->model_enum,this->observation_enum,this->timeinterpolation,this->local,this->weights_enum);
 			mf->misfit=this->misfit;
 			mf->lock=this->lock;
@@ -103,47 +113,80 @@
 		}
 		/*}}}*/
+		int DefinitionEnum(){/*{{{*/
+
+			return this->definitionenum;
+		}
+		/*}}}*/
 		 IssmDouble Response(FemModel* femmodel){/*{{{*/
-
-			 int i;
-			 IssmDouble misfit_t=0.;
-			 IssmDouble all_misfit_t=0.;
+				 
+			 /*diverse: */
+			 IssmDouble time,starttime,finaltime;
 			 IssmDouble dt;
-			 IssmDouble area_t=0.;
-			 IssmDouble all_area_t;
-			 IssmDouble time,starttime,finaltime;
-
+			 
+			 /*recover time parameters: */
 			 femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
 			 femmodel->parameters->FindParam(&finaltime,TimesteppingFinalTimeEnum);
 			 femmodel->parameters->FindParam(&time,TimeEnum);
-
-			 /*If we are locked, return time average: */
-			 if(this->lock)return misfit/(time-starttime);
-
-
-			 for(i=0;i<femmodel->elements->Size();i++){
-				 Element* element=(Element*)femmodel->elements->GetObjectByOffset(i);
-				 misfit_t+=element->Misfit(model_enum,observation_enum,weights_enum);
-				 area_t+=element->MisfitArea(weights_enum);
-			 }
-
-			 ISSM_MPI_Allreduce ( (void*)&misfit_t,(void*)&all_misfit_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
-			 ISSM_MPI_Allreduce ( (void*)&area_t,(void*)&all_area_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
-			 area_t=all_area_t;
-			 misfit_t=all_misfit_t;
-			 
-			 /*Divide by surface area if not nill!: */
-			 if (area_t!=0) misfit_t=misfit_t/area_t;
-
-			 /*Recover delta_t: */
 			 femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
 
-			 /*Add this time's contribution to curent misfit: */
-			 misfit+=dt*misfit_t;
+			 if (this->local){ /*local computation: {{{*/
 
-			 /*Do we lock? i.e. are we at final_time? :*/
-			 if(time==finaltime)this->lock=1;
+				 int i;
+				 IssmDouble misfit_t=0.;
+				 IssmDouble all_misfit_t=0.;
+				 IssmDouble area_t=0.;
+				 IssmDouble all_area_t;
 
-			 /*What we return is the value of misfit / time: */
-			 return misfit/(time-starttime);
+			
+				 /*If we are locked, return time average: */
+				 if(this->lock)return misfit/(time-starttime);
+
+				 for(i=0;i<femmodel->elements->Size();i++){
+					 Element* element=(Element*)femmodel->elements->GetObjectByOffset(i);
+					 misfit_t+=element->Misfit(model_enum,observation_enum,weights_enum);
+					 area_t+=element->MisfitArea(weights_enum);
+				 }
+
+				 ISSM_MPI_Allreduce ( (void*)&misfit_t,(void*)&all_misfit_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+				 ISSM_MPI_Allreduce ( (void*)&area_t,(void*)&all_area_t,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+				 area_t=all_area_t;
+				 misfit_t=all_misfit_t;
+				 
+				 /*Divide by surface area if not nill!: */
+				 if (area_t!=0) misfit_t=misfit_t/area_t;
+
+				 /*Add this time's contribution to curent misfit: */
+				 misfit+=dt*misfit_t;
+
+				 /*Do we lock? i.e. are we at final_time? :*/
+				 if(time==finaltime)this->lock=1;
+
+				 /*What we return is the value of misfit / time: */
+				 return misfit/(time-starttime);
+			 } /*}}}*/
+			 else{ /*global computation: {{{ */
+				 
+				 IssmDouble model, observation;
+				 
+				 /*If we are locked, return time average: */
+				 if(this->lock)return misfit/(time-starttime);
+
+				 /*First, the global  model response: */
+				 model=OutputDefinitionsResponsex(femmodel,this->model_enum);
+				 /*Now, the observation is buried inside the elements, go fish it in the first element (cludgy, needs fixing): */
+				 Element* element=(Element*)femmodel->elements->GetObjectByOffset(0); _assert_(element);
+				 Input* input = element->GetInput(observation_enum); _assert_(input);
+				 input->GetInputAverage(&observation);
+				 
+				 /*Add this time's contribution to curent misfit: */
+				 misfit+=dt*(model-observation);
+				 
+				 /*Do we lock? i.e. are we at final_time? :*/
+				 if(time==finaltime)this->lock=1;
+				 
+				 /*What we return is the value of misfit / time: */
+				 return misfit/(time-starttime);
+			 } /*}}}*/
+
 		 }
 			/*}}}*/
Index: /issm/trunk/src/c/classes/Node.cpp
===================================================================
--- /issm/trunk/src/c/classes/Node.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Node.cpp	(revision 19105)
@@ -94,5 +94,4 @@
 				analysis_enum==BalancethicknessAnalysisEnum ||
 				analysis_enum==HydrologyDCInefficientAnalysisEnum ||
-				analysis_enum==DamageEvolutionAnalysisEnum || 
 				analysis_enum==HydrologyDCEfficientAnalysisEnum ||
 				analysis_enum==LevelsetAnalysisEnum ||
Index: /issm/trunk/src/c/classes/Nodes.cpp
===================================================================
--- /issm/trunk/src/c/classes/Nodes.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Nodes.cpp	(revision 19105)
@@ -49,5 +49,5 @@
 	/*Go through objects, and distribute dofs locally, from 0 to numberofdofsperobject*/
 	for(i=0;i<this->Size();i++){
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
@@ -72,5 +72,5 @@
 	for(i=0;i<this->Size();i++){
 		/*Check that this node corresponds to our analysis currently being carried out: */
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 		if (node->InAnalysis(analysis_type)){
 			node->OffsetDofs(dofcount,setenum);
@@ -89,5 +89,5 @@
 
 	for(i=0;i<this->Size();i++){
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 		if (node->InAnalysis(analysis_type)){
 			node->ShowTrueDofs(truedofs,maxdofspernode,setenum);//give maxdofspernode, column size, so that nodes can index into truedofs
@@ -99,5 +99,5 @@
 	/* Now every cpu knows the true dofs of everyone else that is not a clone*/
 	for(i=0;i<this->Size();i++){
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 		if (node->InAnalysis(analysis_type)){
 			node->UpdateCloneDofs(alltruedofs,maxdofspernode,setenum);
@@ -107,5 +107,5 @@
 	/*Update indexingupdateflag*/
 	for(i=0;i<this->Size();i++){
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 		if (node->InAnalysis(analysis_type)){
 			node->ReindexingDone();
@@ -148,5 +148,5 @@
 	for(i=0;i<this->Size();i++){
 
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
@@ -172,5 +172,5 @@
 	for(int i=0;i<this->Size();i++){
 
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
@@ -197,5 +197,5 @@
 	if(!sorted){
 		for(int i=0;i<this->Size();i++){
-			Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+			Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 			id=node->Id();
 			if(id>max)max=id;
@@ -207,5 +207,5 @@
 		}
 		else{
-			Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(this->Size()-1));
+			Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(this->Size()-1));
 			max = node->Id();
 		}
@@ -238,5 +238,5 @@
 	for(int i=0;i<this->Size();i++){
 
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
@@ -262,5 +262,5 @@
 	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
 	for(int i=0;i<this->Size();i++){
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 
 		/*Ok, this object is a node, ask it to plug values into partition: */
@@ -284,5 +284,5 @@
 	for(i=0;i<this->Size();i++){
 
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
@@ -316,5 +316,5 @@
 	for(int i=0;i<this->Size();i++){
 
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
@@ -335,5 +335,5 @@
 	for(int i=0;i<this->Size();i++){
 
-		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
Index: /issm/trunk/src/c/classes/Options/GenericOption.h
===================================================================
--- /issm/trunk/src/c/classes/Options/GenericOption.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Options/GenericOption.h	(revision 19105)
@@ -132,3 +132,12 @@
 /*}}}*/
 
+/*Special destructors when there is a pointer*/
+template <> inline GenericOption<char*>::~GenericOption(){ /*{{{*/
+
+	if(name)   xDelete<char>(name);
+	if(size)   xDelete<int>(size);
+	if(value)  xDelete<char>(value);
+} 
+/*}}}*/
+
 #endif  /* _OPTIONOBJECT_H */
Index: /issm/trunk/src/c/classes/Options/Options.cpp
===================================================================
--- /issm/trunk/src/c/classes/Options/Options.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Options/Options.cpp	(revision 19105)
@@ -52,5 +52,5 @@
 	for(object=objects.begin();object<objects.end();object++){
 
-		option=dynamic_cast<Option*>(*object);
+		option=xDynamicCast<Option*>(*object);
 		if (!strcmp(option->Name(),name)){
 			_error_("Options \"" << name << "\" found multiple times");
@@ -73,5 +73,18 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		option=dynamic_cast<Option*>(*object);
+		option=xDynamicCast<Option*>(*object);
+		//option=(Option*)(*object); //C-like cast
+		/*There is a crash on some machines (Einar Olason) that needs to be fixed*/
+		if(!option){
+			_printf_("The dynamic_cast from Object* to Option* is failing.\n");
+			_printf_("\n");
+			_printf_("A quick qorkaround consists of using a C-like cast\n");
+			_printf_("\n");
+			_printf_("Open Options.cpp and change the dynamic_cast in Options::GetOption by a C-like cast\n");
+			//_printf_("Open Options.h and replace the dynamic_cast of all the Get functions to C-like cats\n");
+			_printf_("\n");
+			_error_("Make the fix above and recompile ISSM");
+		}
+
 		if (!strncmp(name,option->Name(),strlen(option->Name()))){
 
Index: /issm/trunk/src/c/classes/Options/Options.h
===================================================================
--- /issm/trunk/src/c/classes/Options/Options.h	(revision 19104)
+++ /issm/trunk/src/c/classes/Options/Options.h	(revision 19105)
@@ -26,5 +26,5 @@
 
 			/*Get option*/
-			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+			GenericOption<OptionType>* genericoption=xDynamicCast<GenericOption<OptionType>*>(GetOption(name));
 
 			/*If the pointer is not NULL, the option has been found*/
@@ -41,5 +41,5 @@
 
 			/*Get option*/
-			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+			GenericOption<OptionType>* genericoption=xDynamicCast<GenericOption<OptionType>*>(GetOption(name));
 
 			/*If the pointer is not NULL, the option has been found*/
@@ -57,5 +57,5 @@
 
 			/*Get option*/
-			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+			GenericOption<OptionType>* genericoption=xDynamicCast<GenericOption<OptionType>*>(GetOption(name));
 
 			/*If the pointer is not NULL, the option has been found*/
@@ -72,5 +72,5 @@
 
 			/*Get option*/
-			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
+			GenericOption<OptionType>* genericoption=xDynamicCast<GenericOption<OptionType>*>(GetOption(name));
 
 			/*If the pointer is not NULL, the option has been found*/
@@ -92,5 +92,5 @@
 
 	/*Get option*/
-	GenericOption<char*>* genericoption=dynamic_cast<GenericOption<char*>*>(GetOption(name));
+	GenericOption<char*>* genericoption=xDynamicCast<GenericOption<char*>*>(GetOption(name));
 
 	/*If the pointer is not NULL, the option has been found*/
Index: /issm/trunk/src/c/classes/Params/Parameters.cpp
===================================================================
--- /issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Params/Parameters.cpp	(revision 19105)
@@ -57,5 +57,5 @@
 
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type) return true;
 	}
@@ -70,5 +70,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pbool);
@@ -86,5 +86,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pinteger);
@@ -102,5 +102,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pscalar);
@@ -118,5 +118,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pscalar,time);
@@ -134,5 +134,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pstring);
@@ -151,5 +151,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pstringarray,pM);
@@ -168,5 +168,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pintarray,pM);
@@ -185,5 +185,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pintarray,pM,pN);
@@ -202,5 +202,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pIssmDoublearray,pM);
@@ -219,5 +219,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pIssmDoublearray,pM,pN);
@@ -236,5 +236,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(parray,pM,pmdims_array,pndims_array);
@@ -252,5 +252,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pvec);
@@ -269,5 +269,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pmat);
@@ -286,5 +286,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pfid);
@@ -303,5 +303,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pdataset);
@@ -318,5 +318,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(boolean); //already exists, just set it.
@@ -329,5 +329,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(integer); //already exists, just set it.
@@ -340,5 +340,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(scalar); //already exists, just set it.
@@ -351,5 +351,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(string); //already exists, just set it.
@@ -362,5 +362,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(stringarray,M); //already exists, just set it.
@@ -373,5 +373,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(IssmDoublearray,M); //already exists, just set it.
@@ -384,5 +384,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(IssmDoublearray,M,N); //already exists, just set it.
@@ -395,5 +395,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(intarray,M); //already exists, just set it.
@@ -406,5 +406,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(intarray,M,N); //already exists, just set it.
@@ -417,5 +417,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(vector); //already exists, just set it.
@@ -428,5 +428,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(matrix); //already exists, just set it.
@@ -439,5 +439,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(fid); //already exists, just set it.
@@ -450,5 +450,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
+	param=xDynamicCast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(dataset); //already exists, just set it.
@@ -464,5 +464,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=dynamic_cast<Param*>(*object);
+		param=xDynamicCast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			return (*object);
Index: /issm/trunk/src/c/classes/Vertex.cpp
===================================================================
--- /issm/trunk/src/c/classes/Vertex.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Vertex.cpp	(revision 19105)
@@ -32,15 +32,19 @@
 	this->domaintype     = iomodel->domaintype;
 
-	_assert_(iomodel->Data(BaseEnum) && iomodel->Data(ThicknessEnum) && iomodel->numbernodetoelementconnectivity);
 	switch(iomodel->domaintype){
 		case Domain3DEnum:
-		case Domain2DhorizontalEnum:
+			_assert_(iomodel->Data(BaseEnum) && iomodel->Data(ThicknessEnum));
 			this->sigma = (iomodel->Data(MeshZEnum)[i]-iomodel->Data(BaseEnum)[i])/(iomodel->Data(ThicknessEnum)[i]);
 			break;
+		case Domain2DhorizontalEnum:
+			this->sigma = 0.;
+			break;
 		case Domain2DverticalEnum:
+			_assert_(iomodel->Data(BaseEnum) && iomodel->Data(ThicknessEnum));
 			this->sigma = (iomodel->Data(MeshYEnum)[i]-iomodel->Data(BaseEnum)[i])/(iomodel->Data(ThicknessEnum)[i]);
 			break;
 	}
 
+	_assert_(iomodel->numbernodetoelementconnectivity);
 	this->connectivity = iomodel->numbernodetoelementconnectivity[i];
 
Index: /issm/trunk/src/c/classes/Vertices.cpp
===================================================================
--- /issm/trunk/src/c/classes/Vertices.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/Vertices.cpp	(revision 19105)
@@ -52,5 +52,5 @@
 	/*Go through objects, and distribute pids locally, from 0 to numberofpidsperobject*/
 	for (i=0;i<this->Size();i++){
-		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		Vertex* vertex=xDynamicCast<Vertex*>(this->GetObjectByOffset(i));
 		vertex->DistributePids(&pidcount);
 	}
@@ -72,5 +72,5 @@
 	}
 	for (i=0;i<this->Size();i++){
-		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		Vertex* vertex=xDynamicCast<Vertex*>(this->GetObjectByOffset(i));
 		vertex->OffsetPids(pidcount);
 	}
@@ -82,5 +82,5 @@
 	alltruepids=xNewZeroInit<int>(numberofobjects);
 	for (i=0;i<this->Size();i++){
-		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		Vertex* vertex=xDynamicCast<Vertex*>(this->GetObjectByOffset(i));
 		vertex->ShowTruePids(truepids);
 	}
@@ -89,5 +89,5 @@
 	/* Now every cpu knows the true pids of everyone else that is not a clone*/
 	for(i=0;i<this->Size();i++){
-		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		Vertex* vertex=xDynamicCast<Vertex*>(this->GetObjectByOffset(i));
 		vertex->UpdateClonePids(alltruepids);
 	}
@@ -128,5 +128,5 @@
 	for(i=0;i<this->Size();i++){
 		/*For this object, decide whether it is a clone: */
-		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		Vertex* vertex=xDynamicCast<Vertex*>(this->GetObjectByOffset(i));
 		vertex->SetClone(minranks);
 	}
@@ -145,5 +145,5 @@
 
 	for(i=0;i<this->Size();i++){
-		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		Vertex* vertex=xDynamicCast<Vertex*>(this->GetObjectByOffset(i));
 		sid=vertex->Sid();
 		if (sid>max_sid)max_sid=sid;
@@ -172,5 +172,5 @@
 	for(int i=0;i<this->Size();i++){
 		/*Plug rank into ranks, according to id: */
-		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		Vertex* vertex=xDynamicCast<Vertex*>(this->GetObjectByOffset(i));
 		sid=vertex->Sid();
 		ranks[sid]=my_rank; 
@@ -202,5 +202,5 @@
 
 		/*let vertex fill matrix: */
-		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		Vertex* vertex=xDynamicCast<Vertex*>(this->GetObjectByOffset(i));
 		vertex->ToXYZ(xyz);
 	}
Index: /issm/trunk/src/c/classes/classes.h
===================================================================
--- /issm/trunk/src/c/classes/classes.h	(revision 19104)
+++ /issm/trunk/src/c/classes/classes.h	(revision 19105)
@@ -19,4 +19,6 @@
 #include "./Massfluxatgate.h"
 #include "./Misfit.h"
+#include "./Masscon.h"
+#include "./Massconaxpby.h"
 
 /*Constraints: */
Index: /issm/trunk/src/c/classes/gauss/GaussPenta.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 19105)
@@ -8,4 +8,5 @@
 #include "../../shared/Exceptions/exceptions.h"
 #include "../../shared/MemOps/MemOps.h"
+#include "../../shared/Numerics/recast.h"
 #include "../../shared/Enum/Enum.h"
 #include "../../shared/Numerics/GaussPoints.h"
@@ -750,5 +751,5 @@
 
 	_assert_(gauss->Enum()==GaussTriaEnum);
-	GaussTria* gauss_tria = dynamic_cast<GaussTria*>(gauss);
+	GaussTria* gauss_tria = xDynamicCast<GaussTria*>(gauss);
 
 	gauss_tria->coord1=this->coord1;
Index: /issm/trunk/src/c/classes/kriging/Covertree.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Covertree.cpp	(revision 19105)
+++ /issm/trunk/src/c/classes/kriging/Covertree.cpp	(revision 19105)
@@ -0,0 +1,467 @@
+#include "../classes.h"
+//#include <utility>
+#include <set>
+//#include <vector>
+#include <algorithm>
+
+	/*Constructors/Destructors*/
+Covertree::Covertree(int maxLevel,const std::vector<Observation>& points){
+	this->base = 2.;
+	_root=NULL;
+	_numNodes=0;
+	_maxLevel=maxLevel;//ceilf(log(maxDist)/log(base));
+	_minLevel=_maxLevel-1;
+	std::vector<Observation>::const_iterator it;
+	for(it=points.begin(); it!=points.end(); ++it) {
+		this->insert(*it);//adds data to the covertree object
+	}
+}
+
+Covertree::~Covertree(){
+	if(_root==NULL) return;
+	//Get all of the root's children (from any level),
+	//delete the root, repeat for each of the children
+	std::vector<CoverTreeNode*> nodes;
+	nodes.push_back(_root);
+	while(!nodes.empty()) {
+		CoverTreeNode* byeNode = nodes[0];
+		nodes.erase(nodes.begin());
+		std::vector<CoverTreeNode*> children = byeNode->getAllChildren();
+		nodes.insert(nodes.begin(),children.begin(),children.end());
+		delete byeNode;
+	}   
+}
+
+/*Methods*/
+std::vector<Covertree::CoverTreeNode*> Covertree::kNearestNodes(const Observation& p, const unsigned int& k) const{
+	if(_root==NULL) return std::vector<CoverTreeNode*>();
+	//maxDist is the kth nearest known point to p, and also the farthest
+	//point from p in the set minNodes defined below.
+	double maxDist = p.distance(_root->getObservation());
+	//minNodes stores the k nearest known points to p.
+	std::set<distNodePair> minNodes;
+
+	minNodes.insert(std::make_pair(maxDist,_root));
+	std::vector<distNodePair> Qj(1,std::make_pair(maxDist,_root));
+	for(int level = _maxLevel; level>=_minLevel;level--) {
+		std::vector<distNodePair>::const_iterator it;
+		int size = Qj.size();
+		for(int i=0; i<size; i++) {
+			std::vector<CoverTreeNode*> children =
+			  Qj[i].second->getChildren(level);
+			std::vector<CoverTreeNode*>::const_iterator it2;
+			for(it2=children.begin(); it2!=children.end(); ++it2) {
+				double d = p.distance((*it2)->getObservation());
+				if(d < maxDist || minNodes.size() < k) {
+					minNodes.insert(std::make_pair(d,*it2));
+					//--minNodes.end() gives us an iterator to the greatest
+					//element of minNodes.
+					if(minNodes.size() > k) minNodes.erase(--minNodes.end());
+					maxDist = (--minNodes.end())->first;
+				}
+				Qj.push_back(std::make_pair(d,*it2));
+			}
+		}
+		double sep = maxDist + pow(base, level);
+		size = Qj.size();
+		for(int i=0; i<size; i++) {
+			if(Qj[i].first > sep) {
+				//quickly removes an element from a vector w/o preserving order.
+				Qj[i]=Qj.back();
+				Qj.pop_back();
+				size--; i--;
+			}
+		}
+	}
+	std::vector<CoverTreeNode*> kNN;
+	std::set<distNodePair>::const_iterator it;
+	for(it=minNodes.begin();it!=minNodes.end();++it) {
+		kNN.push_back(it->second);
+	}
+	return kNN;
+}
+bool Covertree::insert_rec(const Observation& p, const std::vector<distNodePair>& Qi, const int& level){
+	std::vector<std::pair<double, CoverTreeNode*> > Qj;
+	double sep = pow(base,level);
+	double minDist = 1.e+50;
+	std::pair<double,CoverTreeNode*> minQiDist(1.e+50,NULL);
+	std::vector<std::pair<double, CoverTreeNode*> >::const_iterator it;
+	for(it=Qi.begin(); it!=Qi.end(); ++it) {
+		if(it->first<minQiDist.first) minQiDist = *it;
+		if(it->first<minDist) minDist=it->first;
+		if(it->first<=sep) Qj.push_back(*it);
+		std::vector<CoverTreeNode*> children = it->second->getChildren(level);
+		std::vector<CoverTreeNode*>::const_iterator it2;
+		for(it2=children.begin();it2!=children.end();++it2) {
+			double d = p.distance((*it2)->getObservation());
+			if(d<minDist) minDist = d;
+			if(d<=sep) {
+				Qj.push_back(std::make_pair(d,*it2));
+			}
+		}
+	}
+	//std::cout << "level: " << level << ", sep: " << sep << ", dist: " << minQDist.first << "\n";
+	if(minDist > sep) {
+		return true;
+	} else {
+		bool found = insert_rec(p,Qj,level-1);
+		//distNodePair minQiDist = distance(p,Qi);
+		if(found && minQiDist.first <= sep) {
+			if(level-1<_minLevel) _minLevel=level-1;
+			minQiDist.second->addChild(level,
+						new CoverTreeNode(p));
+			//std::cout << "parent is ";
+			//minQiDist.second->getObservation().print();
+			_numNodes++;
+			return false;
+		} else {
+			return found;
+		}
+	}
+}
+
+void Covertree::remove_rec(const Observation& p, std::map<int,std::vector<distNodePair> >& coverSets, int level, bool& multi){
+	std::vector<distNodePair>& Qi = coverSets[level];
+	std::vector<distNodePair>& Qj = coverSets[level-1];
+	double minDist = 1.e+50;
+	CoverTreeNode* minNode = _root;
+	CoverTreeNode* parent = 0;
+	double sep = pow(base, level);
+	std::vector<distNodePair>::const_iterator it;
+	//set Qj to be all children q of Qi such that p.distance(q)<=sep
+	//and also keep track of the minimum distance from p to a node in Qj
+	//note that every node has itself as a child, but the
+	//getChildren function only returns non-self-children.
+	for(it=Qi.begin();it!=Qi.end();++it) {
+		std::vector<CoverTreeNode*> children = it->second->getChildren(level);
+		double dist = it->first;
+		if(dist<minDist) {
+			minDist = dist;
+			minNode = it->second;
+		}
+		if(dist <= sep) {
+			Qj.push_back(*it);
+		}
+		std::vector<CoverTreeNode*>::const_iterator it2;
+		for(it2=children.begin();it2!=children.end();++it2) {
+			dist = p.distance((*it2)->getObservation());
+			if(dist<minDist) {
+				minDist = dist;
+				minNode = *it2;
+				if(dist == 0.0) parent = it->second;
+			}
+			if(dist <= sep) {
+				Qj.push_back(std::make_pair(dist,*it2));
+			}
+		}
+	}
+	if(level>_minLevel) remove_rec(p,coverSets,level-1,multi);
+	if(minNode->hasObservation(p)) {
+		//the multi flag indicates the point we removed is from a
+		//node containing multiple points, and we have removed it,
+		//so we don't need to do anything else.
+		if(multi) return;
+		if(!minNode->isSingle()) {
+			minNode->removeObservation(p);
+			multi=true;
+			return;
+		}
+		if(parent!=NULL) parent->removeChild(level, minNode);
+		std::vector<CoverTreeNode*> children = minNode->getChildren(level-1);
+		std::vector<distNodePair>& Q = coverSets[level-1];
+		if(Q.size()==1 && Q[0].second==minNode) {
+			Q.pop_back();
+		} else {
+			for(unsigned int i=0;i<Q.size();i++) {
+				if(Q[i].second==minNode) {
+					Q[i]=Q.back();
+					Q.pop_back();
+					break;
+				}
+			}
+		}
+		std::vector<CoverTreeNode*>::const_iterator it;
+		for(it=children.begin();it!=children.end();++it) {
+			int i = level-1;
+			Observation q = (*it)->getObservation();
+			double minDQ = 1.e+50;
+			CoverTreeNode* minDQNode = NULL;
+			double sep = pow(base,i);
+			bool br=false;
+			while(true) {
+				std::vector<distNodePair>&
+				  Q = coverSets[i];
+				std::vector<distNodePair>::const_iterator it2;
+				minDQ = 1.e+50;
+				for(it2=Q.begin();it2!=Q.end();++it2) {
+					double d = q.distance(it2->second->getObservation());
+					if(d<minDQ) {
+						minDQ = d;
+						minDQNode = it2->second;
+						if(d <=sep) {
+							br=true;
+							break;
+						}
+					}
+				}
+				minDQ=1.e+50;
+				if(br) break;
+				Q.push_back(std::make_pair((*it)->distance(p),*it));
+				i++;
+				sep = pow(base,i);
+			}
+			//minDQNode->getObservation().print();
+			//std::cout << " is level " << i << " parent of ";
+			//(*it)->getObservation().print();
+			if (minDQNode != NULL)
+			 minDQNode->addChild(i,*it);
+		}
+		if(parent!=NULL) {
+			delete minNode;
+			_numNodes--;
+		}
+	}
+}
+
+int Covertree::get_numberofobs(){
+	return _numNodes;
+}
+
+std::pair<double, Covertree::CoverTreeNode*>
+Covertree::distance(const Observation& p,
+			const std::vector<CoverTreeNode*>& Q)
+{
+	double minDist = 1.e+50;
+	CoverTreeNode* minNode;
+	std::vector<CoverTreeNode*>::const_iterator it;
+	for(it=Q.begin();it!=Q.end();++it) {
+		double dist = p.distance((*it)->getObservation());
+		if(dist < minDist) {
+			minDist = dist;
+			minNode = *it;
+		}
+	}
+	return std::make_pair(minDist,minNode);  
+}
+
+void Covertree::insert(const Observation& newObservation)
+{
+	if(_root==NULL) {
+		_root = new CoverTreeNode(newObservation);
+		_numNodes=1;
+		return;
+	}
+	//TODO: this is pretty inefficient, there may be a better way
+	//to check if the node already exists...
+	CoverTreeNode* n = kNearestNodes(newObservation,1)[0];
+	if(newObservation.distance(n->getObservation())==0.0) {
+		n->addObservation(newObservation);
+	} else {
+		//insert_rec acts under the assumption that there are no nodes with
+		//distance 0 to newObservation in the cover tree (the previous lines check it)
+		insert_rec(newObservation,
+					std::vector<distNodePair>
+					(1,std::make_pair(_root->distance(newObservation),_root)),
+					_maxLevel);
+	}
+}
+
+void Covertree::remove(const Observation& p)
+{
+	//Most of this function's code is for the special case of removing the root
+	if(_root==NULL) return;
+	bool removingRoot=_root->hasObservation(p);
+	if(removingRoot && !_root->isSingle()) {
+		_root->removeObservation(p);
+		return;
+	}
+	CoverTreeNode* newRoot=NULL;
+	if(removingRoot) {
+		if(_numNodes==1) {
+			//removing the last node...
+			delete _root;
+			_numNodes--;
+			_root=NULL;
+			return;
+		} else {
+			for(int i=_maxLevel;i>_minLevel;i--) {
+				if(!(_root->getChildren(i).empty())) {
+					newRoot = _root->getChildren(i).back();
+					_root->removeChild(i,newRoot);
+					break;
+				}
+			}
+		}
+	}
+	std::map<int, std::vector<distNodePair> > coverSets;
+	coverSets[_maxLevel].push_back(std::make_pair(_root->distance(p),_root));
+	if(removingRoot)
+	 coverSets[_maxLevel].push_back(std::make_pair(newRoot->distance(p),newRoot));
+	bool multi = false;
+	remove_rec(p,coverSets,_maxLevel,multi);
+	if(removingRoot) {
+		delete _root;
+		_numNodes--;
+		_root=newRoot;
+	}
+}
+
+std::vector<Observation> Covertree::kNearestNeighbors(const Observation& p, const unsigned int& k) const{
+	if(_root==NULL) return std::vector<Observation>();
+	std::vector<CoverTreeNode*> v = kNearestNodes(p, k);
+	std::vector<Observation> kNN;
+	std::vector<CoverTreeNode*>::const_iterator it;
+	for(it=v.begin();it!=v.end();++it) {
+		const std::vector<Observation>& p = (*it)->getObservations();
+		kNN.insert(kNN.end(),p.begin(),p.end());
+		if(kNN.size() >= k) break;
+	}
+	return kNN;
+}
+
+void Covertree::print() const{
+	int d = _maxLevel-_minLevel+1;
+	std::vector<CoverTreeNode*> Q;
+	Q.push_back(_root);
+	for(int i=0;i<d;i++) {
+		std::cout << "LEVEL " << _maxLevel-i << "\n";
+		std::vector<CoverTreeNode*>::const_iterator it;
+		for(it=Q.begin();it!=Q.end();++it) {
+			(*it)->getObservation().print();
+			std::vector<CoverTreeNode*>
+			  children = (*it)->getChildren(_maxLevel-i);
+			std::vector<CoverTreeNode*>::const_iterator it2;
+			for(it2=children.begin();it2!=children.end();++it2) {
+				std::cout << "  ";
+				(*it2)->getObservation().print();
+			}
+		}
+		std::vector<CoverTreeNode*> newQ;
+		for(it=Q.begin();it!=Q.end();++it) {
+			std::vector<CoverTreeNode*>
+			  children = (*it)->getChildren(_maxLevel-i);
+			newQ.insert(newQ.end(),children.begin(),children.end());
+		}
+		Q.insert(Q.end(),newQ.begin(),newQ.end());
+		std::cout << "\n\n";
+	}
+}
+
+Covertree::CoverTreeNode* Covertree::getRoot() const
+{
+	return _root;
+}
+
+Covertree::CoverTreeNode::CoverTreeNode(const Observation& p) {
+	_observations.push_back(p);
+}
+
+std::vector<Covertree::CoverTreeNode*>
+Covertree::CoverTreeNode::getChildren(int level) const
+{
+	std::map<int,std::vector<CoverTreeNode*> >::const_iterator
+	  it = _childMap.find(level);
+	if(it!=_childMap.end()) {
+		return it->second;
+	}
+	return std::vector<CoverTreeNode*>();
+}
+
+void Covertree::CoverTreeNode::addChild(int level, CoverTreeNode* p)
+{
+	_childMap[level].push_back(p);
+}
+
+void Covertree::CoverTreeNode::removeChild(int level, CoverTreeNode* p)
+{
+	std::vector<CoverTreeNode*>& v = _childMap[level];
+	for(unsigned int i=0;i<v.size();i++) {
+		if(v[i]==p) {
+			v[i]=v.back();
+			v.pop_back();
+			break;
+		}
+	}
+}
+
+void Covertree::CoverTreeNode::addObservation(const Observation& p)
+{
+	if(find(_observations.begin(), _observations.end(), p) == _observations.end())
+	 _observations.push_back(p);
+}
+
+void Covertree::CoverTreeNode::removeObservation(const Observation& p)
+{
+	std::vector<Observation>::iterator it =
+	  find(_observations.begin(), _observations.end(), p);
+	if(it != _observations.end())
+	 _observations.erase(it);
+}
+
+double Covertree::CoverTreeNode::distance(const CoverTreeNode& p) const
+{
+	return _observations[0].distance(p.getObservation());
+}
+
+bool Covertree::CoverTreeNode::isSingle() const
+{
+	return _observations.size() == 1;
+}
+
+bool Covertree::CoverTreeNode::hasObservation(const Observation& p) const
+{
+	return find(_observations.begin(), _observations.end(), p) != _observations.end();
+}
+
+const Observation& Covertree::CoverTreeNode::getObservation() const { return _observations[0]; }
+
+std::vector<Covertree::CoverTreeNode*>
+Covertree::CoverTreeNode::getAllChildren() const
+{
+	std::vector<CoverTreeNode*> children;
+	std::map<int,std::vector<CoverTreeNode*> >::const_iterator it;
+	for(it=_childMap.begin();it!=_childMap.end();++it) {
+		children.insert(children.end(), it->second.begin(), it->second.end());
+	}
+	return children;
+}
+
+bool Covertree::isValidTree() const {
+	if(_numNodes==0)
+	 return _root==NULL;
+
+	std::vector<CoverTreeNode*> nodes;
+	nodes.push_back(_root);
+	for(int i=_maxLevel;i>_minLevel;i--) {
+		double sep = pow(base,i);
+		std::vector<CoverTreeNode*>::const_iterator it, it2;
+		//verify separation invariant of cover tree: for each level,
+		//every point is farther than base^level away
+		for(it=nodes.begin(); it!=nodes.end(); ++it) {
+			for(it2=nodes.begin(); it2!=nodes.end(); ++it2) {
+				double dist=(*it)->distance((*it2)->getObservation());
+				if(dist<=sep && dist!=0.0) {
+					std::cout << "Level " << i << " Separation invariant failed.\n";
+					return false;
+				}
+			}
+		}
+		std::vector<CoverTreeNode*> allChildren;
+		for(it=nodes.begin(); it!=nodes.end(); ++it) {        
+			std::vector<CoverTreeNode*> children = (*it)->getChildren(i);
+			//verify covering tree invariant: the children of node n at level
+			//i are no further than base^i away
+			for(it2=children.begin(); it2!=children.end(); ++it2) {
+				double dist = (*it2)->distance((*it)->getObservation());
+				if(dist>sep) {
+					std::cout << "Level" << i << " covering tree invariant failed.n";
+					return false;
+				}
+			}
+			allChildren.insert
+			  (allChildren.end(),children.begin(),children.end());
+		}
+		nodes.insert(nodes.begin(),allChildren.begin(),allChildren.end());
+	}
+	return true;
+}
Index: /issm/trunk/src/c/classes/kriging/Covertree.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/Covertree.h	(revision 19105)
+++ /issm/trunk/src/c/classes/kriging/Covertree.h	(revision 19105)
@@ -0,0 +1,136 @@
+
+#ifndef _COVERTREE_H
+#define _COVERTREE_H
+
+#include <map>
+class Observation;
+
+class Covertree{
+
+	/**
+	 * Cover tree node. Consists of arbitrarily many points P, as long as
+	 * they have distance 0 to each other. Keeps track of its children.
+	 */
+	class CoverTreeNode{
+		private:
+			//_childMap[i] is a vector of the node's children at level i
+			std::map<int,std::vector<CoverTreeNode*> > _childMap;
+			//_observations is all of the points with distance 0 which are not equal.
+			std::vector<Observation> _observations;
+		public:
+			CoverTreeNode(const Observation& o);
+			/**
+			 * Returns the children of the node at level i. Note that this means
+			 * the children exist in cover set i-1, not level i.
+			 *
+			 * Does not include the node itself, though technically every node
+			 * has itself as a child in a cover tree.
+			 */
+			std::vector<CoverTreeNode*> getChildren(int level) const;
+			void addChild(int level, CoverTreeNode* p);
+			void removeChild(int level, CoverTreeNode* p);
+			void addObservation(const Observation& o);
+			void removeObservation(const Observation& o);
+			const std::vector<Observation>& getObservations() { return _observations; }
+			double distance(const CoverTreeNode& p) const;
+
+			bool isSingle() const;
+			bool hasObservation(const Observation& o) const;
+
+			const Observation& getObservation() const;
+
+			/**
+			 * Return every child of the node from any level. This is handy for
+			 * the destructor.
+			 */
+			std::vector<CoverTreeNode*> getAllChildren() const;
+	  }; // CoverTreeNode class
+	private:
+	typedef std::pair<double, CoverTreeNode*> distNodePair;
+
+	CoverTreeNode* _root;
+	unsigned int _numNodes;
+	int _maxLevel;//base^_maxLevel should be the max distance
+	//between any 2 points
+	int _minLevel;//A level beneath which there are no more new nodes.
+
+	std::vector<CoverTreeNode*>
+	  kNearestNodes(const Observation& o, const unsigned int& k) const;
+	/**
+	 * Recursive implementation of the insert algorithm (see paper).
+	 */
+	bool insert_rec(const Observation& p,
+				const std::vector<distNodePair>& Qi,
+				const int& level);
+
+	/**
+	 * Finds the node in Q with the minimum distance to p. Returns a
+	 * pair consisting of this node and the distance.
+	 */
+	distNodePair distance(const Observation& p,
+				const std::vector<CoverTreeNode*>& Q);
+
+
+	void remove_rec(const Observation& p,
+				std::map<int,std::vector<distNodePair> >& coverSets,
+				int level,
+				bool& multi);
+
+	public:
+	double base;
+
+	/**
+	 * Constructs a cover tree which begins with all points in points.
+	 *
+	 * maxDist should be the maximum distance that any two points
+	 * can have between each other. IE p.distance(q) < maxDist for all
+	 * p,q that you will ever try to insert. The cover tree may be invalid
+	 * if an inaccurate maxDist is given.
+	 */
+
+	Covertree(int maxDist,
+				const std::vector<Observation>& points=std::vector<Observation>()); 
+	~Covertree();
+
+	/**
+	 * Just for testing/debugging. Returns true iff the cover tree satisfies the
+	 * the covering tree invariants (every node in level i is greater than base^i
+	 * distance from every other node, and every node in level i is less than
+	 * or equal to base^i distance from its children). See the cover tree
+	 * papers for details.
+	 */
+	bool isValidTree() const;
+
+	/**
+	 * Insert newPoint into the cover tree. If newPoint is already present,
+	 * (that is, newPoint==p for some p already in the tree), then the tree
+	 * is unchanged. If p.distance(newPoint)==0.0 but newPoint!=p, then
+	 * newPoint WILL be inserted and both points may be returned in k-nearest-
+	 * neighbor searches.
+	 */
+	void insert(const Observation& newObservation);
+
+	/**
+	 * Remove point p from the cover tree. If p is not present in the tree,
+	 * it will remain unchanged. Otherwise, this will remove exactly one
+	 * point q from the tree satisfying p==q.
+	 */
+	void remove(const Observation& p);
+
+	/**
+	 * Returns the k nearest points to p in order (the 0th element of the vector
+	 * is closest to p, 1th is next, etc). It may return greater than k points
+	 * if there is a tie for the kth place.
+	 */
+	std::vector<Observation> kNearestNeighbors(const Observation& p, const unsigned int& k) const;
+
+	int get_numberofobs();
+
+	CoverTreeNode* getRoot() const;
+
+	/**
+	 * Print the cover tree.
+	 */
+	void print() const;
+};
+#endif //_COVERTREE_H
Index: /issm/trunk/src/c/classes/kriging/Observation.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observation.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/kriging/Observation.cpp	(revision 19105)
@@ -4,4 +4,6 @@
 
 #include <stdlib.h>
+#include <cmath>
+#include <utility>
 #include "../classes.h"
 
@@ -23,4 +25,14 @@
 }
 /*}}}*/
+Observation::Observation(double x_in, double y_in,double value_in){
+	this->x = x_in;
+	this->y = y_in;
+	this->value = value_in;
+
+	this->xi     = 0;
+	this->yi     = 0;
+	this->index  = 0;
+	this->weight = 0.;
+}
 Observation::~Observation(){/*{{{*/
 	return;
@@ -59,2 +71,27 @@
 }
 /*}}}*/
+
+/*Covertree*/
+void Observation::print(void) const{/*{{{*/
+
+	_printf_("Observation\n");
+	_printf_("   x     : " << this->x << "\n");
+	_printf_("   y     : " << this->y << "\n");
+	_printf_("   value : " << this->value << "\n");
+}
+/*}}}*/
+double Observation::distance(const Observation& ob) const
+{
+	return std::sqrt( (std::pow( (ob.x - this->x), 2 ) + std::pow((ob.y - this->y), 2) ));
+}
+
+bool Observation::operator==(const Observation& ob) const
+{
+	return (ob.x == this->x && ob.y == this->y && ob.value == this->value);
+}
+
+void Observation::WriteXYObs(const Observation& ob, double* px, double* py, double* pobs){
+    *px   = ob.x;
+    *py   = ob.y;
+    *pobs = ob.value;
+}
Index: /issm/trunk/src/c/classes/kriging/Observation.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observation.h	(revision 19104)
+++ /issm/trunk/src/c/classes/kriging/Observation.h	(revision 19105)
@@ -20,14 +20,20 @@
 		Observation();
 		Observation(double x_in,double y_in,int xi_in,int yi_in,int index_in,double value_in);
+		Observation(double x_in,double y_in,double value_in);
 		~Observation();
 
 		/*Object virtual functions definitions*/
+		double  distance(const Observation& ob) const;
+
 		void    Echo();
+		void    print() const;
 		void    DeepEcho()  {_error_("Not implemented yet"); };
 		int     Id()        {_error_("Not implemented yet"); };
 		int     ObjectEnum(){_error_("Not implemented yet"); };
+		bool operator==(const Observation& ob) const;
 		Object *copy();
 
 		/*Management*/
+		void WriteXYObs(const Observation& ob, double* px, double* py, double* pobs);
 		void WriteXYObs(double* px,double* py,double* pobs);
 };
Index: /issm/trunk/src/c/classes/kriging/Observations.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 19105)
@@ -23,4 +23,5 @@
 
 #include "./Quadtree.h"
+#include "./Covertree.h"
 #include "./Variogram.h"
 #include "../../toolkits/toolkits.h"
@@ -31,9 +32,53 @@
 /*Object constructors and destructor*/
 Observations::Observations(){/*{{{*/
-	this->quadtree = NULL;
+	this->treetype  = 0;
+	this->quadtree  = NULL;
+	this->covertree = NULL;
 	return;
 }
 /*}}}*/
 Observations::Observations(IssmPDouble* observations_list,IssmPDouble* x,IssmPDouble* y,int n,Options* options){/*{{{*/
+
+	/*Check that there are observations*/
+	if(n<=0) _error_("No observation found");
+
+	/*Get tree type (FIXME)*/
+	IssmDouble dtree = 0.;
+	options->Get(&dtree,"treetype",1.);
+	this->treetype = reCast<int>(dtree);
+	switch(this->treetype){
+		case 1:
+			this->covertree = NULL;
+			this->InitQuadtree(observations_list,x,y,n,options);
+			break;
+		case 2:
+			this->quadtree = NULL;
+			this->InitCovertree(observations_list,x,y,n,options);
+			break;
+		default:
+			_error_("Tree type "<<this->treetype<<" not supported yet (1: quadtree, 2: covertree)");
+	}
+
+
+
+}
+/*}}}*/
+Observations::~Observations(){/*{{{*/
+	switch(this->treetype){
+		case 1:
+			delete this->quadtree;
+			break;
+		case 2:
+			delete this->covertree;
+			break;
+		default:
+			_error_("Tree type "<<this->treetype<<" not supported yet (1: quadtree, 2: covertree)");
+	}
+	return;
+}
+/*}}}*/
+
+/*Initialize data structures*/
+void Observations::InitQuadtree(IssmPDouble* observations_list,IssmPDouble* x,IssmPDouble* y,int n,Options* options){/*{{{*/
 
 	/*Intermediaries*/
@@ -44,6 +89,6 @@
 	Observation *observation = NULL;
 
-	/*Check that observations is not empty*/
-	if(n==0) _error_("No observation found");
+	/*Checks*/
+	_assert_(n);
 
 	/*Get extrema*/
@@ -89,5 +134,5 @@
 		this->quadtree->ClosestObs(&index,x[i],y[i]);
 		if(index>=0){
-			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(index));
+			observation=xDynamicCast<Observation*>(this->GetObjectByOffset(index));
 			if(pow(observation->x-x[i],2)+pow(observation->y-y[i],2) < minspacing) continue;
 		}
@@ -110,7 +155,14 @@
 }
 /*}}}*/
-Observations::~Observations(){/*{{{*/
-	delete quadtree;
-	return;
+void Observations::InitCovertree(IssmPDouble* observations_list,IssmPDouble* x,IssmPDouble* y,int n,Options* options){/*{{{*/
+
+    int maxdepth = 20;
+	 _printf0_("Generating covertree with a maximum depth " <<  maxdepth <<"... ");
+    this->covertree=new Covertree(maxdepth);
+
+    for(int i=0;i<n;i++){
+		 this->covertree->insert(Observation(x[i],y[i],observations_list[i]));
+    }
+	 _printf0_("done\n");
 }
 /*}}}*/
@@ -131,5 +183,5 @@
 	this->quadtree->ClosestObs(&index,x_interp,y_interp);
 	if(index>=0){
-		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(index));
+		observation=xDynamicCast<Observation*>(this->GetObjectByOffset(index));
 		hmin = sqrt((observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp));
 		if(hmin<radius) radius=hmin;
@@ -139,5 +191,5 @@
 	this->quadtree->RangeSearch(&indices,&nobs,x_interp,y_interp,radius);
 	for (i=0;i<nobs;i++){
-		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[i]));
+		observation=xDynamicCast<Observation*>(this->GetObjectByOffset(indices[i]));
 		h2 = (observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp);
 		if(i==0){
@@ -155,5 +207,5 @@
 	/*Assign output pointer*/
 	if(nobs || hmin==radius){
-		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(index));
+		observation=xDynamicCast<Observation*>(this->GetObjectByOffset(index));
 		*px   = observation->x;
 		*py   = observation->y;
@@ -183,4 +235,9 @@
 }/*}}}*/
 void Observations::ObservationList(IssmPDouble **px,IssmPDouble **py,IssmPDouble **pobs,int* pnobs,IssmPDouble x_interp,IssmPDouble y_interp,IssmPDouble radius,int maxdata){/*{{{*/
+
+	if(this->treetype==2){
+		this->ObservationList2(px,py,pobs,pnobs,x_interp,y_interp,radius,maxdata);
+		return;
+	}
 
 	/*Output and Intermediaries*/
@@ -210,5 +267,5 @@
 	nobs = 0;
 	for(i=0;i<tempnobs;i++){
-		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(tempindices[i]));
+		observation=xDynamicCast<Observation*>(this->GetObjectByOffset(tempindices[i]));
 		h2 = (observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp);
 
@@ -252,5 +309,5 @@
 		/*Loop over all observations and fill in x, y and obs*/
 		for(i=0;i<nobs;i++){
-			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[i]));
+			observation=xDynamicCast<Observation*>(this->GetObjectByOffset(indices[i]));
 			observation->WriteXYObs(&x[i],&y[i],&obs[i]);
 		}
@@ -280,5 +337,5 @@
 		obs = xNew<IssmPDouble>(nobs);
 		for(int i=0;i<this->Size();i++){
-			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(i));
+			observation=xDynamicCast<Observation*>(this->GetObjectByOffset(i));
 			observation->WriteXYObs(&x[i],&y[i],&obs[i]);
 		}
@@ -510,4 +567,5 @@
 void Observations::QuadtreeColoring(IssmPDouble* A,IssmPDouble *x,IssmPDouble *y,int n){/*{{{*/
 
+	if(this->treetype!=1) _error_("Tree type is not quadtree");
 	int xi,yi,level;
 
@@ -532,8 +590,8 @@
 
 	for(i=0;i<this->Size();i++){
-		observation1=dynamic_cast<Observation*>(this->GetObjectByOffset(i));
+		observation1=xDynamicCast<Observation*>(this->GetObjectByOffset(i));
 
 		for(j=i+1;j<this->Size();j++){
-			observation2=dynamic_cast<Observation*>(this->GetObjectByOffset(j));
+			observation2=xDynamicCast<Observation*>(this->GetObjectByOffset(j));
 
 			distance=sqrt(pow(observation1->x - observation2->x,2) + pow(observation1->y - observation2->y,2));
@@ -558,2 +616,47 @@
 	xDelete<IssmPDouble>(counter);
 }/*}}}*/
+
+void Observations::ObservationList2(double **px,double **py,double **pobs,int* pnobs,double x_interp,double y_interp,double radius,int maxdata){/*{{{*/
+    
+
+    double *x            = NULL;
+    double *y            = NULL;
+    double *obs          = NULL;
+    Observation observation=Observation(x_interp,y_interp,0.);
+    std::vector<Observation> kNN;
+
+	 kNN=(this->covertree->kNearestNeighbors(observation, maxdata));
+	 //cout << "kNN's size: " << kNN.size() << " (maxdata = " <<maxdata<<")"<<endl;
+	
+	//kNN is sort from closest to farthest neighbor
+	//searches for the first neighbor that is out of radius
+	//deletes and resizes the kNN vector
+	vector<Observation>::iterator it;
+	if(radius>0.){
+		for (it = kNN.begin(); it != kNN.end(); ++it) {
+			//(*it).print();
+			//cout << "\n" << (*it).distance(observation) << endl;
+			if ((*it).distance(observation) > radius) {
+				break;
+			}
+		}
+		kNN.erase(it, kNN.end());
+	}
+    
+	/*Allocate vectors*/
+	x   = new double[kNN.size()];
+	y   = new double[kNN.size()];
+	obs = new double[kNN.size()];
+
+	/*Loop over all observations and fill in x, y and obs*/
+	int i = 0;
+	for(it = kNN.begin(); it != kNN.end(); ++it) {
+		(*it).WriteXYObs((*it), &x[i], &y[i], &obs[i]);
+		i++;
+	}
+    
+    *px=x;
+    *py=y;
+    *pobs=obs;
+	 *pnobs = kNN.size();
+}/*}}}*/
Index: /issm/trunk/src/c/classes/kriging/Observations.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observations.h	(revision 19104)
+++ /issm/trunk/src/c/classes/kriging/Observations.h	(revision 19105)
@@ -3,4 +3,5 @@
 
 class Quadtree;
+class Covertree;
 class Variogram;
 class Options;
@@ -16,5 +17,7 @@
 
 	private:
-		Quadtree* quadtree;
+		int        treetype;
+		Quadtree*  quadtree;
+		Covertree* covertree;
 
 	public:
@@ -24,4 +27,8 @@
 		Observations(IssmDouble* observations_list,IssmDouble* x,IssmDouble* y,int n,Options* options);
 		~Observations();
+
+		/*Initialize data structures*/
+		void InitQuadtree(IssmDouble* observations_list,IssmDouble* x,IssmDouble* y,int n,Options* options);
+		void InitCovertree(IssmDouble* observations_list,IssmDouble* x,IssmDouble* y,int n,Options* options);
 
 		/*Methods*/
@@ -34,4 +41,5 @@
 		void ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs);
 		void ObservationList(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int maxdata);
+		void ObservationList2(IssmDouble **px,IssmDouble **py,IssmDouble **pobs,int* pnobs,IssmDouble x_interp,IssmDouble y_interp,IssmDouble radius,int maxdata);
 		void QuadtreeColoring(IssmDouble* A,IssmDouble *x,IssmDouble *y,int n);
 		void Variomap(IssmDouble* gamma,IssmDouble *x,int n);
Index: /issm/trunk/src/c/classes/kriging/krigingobjects.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/krigingobjects.h	(revision 19104)
+++ /issm/trunk/src/c/classes/kriging/krigingobjects.h	(revision 19105)
@@ -13,4 +13,5 @@
 #include "./PowerVariogram.h"
 #include "./Quadtree.h"
+#include "./Covertree.h"
 #include "./Observation.h"
 #include "./Observations.h"
Index: /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 19104)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 19105)
@@ -329,4 +329,37 @@
 }
 /*}}}*/
+void ElementMatrix::AddDiagonalToGlobal(Vector<IssmDouble>* pf){/*{{{*/
+
+	IssmDouble* localvalues=NULL;
+
+	/*Check that pf is not NULL*/
+	_assert_(pf); 
+
+	/*In debugging mode, check consistency (no NaN, and values not too big)*/
+	this->CheckConsistency();
+
+	if(this->dofsymmetrical){
+		/*only use row dofs to add values into global matrices: */
+
+		if(this->row_fsize){
+			/*first, retrieve values that are in the f-set from the g-set values matrix: */
+			localvalues=xNew<IssmDouble>(this->row_fsize);
+			for(int i=0;i<this->row_fsize;i++){
+				localvalues[i] = this->values[this->ncols*this->row_flocaldoflist[i]+ this->row_flocaldoflist[i]];
+			}
+
+			/*add local values into global  matrix, using the fglobaldoflist: */
+			pf->SetValues(this->row_fsize,this->row_fglobaldoflist,localvalues,ADD_VAL);
+
+			/*Free ressources:*/
+			xDelete<IssmDouble>(localvalues);
+		}
+	}
+	else{
+		_error_("non dofsymmetrical matrix AddToGlobal routine not support yet!");
+	}
+
+}
+/*}}}*/
 void ElementMatrix::CheckConsistency(void){/*{{{*/
 	/*Check element matrix values, only in debugging mode*/
@@ -339,4 +372,20 @@
 	}
 	#endif
+}
+/*}}}*/
+void ElementMatrix::Lump(void){/*{{{*/
+
+	if(!dofsymmetrical) _error_("not supported yet");
+
+	for(int i=0;i<this->nrows;i++){
+		for(int j=0;j<this->ncols;j++){
+			if(i!=j){
+				this->values[i*this->ncols+i] += this->values[i*this->ncols+j];
+				this->values[i*this->ncols+j]  = 0.;
+			}
+		}
+	}
+
+	return;
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/matrix/ElementMatrix.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 19104)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 19105)
@@ -60,7 +60,9 @@
 		void AddToGlobal(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
 		void AddToGlobal(Matrix<IssmDouble>* Jff);
+		void AddDiagonalToGlobal(Vector<IssmDouble>* pf);
 		void Echo(void);
 		void CheckConsistency(void);
 		void StaticCondensation(int numindices,int* indices);
+		void Lump(void);
 		void Transpose(void);
 		void Init(ElementMatrix* Ke);
Index: sm/trunk/src/c/cores/AnalysisConfiguration.cpp
===================================================================
--- /issm/trunk/src/c/cores/AnalysisConfiguration.cpp	(revision 19104)
+++ 	(revision )
@@ -1,159 +1,0 @@
-/*!\file:  AnalysisConfiguration.cpp
- * \brief: return type of analyses, number of analyses 
- */ 
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "./cores.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void AnalysisConfiguration(int** panalyses,int* pnumanalyses, int solutiontype){
-
-	/*output: */
-	int  numanalyses;
-	int* analyses=NULL;
-
-	/*Analyses lists*/
-	switch(solutiontype){
-
-		case StressbalanceSolutionEnum:
-			numanalyses=7;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=StressbalanceAnalysisEnum;
-			analyses[1]=StressbalanceVerticalAnalysisEnum;
-			analyses[2]=StressbalanceSIAAnalysisEnum;
-			analyses[3]=L2ProjectionBaseAnalysisEnum;
-			analyses[4]=ExtrudeFromBaseAnalysisEnum;
-			analyses[5]=DepthAverageAnalysisEnum;
-			analyses[6]=UzawaPressureAnalysisEnum;
-			break;
-
-		case SteadystateSolutionEnum:
-			numanalyses=7;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=StressbalanceAnalysisEnum;
-			analyses[1]=StressbalanceVerticalAnalysisEnum;
-			analyses[2]=StressbalanceSIAAnalysisEnum;
-			analyses[3]=L2ProjectionBaseAnalysisEnum;
-			analyses[4]=EnthalpyAnalysisEnum;
-			analyses[5]=ThermalAnalysisEnum;
-			analyses[6]=MeltingAnalysisEnum;
-			break;
-
-		case ThermalSolutionEnum:
-			numanalyses=3;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=ThermalAnalysisEnum;
-			analyses[1]=MeltingAnalysisEnum;
-			analyses[2]=EnthalpyAnalysisEnum;
-			break;
-
-		case HydrologySolutionEnum:
-			numanalyses=5;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=HydrologyShreveAnalysisEnum;
-			analyses[1]=HydrologyDCInefficientAnalysisEnum;
-			analyses[2]=HydrologyDCEfficientAnalysisEnum;
-			analyses[3]=L2ProjectionBaseAnalysisEnum;
-			analyses[4]=L2ProjectionEPLAnalysisEnum;
-			break;
-
-		case MasstransportSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=MasstransportAnalysisEnum;
-			break;
-
-		case BalancethicknessSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=BalancethicknessAnalysisEnum;
-			break;
-
-		case Balancethickness2SolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=Balancethickness2AnalysisEnum;
-			break;
-
-		case BalancethicknessSoftSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=BalancethicknessAnalysisEnum;
-			break;
-
-		case BalancevelocitySolutionEnum:
-			numanalyses=3;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=BalancevelocityAnalysisEnum;
-			analyses[1]=SmoothedSurfaceSlopeXAnalysisEnum;
-			analyses[2]=SmoothedSurfaceSlopeYAnalysisEnum;
-			break;
-
-		case SurfaceSlopeSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=L2ProjectionBaseAnalysisEnum;
-			break;
-
-		case BedSlopeSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=L2ProjectionBaseAnalysisEnum;
-			break;
-
-		case GiaSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=GiaAnalysisEnum;
-			break;
-		
-		case DamageEvolutionSolutionEnum:
-			numanalyses=1;
-			analyses=xNew<int>(numanalyses);
-			analyses[0]=DamageEvolutionAnalysisEnum;
-			break;
-
-		case TransientSolutionEnum:
-			numanalyses=20;
-			analyses=xNew<int>(numanalyses);
-			analyses[ 0]=StressbalanceAnalysisEnum;
-			analyses[ 1]=StressbalanceVerticalAnalysisEnum;
-			analyses[ 2]=StressbalanceSIAAnalysisEnum;
-			analyses[ 3]=L2ProjectionBaseAnalysisEnum;
-			analyses[ 4]=ThermalAnalysisEnum;
-			analyses[ 5]=MeltingAnalysisEnum;
-			analyses[ 6]=EnthalpyAnalysisEnum;
-			analyses[ 7]=MasstransportAnalysisEnum;
-			analyses[ 8]=FreeSurfaceBaseAnalysisEnum;
-			analyses[ 9]=FreeSurfaceTopAnalysisEnum;
-			analyses[10]=ExtrudeFromBaseAnalysisEnum;
-			analyses[11]=ExtrudeFromTopAnalysisEnum;
-			analyses[12]=LevelsetAnalysisEnum;
-			analyses[13]=ExtrapolationAnalysisEnum;
-			analyses[14]=LsfReinitializationAnalysisEnum;
-			analyses[15]=DamageEvolutionAnalysisEnum;
-			analyses[16]=HydrologyShreveAnalysisEnum;
-			analyses[17]=HydrologyDCInefficientAnalysisEnum;
-			analyses[18]=HydrologyDCEfficientAnalysisEnum;
-			analyses[19]=L2ProjectionEPLAnalysisEnum;
-			break;
-
-		default:
-			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
-			break;
-	}
-
-	/*Assign output pointers:*/
-	if(pnumanalyses) *pnumanalyses=numanalyses;
-	if(panalyses)    *panalyses=analyses;
-	else              xDelete<int>(analyses);
-}
Index: /issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/WrapperCorePointerFromSolutionEnum.cpp	(revision 19105)
@@ -47,4 +47,5 @@
 			case 2: solutioncore=controlm1qn3_core; break;
 			case 3: solutioncore=controlvalidation_core; break;
+			case 4: solutioncore=controlad_core; break;
 			default: _error_("control type not supported");
 		}
Index: /issm/trunk/src/c/cores/ad_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/ad_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/ad_core.cpp	(revision 19105)
@@ -28,5 +28,5 @@
 	bool    isautodiff       = false;
 	char   *driver           = NULL;
-	size_t  tape_stats[11];
+	size_t  tape_stats[15];
 
 	/*state variables: */
@@ -45,20 +45,8 @@
 			/*First, stop tracing: */
 			trace_off();
-		
-			/*retrieve parameters: */
-			femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
-			femmodel->parameters->FindParam(&num_independents,AutodiffNumIndependentsEnum);
-	
-			/*if no dependents, no point in running a driver: */
-			if(!(num_dependents*num_independents)) return;
-
-			/*for adolc to run in parallel, we 0 out on rank~=0:*/
-			if (my_rank!=0){
-				num_dependents=0; num_independents=0;
-			}
 			
 			/*Print tape statistics so that user can kill this run if something is off already:*/
-			tapestats(my_rank,tape_stats); //reading of tape statistics
-			if(VerboseAutodiff()){
+			if(VerboseAutodiff()){ /*{{{*/
+				tapestats(my_rank,tape_stats); //reading of tape statistics
 				int commSize=IssmComm::GetSize();
 				int *sstats=new int[7];
@@ -99,6 +87,18 @@
 				}
 				delete [] sstats;
+			} /*}}}*/
+
+			/*retrieve parameters: */
+			femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
+			femmodel->parameters->FindParam(&num_independents,AutodiffNumIndependentsEnum);
+	
+			/*if no dependents, no point in running a driver: */
+			if(!(num_dependents*num_independents)) return;
+
+			/*for adolc to run in parallel, we 0 out on rank~=0:*/
+			if (my_rank!=0){
+				num_dependents=0; num_independents=0;
 			}
-
+			
 			/*retrieve state variable: */
 			femmodel->parameters->FindParam(&axp,&dummy,AutodiffXpEnum);
@@ -111,5 +111,5 @@
 
 			/*get the EDF pointer:*/
-			ext_diff_fct *anEDF_for_solverx_p=dynamic_cast<GenericParam<Adolc_edf> * >(femmodel->parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p;
+			ext_diff_fct *anEDF_for_solverx_p=xDynamicCast<GenericParam<Adolc_edf> * >(femmodel->parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p;
 
 			/*Branch according to AD driver: */
@@ -258,5 +258,4 @@
 				/*call driver: */
 				fos_reverse(my_rank,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
-				if(VerboseAutodiff())_printf0_("   done with fos_reverse\n");
 
 				/*add to results*/
Index: /issm/trunk/src/c/cores/adgradient_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/adgradient_core.cpp	(revision 19105)
+++ /issm/trunk/src/c/cores/adgradient_core.cpp	(revision 19105)
@@ -0,0 +1,188 @@
+/*!\file adgradient_core
+ * \brief: compute gradient for all scalar depenendents, then sum them up as output. This relies mainly on the fos_reverse 
+ * driver, hence the incapacity to merge this with ad_core.cpp.
+ */
+
+/*Includes: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <set>
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+/*}}}*/
+
+void adgradient_core(FemModel* femmodel){
+
+	/*diverse: */
+	int     i;
+	int     dummy;
+	int     num_dependents=0;
+	int     num_dependents_old=0;
+	int     num_independents=0;
+	bool    isautodiff       = false;
+	int     aDepIndex=0;
+	int     my_rank=IssmComm::GetRank();
+
+	/*state variables: */
+	IssmDouble *axp = NULL;
+	IssmPDouble     *xp  = NULL;
+
+	/*intermediary: */
+	IssmPDouble *aWeightVector=NULL;
+	IssmPDouble *weightVectorTimesJac=NULL;
+	
+	/*output: */
+	IssmPDouble *totalgradient=NULL;
+
+	/*AD mode on?: */
+	femmodel->parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+
+	if(isautodiff){
+
+		#ifdef _HAVE_ADOLC_
+			if(VerboseAutodiff())_printf0_("   start ad core\n"); 
+
+			/*First, stop tracing: */
+			trace_off();
+			
+			if(VerboseAutodiff()){ /*{{{*/
+				size_t  tape_stats[15];
+				tapestats(my_rank,tape_stats); //reading of tape statistics
+				int commSize=IssmComm::GetSize();
+				int *sstats=new int[7];
+				sstats[0]=tape_stats[NUM_OPERATIONS];
+				sstats[1]=tape_stats[OP_FILE_ACCESS];
+				sstats[2]=tape_stats[NUM_LOCATIONS];
+				sstats[3]=tape_stats[LOC_FILE_ACCESS];
+				sstats[4]=tape_stats[NUM_VALUES];
+				sstats[5]=tape_stats[VAL_FILE_ACCESS];
+				sstats[6]=tape_stats[TAY_STACK_SIZE];
+				int *rstats=NULL;
+				if (my_rank==0) rstats=new int[commSize*7];
+				ISSM_MPI_Gather(sstats,7,ISSM_MPI_INT,rstats,7,ISSM_MPI_INT,0,IssmComm::GetComm());
+				if (my_rank==0) {
+					int offset=50;
+					int rOffset=(commSize/10)+1;
+					_printf_("   ADOLC statistics: \n");
+					_printf_("     "<<setw(offset)<<left<<"#independents: " <<setw(12)<<right<<tape_stats[NUM_INDEPENDENTS] << "\n");
+					_printf_("     "<<setw(offset)<<left<<"#dependents: " <<setw(12)<<right<<tape_stats[NUM_DEPENDENTS] << "\n");
+					_printf_("     "<<setw(offset)<<left<<"max #live active variables: " <<setw(12)<<right<<tape_stats[NUM_MAX_LIVES] << "\n");
+					_printf_("     operations: entry size "<< sizeof(unsigned char) << " Bytes \n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffObufsizeEnum) " <<setw(12)<<right<<tape_stats[OP_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+0] << (rstats[r*7+1]?" ->file":"") << "\n");
+					_printf_("     locations: entry size " << sizeof(locint) << " Bytes\n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffLbufsizeEnum) " <<setw(12)<<right<<tape_stats[LOC_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+2] << (rstats[r*7+3]?" ->file":"") << "\n");
+					_printf_("     constant values: entry size " << sizeof(double) << " Bytes\n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffCbufsizeEnum) " <<setw(12)<<right<<tape_stats[VAL_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+4] << (rstats[r*7+5]?" ->file":"") << "\n");
+					_printf_("     Taylor stack: entry size " << sizeof(revreal) << " Bytes\n");
+					_printf_("     "<<setw(offset)<<left<<"  #entries in buffer (AutodiffTbufsizeEnum) " <<setw(12)<<right<<tape_stats[TAY_BUFFER_SIZE] << "\n");
+					for (int r=0;r<commSize;++r)
+					_printf_("       ["<<setw(rOffset)<<right<<r<<"]"<<setw(offset-rOffset-4)<<left<<" #entries total" <<setw(12)<<right<<rstats[r*7+6] << (rstats[r*7+6]>tape_stats[TAY_BUFFER_SIZE]?" ->file":"") << "\n");
+					delete []rstats;
+			}
+			delete [] sstats;
+		} /*}}}*/
+		
+			/*retrieve parameters: */
+			femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
+			femmodel->parameters->FindParam(&num_independents,AutodiffNumIndependentsEnum);
+			
+			/*if no dependents, no point in running a driver: */
+			if(!(num_dependents*num_independents)) return;
+
+			/*for adolc to run in parallel, we 0 out on rank~=0. But we still keep track of num_dependents:*/
+			num_dependents_old=num_dependents;
+			if (my_rank!=0){
+				num_dependents=0; num_independents=0;
+			}
+			
+			/*retrieve state variable: */
+			femmodel->parameters->FindParam(&axp,&dummy,AutodiffXpEnum);
+			
+			/* driver argument */
+			xp=xNew<double>(num_independents);
+			for(i=0;i<num_independents;i++){
+				xp[i]=reCast<double,IssmDouble>(axp[i]);
+			}
+
+			/*get the EDF pointer:*/
+			ext_diff_fct *anEDF_for_solverx_p=xDynamicCast<GenericParam<Adolc_edf> * >(femmodel->parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p;
+
+			/* these are always needed regardless of the interpreter */
+			anEDF_for_solverx_p->dp_x=xNew<double>(anEDF_for_solverx_p->max_n);
+			anEDF_for_solverx_p->dp_y=xNew<double>(anEDF_for_solverx_p->max_m);
+
+			/* Ok, now we are going to call the fos_reverse in a loop on the index, from 0 to num_dependents, so 
+			 * as to generate num_dependents gradients: */
+
+			/*Initialize outputs: */
+			totalgradient=xNewZeroInit<IssmPDouble>(num_independents);
+			
+			for(aDepIndex=0;aDepIndex<num_dependents_old;aDepIndex++){
+
+				/*initialize direction index in the weights vector: */
+				aWeightVector=xNewZeroInit<IssmPDouble>(num_dependents);
+				if (my_rank==0) aWeightVector[aDepIndex]=1.0;
+				
+				/*initialize output gradient: */
+				weightVectorTimesJac=xNew<IssmPDouble>(num_independents);
+
+				/*set the forward method function pointer: */
+				#ifdef _HAVE_GSL_
+				anEDF_for_solverx_p->fos_reverse=EDF_fos_reverse_for_solverx;
+				#endif
+				#ifdef _HAVE_MUMPS_
+				anEDF_for_solverx_p->fos_reverse_iArr=fos_reverse_mumpsSolveEDF;
+				#endif
+
+				anEDF_for_solverx_p->dp_U=xNew<IssmPDouble>(anEDF_for_solverx_p->max_m);
+				anEDF_for_solverx_p->dp_Z=xNew<IssmPDouble>(anEDF_for_solverx_p->max_n);
+
+				/*call driver: */
+				fos_reverse(my_rank,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
+
+				/*Add to totalgradient: */
+				if(my_rank==0)for(i=0;i<num_independents;i++)totalgradient[i]+=weightVectorTimesJac[i];
+
+				/*free resources :*/
+				xDelete(weightVectorTimesJac);
+				xDelete(aWeightVector);
+			}
+		
+			/*add totalgradient to results*/
+			femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,totalgradient,num_independents,1,1,0.0));
+
+			if(VerboseAutodiff())_printf0_("   end ad core\n");
+			
+			/* delete the allocated space for the parameters and free ressources:{{{*/
+			xDelete(anEDF_for_solverx_p->dp_x);
+			xDelete(anEDF_for_solverx_p->dp_X);
+			xDelete(anEDF_for_solverx_p->dpp_X);
+			xDelete(anEDF_for_solverx_p->dp_y);
+			xDelete(anEDF_for_solverx_p->dp_Y);
+			xDelete(anEDF_for_solverx_p->dpp_Y);
+			xDelete(anEDF_for_solverx_p->dp_U);
+			xDelete(anEDF_for_solverx_p->dpp_U);
+			xDelete(anEDF_for_solverx_p->dp_Z);
+			xDelete(anEDF_for_solverx_p->dpp_Z);
+			xDelete(xp);
+			xDelete(totalgradient);
+			xDelete(axp); /*}}}*/
+		#else
+			_error_("Should not be requesting AD drivers when an AD library is not available!");
+		#endif
+	}
+}
Index: /issm/trunk/src/c/cores/adjointstressbalance_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/adjointstressbalance_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/adjointstressbalance_core.cpp	(revision 19105)
@@ -16,13 +16,26 @@
 	bool save_results;
 	bool conserve_loads   = true;
+	int fe_FS;
 
 	/*retrieve parameters:*/
 	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&fe_FS,FlowequationFeFSEnum);
 
 	/*Compute velocities*/
 	if(VerboseSolution()) _printf0_("   computing velocities\n");
 	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
-	solutionsequence_nonlinear(femmodel,conserve_loads); 
+
+	if(VerboseSolution()) _printf0_("   computing velocities\n");
+	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+	if(isFS){
+		if (fe_FS==LATaylorHoodEnum || fe_FS==LACrouzeixRaviartEnum)
+		 solutionsequence_la(femmodel);
+		else
+		 solutionsequence_nonlinear(femmodel,conserve_loads); 
+	}
+	else{
+		solutionsequence_nonlinear(femmodel,conserve_loads); 
+	}
 
 	/*Call SurfaceAreax, because some it might be needed by PVector*/
@@ -37,9 +50,13 @@
 	if(save_results || true){
 		if(VerboseSolution()) _printf0_("   saving results\n");
-		if (isFS){
-			//int outputs[4] = {AdjointxEnum,AdjointyEnum,AdjointzEnum,AdjointpEnum};
-			//femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],4);
-			int outputs[3] = {AdjointxEnum,AdjointyEnum,AdjointpEnum};
-			femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
+		if(isFS){
+			if(fe_FS==LATaylorHoodEnum || fe_FS==LACrouzeixRaviartEnum){
+				int outputs[2] = {AdjointxEnum,AdjointyEnum};
+				femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],2);
+			}
+			else{
+				int outputs[3] = {AdjointxEnum,AdjointyEnum,AdjointpEnum};
+				femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
+			}
 		}
 		else{
Index: /issm/trunk/src/c/cores/balancethickness2_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/balancethickness2_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/balancethickness2_core.cpp	(revision 19105)
@@ -13,19 +13,31 @@
 
 	/*parameters: */
-	bool save_results;
-
-	/*activate formulation: */
-	femmodel->SetCurrentConfiguration(Balancethickness2AnalysisEnum);
+	bool        save_results;
+	IssmDouble  l = 3.;
 
 	/*recover parameters: */
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
 
+	if(VerboseSolution()) _printf0_("computing smooth surface slopes:\n");
+	//femmodel->parameters->SetParam(l,SmoothThicknessMultiplierEnum);
+	//femmodel->SetCurrentConfiguration(SmoothAnalysisEnum);
+	//femmodel->parameters->SetParam(SurfaceSlopeXEnum,InputToSmoothEnum);
+	//solutionsequence_linear(femmodel);
+	//femmodel->parameters->SetParam(SurfaceSlopeYEnum,InputToSmoothEnum);
+	//solutionsequence_linear(femmodel);
+	surfaceslope_core(femmodel);
+
 	if(VerboseSolution()) _printf0_("call computational core:\n");
+	femmodel->SetCurrentConfiguration(Balancethickness2AnalysisEnum);
 	solutionsequence_linear(femmodel);
+	//solutionsequence_nonlinear(femmodel,false);
 
 	if(save_results){
 		if(VerboseSolution()) _printf0_("   saving results\n");
-		int outputs[4] = {ThicknessEnum,PotentialEnum,VxEnum,VyEnum};
-		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],4);
+		const int numoutputs = 6;
+		int outputs[numoutputs] = {SurfaceEnum,SurfaceSlopeXEnum,SurfaceSlopeYEnum,VxEnum,VyEnum,VelEnum};
+		//const int numoutputs = 4;
+		//int outputs[numoutputs] = {SurfaceEnum,VxEnum,VyEnum,VelEnum};
+		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],numoutputs);
 	}
 
Index: /issm/trunk/src/c/cores/balancevelocity_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/balancevelocity_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/balancevelocity_core.cpp	(revision 19105)
@@ -13,15 +13,17 @@
 
 	/*parameters: */
-	bool save_results;
+	bool        save_results;
+	IssmDouble  l = 8.;
 
 	/*recover parameters: */
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
 
-	if(VerboseSolution()) _printf0_("computing smoothed slopes:\n");
-	femmodel->SetCurrentConfiguration(SmoothedSurfaceSlopeXAnalysisEnum);
+	if(VerboseSolution()) _printf0_("computing smooth driving stress:\n");
+	femmodel->parameters->SetParam(l,SmoothThicknessMultiplierEnum);
+	femmodel->SetCurrentConfiguration(SmoothAnalysisEnum);
+	femmodel->parameters->SetParam(DrivingStressXEnum,InputToSmoothEnum);
 	solutionsequence_linear(femmodel);
-	femmodel->SetCurrentConfiguration(SmoothedSurfaceSlopeYAnalysisEnum);
+	femmodel->parameters->SetParam(DrivingStressYEnum,InputToSmoothEnum);
 	solutionsequence_linear(femmodel);
-	//surfaceslope_core(femmodel);
 
 	if(VerboseSolution()) _printf0_("call computational core:\n");
@@ -31,5 +33,5 @@
 	if(save_results){
 		if(VerboseSolution()) _printf0_("   saving results\n");
-		int outputs[3] = {SurfaceSlopeXEnum,SurfaceSlopeYEnum,VelEnum};
+		int outputs[3] = {DrivingStressXEnum,DrivingStressYEnum,VelEnum};
 		femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
 	}
Index: /issm/trunk/src/c/cores/controlad_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/controlad_core.cpp	(revision 19105)
+++ /issm/trunk/src/c/cores/controlad_core.cpp	(revision 19105)
@@ -0,0 +1,327 @@
+/*!\file: controlad_core.cpp
+ * \brief: core of the ad control solution 
+ */ 
+
+#include <config.h>
+#include "./cores.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+#if defined (_HAVE_M1QN3_)  & defined (_HAVE_ADOLC_)
+/*m1qn3 prototypes {{{*/
+extern "C" void *ctonbe_; // DIS mode : Conversion
+extern "C" void *ctcabe_; // DIS mode : Conversion
+extern "C" void *euclid_; // Scalar product
+typedef void (*SimulFunc) (long* indic,long* n, double* x, double* pf,double* g,long [],float [],void* dzs);
+extern "C" void m1qn3_ (void f(long* indic,long* n, double* x, double* pf,double* g,long [],float [],void* dzs),
+			void **, void **, void **,
+			long *, double [], double *, double [], double*, double *,
+			double *, char [], long *, long *, long *, long *, long *, long *, long [], double [], long *,
+			long *, long *, long [], float [],void* );
+
+/*Cost function prototype*/
+void simulad(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs);
+FemModel* presimulad(int* pintn, double** pX, FemModel* femmodel);
+void postsimulad(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs);
+/*}}}*/
+void controlad_core(FemModel* femmodel){ /*{{{*/
+
+	/*Intermediaries*/
+	FemModel*    femmodelad=NULL;
+	int          i;
+	long         omode;
+	IssmPDouble  f,dxmin,gttol;
+	IssmDouble   dxmind,gttold; 
+	int          maxsteps,maxiter;
+	int          intn,solution_type;
+	IssmPDouble  *X  = NULL;
+	IssmDouble   *Xd  = NULL;
+	IssmPDouble  *G  = NULL;
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&maxsteps,InversionMaxstepsEnum);
+	femmodel->parameters->FindParam(&maxiter,InversionMaxiterEnum);
+	femmodel->parameters->FindParam(&dxmind,InversionDxminEnum); dxmin=reCast<IssmPDouble>(dxmind);
+	femmodel->parameters->FindParam(&gttold,InversionGttolEnum); gttol=reCast<IssmPDouble>(gttold);
+	femmodel->parameters->SetParam(false,SaveResultsEnum);
+
+	/*Initialize M1QN3 parameters*/
+	if(VerboseControl())_printf0_("   Initialize M1QN3 parameters\n");
+	SimulFunc costfuncion  = &simulad;  /*Cost function address*/
+	void**    prosca       = &euclid_;  /*Dot product function (euclid is the default)*/
+	char      normtype[]   = "dfn";     /*Norm type: dfn = scalar product defined by prosca*/
+	long      izs[5];                   /*Arrays used by m1qn3 subroutines*/
+	long      iz[5];                    /*Integer m1qn3 working array of size 5*/
+	float     rzs[1];                   /*Arrays used by m1qn3 subroutines*/
+	long      impres       = 0;         /*verbosity level*/
+	long      imode[3]     = {0};       /*scaling and starting mode, 0 by default*/
+	long      indic        = 4;         /*compute f and g*/
+	long      reverse      = 0;         /*reverse or direct mode*/
+	long      io           = 6;         /*Channel number for the output*/
+
+	/*Optimization criterions*/
+	long niter = long(maxsteps); /*Maximum number of iterations*/
+	long nsim  = long(maxiter);/*Maximum number of function calls*/
+
+	/*Run the first part of simulad, in order to get things started!:*/
+	femmodelad=presimulad(&intn,&X,femmodel);
+
+	/*Get problem dimension and initialize gradient: */
+	long n = long(intn);
+	G = xNew<IssmPDouble>(n);
+
+	/*Allocate m1qn3 working arrays (see doc)*/
+	long      m   = 100;
+	long      ndz = 4*n+m*(2*n+1);
+	double*   dz  = xNew<double>(ndz);
+
+	if(VerboseControl())_printf0_("   Computing initial solution\n");
+	_printf0_("\n");
+	_printf0_("Cost function f(x)   | Gradient norm |g(x)| |  List of contributions\n");
+	_printf0_("____________________________________________________________________\n");
+
+	//run post simular phase, to fire up the control optimization
+	postsimulad(&indic,&n,X,&f,G,izs,rzs,(void*)femmodelad); 
+	double f1=f;
+
+	m1qn3_(costfuncion,prosca,&ctonbe_,&ctcabe_,
+				&n,X,&f,G,&dxmin,&f1,
+				&gttol,normtype,&impres,&io,imode,&omode,&niter,&nsim,iz,dz,&ndz,
+				&reverse,&indic,izs,rzs,(void*)femmodel);
+
+	switch(int(omode)){
+		case 0:  _printf0_("   Stop requested (indic = 0)\n"); break;
+		case 1:  _printf0_("   Convergence reached (gradient satisfies stopping criterion)\n"); break;
+		case 2:  _printf0_("   Bad initialization\n"); break;
+		case 3:  _printf0_("   Line search failure\n"); break;
+		case 4:  _printf0_("   Maximum number of iterations exceeded\n");break;
+		case 5:  _printf0_("   Maximum number of function calls exceeded\n"); break;
+		case 6:  _printf0_("   stopped on dxmin during line search\n"); break;
+		case 7:  _printf0_("   <g,d> > 0  or  <y,s> <0\n"); break;
+		default: _printf0_("   Unknown end condition\n");
+	}
+	
+	/*Save results:*/
+	femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,G,n,1,1,0.0));
+	femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffXpEnum,X,intn,1,1,0.0));
+
+	/*Clean-up and return*/
+	xDelete<double>(G);
+	xDelete<double>(X);
+	xDelete<double>(dz);
+}/*}}}*/
+FemModel* presimulad(int* pintn, double** pX, FemModel* femmodel){ /*{{{*/
+
+	/*Intermediaries:*/
+	char* rootpath=NULL;
+	char* inputfilename=NULL;
+	char* outputfilename=NULL;
+	char* toolkitsfilename=NULL;
+	char* lockfilename=NULL;
+	int         solution_type;
+	IssmDouble    pfd;
+	IssmDouble*   Xd=NULL;
+	int           intn;
+	IssmPDouble*   X=NULL;
+	int            i;
+	
+	/*Now things get complicated. The femmodel we recovered did not initialize an AD trace, so we can't compute gradients with it. We are going to recreate 
+	 *a new femmodel, identical in all aspects to the first one, with trace on though, which will allow us to run the forward mode and get the gradient 
+	 in one run of the solution core. So first recover the filenames required for the FemModel constructor, then call a new ad tailored constructor:*/
+	femmodel->parameters->FindParam(&rootpath,RootPathEnum);
+	femmodel->parameters->FindParam(&inputfilename,InputFileNameEnum);
+	femmodel->parameters->FindParam(&outputfilename,OutputFileNameEnum);
+	femmodel->parameters->FindParam(&toolkitsfilename,ToolkitsFileNameEnum);
+	femmodel->parameters->FindParam(&lockfilename,LockFileNameEnum);
+
+	femmodel=new FemModel(rootpath, inputfilename, outputfilename, toolkitsfilename, lockfilename, femmodel->comm, femmodel->solution_type,NULL);
+
+	
+	/*Get initial guess:*/
+	femmodel->parameters->FindParam(&Xd,&intn,AutodiffXpEnum);
+	X=xNew<IssmPDouble>(intn); for(i=0;i<intn;i++) X[i]=reCast<IssmPDouble>(Xd[i]); 
+
+	xDelete<char>(rootpath);
+	xDelete<char>(inputfilename);
+	xDelete<char>(outputfilename);
+	xDelete<char>(toolkitsfilename);
+	xDelete<char>(lockfilename);
+	xDelete<IssmDouble>(Xd);
+
+	*pintn=intn;
+	*pX=X;
+
+	return femmodel;
+
+} /*}}}*/
+void postsimulad(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs){ /*{{{*/
+
+	/*Intermediaries:*/
+	char* rootpath=NULL;
+	char* inputfilename=NULL;
+	char* outputfilename=NULL;
+	char* toolkitsfilename=NULL;
+	char* lockfilename=NULL;
+	IssmPDouble* G2=NULL;
+	int         solution_type;
+	FemModel   *femmodel  =  NULL;
+	IssmDouble    pfd;
+	int            i;
+	
+	/*Recover Femmodel*/
+	femmodel  = (FemModel*)dzs;
+
+	/*Recover number of cost functions responses*/
+	int num_responses;
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	/*Compute solution:*/
+	void (*solutioncore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	solutioncore(femmodel);
+
+	/*Compute objective function*/
+	IssmDouble* Jlist = NULL;
+	femmodel->CostFunctionx(&pfd,&Jlist,NULL); *pf=reCast<IssmPDouble>(pfd);
+	_printf0_("f(x) = "<<setw(12)<<setprecision(7)<<*pf<<"  |  ");
+	
+	/*Compute gradient using AD. Gradient is in the results after the ad_core is called*/
+	adgradient_core(femmodel); 
+
+	if(IssmComm::GetRank()==0){
+		IssmPDouble* G_temp=NULL;
+		GenericExternalResult<IssmPDouble*>* gradient=(GenericExternalResult<IssmPDouble*>*)femmodel->results->FindResult(AutodiffJacobianEnum); _assert_(gradient);
+		G_temp=gradient->GetValues();
+		/*copy onto G2, to avoid a leak: */
+		G2=xNew<IssmPDouble>(*n); 
+		xMemCpy<IssmPDouble>(G2,G_temp,*n);
+	}
+	else G2=xNew<IssmPDouble>(*n);
+
+	/*MPI broadcast results:*/
+	ISSM_MPI_Bcast(G2,*n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+	
+	/*Send gradient to m1qn3 core: */
+	for(long i=0;i<*n;i++) G[i] = G2[i];
+	
+	/*Constrain X and G*/
+	IssmDouble  Gnorm = 0.;
+	for(long i=0;i<*n;i++) Gnorm += G[i]*G[i];
+	Gnorm = sqrt(Gnorm);
+
+	/*Print info*/
+	_printf0_("       "<<setw(12)<<setprecision(7)<<Gnorm<<" |");
+	for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[i]);
+	_printf0_("\n");
+
+	/*Clean-up and return*/
+	xDelete<IssmDouble>(Jlist);
+	xDelete<IssmPDouble>(G2);
+	
+	xDelete<char>(rootpath);
+	xDelete<char>(inputfilename);
+	xDelete<char>(outputfilename);
+	xDelete<char>(toolkitsfilename);
+	xDelete<char>(lockfilename);
+
+} /*}}}*/
+void simulad(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs){ /*{{{*/
+
+	/*Intermediaries:*/
+	char* rootpath=NULL;
+	char* inputfilename=NULL;
+	char* outputfilename=NULL;
+	char* toolkitsfilename=NULL;
+	char* lockfilename=NULL;
+	IssmPDouble* G2=NULL;
+	int         solution_type;
+	FemModel   *femmodel  =  NULL;
+	FemModel   *femmodelad  = NULL;
+	IssmDouble    pfd;
+	int            i;
+	
+	/*Recover Femmodel*/
+	femmodel  = (FemModel*)dzs;
+
+	/*Recover number of cost functions responses*/
+	int num_responses;
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+
+	/*Now things get complicated. The femmodel we recovered did not initialize an AD trace, so we can't compute gradients with it. We are going to recreate 
+	 *a new femmodel, identical in all aspects to the first one, with trace on though, which will allow us to run the forward mode and get the gradient 
+	 in one run of the solution core. So first recover the filenames required for the FemModel constructor, then call a new ad tailored constructor:*/
+	femmodel->parameters->FindParam(&rootpath,RootPathEnum);
+	femmodel->parameters->FindParam(&inputfilename,InputFileNameEnum);
+	femmodel->parameters->FindParam(&outputfilename,OutputFileNameEnum);
+	femmodel->parameters->FindParam(&toolkitsfilename,ToolkitsFileNameEnum);
+	femmodel->parameters->FindParam(&lockfilename,LockFileNameEnum);
+
+	femmodelad=new FemModel(rootpath, inputfilename, outputfilename, toolkitsfilename, lockfilename, femmodel->comm, femmodel->solution_type,X);
+	femmodel=femmodelad; //We can do this, because femmodel is being called from outside, not by reference, so we won't erase it
+	
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	/*Compute solution:*/
+	void (*solutioncore)(FemModel*)=NULL;
+	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
+	solutioncore(femmodel);
+
+	/*Compute objective function*/
+	IssmDouble* Jlist = NULL;
+	femmodel->CostFunctionx(&pfd,&Jlist,NULL); *pf=reCast<IssmPDouble>(pfd);
+	_printf0_("f(x) = "<<setw(12)<<setprecision(7)<<*pf<<"  |  ");
+	
+	/*Compute gradient using AD. Gradient is in the results after the ad_core is called*/
+	adgradient_core(femmodel); 
+
+	if(IssmComm::GetRank()==0){
+		IssmPDouble* G_temp=NULL;
+		GenericExternalResult<IssmPDouble*>* gradient=(GenericExternalResult<IssmPDouble*>*)femmodel->results->FindResult(AutodiffJacobianEnum); _assert_(gradient);
+		G_temp=gradient->GetValues();
+		/*copy onto G2, to avoid a leak: */
+		G2=xNew<IssmPDouble>(*n); 
+		xMemCpy<IssmPDouble>(G2,G_temp,*n);
+	}
+	else G2=xNew<IssmPDouble>(*n);
+
+	/*MPI broadcast results:*/
+	ISSM_MPI_Bcast(G2,*n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+	
+	/*Send gradient to m1qn3 core: */
+	for(long i=0;i<*n;i++) G[i] = G2[i];
+	
+	/*Recover Gnorm: */
+	IssmDouble  Gnorm = 0.;
+	for(int i=0;i<*n;i++) Gnorm += G[i]*G[i];
+	Gnorm = sqrt(Gnorm);
+
+	/*Print info*/
+	_printf0_("       "<<setw(12)<<setprecision(7)<<Gnorm<<" |");
+	for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[i]);
+	_printf0_("\n");
+
+	/*Clean-up and return*/
+	xDelete<IssmDouble>(Jlist);
+	xDelete<IssmPDouble>(G2);
+	
+	xDelete<char>(rootpath);
+	xDelete<char>(inputfilename);
+	xDelete<char>(outputfilename);
+	xDelete<char>(toolkitsfilename);
+	xDelete<char>(lockfilename);
+	if(femmodelad)delete femmodelad;
+
+} /*}}}*/
+#else
+void controlad_core(FemModel* femmodel){ /*{{{*/
+	_error_("AD and/or M1QN3 not installed");
+}/*}}}*/
+#endif //_HAVE_M1QN3_
Index: /issm/trunk/src/c/cores/controlm1qn3_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/controlm1qn3_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/controlm1qn3_core.cpp	(revision 19105)
@@ -11,5 +11,5 @@
 #include "../solutionsequences/solutionsequences.h"
 
-#if defined (_HAVE_M1QN3_)
+#if defined (_HAVE_M1QN3_) & !defined(_HAVE_ADOLC_)
 /*m1qn3 prototypes*/
 extern "C" void *ctonbe_; // DIS mode : Conversion
@@ -32,5 +32,6 @@
 	double       f,dxmin,gttol; 
 	int          maxsteps,maxiter;
-	int          intn,num_controls,solution_type;
+	int          intn,numberofvertices,num_controls,solution_type;
+	IssmDouble  *scaling_factors = NULL;
 	IssmDouble  *X  = NULL;
 	IssmDouble  *G  = NULL;
@@ -43,5 +44,7 @@
 	femmodel->parameters->FindParam(&dxmin,InversionDxminEnum);
 	femmodel->parameters->FindParam(&gttol,InversionGttolEnum);
+	femmodel->parameters->FindParam(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
 	femmodel->parameters->SetParam(false,SaveResultsEnum);
+	numberofvertices=femmodel->vertices->NumberOfVertices();
 
 	/*Initialize M1QN3 parameters*/
@@ -60,6 +63,6 @@
 
 	/*Optimization criterions*/
-	long      niter        = long(maxsteps); /*Maximum number of iterations*/
-	long      nsim         = long(maxiter);/*Maximum number of function calls*/
+	long niter = long(maxsteps); /*Maximum number of iterations*/
+	long nsim  = long(maxiter);/*Maximum number of function calls*/
 
 	/*Get initial guess*/
@@ -69,8 +72,17 @@
 	Xpetsc->GetSize(&intn);
 	delete Xpetsc;
+	_assert_(intn==numberofvertices*num_controls);
 
 	/*Get problem dimension and initialize gradient and initial guess*/
 	long n = long(intn);
 	G = xNew<double>(n);
+
+	/*Scale control for M1QN3*/
+	for(int i=0;i<numberofvertices;i++){
+		for(int c=0;c<num_controls;c++){
+			int index = num_controls*i+c;
+			X[index] = X[index]/scaling_factors[c];
+		}
+	}
 
 	/*Allocate m1qn3 working arrays (see doc)*/
@@ -81,13 +93,17 @@
 	if(VerboseControl())_printf0_("   Computing initial solution\n");
 	_printf0_("\n");
-	_printf0_("Cost function f(x)   |  List of contributions\n");
-	_printf0_("_____________________________________________\n");
-	indic = 0; //no adjoint required
+	_printf0_("Cost function f(x)   | Gradient norm |g(x)| |  List of contributions\n");
+	_printf0_("____________________________________________________________________\n");
+
+	/*Initialize Gradient and cost function of M1QN3*/
+	indic = 4; //adjoint and gradient required
 	simul(&indic,&n,X,&f,G,izs,rzs,(void*)femmodel);
-	double f1=f;
-
-	indic = 4; //adjoint and gradient required
+
+	/*Estimation of the expected decrease in f during the first iteration*/
+	double df1=f;
+
+	/*Call M1QN3 solver*/
 	m1qn3_(costfuncion,prosca,&ctonbe_,&ctcabe_,
-				&n,X,&f,G,&dxmin,&f1,
+				&n,X,&f,G,&dxmin,&df1,
 				&gttol,normtype,&impres,&io,imode,&omode,&niter,&nsim,iz,dz,&ndz,
 				&reverse,&indic,izs,rzs,(void*)femmodel);
@@ -105,5 +121,17 @@
 	}
 
-	/*Get solution*/
+	/*Constrain solution vector*/
+	IssmDouble  *XL = NULL;
+	IssmDouble  *XU = NULL;
+	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
+	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
+	for(int i=0;i<numberofvertices;i++){
+		for(int c=0;c<num_controls;c++){
+			int index = num_controls*i+c;
+			X[index] = X[index]*scaling_factors[c];
+			if(X[index]>XU[index]) X[index]=XU[index];
+			if(X[index]<XL[index]) X[index]=XL[index];
+		}
+	}
 	SetControlInputsFromVectorx(femmodel,X);
 	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
@@ -122,4 +150,7 @@
 	xDelete<double>(X);
 	xDelete<double>(dz);
+	xDelete<double>(XU);
+	xDelete<double>(XL);
+	xDelete<double>(scaling_factors);
 }
 
@@ -132,6 +163,10 @@
 
 	/*Recover number of cost functions responses*/
-	int num_responses;
+	int num_responses,num_controls,numberofvertices;
+	IssmDouble* scaling_factors = NULL;
 	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
+	femmodel->parameters->FindParam(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
+	numberofvertices=femmodel->vertices->NumberOfVertices();
 
 	/*Constrain input vector*/
@@ -140,7 +175,11 @@
 	GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
 	GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
-	for(long i=0;i<*n;i++){
-		if(X[i]>XU[i]) X[i]=XU[i];
-		if(X[i]<XL[i]) X[i]=XL[i];
+	for(int i=0;i<numberofvertices;i++){
+		for(int c=0;c<num_controls;c++){
+			int index = num_controls*i+c;
+			X[index] = X[index]*scaling_factors[c];
+			if(X[index]>XU[index]) X[index]=XU[index];
+			if(X[index]<XL[index]) X[index]=XL[index];
+		}
 	}
 
@@ -162,11 +201,13 @@
 	_printf0_("f(x) = "<<setw(12)<<setprecision(7)<<*pf<<"  |  ");
 
-	/*Retrieve objective functions independently*/
-	for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[i]);
-	_printf0_("\n");
-	xDelete<IssmDouble>(Jlist);
-
-	if(indic==0){
+	if(*indic==0){
 		/*dry run, no gradient required*/
+
+		/*Retrieve objective functions independently*/
+		_printf0_("            N/A |\n");
+		for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[i]);
+		_printf0_("\n");
+
+		xDelete<IssmDouble>(Jlist);
 		xDelete<IssmDouble>(XU);
 		xDelete<IssmDouble>(XL);
@@ -185,12 +226,27 @@
 
 	/*Constrain Gradient*/
-	for(long i=0;i<*n;i++){
-		if(X[i]>=XU[i]) G[i]=0.;
-		if(X[i]<=XL[i]) G[i]=0.;
-	}
+	IssmDouble  Gnorm = 0.;
+	for(int i=0;i<numberofvertices;i++){
+		for(int c=0;c<num_controls;c++){
+			int index = num_controls*i+c;
+			if(X[index]>=XU[index]) G[index]=0.;
+			if(X[index]<=XL[index]) G[index]=0.;
+			G[index] = G[index]*scaling_factors[c];
+			X[index] = X[index]/scaling_factors[c];
+			Gnorm += G[index]*G[index];
+		}
+	}
+	Gnorm = sqrt(Gnorm);
+
+	/*Print info*/
+	_printf0_("       "<<setw(12)<<setprecision(7)<<Gnorm<<" |");
+	for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[i]);
+	_printf0_("\n");
 
 	/*Clean-up and return*/
+	xDelete<IssmDouble>(Jlist);
 	xDelete<IssmDouble>(XU);
 	xDelete<IssmDouble>(XL);
+	xDelete<IssmDouble>(scaling_factors);
 }
 
Index: /issm/trunk/src/c/cores/controltao_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/controltao_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/controltao_core.cpp	(revision 19105)
@@ -129,4 +129,6 @@
 	TaoFinalize();
 	#endif
+	G->pvector->vector = NULL;
+	delete G;
 }
 
Index: /issm/trunk/src/c/cores/controlvalidation_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/controlvalidation_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/controlvalidation_core.cpp	(revision 19105)
@@ -12,6 +12,9 @@
 
 	int         solution_type,n;
-	IssmDouble  j0,j;
+	int         num_responses;
+	IssmDouble  j0,j,yts;
 	IssmDouble  Ialpha,exponent,alpha;
+	IssmDouble* scaling_factors = NULL;
+	IssmDouble* jlist = NULL;
 	IssmDouble *G = NULL;
 	IssmDouble *X = NULL;
@@ -25,4 +28,7 @@
 	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
 	femmodel->parameters->SetParam(false,SaveResultsEnum);
+	femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
+	femmodel->parameters->FindParam(&scaling_factors,NULL,InversionControlScalingFactorsEnum);
 
 	/*Get initial guess*/
@@ -33,6 +39,5 @@
 	delete Xpetsc;
 
-	/*Allocate Gradient and current vector*/
-	G = xNew<IssmDouble>(n);
+	/*Allocate current vector*/
 	X = xNew<IssmDouble>(n);
 
@@ -45,17 +50,16 @@
 	if(VerboseControl()) _printf0_("   Compute Adjoint\n");
 	adjointcore(femmodel);
+
 	if(VerboseControl()) _printf0_("   Compute Initial cost function\n");
-	femmodel->CostFunctionx(&j0,NULL,NULL);
+	femmodel->CostFunctionx(&j0,&jlist,NULL);
+	_printf0_("Initial cost function J(x) = "<<setw(12)<<setprecision(7)<<j0<<"\n");
+	xDelete<IssmDouble>(jlist);
+
 	if(VerboseControl()) _printf0_("   Compute Gradient\n");
 	Gradjx(&G,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
 	for(int i=0;i<n;i++) G[i] = -G[i];
 
-	/*Range of tests*/
-	IssmDouble exp0 = 0.;
-	IssmDouble incr = -0.2;
-	IssmDouble exp1 = -10.;
-	int        num  = reCast<int,IssmDouble>((exp1-exp0)/incr);
-
 	/*Allocate output*/
+	int num = 26;
 	IssmDouble* output = xNew<IssmDouble>(2*num);
 
@@ -65,10 +69,7 @@
 	for(int m=0;m<num;m++){
 
-		/*Calculate alpha = 10^-exponent*/
-		exponent = exp0+m*incr;
-		alpha    = pow(10.,exponent);
-
 		/*Create new vector*/
-		for(int i=0;i<n;i++) X[i] = X0[i] + alpha;
+		alpha    = pow(2.,-m);
+		for(int i=0;i<n;i++) X[i] = X0[i] + alpha*scaling_factors[0];
 
 		/*Calculate j(k+alpha delta k) */
@@ -78,5 +79,5 @@
 
 		IssmDouble Den = 0.;
-		for(int i=0;i<n;i++) Den += alpha * G[i] * 1.;
+		for(int i=0;i<n;i++) Den += alpha* G[i] * scaling_factors[0];
 		Ialpha = fabs((j - j0)/Den - 1.);
 
@@ -95,6 +96,9 @@
 	femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,JEnum,output,num,2,1,0));
 	#endif
+	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
+	femmodel->OutputControlsx(&femmodel->results);
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(output);
 	xDelete<IssmDouble>(G);
 	xDelete<IssmDouble>(X);
Index: /issm/trunk/src/c/cores/cores.h
===================================================================
--- /issm/trunk/src/c/cores/cores.h	(revision 19104)
+++ /issm/trunk/src/c/cores/cores.h	(revision 19105)
@@ -29,4 +29,5 @@
 void controltao_core(FemModel* femmodel);
 void controlm1qn3_core(FemModel* femmodel);
+void controlad_core(FemModel* femmodel);
 void controlvalidation_core(FemModel* femmodel);
 void masstransport_core(FemModel* femmodel);
@@ -42,4 +43,5 @@
 void dakota_core(FemModel* femmodel);
 void ad_core(FemModel* femmodel);
+void adgradient_core(FemModel* femmodel);
 void dummy_core(FemModel* femmodel);
 void gia_core(FemModel* femmodel);
@@ -57,5 +59,4 @@
 
 //solution configuration
-void AnalysisConfiguration(int** pcores,int* pnumcores, int solutiontype);
 void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype);
 void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore=false);
Index: /issm/trunk/src/c/cores/damage_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/damage_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/damage_core.cpp	(revision 19105)
@@ -34,5 +34,5 @@
 		femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
 	}
-	
+
 	/*Free resources:*/	
 	if(numoutputs){
Index: /issm/trunk/src/c/cores/extrudefrombase_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/extrudefrombase_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/extrudefrombase_core.cpp	(revision 19105)
@@ -27,5 +27,5 @@
 	if(elementtype==PentaEnum){
 		int inputenum; femmodel->parameters->FindParam(&inputenum,InputToExtrudeEnum);
-		InputExtrudex(femmodel,inputenum);
+		InputExtrudex(femmodel,inputenum,-1);
 	}
 	else{
Index: /issm/trunk/src/c/cores/extrudefromtop_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/extrudefromtop_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/extrudefromtop_core.cpp	(revision 19105)
@@ -12,10 +12,26 @@
 void extrudefromtop_core(FemModel* femmodel){
 
+	/*Intermediaries*/
+	int elementtype,domaintype;
+
 	if(VerboseSolution()) _printf0_("extruding solution from top...\n");
 
-	/*Call on core computations: */
-	femmodel->SetCurrentConfiguration(ExtrudeFromTopAnalysisEnum);
-	femmodel->UpdateConstraintsExtrudeFromTopx();
-	solutionsequence_linear(femmodel);
+	/*Get parameters*/
+	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
+	femmodel->parameters->FindParam(&elementtype,MeshElementtypeEnum);
 
+	/*If this is a 2D horizontal domain, return (no need to extrude)*/
+	if(domaintype==Domain2DhorizontalEnum) return;
+
+	/*Special method for Penta, otherwise call solution sequence*/
+	if(elementtype==PentaEnum){
+		int inputenum; femmodel->parameters->FindParam(&inputenum,InputToExtrudeEnum);
+		InputExtrudex(femmodel,inputenum,+1);
+	}
+	else{
+		/*Call on core computations: */
+		femmodel->SetCurrentConfiguration(ExtrudeFromTopAnalysisEnum);
+		femmodel->UpdateConstraintsExtrudeFromTopx();
+		solutionsequence_linear(femmodel);
+	}
 }
Index: /issm/trunk/src/c/cores/masstransport_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/masstransport_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/masstransport_core.cpp	(revision 19105)
@@ -16,5 +16,5 @@
 	bool   save_results;
 	bool   isFS,isfreesurface,dakota_analysis;
-	int    solution_type;
+	int    solution_type,stabilization;
 	char** requested_outputs = NULL;
 
@@ -29,4 +29,5 @@
 	femmodel->parameters->FindParam(&domaintype,DomainTypeEnum);
 	femmodel->parameters->FindParam(&numoutputs,MasstransportNumRequestedOutputsEnum);
+	femmodel->parameters->FindParam(&stabilization,MasstransportStabilizationEnum);
 	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,MasstransportRequestedOutputsEnum);
 
@@ -49,5 +50,10 @@
 	else{
 		if(VerboseSolution()) _printf0_("   call computational core\n");
-		solutionsequence_linear(femmodel);
+		if(stabilization==4){
+			solutionsequence_fct(femmodel);
+		}
+		else{
+			solutionsequence_linear(femmodel);
+		}
 		femmodel->parameters->SetParam(ThicknessEnum,InputToExtrudeEnum);
 		extrudefrombase_core(femmodel);
Index: /issm/trunk/src/c/cores/thermal_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/thermal_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/thermal_core.cpp	(revision 19105)
@@ -28,18 +28,7 @@
 
 	if(isenthalpy){
-
-		if(VerboseSolution()) _printf0_("   computing enthalpy\n");
-		femmodel->SetCurrentConfiguration(EnthalpyAnalysisEnum);
-		solutionsequence_nonlinear(femmodel,true);
-
-		/*transfer enthalpy to enthalpy picard for the next step: */
-		InputDuplicatex(femmodel,EnthalpyEnum,EnthalpyPicardEnum);
-
-		if(solution_type!=SteadystateSolutionEnum){
-			/*Post process*/
-			enthalpy_analysis = new EnthalpyAnalysis();
-			enthalpy_analysis->PostProcessing(femmodel);
-			delete enthalpy_analysis;
-		}
+		enthalpy_analysis = new EnthalpyAnalysis();
+		enthalpy_analysis->Core(femmodel);
+		delete enthalpy_analysis;
 	}
 	else{
Index: /issm/trunk/src/c/cores/transient_core.cpp
===================================================================
--- /issm/trunk/src/c/cores/transient_core.cpp	(revision 19104)
+++ /issm/trunk/src/c/cores/transient_core.cpp	(revision 19105)
@@ -21,5 +21,5 @@
 	/*parameters: */
 	IssmDouble starttime,finaltime,dt,yts;
-	bool       isstressbalance,ismasstransport,isFS,isthermal,isgroundingline,isgia,islevelset,isdamageevolution,ishydrology;
+	bool       isstressbalance,ismasstransport,isFS,isthermal,isgroundingline,isgia,islevelset,isdamageevolution,ishydrology,iscalving;
 	bool       save_results,dakota_analysis;
 	bool       time_adapt=false;
@@ -53,4 +53,5 @@
 	femmodel->parameters->FindParam(&ishydrology,TransientIshydrologyEnum);
 	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&iscalving,TransientIscalvingEnum);
 	if(isgroundingline) femmodel->parameters->FindParam(&groundingline_migration,GroundinglineMigrationEnum);
 	femmodel->parameters->FindParam(&numoutputs,TransientNumRequestedOutputsEnum);
@@ -101,5 +102,6 @@
 
 		if(islevelset){
-			if(VerboseSolution()) _printf0_("   computing movement of ice boundaries\n");
+			if(iscalving) Calvingx(femmodel);
+			if(VerboseSolution()) _printf0_("   computing levelset transport\n");
 			/* smoothen slope of lsf for computation of normal on ice domain*/
 			levelsetfunctionslope_core(femmodel);
@@ -107,6 +109,6 @@
 			/* extrapolate velocities onto domain with no ice */
 			Analysis* extanalysis = new ExtrapolationAnalysis();
-			const int nvars=2;
-			int vars[nvars] = {VxEnum, VyEnum};
+			const int nvars=3;
+			int vars[nvars] = {VxEnum, VyEnum, ThicknessEnum};
 			for(int iv=0;iv<nvars;iv++){
 				femmodel->parameters->SetParam(vars[iv],ExtrapolationVariableEnum); 
@@ -139,10 +141,11 @@
 			GroundinglineMigrationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
 
-			if(groundingline_migration==ContactEnum){
-				femmodel->parameters->SetParam(MaskGroundediceLevelsetEnum,InputToExtrudeEnum);
-				extrudefrombase_core(femmodel);
-				femmodel->parameters->SetParam(BaseEnum,InputToExtrudeEnum);
-				extrudefrombase_core(femmodel);
-			}
+			femmodel->parameters->SetParam(MaskGroundediceLevelsetEnum,InputToExtrudeEnum);
+			extrudefrombase_core(femmodel);
+			femmodel->parameters->SetParam(BaseEnum,InputToExtrudeEnum);
+			extrudefrombase_core(femmodel);
+			femmodel->parameters->SetParam(SurfaceEnum,InputToExtrudeEnum);
+			extrudefrombase_core(femmodel);
+				
 			if(save_results){
 				int outputs[3] = {SurfaceEnum,BaseEnum,MaskGroundediceLevelsetEnum};
Index: /issm/trunk/src/c/main/kriging.cpp
===================================================================
--- /issm/trunk/src/c/main/kriging.cpp	(revision 19104)
+++ /issm/trunk/src/c/main/kriging.cpp	(revision 19105)
@@ -58,5 +58,5 @@
 		results->AddObject(new GenericExternalResult<double*>(results->Size()+1,1,error,ninterp,1,1,0));
 		for(int i=0;i<results->Size();i++){
-			ExternalResult* result=dynamic_cast<ExternalResult*>(results->GetObjectByOffset(i));
+			ExternalResult* result=xDynamicCast<ExternalResult*>(results->GetObjectByOffset(i));
 			result->WriteData(output_fid,1);
 		}
Index: /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 19105)
@@ -134,5 +134,5 @@
 	k=0;
 	for(i=0;i<femmodel->elements->Size();i++){
-		element = dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element = xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		lidlist = xNew<int>(element->GetNumberOfNodes());
 		element->GetNodesLidList(lidlist);
@@ -157,5 +157,5 @@
 	k=0;
 	for(i=0;i<femmodel->loads->Size();i++){
-		load = dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+		load = xDynamicCast<Load*>(femmodel->loads->GetObjectByOffset(i));
 		if(!load->InAnalysis(configuration_type)) continue;
 		lidlist = xNew<int>(load->GetNumberOfNodes());
@@ -190,5 +190,5 @@
 	/*Create connectivity vector*/
 	for(i=0;i<femmodel->nodes->Size();i++){
-		Node* node=dynamic_cast<Node*>(femmodel->nodes->GetObjectByOffset(i));
+		Node* node=xDynamicCast<Node*>(femmodel->nodes->GetObjectByOffset(i));
 		if(node->InAnalysis(configuration_type)){
 
@@ -214,5 +214,5 @@
 			for(j=head_e[node->Lid()];j!=-1;j=next_e[j]){
 				offset=count2offset_e[j];
-				element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(offset));
+				element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(offset));
 				element->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,flagsindices,set1enum,set2enum);
 				if(node->IsClone()){
@@ -226,5 +226,5 @@
 			for(j=head_l[node->Lid()];j!=-1;j=next_l[j]){
 				offset=count2offset_l[j];
-				load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(offset));
+				load=xDynamicCast<Load*>(femmodel->loads->GetObjectByOffset(offset));
 				load->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,flagsindices,set1enum,set2enum);
 				if(node->IsClone()){
@@ -256,5 +256,5 @@
 		o_nnz=xNew<int>(m);
 		for(i=0;i<femmodel->nodes->Size();i++){
-			Node* node=dynamic_cast<Node*>(femmodel->nodes->GetObjectByOffset(i));
+			Node* node=xDynamicCast<Node*>(femmodel->nodes->GetObjectByOffset(i));
 			if(node->InAnalysis(configuration_type) && !node->IsClone()){
 				for(j=0;j<node->indexing.fsize;j++){
Index: /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 19105)
@@ -41,5 +41,5 @@
 	/*loop on each element, and add contribution of the element to the partition (surface weighted average): */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->AverageOntoPartition(partition_contributions,partition_areas,vertex_response,qmu_part);
 	}
Index: /issm/trunk/src/c/modules/Calvingx/Calvingx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Calvingx/Calvingx.cpp	(revision 19105)
+++ /issm/trunk/src/c/modules/Calvingx/Calvingx.cpp	(revision 19105)
@@ -0,0 +1,38 @@
+/*!\file Calvingx
+ * \brief: compute inverse method gradient
+ */
+
+#include "./Calvingx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void Calvingx(FemModel* femmodel){
+
+	/*Recover Calving law Enum*/
+	int calvinglaw;
+	femmodel->parameters->FindParam(&calvinglaw,CalvingLawEnum);
+
+	/*Calculate calving rate*/
+	switch(calvinglaw){
+		case DefaultCalvingEnum:
+			break;
+		case CalvingLevermannEnum:
+			if(VerboseModule()) _printf0_("   computing Levermann's calving rate\n");
+			femmodel->StrainRateparallelx();
+			femmodel->StrainRateperpendicularx();
+			femmodel->CalvingRateLevermannx();
+			break;
+		case CalvingPiEnum:
+			if(VerboseModule()) _printf0_("   computing Pi's calving rate\n");
+			femmodel->StrainRateparallelx();
+			femmodel->DeviatoricStressx();
+			femmodel->CalvingRatePix();
+			break;
+		case CalvingDevEnum:
+			femmodel->CalvingRateDevx();
+			femmodel->ElementOperationx(&Element::CalvingRateDev);
+			break;
+		default:
+			_error_("Caving law "<<EnumToStringx(calvinglaw)<<" not supported yet");
+	}
+}
Index: /issm/trunk/src/c/modules/Calvingx/Calvingx.h
===================================================================
--- /issm/trunk/src/c/modules/Calvingx/Calvingx.h	(revision 19105)
+++ /issm/trunk/src/c/modules/Calvingx/Calvingx.h	(revision 19105)
@@ -0,0 +1,10 @@
+#ifndef _CALVINGX_H
+#define _CALVINGX_H
+
+#include "../../classes/classes.h"
+#include "../../analyses/analyses.h"
+
+/* local prototypes: */
+void Calvingx(FemModel* femmodel);
+
+#endif
Index: /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 19105)
@@ -24,5 +24,5 @@
 	if(VerboseMProcessor()) _printf0_("      Configuring elements...\n");
 	for(i=0;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->Configure(elements,loads,nodes,vertices,materials,parameters);
 	}
Index: /issm/trunk/src/c/modules/CoordinateSystemTransformx/CoordinateSystemTransformx.cpp
===================================================================
--- /issm/trunk/src/c/modules/CoordinateSystemTransformx/CoordinateSystemTransformx.cpp	(revision 19105)
+++ /issm/trunk/src/c/modules/CoordinateSystemTransformx/CoordinateSystemTransformx.cpp	(revision 19105)
@@ -0,0 +1,40 @@
+/*!\file TriMeshx
+ * \brief: x code for TriMesh mesher
+ */
+
+/*Header files*/
+#include "./CoordinateSystemTransformx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include <proj_api.h>
+
+void CoordinateSystemTransformx(IssmDouble** px_dest,IssmDouble** py_dest,IssmDouble* x_src,IssmDouble* y_src,int size,const char* str_src,const char* str_dst){
+
+#if !defined(_HAVE_PROJ4_)
+	_error_("proj.4 has not been installed");
+#else
+
+	/*Allocate output and initialize values as src*/
+	_assert_(size>0);
+	IssmDouble* x_dest = xNew<IssmDouble>(size);
+	IssmDouble* y_dest = xNew<IssmDouble>(size);
+	for(int i=0;i<size;i++){
+		x_dest[i] = x_src[i];
+		y_dest[i] = y_src[i];
+	}
+
+	/*Create proj.4 projection objects for src and dst*/
+	projPJ pj_src  = pj_init_plus(str_src);
+	projPJ pj_dst  = pj_init_plus(str_dst);
+	if(!pj_src) _error_("Failed to initialize PROJ.4 with source projection \""    <<str_src<<"\"\n");
+	if(!pj_dst) _error_("Failed to initialize PROJ.4 with destination projection\""<<str_dst<<"\"\n");
+
+	/*Perform transformation*/
+	int p = pj_transform(pj_src,pj_dst,size,1,x_dest,y_dest,NULL);
+	if(p!=0) _error_("Reprojection failed, PROJ.4 error code: "<<p<<"\n");
+
+	/*Output : */
+	*px_dest=x_dest;
+	*py_dest=y_dest;
+#endif
+}
Index: /issm/trunk/src/c/modules/CoordinateSystemTransformx/CoordinateSystemTransformx.h
===================================================================
--- /issm/trunk/src/c/modules/CoordinateSystemTransformx/CoordinateSystemTransformx.h	(revision 19105)
+++ /issm/trunk/src/c/modules/CoordinateSystemTransformx/CoordinateSystemTransformx.h	(revision 19105)
@@ -0,0 +1,11 @@
+/*!\file:  CoordinateSystemTransformx.h
+ */ 
+
+#ifndef _CORRDSYSTRANFER_
+#define _CORRDSYSTRANFER_
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void CoordinateSystemTransformx(IssmDouble** px_dest,IssmDouble** py_dest,IssmDouble* x_src,IssmDouble* y_src,int size,const char* str_src,const char* str_dst);
+#endif  
Index: /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp
===================================================================
--- /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 19105)
@@ -29,5 +29,5 @@
 	/*Create and assemble matrix*/
 	for(i=0;i<femmodel->elements->Size();i++){
-		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		ElementMatrix* Je = analysis->CreateJacobianMatrix(element);
 		if(Je) Je->AddToGlobal(Jff);
Index: /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 19105)
@@ -16,5 +16,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		J+=DragCoefficientAbsGradient(element);
 	}
Index: /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetx.cpp	(revision 19105)
+++ /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetx.cpp	(revision 19105)
@@ -0,0 +1,36 @@
+/*! \file  ExpToLevelSetx.c
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./ExpToLevelSetx.h"
+
+int ExpToLevelSetx(double** pdistance,double* x, double* y, int nods, Contours* contours){
+
+	/*Contour:*/
+	double value;
+
+	/*output: */
+	double*  distance;
+	distance   = xNewZeroInit<double>(nods);
+
+	/*initialize thread parameters: */
+	ExpToLevelSetxThreadStruct gate;
+	gate.contours  = contours;
+	gate.nods      = nods;
+	gate.distance    = distance;
+	gate.x         = x;
+	gate.y         = y;
+
+	/*launch the thread manager with ExpToLevelSetxt as a core: */
+	LaunchThread(ExpToLevelSetxt,(void*)&gate,_NUMTHREADS_);
+
+	/*Assign output pointers: */
+	*pdistance=distance;
+
+	return 1;
+}
Index: /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetx.h
===================================================================
--- /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetx.h	(revision 19105)
+++ /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetx.h	(revision 19105)
@@ -0,0 +1,27 @@
+/*
+	ExpToLevelSetx.h
+*/
+
+#ifndef _EXPTOLEVELSETX_H
+#define _EXPTOLEVELSETX_H
+
+#include "../../shared/shared.h"
+#include "../../classes/classes.h"
+
+/*threading: */
+typedef struct{
+
+	Contours *contours;
+	int       nods;
+	double   *distance;
+	double   *x;
+	double   *y;
+
+} ExpToLevelSetxThreadStruct;
+
+/* local prototypes: */
+int ExpToLevelSetx(double** pdistance,double* x, double* y,int nods, Contours* contours);
+
+void* ExpToLevelSetxt(void* vExpToLevelSetxThreadStruct);
+
+#endif /* _EXPTOLEVELSETX_H */
Index: /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetxt.cpp	(revision 19105)
+++ /issm/trunk/src/c/modules/ExpToLevelSetx/ExpToLevelSetxt.cpp	(revision 19105)
@@ -0,0 +1,104 @@
+/*!\file:  ExpToLevelSetxt.cpp
+ * \brief  "thread" core code for figuring out level set value from a contour and a cloud of points.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*Include files: {{{*/
+#include "./ExpToLevelSetx.h"
+double minimum_distance(double x1, double y1, double x2, double y2, double x0, double y0);
+void ContourToLevelSet(double* distance,double* contourx, double* contoury, int contournods, double* x, double* y, int i0, int i10);
+/*}}}*/
+
+void* ExpToLevelSetxt(void* vpthread_handle){
+
+	/*gate variables :*/
+	ExpToLevelSetxThreadStruct *gate        = NULL;
+	pthread_handle             *handle      = NULL;
+	int  i,i1,i0;
+
+	/*recover handle and gate: */
+	handle          = (pthread_handle*)vpthread_handle;
+	gate            = (ExpToLevelSetxThreadStruct*)handle->gate;
+	int my_thread   = handle->id;
+	int num_threads = handle->num;
+
+	/*recover parameters :*/
+	Contours* contours  = gate->contours;
+	int       nods      = gate->nods;
+	double   *distance    = gate->distance;
+	double   *x         = gate->x;
+	double   *y         = gate->y;
+
+	/*distribute indices across threads :*/
+	PartitionRange(&i0,&i1,nods,num_threads,my_thread);
+
+	/*Loop through all contours: */
+	for (i=0;i<contours->Size();i++){
+		Contour<double>* contour=(Contour<double>*)contours->GetObjectByOffset(i);
+		ContourToLevelSet(distance,contour->x,contour->y,contour->nods,x,y,i0,i1);
+	}
+
+	return NULL;
+}
+
+void ContourToLevelSet(double* dist,double* contourx, double* contoury, int contournods, double* x, double* y, int i0, int i1){/*{{{*/
+	int i,j;
+	double x0,y0;
+	double x1,y1;
+	double x2,y2;
+	double mind;
+	
+	for(i=i0;i<i1;i++){
+		x0=x[i]; y0=y[i];
+
+		/*Figure out distance from (x0,y0) to contour: */
+		mind=INFINITY;
+		for (j=0;j<contournods-1;j++){
+			x1=contourx[j]; y1=contoury[j];
+			x2=contourx[j+1]; y2=contoury[j+1];
+			mind=min(mind,minimum_distance(x1,y1,x2,y2,x0,y0));
+		}
+		dist[i]=mind;
+	}
+
+}
+double ddistance(double x1,double y1,double x2,double y2){
+	return sqrt(pow(x2-x1,2)+pow(y2-y1,2));
+}
+double ddot(double x1, double y1, double x2, double y2){
+	return x1*x2+y1*y2;
+}
+
+bool isPointLeftOfRay(double x, double y, double raySx, double raySy, double rayEx, double rayEy) {
+	  return (y-raySy)*(rayEx-raySx)
+		    >      (x-raySx)*(rayEy-raySy); 
+}
+
+double minimum_distance(double x1, double y1, double x2, double y2, double x0, double y0){
+	
+	// Return minimum distance between line segment [(x1,y1) (x2,y2)] and point (x0,y0) (v=(x1,y1), w=(x2,y2) and p=(x0,y0)
+	double projectionx; 
+	double projectiony; 
+	double l2;
+	double t;
+
+	l2 = pow(x2-x1,2)+pow(y2-y1,2); // i.e. |w-v|^2 -  avoid a sqrt
+
+	if (l2 == 0.0) return ddistance(x0,y0, x1,y1); // v == w case
+	// Consider the line extending the segment, parameterized as v + t (w - v).
+	//         // We find projection of point p onto the line. 
+	//           // It falls where t = [(p-v) . (w-v)] / |w-v|^2
+	t = ddot(x0-x1,y0-y1, x2-x1, y2-y1) / l2;
+	if (t < 0.0) return ddistance(x0,y0, x1, y1);       // Beyond the 'v' end of the segment
+	else if (t > 1.0) return ddistance(x0,y0, x2,y2);  // Beyond the 'w' end of the segment
+	
+	projectionx= x1 + t* (x2-x1);  // Projection falls on the segment
+	projectiony= y1 + t* (y2-y1);
+	return ddistance(x0, y0, projectionx, projectiony);
+}
+/*}}}*/
Index: /issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp	(revision 19105)
@@ -33,5 +33,5 @@
 
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->LinearFloatingiceMeltingRate();
 	}
Index: /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 19105)
@@ -32,5 +32,5 @@
 	Analysis* analysis = EnumToAnalysis(analysisenum);
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		analysis->GetSolutionFromInputs(solution,element);
 	}
Index: /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 19105)
@@ -7,5 +7,5 @@
 #include "../../toolkits/toolkits.h"
 
-void GetVectorFromControlInputsx(Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data){
+void GetVectorFromControlInputsx(Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,const char* data,bool onsid){
 
 	int  num_controls;
@@ -23,5 +23,5 @@
 		for(int j=0;j<elements->Size();j++){
 			Element* element=(Element*)elements->GetObjectByOffset(j);
-			element->GetVectorFromControlInputs(vector,control_type[i],i,data);
+			element->GetVectorFromControlInputs(vector,control_type[i],i,data,onsid);
 		}
 	}
@@ -34,5 +34,5 @@
 }
 
-void GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){
+void GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data,bool onsid){
 
 	/*output: */
@@ -42,5 +42,5 @@
 	Vector<IssmDouble>* vec_vector=NULL;
 
-	GetVectorFromControlInputsx( &vec_vector, elements,nodes, vertices, loads, materials, parameters,data);
+	GetVectorFromControlInputsx( &vec_vector, elements,nodes, vertices, loads, materials, parameters,data,onsid);
 	vector=vec_vector->ToMPISerial();
 
Index: /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 19104)
+++ /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 19105)
@@ -8,6 +8,6 @@
 
 /* local prototypes: */
-void	GetVectorFromControlInputsx( Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
-void	GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value");
+void	GetVectorFromControlInputsx( Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value",bool onsid=false);
+void	GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,const char* data="value",bool onsid=false);
 
 #endif  /* _GETVECTORFROMCONTROLINPUTSXX_H */
Index: /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 19105)
@@ -7,22 +7,23 @@
 #include "../../toolkits/toolkits.h"
 
-void GetVectorFromInputsx( Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type){
+void GetVectorFromInputsx(Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type){
 
 	int i;
 	Vector<IssmDouble>* vector=NULL;
 
-	if(type==VertexEnum){
-
-		/*Allocate vector*/
+	switch(type){
+	case VertexPIdEnum: case VertexSIdEnum:
 		vector=new Vector<IssmDouble>(femmodel->vertices->NumberOfVertices());
-
-		/*Look up in elements*/
-		for(i=0;i<femmodel->elements->Size();i++){
-			Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-			element->GetVectorFromInputs(vector,name);
-		}
+		break;
+	case NodesEnum:case NodeSIdEnum:
+		vector=new Vector<IssmDouble>(femmodel->nodes->NumberOfNodes());
+		break;
+	default:
+			_error_("vector type: " << EnumToStringx(type) << " not supported yet!");
 	}
-	else{
-		_error_("vector type: " << EnumToStringx(type) << " not supported yet!");
+	/*Look up in elements*/
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->GetVectorFromInputs(vector,name,type);
 	}
 
Index: /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 19105)
@@ -15,5 +15,4 @@
 	Element            *element                          = NULL;
 
-	if(VerboseModule()) _printf0_("   Migrating grounding line\n");
 
 	/*retrieve parameters: */
@@ -22,4 +21,6 @@
 
 	if(migration_style==NoneEnum) return;
+	
+	if(VerboseModule()) _printf0_("   Migrating grounding line\n");
 
 	/*Set toolkit to default*/
@@ -39,4 +40,5 @@
 		case SubelementMigrationEnum:
 		case SubelementMigration2Enum:
+		case GroundingOnlyEnum:
 			/*Nothing additional to do here, MigrateGroundingLine takes care of everything*/
 			break;
@@ -47,5 +49,5 @@
 	/*Migrate grounding line : */
 	for(int i=0;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->MigrateGroundingLine(phi_ungrounding);
 	}
@@ -72,5 +74,5 @@
 	/*Fill vector vertices_potentially_floating: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->FSContactMigration(vertexgrounded,vertexfloating);
 	}
@@ -81,19 +83,10 @@
 	serial_vertexgrounded=vertexgrounded->ToMPISerial();
 	serial_vertexfloating=vertexfloating->ToMPISerial();
-
-	/*find vertices on GL */
 	for(int i=0;i<numberofvertices;i++){
-		if(serial_vertexgrounded[i]==1. && serial_vertexfloating[i]==1.){
-			phi[i]=0.;
-		}
-		else if(serial_vertexgrounded[i]==1.){
-			phi[i]=1.;
-		}
-		else if(serial_vertexfloating[i]==1.){
-			phi[i]=-1.;
-		}
-		else{
-			phi[i]=9999.;
-		}
+			if (serial_vertexgrounded[i]==1. && serial_vertexfloating[i]==1.) phi[i]=0.;
+			else if (serial_vertexgrounded[i]==1) phi[i]=1;
+			else if (serial_vertexfloating[i]==1) phi[i]=-1;
+			else if (serial_vertexgrounded[i]>10) phi[i]=9999;
+			else phi[i]=-9999;
 	}
 
@@ -120,5 +113,5 @@
 	/*Fill vector vertices_potentially_floating: */
 	for(i=0;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->PotentialUngrounding(vec_vertices_potentially_ungrounding);
 	}
@@ -148,6 +141,6 @@
 	vec_phi=new Vector<IssmDouble>(vertices->NumberOfVertices());
 	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		element->GetVectorFromInputs(vec_phi,MaskGroundediceLevelsetEnum);
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		element->GetVectorFromInputs(vec_phi,MaskGroundediceLevelsetEnum,VertexPIdEnum);
 	}
 	vec_phi->Assemble();
@@ -162,5 +155,5 @@
 		/*Figure out if any of the nodes of the element will be floating -> elements neighbouting the floating ice*/
 		for(i=0;i<elements->Size();i++){
-			element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+			element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 			vec_elements_neighboring_floatingice->SetValue(element->Sid(),element->IsNodeOnShelfFromFlags(phi)?1.0:0.0,INS_VAL);
 		}
@@ -173,5 +166,5 @@
 		local_nflipped=0;
 		for(i=0;i<elements->Size();i++){
-			element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+			element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 			if(reCast<int,IssmDouble>(elements_neighboring_floatingce[element->Sid()])){
 				local_nflipped+=element->UpdatePotentialUngrounding(vertices_potentially_ungrounding,vec_phi,phi);
Index: /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 19105)
@@ -12,5 +12,5 @@
 	/*Go through elemnets, and ask to carry out the operation on inputs: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->InputControlUpdate(scalar,save_parameter);
 	}
Index: /issm/trunk/src/c/modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/InputDepthAverageAtBasex/InputDepthAverageAtBasex.cpp	(revision 19105)
@@ -10,5 +10,5 @@
 void InputDepthAverageAtBasex(FemModel* femmodel,int original_enum, int new_enum){
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputDepthAverageAtBase(original_enum,new_enum);
 	}
Index: /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 19105)
@@ -11,5 +11,5 @@
 	/*Go through elemnets, and ask to reinitialie the input: */
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputDuplicate(original_enum,new_enum);
 	}
Index: /issm/trunk/src/c/modules/InputExtrudex/InputExtrudex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputExtrudex/InputExtrudex.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/InputExtrudex/InputExtrudex.cpp	(revision 19105)
@@ -8,8 +8,8 @@
 #include "../../toolkits/toolkits.h"
 
-void InputExtrudex(FemModel* femmodel,int input_enum){
+void InputExtrudex(FemModel* femmodel,int input_enum,int start){
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-		element->InputExtrude(input_enum);
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->InputExtrude(input_enum,start);
 	}
 }
Index: /issm/trunk/src/c/modules/InputExtrudex/InputExtrudex.h
===================================================================
--- /issm/trunk/src/c/modules/InputExtrudex/InputExtrudex.h	(revision 19104)
+++ /issm/trunk/src/c/modules/InputExtrudex/InputExtrudex.h	(revision 19105)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void InputExtrudex(FemModel* femmodel,int input_enum);
+void InputExtrudex(FemModel* femmodel,int input_enum,int start);
 
 #endif  /* _INPUTDUPLICATEX_H */
Index: /issm/trunk/src/c/modules/InputScalex/InputScalex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputScalex/InputScalex.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/InputScalex/InputScalex.cpp	(revision 19105)
@@ -15,5 +15,5 @@
 	/*Go through elemnets, and ask to reinitialie the input: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->InputScale(enum_type,scale_factor);
 	}
Index: /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 19105)
@@ -14,5 +14,5 @@
 	/*Elements and loads drive the update: */
 	for(i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromConstant(constant,name);
 	}
@@ -35,5 +35,5 @@
 	/*Elements and loads drive the update: */
 	for(i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromConstant(constant,name);
 	}
@@ -56,5 +56,5 @@
 	/*Elements and loads drive the update: */
 	for(i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromConstant(constant,name);
 	}
@@ -78,5 +78,5 @@
 	/*Elements and loads drive the update: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->InputUpdateFromConstant(constant,name);
 	}
Index: /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 19105)
@@ -20,5 +20,5 @@
 		/*Update elements, nodes, loads and materials from inputs: */
 		for(i=0;i<femmodel->elements->Size();i++){
-			Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 			element->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
 		}
Index: /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 19105)
@@ -30,5 +30,5 @@
 	Analysis* analysis = EnumToAnalysis(analysisenum);
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		analysis->InputUpdateFromSolution(solution,element);
 	}
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 19105)
@@ -22,5 +22,5 @@
 	/*Update elements, nodes, loads and materials from inputs: */
 	for(i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromVectorDakota(vector,name,type);
 	}
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 19105)
@@ -20,5 +20,5 @@
 	/*Update elements, nodes, loads and materials from inputs: */
 	for(i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromVector(vector,name,type);
 	}
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 19105)
@@ -49,10 +49,10 @@
 
 	/*read background mesh*/
-	Mesh Th(index_data,x_data,y_data,nods_data,nels_data); 
+	Mesh* Th=new Mesh(index_data,x_data,y_data,nods_data,nels_data); 
 
 	/*Get reference number (for subdomains)*/
-	long* reft = xNew<long>(Th.nbt);
-	Th.TriangleReferenceList(reft);
-	Th.CreateSingleVertexToTriangleConnectivity();
+	long* reft = xNew<long>(Th->nbt);
+	Th->TriangleReferenceList(reft);
+	Th->CreateSingleVertexToTriangleConnectivity();
 
 	/*Get domain boundaries*/
@@ -79,8 +79,8 @@
 		/*Get current point coordinates*/
 		r.x=x_interp[i]; r.y=y_interp[i];
-		I2 I=Th.R2ToI2(r);
+		I2 I=Th->R2ToI2(r);
 
 		/*Find triangle holding r/I*/
-		Triangle &tb=*Th.TriangleFindFromCoord(I,dete);
+		Triangle &tb=*Th->TriangleFindFromCoord(I,dete);
 
 		/*point inside convex*/
@@ -92,9 +92,9 @@
 			areacoord[2]= (double) dete[2]/tb.det;
 			/*3 vertices of the triangle*/
-			i0=Th.GetId(tb[0]);
-			i1=Th.GetId(tb[1]);
-			i2=Th.GetId(tb[2]);
+			i0=Th->GetId(tb[0]);
+			i1=Th->GetId(tb[1]);
+			i2=Th->GetId(tb[2]);
 			/*triangle number*/
-			it=Th.GetId(tb);
+			it=Th->GetId(tb);
 
 			/*Inside convex but outside mesh*/
@@ -120,9 +120,9 @@
 				areacoord[OppositeVertex[k]] = 1 - aa -bb;
 				//3 vertices of the triangle
-				i0=Th.GetId(tc[0]);
-				i1=Th.GetId(tc[1]);
-				i2=Th.GetId(tc[2]);
+				i0=Th->GetId(tc[0]);
+				i1=Th->GetId(tc[1]);
+				i2=Th->GetId(tc[2]);
 				//triangle number
-				it=Th.GetId(tc);
+				it=Th->GetId(tc);
 			}
 		}
@@ -145,4 +145,5 @@
 
 	/*clean-up and return*/
+	delete Th;
 	xDelete<long>(reft);
 	*pdata_interp=data_interp;
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 19105)
@@ -129,8 +129,13 @@
 		ysegment[0]=yc[i];
 		ysegment[1]=yc[i+1];
-		ElementSegment(segments_dataset,el, xnodes,ynodes,xsegment,ysegment);
-	}
-}/*}}}*/
-void ElementSegment(DataSet* segments_dataset,int el,double* xnodes,double* ynodes,double* xsegment,double* ysegment){/*{{{*/
+		/*if (el==318 && i==9){
+			_printf_("contour: " << i << " " << xsegment[0] << " " << ysegment[0] << " " << xsegment[1] << " " << ysegment[1] 
+				<< " " << xnodes[0] << " " << xnodes[1] << " " << xnodes[2] << " " << ynodes[0] << " " << ynodes[1] << " " << 
+				ynodes[2] << "\n");
+		}*/
+		ElementSegment(segments_dataset,el, i, xnodes,ynodes,xsegment,ysegment);
+	}
+}/*}}}*/
+void ElementSegment(DataSet* segments_dataset,int el, int contouri, double* xnodes,double* ynodes,double* xsegment,double* ysegment){/*{{{*/
 
 	/*We have a tria element (xnodes,ynodes) and a segment (xsegment,ysegment). Find whether they intersect. 
@@ -159,9 +164,42 @@
 	edge3=SegmentIntersect(&gamma1,&gamma2, xel,yel,xsegment,ysegment);
 
-	/*edge can be either IntersectEnum (one iand only one intersection between the edge and the segment), ColinearEnum (edge and segment are collinear) and SeparateEnum (no intersection): */
+	/*edge can be either IntersectEnum (one and only one intersection between the edge and the segment), ColinearEnum (edge and segment are collinear) and SeparateEnum (no intersection): */
+		
+	/*if (el==318 && contouri==9){
+		_printf_(edge1 << " " << edge2 << " " << edge3 << " "  << alpha1 << " " << alpha2 << " " << beta1 << " " << beta2 << " " << gamma1 << " " << gamma2 << " " << xsegment[0] << " "  << xsegment[1] << " " << ysegment[0] << " " << ysegment[1] << " " << xnodes[0] << " " << xnodes[1] << " " << xnodes[2] << " " << ynodes[0] << " " << ynodes[1] << " " << ynodes[2]);
+	
+	_printf_("Bool" << (edge1==IntersectEnum) || (edge2==IntersectEnum) || (edge3==IntersectEnum));
+	}*/
 
 	if(    (edge1==IntersectEnum) && (edge2==IntersectEnum) && (edge3==IntersectEnum)   ){
-		/*This case is impossible: */
-		_error_("error: a line cannot go through 3 different vertices!");
+
+		/*This can only be the case if the segment intersected through one vertex, meaning a pair from alpha1, beta1 or gamma1  is 0:*/
+		if (alpha1!=0 && alpha1!=1){
+			/*The vertex opposite edge 1 was intersected:*/
+			xfinal[0]=xsegment[0]+alpha1*(xsegment[1]-xsegment[0]);
+			yfinal[0]=ysegment[0]+alpha1*(ysegment[1]-ysegment[0]);
+			xfinal[1]=xnodes[2];
+			yfinal[1]=ynodes[2];
+		}
+		else if (beta1!=0 && beta1!=1){
+			/*The vertex opposite edge 2 was intersected:*/
+			xfinal[0]=xsegment[0]+beta1*(xsegment[1]-xsegment[0]);
+			yfinal[0]=ysegment[0]+beta1*(ysegment[1]-ysegment[0]);
+			xfinal[1]=xnodes[0];
+			yfinal[1]=ynodes[0];
+		}
+		else if (gamma1!=0 && gamma1!=1){
+			/*The vertex opposite edge 3 was intersected:*/
+			xfinal[0]=xsegment[0]+gamma1*(xsegment[1]-xsegment[0]);
+			yfinal[0]=ysegment[0]+gamma1*(ysegment[1]-ysegment[0]);
+			xfinal[1]=xnodes[1];
+			yfinal[1]=ynodes[1];
+		}
+		segments_dataset->AddObject(new  Segment<double>(el+1,xfinal[0],yfinal[0],xfinal[1],yfinal[1]));
+
+		
+		/*This case is impossible: not quite! */
+		//_printf_(alpha1 << " " << alpha2 << " " << beta1 << " " << beta2 << " " << gamma1 << " " << gamma2 << " " << xsegment[0] << " "  << xsegment[1] << " " << ysegment[0] << " " << ysegment[1] << " " << xnodes[0] << " " << xnodes[1] << " " << xnodes[2] << " " << ynodes[0] << " " << ynodes[1] << " " << ynodes[2]);
+		/* _error_("error: a line cannot go through 3 different vertices!");*/
 	}
 	else if(    ((edge1==IntersectEnum) && (edge2==IntersectEnum)) || ((edge2==IntersectEnum) && (edge3==IntersectEnum)) || ((edge3==IntersectEnum) && (edge1==IntersectEnum))   ){
@@ -187,4 +225,8 @@
 	}
 	else if(  (edge1==IntersectEnum) || (edge2==IntersectEnum) || (edge3==IntersectEnum)   ){
+	
+		/*if (el==318 && contouri==9){
+			_printf_("hello" <<  " NodeInElement 0 " << (NodeInElement(xnodes,ynodes,xsegment[0],ysegment[0])) <<  " NodeInElement 1 " << (NodeInElement(xnodes,ynodes,xsegment[1],ysegment[1])));
+		}*/
 
 		/*segment intersect only 1 edge. Figure out where the first point in the segment is, inside or outside the element, 
@@ -196,9 +238,35 @@
 			if(edge3==IntersectEnum){coord2=gamma1;}
 		}
-		else{
+		else if (NodeInElement(xnodes,ynodes,xsegment[1],ysegment[1])){
 			if(edge1==IntersectEnum){coord1=alpha1;}
 			if(edge2==IntersectEnum){coord1=beta1;}
 			if(edge3==IntersectEnum){coord1=gamma1;}
 			coord2=1.0;
+		}
+		else{
+			double tolerance=1e-10;
+			/*Ok, we have an issue here. Probably one of the segments' end is on a vertex, within a certain tolerance!*/
+			if (IsIdenticalNode(xnodes[0],ynodes[0],xsegment[0],ysegment[0],tolerance) ||
+				IsIdenticalNode(xnodes[1],ynodes[1],xsegment[0],ysegment[0],tolerance) ||
+				IsIdenticalNode(xnodes[2],ynodes[2],xsegment[0],ysegment[0],tolerance)){
+				
+				/*ok, segments[0] is common to one of our vertices: */
+				//if (el==318 && contouri==9){ _printf_("ok1" << "\n"); }
+				coord1=0;
+				if(edge1==IntersectEnum){coord2=alpha1;}
+				if(edge2==IntersectEnum){coord2=beta1;}
+				if(edge3==IntersectEnum){coord2=gamma1;}
+			}
+			else if (IsIdenticalNode(xnodes[0],ynodes[0],xsegment[1],ysegment[1],tolerance) ||
+				     IsIdenticalNode(xnodes[1],ynodes[1],xsegment[1],ysegment[1],tolerance) ||
+				     IsIdenticalNode(xnodes[2],ynodes[2],xsegment[1],ysegment[1],tolerance)){
+
+				/*ok, segments[1] is common to one of our vertices: */
+				//if (el==318 && contouri==9){ _printf_("ok2" << "\n"); }
+				if(edge1==IntersectEnum){coord1=alpha1;}
+				if(edge2==IntersectEnum){coord1=beta1;}
+				if(edge3==IntersectEnum){coord1=gamma1;}
+				coord2=1.0;
+			}
 		}
 
@@ -344,2 +412,8 @@
 	return IntersectEnum;
 }/*}}}*/
+bool IsIdenticalNode(double x1, double y1, double x2, double y2, double tolerance){ /*{{{*/
+
+	if (sqrt(pow(x1-x2,2.0) + pow(y1-y2,2))<tolerance)return true;
+	else return false;
+
+}/*}}}*/
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 19104)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 19105)
@@ -13,7 +13,8 @@
 void MeshSegmentsIntersection(double** psegments, int* pnumsegs,int* index, double* x, double* y, int nel, int nods, double* xc, double* yc, int numnodes);
 void ElementSegmentsIntersection(DataSet* segments_dataset,int el, double* xnodes,double* ynodes,double* xc,double* yc,int numnodes);
-void ElementSegment(DataSet* segments_dataset,int el,double* xnodes,double* ynodes,double* xsegment,double* ysegment);
+void ElementSegment(DataSet* segments_dataset,int el,int contouri, double* xnodes,double* ynodes,double* xsegment,double* ysegment);
 int  SegmentIntersect(double* palpha, double* pbeta, double* x1, double* y1, double* x2, double* y2);
 bool NodeInElement(double* xnodes, double* ynodes, double x, double y);
+bool IsIdenticalNode(double x1, double y1, double x2, double y2, double tolerance);
 
 #endif /* _MESHPROFILEINTERSECTIONX_H */
Index: /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 19105)
@@ -115,9 +115,4 @@
 		parameters->AddObject(new DataSetParam(AutodiffIndependentObjectsEnum,iomodel->independent_objects));
 		/*}}}*/
-
-		#endif
-	}
-
-	#ifdef _HAVE_ADOLC_
 		/*initialize a placeholder to store solver pointers: {{{*/
 		GenericParam<Adolc_edf> *theAdolcEDF_p=new GenericParam<Adolc_edf>(AdolcParamEnum);
@@ -159,4 +154,4 @@
 		/*}}}*/
 	#endif
-
+	}
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 19105)
@@ -13,6 +13,6 @@
 	int         inversiontype;
 	int         nsteps;
-	int         num_control_type;
-	int         num_cm_responses;
+	int         num_controls;
+	int         num_costfunc;
 	int        *control_type     = NULL;
 	int        *maxiter          = NULL;
@@ -20,4 +20,5 @@
 	IssmDouble *cm_jump          = NULL;
 	IssmDouble *optscal          = NULL;
+	IssmDouble *control_scaling_factors = NULL;
 
 	/*retrieve some parameters: */
@@ -30,5 +31,4 @@
 		parameters->AddObject(iomodel->CopyConstantObject(InversionNumControlParametersEnum));
 		parameters->AddObject(iomodel->CopyConstantObject(InversionNumCostFunctionsEnum));
-		parameters->AddObject(iomodel->CopyConstantObject(InversionIncompleteAdjointEnum));
 
 		/*What solution type?*/
@@ -41,12 +41,13 @@
 
 		/*Now, recover fit, optscal and maxiter as vectors: */
-		iomodel->FetchData(&control_type,NULL,&num_control_type,InversionControlParametersEnum);
-		iomodel->FetchData(&cm_responses,NULL,&num_cm_responses,InversionCostFunctionsEnum);
-		parameters->AddObject(new IntVecParam(InversionControlParametersEnum,control_type,num_control_type));
-		parameters->AddObject(new IntVecParam(InversionCostFunctionsEnum,cm_responses,num_cm_responses));
+		iomodel->FetchData(&control_type,NULL,&num_controls,InversionControlParametersEnum);
+		iomodel->FetchData(&cm_responses,NULL,&num_costfunc,InversionCostFunctionsEnum);
+		parameters->AddObject(new IntVecParam(InversionControlParametersEnum,control_type,num_controls));
+		parameters->AddObject(new IntVecParam(InversionCostFunctionsEnum,cm_responses,num_costfunc));
 
 		/*Inversion type specifics*/
 		switch(inversiontype){
 			case 0:/*Brent Search*/
+				parameters->AddObject(iomodel->CopyConstantObject(InversionIncompleteAdjointEnum));
 				parameters->AddObject(iomodel->CopyConstantObject(InversionNstepsEnum));
 				parameters->AddObject(iomodel->CopyConstantObject(InversionCostFunctionThresholdEnum));
@@ -54,9 +55,10 @@
 				iomodel->FetchData(&optscal,NULL,NULL,InversionGradientScalingEnum);
 				iomodel->FetchData(&maxiter,NULL,NULL,InversionMaxiterPerStepEnum);
-				parameters->AddObject(new DoubleMatParam(InversionGradientScalingEnum,optscal,nsteps,num_control_type));
+				parameters->AddObject(new DoubleMatParam(InversionGradientScalingEnum,optscal,nsteps,num_controls));
 				parameters->AddObject(new DoubleVecParam(InversionStepThresholdEnum,cm_jump,nsteps));
 				parameters->AddObject(new IntVecParam(InversionMaxiterPerStepEnum,maxiter,nsteps));
 				break;
 			case 1:/*TAO*/
+				parameters->AddObject(iomodel->CopyConstantObject(InversionIncompleteAdjointEnum));
 				parameters->AddObject(iomodel->CopyConstantObject(InversionFatolEnum));
 				parameters->AddObject(iomodel->CopyConstantObject(InversionFrtolEnum));
@@ -69,10 +71,24 @@
 				break;
 			case 2:/*M1QN3*/
+				parameters->AddObject(iomodel->CopyConstantObject(InversionIncompleteAdjointEnum));
 				parameters->AddObject(iomodel->CopyConstantObject(InversionDxminEnum));
 				parameters->AddObject(iomodel->CopyConstantObject(InversionGttolEnum));
 				parameters->AddObject(iomodel->CopyConstantObject(InversionMaxstepsEnum));
 				parameters->AddObject(iomodel->CopyConstantObject(InversionMaxiterEnum));
+				iomodel->FetchData(&control_scaling_factors,NULL,NULL,InversionControlScalingFactorsEnum);
+				parameters->AddObject(new DoubleVecParam(InversionControlScalingFactorsEnum,control_scaling_factors,num_controls));
 				break;
 			case 3:/*Validation*/
+				parameters->AddObject(iomodel->CopyConstantObject(InversionIncompleteAdjointEnum));
+				iomodel->FetchData(&control_scaling_factors,NULL,NULL,InversionControlScalingFactorsEnum);
+				parameters->AddObject(new DoubleVecParam(InversionControlScalingFactorsEnum,control_scaling_factors,num_controls));
+				break;
+			case 4:/*M1QN3 AD*/
+				parameters->AddObject(iomodel->CopyConstantObject(InversionDxminEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionGttolEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionMaxstepsEnum));
+				parameters->AddObject(iomodel->CopyConstantObject(InversionMaxiterEnum));
+				iomodel->FetchData(&control_scaling_factors,NULL,NULL,InversionControlScalingFactorsEnum);
+				parameters->AddObject(new DoubleVecParam(InversionControlScalingFactorsEnum,control_scaling_factors,num_controls));
 				break;
 			default:
@@ -84,4 +100,5 @@
 		xDelete<int>(cm_responses);
 		xDelete<int>(maxiter);
+		xDelete<IssmDouble>(control_scaling_factors);
 		iomodel->DeleteData(cm_jump,InversionStepThresholdEnum);
 		iomodel->DeleteData(optscal,InversionGradientScalingEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 19105)
@@ -12,8 +12,8 @@
 
 	/*Intermediary*/
-	int       control;
+	int       control,cost_function,domaintype;
 	Element  *element = NULL;
 	Material *material = NULL;
-	int       num_control_type;
+	int       num_control_type,num_cost_functions;
 	bool      control_analysis;
 
@@ -23,12 +23,24 @@
 
 	/*Now, return if no control*/
-	if (!control_analysis) return;
-
-	/*Fetch data needed: */
-	iomodel->FetchDataToInput(elements,InversionVxObsEnum,0.);
-	iomodel->FetchDataToInput(elements,InversionVyObsEnum,0.); 
-	iomodel->FetchDataToInput(elements,InversionThicknessObsEnum,0.);
+	if(!control_analysis) return;
 
 	iomodel->FetchData(5,InversionControlParametersEnum,InversionCostFunctionsEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
+
+	/*Fetch Observations */
+	iomodel->Constant(&num_cost_functions,InversionNumCostFunctionsEnum);
+	iomodel->Constant(&domaintype,DomainTypeEnum);
+	for(int i=0;i<num_cost_functions;i++){
+		cost_function= reCast<int,IssmDouble>(iomodel->Data(InversionCostFunctionsEnum)[i]);
+		if(     cost_function==ThicknessAbsMisfitEnum) iomodel->FetchDataToInput(elements,InversionThicknessObsEnum);
+		else if(cost_function==SurfaceAbsMisfitEnum)   iomodel->FetchDataToInput(elements,InversionSurfaceObsEnum);
+		else if(cost_function==SurfaceAbsVelMisfitEnum
+			  || cost_function==SurfaceRelVelMisfitEnum
+			  || cost_function==SurfaceLogVelMisfitEnum
+			  || cost_function==SurfaceLogVxVyMisfitEnum
+			  || cost_function==SurfaceAverageVelMisfitEnum){
+			iomodel->FetchDataToInput(elements,InversionVxObsEnum);
+			if (domaintype!=Domain2DverticalEnum) iomodel->FetchDataToInput(elements,InversionVyObsEnum); 
+		}
+	}
 
 	for(int i=0;i<num_control_type;i++){
@@ -36,12 +48,13 @@
 		switch(control){
 			/*List of supported controls*/
-			case BalancethicknessThickeningRateEnum: 
+		  case BalancethicknessThickeningRateEnum: 
 			case VxEnum:
 			case VyEnum:
 			case ThicknessEnum:
-			case FrictionCoefficientEnum:
-			case BalancethicknessNuxEnum:
-			case BalancethicknessNuyEnum:
-			case BalancethicknessApparentMassbalanceEnum:
+		  case FrictionCoefficientEnum:
+		  case FrictionAsEnum:
+		  case BalancethicknessApparentMassbalanceEnum:
+			case BalancethicknessOmegaEnum:
+			case MaterialsRheologyBEnum: 
 				iomodel->FetchData(1,control); 
 				break;
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 19105)
@@ -533,4 +533,45 @@
 			}
 			break;
+		case LACrouzeixRaviartEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P2b velocity*/
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(id0+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(my_edges[i]){
+					nodes->AddObject(new Node(id0+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			id0 = id0+iomodel->numberofvertices+iomodel->numberofedges;
+			if(iomodel->meshelementtype==PentaEnum){
+				FacesPartitioning(&my_faces,iomodel);
+				for(i=0;i<iomodel->numberoffaces;i++){
+					if(iomodel->faces[i*iomodel->facescols+2]==2){/*Vertical quads*/
+						if(my_faces[i]){
+							node = new Node(id0+i+1,iomodel->numberofvertices+iomodel->numberofedges+i,lid++,0,iomodel,analysis,FSvelocityEnum);
+							nodes->AddObject(node);
+						}
+					}
+					else if(iomodel->faces[i*iomodel->facescols+2]==1){/*Triangular base/top*/
+						/*Nothing*/
+					}
+					else{
+						_error_("not supported");
+					}
+				}
+				id0 = id0+iomodel->numberoffaces;
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					nodes->AddObject(new Node(id0+i+1,id0-iomodel->nodecounter+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+
+			/*No pressure*/
+			break;
 
 		default:
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp	(revision 19105)
@@ -28,6 +28,7 @@
 				
 				/*massfluxatgate variables: */
-				int          numgates;
+				int          temp,numgates;
 				char       **gatenames               = NULL;
+				int        *gatedefinitionenums      = NULL;
 				IssmDouble **gatesegments            = NULL;
 				int         *gatesegments_M          = NULL;
@@ -36,8 +37,9 @@
 				/*Fetch segments and names: */
 				iomodel->FetchMultipleData(&gatenames,&numgates,MassfluxatgateNameEnum);
-				iomodel->FetchMultipleData(&gatesegments,&gatesegments_M,NULL,&numgates,MassfluxatgateSegmentsEnum);
+				iomodel->FetchMultipleData(&gatedefinitionenums,&temp,MassfluxatgateDefinitionenumEnum); _assert_(temp==numgates);
+				iomodel->FetchMultipleData(&gatesegments,&gatesegments_M,NULL,&temp,MassfluxatgateSegmentsEnum);_assert_(temp==numgates); 
 
 				for(j=0;j<numgates;j++){
-					output_definitions->AddObject(new Massfluxatgate<IssmDouble>(gatenames[j],gatesegments_M[j],gatesegments[j]));
+					output_definitions->AddObject(new Massfluxatgate<IssmDouble>(gatenames[j],gatedefinitionenums[j],gatesegments_M[j],gatesegments[j]));
 				}
 				/*Free ressources:*/
@@ -49,4 +51,5 @@
 				xDelete<IssmDouble*>(gatesegments);
 				xDelete<int>(gatesegments_M);
+				xDelete<int>(gatedefinitionenums);
 				/*}}}*/
 			}
@@ -57,4 +60,5 @@
 				int          nummisfits;
 				char**       misfit_name_s             = NULL;    
+				int*         misfit_definitionenums_s             = NULL;    
 				int*         misfit_model_enum_s        = NULL;
 				IssmDouble** misfit_observation_s      = NULL;
@@ -62,4 +66,5 @@
 				int*         misfit_observation_M_s    = NULL;
 				int*         misfit_observation_N_s    = NULL;
+				int*         misfit_local_s = NULL;
 				char**       misfit_timeinterpolation_s = NULL;
 				IssmDouble** misfit_weights_s           = NULL;
@@ -70,8 +75,10 @@
 				/*Fetch name, model_enum, observation, observation_enum, etc ... (see src/m/classes/misfit.m): */
 				iomodel->FetchMultipleData(&misfit_name_s,&nummisfits,MisfitNameEnum);
+				iomodel->FetchMultipleData(&misfit_definitionenums_s,&nummisfits,MisfitDefinitionenumEnum);
 				iomodel->FetchMultipleData(&misfit_model_enum_s,&nummisfits,MisfitModelEnumEnum);
 				iomodel->FetchMultipleData(&misfit_observation_s,&misfit_observation_M_s,&misfit_observation_N_s,&nummisfits,MisfitObservationEnum);
 				iomodel->FetchMultipleData(&misfit_observation_enum_s,&nummisfits,MisfitObservationEnumEnum);
 				iomodel->FetchMultipleData(&misfit_timeinterpolation_s,&nummisfits,MisfitTimeinterpolationEnum);
+				iomodel->FetchMultipleData(&misfit_local_s,&nummisfits,MisfitLocalEnum);
 				iomodel->FetchMultipleData(&misfit_weights_s,&misfit_weights_M_s,&misfit_weights_N_s,&nummisfits,MisfitWeightsEnum);
 				iomodel->FetchMultipleData(&misfit_weights_enum_s,&nummisfits,MisfitWeightsEnumEnum);
@@ -80,9 +87,9 @@
 
 					/*First create a misfit object for that specific enum (misfit_model_enum_s[j]):*/
-					output_definitions->AddObject(new Misfit(misfit_name_s[j],misfit_model_enum_s[j],misfit_observation_enum_s[j],misfit_timeinterpolation_s[j],misfit_weights_enum_s[j]));
+					output_definitions->AddObject(new Misfit(misfit_name_s[j],misfit_definitionenums_s[j],misfit_model_enum_s[j],misfit_observation_enum_s[j],misfit_timeinterpolation_s[j],(bool)misfit_local_s[j],misfit_weights_enum_s[j]));
 
 					/*Now, for this particular misfit object, make sure we plug into the elements: the observation, and the weights.*/
 					for(i=0;i<elements->Size();i++){
-						Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+						Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 						element->InputCreate(misfit_observation_s[j], iomodel,misfit_observation_M_s[j],misfit_observation_N_s[j],1,misfit_observation_enum_s[j],7);
 						element->InputCreate(misfit_weights_s[j], iomodel,misfit_weights_M_s[j],misfit_weights_N_s[j],1,misfit_weights_enum_s[j],7);
@@ -103,8 +110,10 @@
 				xDelete<char*>(misfit_name_s);
 				xDelete<int>(misfit_model_enum_s);
+				xDelete<int>(misfit_definitionenums_s);
 				xDelete<IssmDouble*>(misfit_observation_s);
 				xDelete<int>(misfit_observation_enum_s);
 				xDelete<int>(misfit_observation_M_s);
 				xDelete<int>(misfit_observation_N_s);
+				xDelete<int>(misfit_local_s);
 				xDelete<char*>(misfit_timeinterpolation_s);
 				xDelete<IssmDouble*>(misfit_weights_s);
@@ -114,5 +123,82 @@
 				/*}}}*/
 			}
-
+			else if (output_definition_enums[i]==MassconEnum){
+				/*Deal with masscons: {{{*/
+				
+				/*masscon variables: */
+				int          nummasscons;
+				char**       masscon_name_s             = NULL;    
+				int*         masscon_definitionenum_s   = NULL;    
+				IssmDouble** masscon_levelset_s           = NULL;
+				int*         masscon_levelset_M_s    = NULL;
+				int*         masscon_levelset_N_s    = NULL;
+
+				/*Fetch name and levelset, etc ... (see src/m/classes/masscon.m): */
+				iomodel->FetchMultipleData(&masscon_name_s,&nummasscons,MassconNameEnum);
+				iomodel->FetchMultipleData(&masscon_definitionenum_s,&nummasscons,MassconDefinitionenumEnum);
+				iomodel->FetchMultipleData(&masscon_levelset_s,&masscon_levelset_M_s,&masscon_levelset_N_s,&nummasscons,MassconLevelsetEnum);
+				for(j=0;j<nummasscons;j++){
+
+					/*Create a masscon object: */
+					output_definitions->AddObject(new Masscon(masscon_name_s[j],masscon_definitionenum_s[j],masscon_levelset_s[j],masscon_levelset_M_s[j]));
+
+				}
+
+				/*Free ressources:*/
+				for(j=0;j<nummasscons;j++){
+					char* string=NULL;
+					IssmDouble* matrix = NULL;
+
+					string = masscon_name_s[j];    xDelete<char>(string);
+					matrix = masscon_levelset_s[j]; xDelete<IssmDouble>(matrix);
+				}
+				xDelete<char*>(masscon_name_s);
+				xDelete<IssmDouble*>(masscon_levelset_s);
+				xDelete<int>(masscon_levelset_M_s);
+				xDelete<int>(masscon_levelset_N_s);
+				xDelete<int>(masscon_definitionenum_s);
+				/*}}}*/
+			}
+			else if (output_definition_enums[i]==MassconaxpbyEnum){
+				/*Deal with masscon combinations: {{{*/
+				
+				/*masscon variables: */
+				char**       masscon_name_s             = NULL;    
+				int*         masscon_definitionenum_s             = NULL;    
+				char**       masscon_namex_s             = NULL;    
+				char**       masscon_namey_s             = NULL;    
+				IssmDouble*  masscon_alpha_s     = NULL;
+				IssmDouble*  masscon_beta_s     = NULL;
+				int          num;
+
+				/*Fetch names and multiplicators, etc ... (see src/m/classes/masscon_axpby.m): */
+				iomodel->FetchMultipleData(&masscon_name_s,&num,MassconaxpbyNameEnum);
+				iomodel->FetchMultipleData(&masscon_definitionenum_s,&num,MassconaxpbyDefinitionenumEnum);
+				iomodel->FetchMultipleData(&masscon_namex_s,&num,MassconaxpbyNamexEnum);
+				iomodel->FetchMultipleData(&masscon_namey_s,&num,MassconaxpbyNameyEnum);
+				iomodel->FetchMultipleData(&masscon_alpha_s,&num,MassconaxpbyAlphaEnum);
+				iomodel->FetchMultipleData(&masscon_beta_s,&num,MassconaxpbyBetaEnum);
+				for(j=0;j<num;j++){
+
+					/*Create a masscon axpyb object: */
+					output_definitions->AddObject(new Massconaxpby(masscon_name_s[j],masscon_definitionenum_s[j],masscon_namex_s[j],masscon_namey_s[j],masscon_alpha_s[j],masscon_beta_s[j]));
+
+				}
+
+				/*Free ressources:*/
+				for(j=0;j<num;j++){
+					char* string=NULL;
+					string = masscon_name_s[j];    xDelete<char>(string);
+					string = masscon_namex_s[j];    xDelete<char>(string);
+					string = masscon_namey_s[j];    xDelete<char>(string);
+				}
+				xDelete<char*>(masscon_name_s);
+				xDelete<char*>(masscon_namex_s);
+				xDelete<char*>(masscon_namey_s);
+				xDelete<int>(masscon_definitionenum_s);
+				xDelete<IssmDouble>(masscon_alpha_s);
+				xDelete<IssmDouble>(masscon_beta_s);
+				/*}}}*/
+			}
 			else _error_("output definition enum " << output_definition_enums[i] << "not supported yet!");
 		}
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 19105)
@@ -22,5 +22,5 @@
 	char**      requestedoutputs = NULL;
 	IssmDouble  time;
-	bool        isdelta18o;
+	bool        isdelta18o,ismungsm;
 
 	/*parameters for mass flux:*/
@@ -37,4 +37,8 @@
 	int          count;
 
+	IssmDouble *temp = NULL;
+	IssmDouble  yts;
+	int         N,M;
+
 	/*Make sure current dataset is empty*/
 	_assert_(parameters->Size()==0); 
@@ -43,8 +47,5 @@
 	parameters->AddObject(iomodel->CopyConstantObject(DomainTypeEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(DomainDimensionEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(MeshElementtypeEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsOutputFrequencyEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(SteadystateReltolEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(SteadystateMaxiterEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(ConstantsYtsEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingStartTimeEnum));
@@ -57,5 +58,4 @@
 	parameters->AddObject(iomodel->CopyConstantObject(DebugProfilingEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(MeshAverageVertexConnectivityEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(ConstantsReferencetemperatureEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsWaitonlockEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberofelementsEnum));
@@ -63,29 +63,37 @@
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsResultsOnNodesEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsIoGatherEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(GroundinglineMigrationEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(TransientIsstressbalanceEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(TransientIsmasstransportEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(TransientIsthermalEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(TransientIsgroundinglineEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(TransientIsgiaEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(TransientIslevelsetEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(TransientIsdamageevolutionEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(TransientIshydrologyEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(MaterialsRheologyLawEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(AutodiffIsautodiffEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(QmuIsdakotaEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(InversionIscontrolEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(InversionTypeEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(GiaCrossSectionShapeEnum));
-
-	/*For stress balance only*/
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRiftPenaltyThresholdEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceMaxiterEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRestolEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceReltolEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceAbstolEnum));
-	if(iomodel->domaintype==Domain3DEnum)
-	 parameters->AddObject(iomodel->CopyConstantObject(MeshNumberoflayersEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(CalvingLawEnum));
+	{/*This is specific to ice...*/
+		parameters->AddObject(iomodel->CopyConstantObject(MeshElementtypeEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(SteadystateReltolEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(SteadystateMaxiterEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(ConstantsReferencetemperatureEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(GroundinglineMigrationEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(TransientIsstressbalanceEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(TransientIsmasstransportEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(TransientIsthermalEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(TransientIsgroundinglineEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(TransientIsgiaEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(TransientIslevelsetEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(TransientIsdamageevolutionEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(TransientIshydrologyEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(TransientIscalvingEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(MaterialsRheologyLawEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(GiaCrossSectionShapeEnum));
+
+		/*For stress balance only*/
+		parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRiftPenaltyThresholdEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(StressbalanceMaxiterEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRestolEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(StressbalanceReltolEnum));
+		parameters->AddObject(iomodel->CopyConstantObject(StressbalanceAbstolEnum));
+		if(iomodel->domaintype==Domain3DEnum)
+		 parameters->AddObject(iomodel->CopyConstantObject(MeshNumberoflayersEnum));
+	}
 
 	/*Surface mass balance parameters*/
@@ -98,12 +106,33 @@
 		case SMBpddEnum:
 			parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsIsdelta18oEnum));
+			parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsIsmungsmEnum));
 			parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsDesfacEnum));
 			parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsS0pEnum));
+			parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsS0tEnum));
+			parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsRlapsEnum));
+			parameters->AddObject(iomodel->CopyConstantObject(SurfaceforcingsRlapslgmEnum));
 			iomodel->Constant(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+			iomodel->Constant(&ismungsm,SurfaceforcingsIsmungsmEnum);
+
+			if(ismungsm){
+			  iomodel->FetchData(&temp,&N,&M,SurfaceforcingsPfacEnum); _assert_(N==2);
+			  for(i=0;i<M;i++) temp[M+i]=temp[M+i];
+			  parameters->AddObject(new TransientParam(SurfaceforcingsPfacEnum,&temp[0],&temp[M],M));
+			  iomodel->DeleteData(temp,SurfaceforcingsPfacEnum);
+			
+			  iomodel->FetchData(&temp,&N,&M,SurfaceforcingsTdiffEnum); _assert_(N==2);
+			  for(i=0;i<M;i++) temp[M+i]=temp[M+i];
+			  parameters->AddObject(new TransientParam(SurfaceforcingsTdiffEnum,&temp[0],&temp[M],M));
+			  iomodel->DeleteData(temp,SurfaceforcingsTdiffEnum);
+
+			  iomodel->FetchData(&temp,&N,&M,SurfaceforcingsSealevEnum); _assert_(N==2);
+			  for(i=0;i<M;i++) temp[M+i]=temp[M+i];
+			  parameters->AddObject(new TransientParam(SurfaceforcingsSealevEnum,&temp[0],&temp[M],M));
+			  iomodel->DeleteData(temp,SurfaceforcingsSealevEnum);
+			}
+
 			if(isdelta18o){
-				IssmDouble *temp = NULL;
-				IssmDouble  yts;
-				int         N,M;
 				iomodel->Constant(&yts,ConstantsYtsEnum);
+
 				iomodel->FetchData(&temp,&N,&M,SurfaceforcingsDelta18oEnum); _assert_(N==2);
 				for(i=0;i<M;i++) temp[M+i]=yts*temp[M+i];
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 19105)
@@ -13,8 +13,7 @@
 #include "./ModelProcessorx.h"
 
-void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* IOMODEL,FILE* toolkitfile, char* rootpath,const int solution_enum,const int nummodels,const int* analysis_enum_list){
+void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters,IoModel* iomodel,FILE* toolkitfile, char* rootpath,const int solution_enum,const int nummodels,const int* analysis_enum_list){
 
 	int   i,analysis_enum,verbose;
-	bool  isthermal,ismasstransport,isstressbalance,isgroundingline,isenthalpy,islevelset,isdamage,ishydrology;
 
 	/*Initialize datasets*/
@@ -27,18 +26,6 @@
 	Parameters  *parameters  = new Parameters();
 
-	/*Initialize IoModel from input file*/
-	IoModel* iomodel = new IoModel(IOMODEL);
-
 	/*Fetch parameters: */
 	iomodel->Constant(&verbose,VerboseEnum);
-	iomodel->Constant(&isthermal,TransientIsthermalEnum);
-	iomodel->Constant(&isenthalpy,ThermalIsenthalpyEnum);
-	iomodel->Constant(&islevelset,TransientIslevelsetEnum);
-	iomodel->Constant(&ismasstransport,TransientIsmasstransportEnum);
-	iomodel->Constant(&isstressbalance,TransientIsstressbalanceEnum);
-	iomodel->Constant(&isgroundingline,TransientIsgroundinglineEnum);
-	iomodel->Constant(&isdamage,TransientIsdamageevolutionEnum);
-	iomodel->Constant(&ishydrology,TransientIshydrologyEnum);
-
 	SetVerbosityLevel(verbose);
 
@@ -58,29 +45,4 @@
 		analysis_enum=analysis_enum_list[i];
 		parameters->AddObject(new IntParam(AnalysisCounterEnum,i));
-
-		/*Hack for trasient runs (FIXME: to be improved)*/
-		if(solution_enum==TransientSolutionEnum && analysis_enum==ThermalAnalysisEnum  && iomodel->domaintype==Domain2DhorizontalEnum) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==MeltingAnalysisEnum  && iomodel->domaintype==Domain2DhorizontalEnum) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && iomodel->domaintype==Domain2DhorizontalEnum) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==ThermalAnalysisEnum && isthermal==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==MeltingAnalysisEnum && isthermal==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && isthermal==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==ThermalAnalysisEnum && isenthalpy==true) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==MeltingAnalysisEnum && isenthalpy==true) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && isenthalpy==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==MasstransportAnalysisEnum && ismasstransport==false && isgroundingline==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==StressbalanceAnalysisEnum && isstressbalance==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==StressbalanceVerticalAnalysisEnum && isstressbalance==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==StressbalanceSIAAnalysisEnum && isstressbalance==false) continue;
-		if(solution_enum==SteadystateSolutionEnum && analysis_enum==ThermalAnalysisEnum && isenthalpy==true) continue;
-		if(solution_enum==SteadystateSolutionEnum && analysis_enum==MeltingAnalysisEnum && isenthalpy==true) continue;
-		if(solution_enum==SteadystateSolutionEnum && analysis_enum==EnthalpyAnalysisEnum && isenthalpy==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==LevelsetAnalysisEnum && islevelset==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==ExtrapolationAnalysisEnum && islevelset==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==LsfReinitializationAnalysisEnum && islevelset==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==HydrologyShreveAnalysisEnum && ishydrology==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==HydrologyDCEfficientAnalysisEnum && ishydrology==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==HydrologyDCInefficientAnalysisEnum && ishydrology==false) continue;
-		if(solution_enum==TransientSolutionEnum && analysis_enum==DamageEvolutionAnalysisEnum && isdamage==false) continue;
 
 		if(VerboseMProcessor()) _printf0_("   creating datasets for analysis " << EnumToStringx(analysis_enum) << "\n");
@@ -128,7 +90,4 @@
 	if(VerboseMProcessor()) _printf0_("   done with model processor \n");
 
-	/*Free resources:*/
-	delete iomodel;
-
 	/*Assign output pointers:*/
 	*pelements    = elements;
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 19104)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 19105)
@@ -9,5 +9,5 @@
 #include "../../analyses/analyses.h"
 
-void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* iomodel_handle,FILE* toolkitfile, char* rootpath,const int solution_type,const int nummodels,const int* analysis_type_listh);
+void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters,IoModel* iomodel,FILE* toolkitfile, char* rootpath,const int solution_type,const int nummodels,const int* analysis_type_listh);
 
 /*Creation of fem datasets: general drivers*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 19105)
@@ -65,5 +65,5 @@
 
 	/*First: add all the nodes of all the elements belonging to this cpu*/
-	if(iomodel->domaintype==Domain2DhorizontalEnum){
+	if(iomodel->domaintype==Domain2DhorizontalEnum || iomodel->domaintype==Domain2DverticalEnum){
 		for (i=0;i<iomodel->numberofelements;i++){
 			if (my_elements[i]){
@@ -83,44 +83,46 @@
 	CreateFaces(iomodel);
 
-	/*!All elements have been partitioned above, only create elements for this CPU: */
-	for(int i=0;i<iomodel->numberoffaces;i++){
+	if(iomodel->domaintype==Domain2DhorizontalEnum){
+		/*!All elements have been partitioned above, only create elements for this CPU: */
+		for(int i=0;i<iomodel->numberoffaces;i++){
 
-		/*Get left and right elements*/
-		e1=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
-		e2=iomodel->faces[4*i+3]-1; //faces are [node1 node2 elem1 elem2]
+			/*Get left and right elements*/
+			e1=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
+			e2=iomodel->faces[4*i+3]-1; //faces are [node1 node2 elem1 elem2]
 
-		/* 1) If the element e1 is in the current partition
-		 * 2) and if the face of the element is shared by another element (internal face)
-		 * 3) and if this element is not in the same partition:
-		 * we must clone the nodes on this partition so that the loads (Numericalflux)
-		 * will have access to their properties (dofs,...)*/
-		if(my_elements[e1] && e2!=-2 && !my_elements[e2]){
+			/* 1) If the element e1 is in the current partition
+			 * 2) and if the face of the element is shared by another element (internal face)
+			 * 3) and if this element is not in the same partition:
+			 * we must clone the nodes on this partition so that the loads (Numericalflux)
+			 * will have access to their properties (dofs,...)*/
+			if(my_elements[e1] && e2!=-2 && !my_elements[e2]){
 
-			/*1: Get vertices ids*/
-			i1=iomodel->faces[4*i+0];
-			i2=iomodel->faces[4*i+1];
+				/*1: Get vertices ids*/
+				i1=iomodel->faces[4*i+0];
+				i2=iomodel->faces[4*i+1];
 
-			/*2: Get the column where these ids are located in the index*/
-			pos=UNDEF;
-			for(int j=0;j<3;j++){
-				if(iomodel->elements[3*e2+j]==i1) pos=j;
-			}
+				/*2: Get the column where these ids are located in the index*/
+				pos=UNDEF;
+				for(int j=0;j<3;j++){
+					if(iomodel->elements[3*e2+j]==i1) pos=j;
+				}
 
-			/*3: We have the id of the elements and the position of the vertices in the index
-			 * we can now create the corresponding nodes:*/
-			if(pos==0){
-				my_nodes[e2*3+0]=true;
-				my_nodes[e2*3+2]=true;
-			}
-			else if(pos==1){
-				my_nodes[e2*3+1]=true;
-				my_nodes[e2*3+0]=true;
-			}
-			else if(pos==2){
-				my_nodes[e2*3+2]=true;
-				my_nodes[e2*3+1]=true;
-			}
-			else{
-				_error_("Problem in faces creation");
+				/*3: We have the id of the elements and the position of the vertices in the index
+				 * we can now create the corresponding nodes:*/
+				if(pos==0){
+					my_nodes[e2*3+0]=true;
+					my_nodes[e2*3+2]=true;
+				}
+				else if(pos==1){
+					my_nodes[e2*3+1]=true;
+					my_nodes[e2*3+0]=true;
+				}
+				else if(pos==2){
+					my_nodes[e2*3+2]=true;
+					my_nodes[e2*3+1]=true;
+				}
+				else{
+					_error_("Problem in faces creation");
+				}
 			}
 		}
Index: /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 19105)
@@ -20,5 +20,5 @@
 	 *element, figure out  if they hold the vertex, and the data. If so, return it: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		found=element->NodalValue(&value,index,natureofdataenum);
 		if(found){
Index: /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp
===================================================================
--- /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.cpp	(revision 19105)
@@ -10,21 +10,18 @@
 IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,const char* output_string){
 
-	Definition *definition         = NULL;
-	DataSet    *output_definitions = NULL;
-	IssmDouble  return_value;
-
 	/*Ok, go find the output definitions dataset in the parameters, where our responses are hiding: */
-	output_definitions=((DataSetParam*)femmodel->parameters->FindParamObject(OutputdefinitionEnum))->value;
+	DataSet* output_definitions=((DataSetParam*)femmodel->parameters->FindParamObject(OutputdefinitionEnum))->value;
 
 	/*Now, go through the output definitions, and retrieve the object which corresponds to our requested response, output_string: */
 	for(int i=0;i<output_definitions->Size();i++){
 		
-		definition=dynamic_cast<Definition*>(output_definitions->GetObjectByOffset(i));
+		//Definition* definition=xDynamicCast<Definition*>(output_definitions->GetObjectByOffset(i));
+		Definition* definition=dynamic_cast<Definition*>(output_definitions->GetObjectByOffset(i));
 
 		char* name = definition->Name();
-		if (strcmp(name,output_string)==0){
+		if(strcmp(name,output_string)==0){
 
 			/*This is the object that we have been chasing for. compute the response and return: */
-			return_value=definition->Response(femmodel);
+			IssmDouble return_value=definition->Response(femmodel);
 		
 			/*cleanup: */
@@ -41,2 +38,29 @@
 
 }
+
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum){
+
+	/*Ok, go find the output definitions dataset in the parameters, where our responses are hiding: */
+	DataSet* output_definitions=((DataSetParam*)femmodel->parameters->FindParamObject(OutputdefinitionEnum))->value;
+
+	/*Now, go through the output definitions, and retrieve the object which corresponds to our requested response, output_enum: */
+	for(int i=0;i<output_definitions->Size();i++){
+		
+		//Definition* definition=xDynamicCast<Definition*>(output_definitions->GetObjectByOffset(i));
+		Definition* definition=dynamic_cast<Definition*>(output_definitions->GetObjectByOffset(i));
+
+		int en = definition->DefinitionEnum();
+		if(en==output_enum){
+
+			/*This is the object that we have been chasing for. compute the response and return: */
+			IssmDouble return_value=definition->Response(femmodel);
+		
+			/*return:*/
+			return return_value;
+		}
+	}
+	
+	/*If we are here, did not find the definition for this response, not good!: */
+	_error_("Could not find the response for output definition " << output_enum << " because could not find the definition itself!");
+
+}
Index: /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h
===================================================================
--- /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h	(revision 19104)
+++ /issm/trunk/src/c/modules/OutputDefinitionsResponsex/OutputDefinitionsResponsex.h	(revision 19105)
@@ -9,4 +9,5 @@
 /* local prototypes: */
 IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,const char* output_string);
+IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
 
 #endif  /* _OUTPUTDEFINITIONSRESPONSEXX_H */
Index: /issm/trunk/src/c/modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.cpp	(revision 19105)
@@ -12,5 +12,5 @@
 
 	for (int i=0;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		element->ResetFSBasalBoundaryCondition();
 	}
Index: /issm/trunk/src/c/modules/RheologyBAbsGradientx/RheologyBAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/RheologyBAbsGradientx/RheologyBAbsGradientx.cpp	(revision 19105)
+++ /issm/trunk/src/c/modules/RheologyBAbsGradientx/RheologyBAbsGradientx.cpp	(revision 19105)
@@ -0,0 +1,79 @@
+/*!\file RheologyBAbsGradientx
+ * \brief: compute misfit between observations and model
+ */
+
+#include "./RheologyBAbsGradientx.h"
+
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void RheologyBAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+
+	/*output: */
+	IssmDouble J=0.;
+	IssmDouble J_sum;
+
+	/*Compute Misfit: */
+	for(int i=0;i<elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
+		J+=RheologyBAbsGradient(element);
+	}
+
+	/*Sum all J from all cpus of the cluster:*/
+	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+
+IssmDouble RheologyBAbsGradient(Element* element){
+
+	int         domaintype,numcomponents;
+	IssmDouble  Jelem=0.;
+	IssmDouble  misfit,Jdet;
+	IssmDouble  dp[3],weight;
+	IssmDouble* xyz_list      = NULL;
+
+	/*If on water, return 0: */
+	if(!element->IsIceInElement()) return 0.;
+
+	/*Get problem dimension*/
+	element->FindParam(&domaintype,DomainTypeEnum);
+	switch(domaintype){
+		case Domain2DverticalEnum:   numcomponents   = 1; break;
+		case Domain3DEnum:           numcomponents   = 2; break;
+		case Domain2DhorizontalEnum: numcomponents   = 2; break;
+		default: _error_("not supported yet");
+	}
+
+	/* Get node coordinates*/
+	element->GetVerticesCoordinates(&xyz_list);
+
+	/*Retrieve all inputs we will be needing: */
+	Input* weights_input=element->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* rheologyb_input=element->GetInput(MaterialsRheologyBEnum);                  _assert_(rheologyb_input);
+
+	/* Start  looping on the number of gaussian points: */
+	Gauss* gauss=element->NewGauss(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		element->JacobianDeterminant(&Jdet,xyz_list,gauss);
+
+		/*Get all parameters at gaussian point*/
+		weights_input->GetInputValue(&weight,gauss,RheologyBAbsGradientEnum);
+		rheologyb_input->GetInputDerivativeValue(&dp[0],xyz_list,gauss);
+
+		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
+		Jelem+=weight*1/2*(dp[0]*dp[0] + dp[1]*dp[1])*Jdet*gauss->weight;
+	}
+
+	/*clean up and Return: */
+	xDelete<IssmDouble>(xyz_list);
+	delete gauss;
+	return Jelem;
+}
Index: /issm/trunk/src/c/modules/RheologyBAbsGradientx/RheologyBAbsGradientx.h
===================================================================
--- /issm/trunk/src/c/modules/RheologyBAbsGradientx/RheologyBAbsGradientx.h	(revision 19105)
+++ /issm/trunk/src/c/modules/RheologyBAbsGradientx/RheologyBAbsGradientx.h	(revision 19105)
@@ -0,0 +1,14 @@
+/*!\file:  RheologyBAbsGradientx.h
+ * \brief header file for inverse methods misfit computation
+ */ 
+
+#ifndef _RHEOLOGYBGRADIENTX_H
+#define _RHEOLOGYBGRADIENTX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void RheologyBAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+IssmDouble RheologyBAbsGradient(Element* element);
+
+#endif
Index: /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 19105)
@@ -16,5 +16,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		J+=RheologyBbarAbsGradient(element);
 	}
Index: /issm/trunk/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/SetActiveNodesLSMx/SetActiveNodesLSMx.cpp	(revision 19105)
@@ -22,5 +22,5 @@
 
 	for(i=0;i<elements->Size();i++){
-		Element    *element  = dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element    *element  = xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		int         numnodes = element->GetNumberOfNodes();
 		IssmDouble *mask     = xNew<IssmDouble>(numnodes);
@@ -59,5 +59,5 @@
 					analysis_type==BalancethicknessAnalysisEnum ||
 					analysis_type==HydrologyDCInefficientAnalysisEnum ||
-					analysis_type==DamageEvolutionAnalysisEnum || 
+					//analysis_type==DamageEvolutionAnalysisEnum || 
 					analysis_type==HydrologyDCEfficientAnalysisEnum ||
 					analysis_type==LevelsetAnalysisEnum ||
@@ -104,5 +104,5 @@
 	/*Fill vector with values: */
 	for(i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		SetMaskOfIceElement(vec_mask_ice, element);
 	}
@@ -115,5 +115,5 @@
 	/*Clean up and return*/
 	delete vec_mask_ice;
-	delete mask_ice;
+	xDelete<IssmDouble>(mask_ice);
 
 }/*}}}*/
Index: /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 19105)
@@ -16,5 +16,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		J+=SurfaceAbsVelMisfit(element);
 	}
Index: /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 19105)
@@ -20,5 +20,5 @@
 	/*Compute gradients: */
 	for(int i=0;i<femmodel->elements->Size();i++){
-		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		S+=element->SurfaceArea();
 	}
Index: /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 19105)
@@ -17,5 +17,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		J+=SurfaceAverageVelMisfit(element);
 	}
Index: /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 19105)
@@ -16,5 +16,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		J+=SurfaceLogVelMisfit(element);
 	}
Index: /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 19105)
@@ -16,5 +16,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		J+=SurfaceLogVxVyMisfit(element);
 	}
Index: /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp	(revision 19105)
@@ -11,5 +11,5 @@
 	/*Intermediaties*/
 	int  smb_model;
-	bool isdelta18o;
+	bool isdelta18o,ismungsm;
 
 	/*First, get SMB model from parameters*/
@@ -23,7 +23,12 @@
 		case SMBpddEnum:
 			femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+			femmodel->parameters->FindParam(&ismungsm,SurfaceforcingsIsmungsmEnum);
 			if(isdelta18o){
-				if(VerboseSolution()) _printf0_("   call Delta18oParametrization module\n");
+				if(VerboseSolution()) _printf0_("   call Delta18oParameterization module\n");
 				Delta18oParameterizationx(femmodel);
+			} 
+			if(ismungsm){
+				if(VerboseSolution()) _printf0_("   call MungsmtpParameterization module\n");
+				MungsmtpParameterizationx(femmodel);
 			} 
 			if(VerboseSolution()) _printf0_("   call positive degree day module\n");
@@ -31,17 +36,17 @@
 			break;
 		case SMBgradientsEnum:
-			if(VerboseSolution())_printf_("	call smb gradients module\n");
+			if(VerboseSolution())_printf0_("	call smb gradients module\n");
 			SmbGradientsx(femmodel);
 			break;
 		case SMBhenningEnum:
-			if(VerboseSolution())_printf_("  call smb Henning module\n");
+			if(VerboseSolution())_printf0_("  call smb Henning module\n");
 			SmbHenningx(femmodel);
 			break;
 		case SMBcomponentsEnum:
-			if(VerboseSolution())_printf_("  call smb Components module\n");
+			if(VerboseSolution())_printf0_("  call smb Components module\n");
 			SmbComponentsx(femmodel);
 			break;
 		case SMBmeltcomponentsEnum:
-			if(VerboseSolution())_printf_("  call smb Melt Components module\n");
+			if(VerboseSolution())_printf0_("  call smb Melt Components module\n");
 			SmbMeltComponentsx(femmodel);
 			break;
@@ -64,5 +69,5 @@
 	/*Loop over all the elements of this partition*/
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 
 		/*Allocate all arrays*/
@@ -85,6 +90,6 @@
 
 		/*Get material parameters :*/
-		rho_ice=element->matpar->GetRhoIce();
-		rho_water=element->matpar->GetRhoFreshwater();
+		rho_ice=element->matpar->GetMaterialParameter(MaterialsRhoIceEnum);
+		rho_water=element->matpar->GetMaterialParameter(MaterialsRhoFreshwaterEnum);
 
 		// loop over all vertices
@@ -113,6 +118,14 @@
 
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->Delta18oParameterization();
+	}
+
+}/*}}}*/
+void MungsmtpParameterizationx(FemModel* femmodel){/*{{{*/
+
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->MungsmtpParameterization();
 	}
 
@@ -144,4 +157,6 @@
 	IssmDouble tstar; // monthly mean surface temp
 
+	bool ismungsm;
+
 	IssmDouble *pdds    = NULL;
 	IssmDouble *pds     = NULL;
@@ -150,4 +165,7 @@
 	pdds=xNew<IssmDouble>(NPDMAX+1); 
 	pds=xNew<IssmDouble>(NPDCMAX+1); 
+
+	// Get ismungsm parameter
+	femmodel->parameters->FindParam(&ismungsm,SurfaceforcingsIsmungsmEnum);
 
 	/* initialize PDD (creation of a lookup table)*/
@@ -204,8 +222,7 @@
 
 	for(i=0;i<femmodel->elements->Size();i++){
-		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
-		element->PositiveDegreeDay(pdds,pds,signorm);
-	}
-
+		element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->PositiveDegreeDay(pdds,pds,signorm,ismungsm);
+	}
 	/*free ressouces: */
 	xDelete<IssmDouble>(pdds);
@@ -234,5 +251,5 @@
 	/*Loop over all the elements of this partition*/
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 
 		/*Get reference SMB (uncorrected) and allocate all arrays*/
@@ -263,8 +280,9 @@
 			}
             
-            /* Compute smb including anomaly,
-             correct for number of seconds in a year [s/yr]*/
-            smb = smb + anomaly*yts;
-            
+			/* Compute smb including anomaly,
+				correct for number of seconds in a year [s/yr]*/
+			smb = smb/yts + anomaly;
+
+
 			/*Update array accordingly*/
 			smblist[v] = smb;
@@ -292,5 +310,5 @@
 	/*Loop over all the elements of this partition*/
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 
 		/*Allocate all arrays*/
@@ -333,5 +351,5 @@
 	/*Loop over all the elements of this partition*/
 	for(int i=0;i<femmodel->elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 
 		/*Allocate all arrays*/
Index: /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h	(revision 19104)
+++ /issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.h	(revision 19105)
@@ -12,4 +12,5 @@
 void SmbGradientsx(FemModel* femmodel);
 void Delta18oParameterizationx(FemModel* femmodel);
+void MungsmtpParameterizationx(FemModel* femmodel);
 void PositiveDegreeDayx(FemModel* femmodel);
 void SmbHenningx(FemModel* femmodel);
Index: /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 19105)
@@ -16,5 +16,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		J+=SurfaceRelVelMisfit(element);
 	}
Index: /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 19105)
@@ -31,6 +31,9 @@
 	Analysis* analysis = EnumToAnalysis(analysisenum);
 
+	/*Check if there are penalties*/
+	bool ispenalty = femmodel->loads->IsPenalty(configuration_type);
+
 	/*First, we might need to do a dry run to get kmax if penalties are employed*/
-	if(femmodel->loads->IsPenalty(configuration_type)){
+	if(ispenalty){
 
 		/*Allocate Kff_temp*/
@@ -40,5 +43,5 @@
 		/*Get complete stiffness matrix without penalties*/
 		for (i=0;i<femmodel->elements->Size();i++){
-			element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 			ElementMatrix* Ke = analysis->CreateKMatrix(element);
 			ElementVector* pe = analysis->CreatePVector(element);
@@ -50,5 +53,5 @@
 
 		for (i=0;i<femmodel->loads->Size();i++){
-			load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+			load=xDynamicCast<Load*>(femmodel->loads->GetObjectByOffset(i));
 			if(load->InAnalysis(configuration_type)) load->CreateKMatrix(Kff_temp,NULL);
 		}
@@ -71,5 +74,5 @@
 	/*Fill stiffness matrix and load vector from elements*/
 	for (i=0;i<femmodel->elements->Size();i++){
-		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		ElementMatrix* Ke = analysis->CreateKMatrix(element);
 		ElementVector* pe = analysis->CreatePVector(element);
@@ -85,5 +88,5 @@
 	/*Fill stiffness matrix and load vector from loads*/
 	for(i=0;i<femmodel->loads->Size();i++){
-		load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+		load=xDynamicCast<Load*>(femmodel->loads->GetObjectByOffset(i));
 		if(load->InAnalysis(configuration_type)){
 			load->CreateKMatrix(Kff,Kfs);
@@ -93,7 +96,7 @@
 
 	/*Now deal with penalties (only in loads)*/
-	if(femmodel->loads->IsPenalty(configuration_type)){
+	if(ispenalty){
 		for (i=0;i<femmodel->loads->Size();i++){
-			load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+			load=xDynamicCast<Load*>(femmodel->loads->GetObjectByOffset(i));
 			if(load->InAnalysis(configuration_type)){
 				load->PenaltyCreateKMatrix(Kff,Kfs,kmax);
@@ -106,5 +109,5 @@
 	if(pdf){
 		for(i=0;i<femmodel->elements->Size();i++){
-			element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			element=xDynamicCast<Element*>(femmodel->elements->GetObjectByOffset(i));
 			ElementVector* de=analysis->CreateDVector(element);
 			if(de) de->InsertIntoGlobal(df);
Index: /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 19105)
@@ -16,5 +16,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		J+=ThicknessAbsMisfit(element);
 	}
Index: /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 19105)
@@ -16,5 +16,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		J+=ThicknessAcrossGradient(element);
 	}
Index: /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 19104)
+++ /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 19105)
@@ -16,5 +16,5 @@
 	/*Compute Misfit: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		Element* element=xDynamicCast<Element*>(elements->GetObjectByOffset(i));
 		J+=ThicknessAlongGradient(element);
 	}
Index: /issm/trunk/src/c/modules/modules.h
===================================================================
--- /issm/trunk/src/c/modules/modules.h	(revision 19104)
+++ /issm/trunk/src/c/modules/modules.h	(revision 19105)
@@ -12,4 +12,5 @@
 #include "./BamgConvertMeshx/BamgConvertMeshx.h"
 #include "./BamgTriangulatex/BamgTriangulatex.h"
+#include "./Calvingx/Calvingx.h"
 #include "./Chacox/Chacox.h"
 #include "./ConfigureObjectsx/ConfigureObjectsx.h"
@@ -20,4 +21,5 @@
 #include "./CreateJacobianMatrixx/CreateJacobianMatrixx.h"
 #include "./DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
+#include "./ExpToLevelSetx/ExpToLevelSetx.h"
 #include "./ElementConnectivityx/ElementConnectivityx.h"
 #include "./GetSolutionFromInputsx/GetSolutionFromInputsx.h"
@@ -76,4 +78,5 @@
 #include "./ResetFSBasalBoundaryConditionx/ResetFSBasalBoundaryConditionx.h"
 #include "./RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h"
+#include "./RheologyBAbsGradientx/RheologyBAbsGradientx.h"
 #include "./Scotchx/Scotchx.h"
 #include "./Shp2Kmlx/Shp2Kmlx.h"
Index: /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 19104)
+++ /issm/trunk/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp	(revision 19105)
@@ -17,10 +17,9 @@
   IssmDouble glacialindex; // used to vary present day temperature
 
-  glacialindex = 0.;//(Delta18oTime-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceTime-Delta18oSurfacePresent))
-  //  /(Delta18oLgm-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceLgm-Delta18oSurfacePresent));
+  glacialindex = (Delta18oTime-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceTime-Delta18oSurfacePresent))
+    /(Delta18oLgm-Delta18oPresent-delta18oLapseRate*(Delta18oSurfaceLgm-Delta18oSurfacePresent)); // Tarasov 2004 paper
 
-  for (int imonth = 0; imonth<12; imonth++){  
+  for (int imonth = 0; imonth<12; imonth++){
     monthlytemperaturestmp[imonth] = glacialindex*TemperaturesLgm[imonth] + (1.-glacialindex)*TemperaturesPresentday[imonth];
-    //monthlyprectmp[imonth] = 1.5*pow(2,((monthlytemperaturestmp[imonth]-273.15-0)/10)); //equation from rob's paper
     monthlyprectmp[imonth] = PrecipitationsPresentday[imonth];
 
@@ -29,4 +28,3 @@
     *(monthlyprecout+imonth) = monthlyprectmp[imonth];
   }
-  // printf(" tempera %f\n",monthlytemperaturestmp[1]);
 }
Index: /issm/trunk/src/c/shared/Elements/ComputeMungsmTemperaturePrecipitation.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/ComputeMungsmTemperaturePrecipitation.cpp	(revision 19105)
+++ /issm/trunk/src/c/shared/Elements/ComputeMungsmTemperaturePrecipitation.cpp	(revision 19105)
@@ -0,0 +1,31 @@
+/* file:  ComputeMungsmTemperaturePrecipitation.cpp
+   Compute the temperature and precipitation at time t from 
+   the data at present day and lgm.
+   The interpolation is done from some factors extracted from the MUNGSM
+ */
+
+#include "./elements.h"
+#include "../Numerics/numerics.h"
+
+void ComputeMungsmTemperaturePrecipitation(IssmDouble TdiffTime, IssmDouble PfacTime,
+					   IssmDouble* PrecipitationsLgm, IssmDouble* PrecipitationsPresentday,
+					   IssmDouble* TemperaturesLgm, IssmDouble* TemperaturesPresentday,
+					   IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout){ 
+
+  IssmDouble monthlytemperaturestmp[12],monthlyprectmp[12];
+  IssmDouble tdiffh;  
+
+
+  for (int imonth = 0; imonth<12; imonth++){
+    tdiffh = TdiffTime*( TemperaturesLgm[imonth] - TemperaturesPresentday[imonth] );
+    monthlytemperaturestmp[imonth] = tdiffh + TemperaturesPresentday[imonth] ;
+
+    monthlyprectmp[imonth] =min(1.5, PrecipitationsPresentday[imonth] * pow(PrecipitationsLgm[imonth],PfacTime));   // [m/month]
+
+    /*Assign output pointer*/
+    *(monthlytemperaturesout+imonth) = monthlytemperaturestmp[imonth];
+    *(monthlyprecout+imonth) = monthlyprectmp[imonth];
+  }
+  // printf(" tempera %f\n",monthlytemperaturestmp[1]);
+}
+ 
Index: /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 19104)
+++ /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 19105)
@@ -1,4 +1,5 @@
 /* file:  PddSurfaceMassBlance.cpp
    Calculating the surface mass balance using the positive degree day method.
+   Updating the precipitation and temperature to the new elevation
  */
 
@@ -6,5 +7,10 @@
 #include "../Numerics/numerics.h"
 
-IssmDouble PddSurfaceMassBlance(IssmDouble* monthlytemperatures, IssmDouble* monthlyprec, IssmDouble* pdds, IssmDouble* pds, IssmDouble signorm, IssmDouble yts, IssmDouble h, IssmDouble s, IssmDouble rho_ice, IssmDouble rho_water, IssmDouble desfac, IssmDouble s0p){ 
+IssmDouble PddSurfaceMassBalance(IssmDouble* monthlytemperatures, IssmDouble* monthlyprec,
+				 IssmDouble* pdds, IssmDouble* pds, IssmDouble signorm,
+				 IssmDouble yts, IssmDouble h, IssmDouble s, IssmDouble desfac,
+				 IssmDouble s0t,IssmDouble s0p, IssmDouble rlaps,IssmDouble rlapslgm,
+				 IssmDouble TdiffTime,IssmDouble sealevTime,
+				 IssmDouble rho_water,IssmDouble rho_ice){
 
   // output:
@@ -20,10 +26,14 @@
   IssmDouble sconv; //rhow_rain/rhoi / 12 months
 
-  IssmDouble lapser=6.5, sealev=0.;    // lapse rate. degrees per meter. 7.5 lev's 99 paper, 9 Marshall 99 paper
-  // IssmDouble desfac = 0.5;                 // desert elevation factor
-  // IssmDouble s0p=0.;         // should be set to elevation from precip source
-  IssmDouble s0t=0.;         // should be set to elevation from temperature source
+  //IssmDouble  sealev=0.;         // degrees per meter. 7.5 lev's 99 paper, 9 Marshall 99 paper
+  //IssmDouble  Pfac=0.5,Tdiff=0.5;
+  IssmDouble rtlaps;
+  // IssmDouble lapser=6.5         // lapse rate
+  // IssmDouble desfac = 0.3;      // desert elevation factor
+  // IssmDouble s0p=0.;            // should be set to elevation from precip source
+  // IssmDouble s0t=0.;         // should be set to elevation from temperature source
   IssmDouble st;             // elevation between altitude of the temp record and current altitude
   IssmDouble sp;             // elevation between altitude of the prec record and current altitude
+  IssmDouble deselcut=1.0;
 
   // PDD and PD constants and variables
@@ -35,8 +45,8 @@
   IssmDouble pddt, pd; // pd: snow/precip fraction, precipitation falling as snow
 
-  IssmDouble q, qmpt; // q is desert/elev. fact, hnpfac is huybrect fact, and pd is normal dist.
-  IssmDouble qm = 0.;        // snow part of the precipitation 
-  IssmDouble qmt = 0.;       // precipitation without desertification effect adjustment
-  IssmDouble qmp = 0.;       // desertification taken into account
+  IssmDouble q, qmpt;   // q is desert/elev. fact, hnpfac is huybrect fact, and pd is normal dist.
+  IssmDouble qm = 0.;   // snow part of the precipitation 
+  IssmDouble qmt = 0.;  // precipitation without desertification effect adjustment
+  IssmDouble qmp = 0.;  // desertification taken into account
   IssmDouble pdd = 0.;     
   IssmDouble frzndd = 0.;  
@@ -68,10 +78,15 @@
 
   // seasonal loop
-    for (iqj = 0; iqj < 12; iqj++){
-      imonth =  ismon[iqj];
-
-      st=(s-s0t)/1000.;
-      tstar = monthlytemperatures[imonth] - lapser *max(st,sealev);
-      Tsurf = tstar*deltm+Tsurf;        
+  for (iqj = 0; iqj < 12; iqj++){
+    imonth =  ismon[iqj];
+    
+    /*********compute lapse rate ****************/
+    st=(s-s0t)/1000.;
+    rtlaps=TdiffTime*rlapslgm + (1.-TdiffTime)*rlaps; // lapse rate
+    
+    /*********compute Surface temperature *******/
+    monthlytemperatures[imonth]=monthlytemperatures[imonth] - rtlaps *max(st,sealevTime*0.001);
+    tstar = monthlytemperatures[imonth];
+    Tsurf = tstar*deltm+Tsurf;        
 
       /*********compute PD ****************/
@@ -83,9 +98,9 @@
 
       /******exp des/elev precip reduction*******/
-      sp=(s-s0p)/1000.; // deselev effect is wrt chng in topo
+      sp=(s-s0p)/1000.-deselcut; // deselev effect is wrt chng in topo
       if (sp>0.0){q = exp(-desfac*sp);}
       else {q = 1.0;}
 
-      qmt= qmt + monthlyprec[imonth]*sconv;  //*sconv to convert in m of ice equivalent per month
+      qmt= qmt + monthlyprec[imonth]*sconv;  //*sconv to convert in m of ice equivalent per month  
       qmpt= q*monthlyprec[imonth]*sconv;           
       qmp= qmp + qmpt;
@@ -95,5 +110,5 @@
       // ndd(month)=-(tstar-pdd(month)) since ndd+pdd gives expectation of
       // gaussian=T_m, so ndd=-(Tsurf-pdd)
-      if (iqj>5 &&  iqj<9){ Tsum=Tsum+tstar;} 
+      if (iqj>5 && iqj<9){ Tsum=Tsum+tstar;} 
 
       if (tstar >= siglim) {pdd = pdd + tstar*deltm;}
@@ -103,4 +118,8 @@
 	frzndd = frzndd - (tstar-pddsig)*deltm;}
       else{frzndd = frzndd - tstar*deltm; }
+
+      /*Assign output pointer*/
+      *(monthlytemperatures+imonth) = monthlytemperatures[imonth];
+      *(monthlyprec+imonth) = monthlyprec[imonth];      
   } // end of seasonal loop 
   //******************************************************************
Index: /issm/trunk/src/c/shared/Elements/StressIntensityIntegralWeight.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/StressIntensityIntegralWeight.cpp	(revision 19105)
+++ /issm/trunk/src/c/shared/Elements/StressIntensityIntegralWeight.cpp	(revision 19105)
@@ -0,0 +1,31 @@
+/* \file StressIntensityIntegralWeight.cpp
+ * \Weight to integrate the stress along the ice flow direction to compute the stress intensity factor : Linear Fracture Mechanics (see "Combining damage and fracture mechanics to model calving",Krug 2014 in the appendix) 
+ */
+
+#include <math.h>
+
+#include "../Numerics/types.h"
+
+IssmDouble StressIntensityIntegralWeight(IssmDouble depth, IssmDouble water_depth, IssmDouble thickness){
+
+	/*output: */
+	IssmDouble beta;
+
+	/*intermediaries: */
+	IssmDouble M1,M2,M3,x,y,d;
+	const double pi = 3.141592653589793;
+	x    = water_depth/thickness;
+	y    = depth;
+	d    = water_depth;
+
+	M1   = 0.0719768-1.513476*x-61.1001*pow(x,2)+1554.95*pow(x,3)-14583.8*pow(x,4)+71590.7*pow(x,5)-205384*pow(x,6)+356469*pow(x,7)-368270*pow(x,8)+208233*pow(x,9)-49544*pow(x,10);
+	//printf("M1 : %g",M1);
+	M2   = 0.246984+6.47583*x+176.456*pow(x,2)-4058.76*pow(x,3)+37303.8*pow(x,4)-181755*pow(x,5)+520551*pow(x,6)-904370*pow(x,7)+936863*pow(x,8)-531940*pow(x,9)+127291*pow(x,10);
+	//printf("M2 : %g",M2);
+	M3   = 0.529659-22.3235*x+532.074*pow(x,2)-5479.53*pow(x,3)+28592.2*pow(x,4)-81388.6*pow(x,5)+128746*pow(x,6)-106246*pow(x,7)+35780.7*pow(x,8);
+	//printf("M3 : %g",M3);
+
+	beta = 2/sqrt(2*pi*(d-y))*(1+M1*sqrt(1-y/d)+M2*(1-y/d)+M3*pow((1-y/d),1.5));
+
+	return beta;
+}
Index: /issm/trunk/src/c/shared/Elements/elements.h
===================================================================
--- /issm/trunk/src/c/shared/Elements/elements.h	(revision 19104)
+++ /issm/trunk/src/c/shared/Elements/elements.h	(revision 19105)
@@ -13,13 +13,21 @@
 IssmDouble LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure, IssmDouble n, IssmDouble betaCC, IssmDouble referencetemperature, IssmDouble heatcapacity, IssmDouble latentheat);
 // IssmDouble LliboutryDuval(IssmDouble temperature, IssmDouble waterfraction, IssmDouble depth,IssmDouble n);
-IssmDouble PddSurfaceMassBlance(IssmDouble* monthlytemperatures,  IssmDouble* monthlyprec, IssmDouble* pdds, IssmDouble* pds, 
-				IssmDouble signorm, IssmDouble yts, IssmDouble h, IssmDouble s,
-				IssmDouble rho_ice, IssmDouble rho_water, IssmDouble desfac, IssmDouble s0p);
+IssmDouble PddSurfaceMassBalance(IssmDouble* monthlytemperatures,  IssmDouble* monthlyprec,
+				 IssmDouble* pdds, IssmDouble* pds,IssmDouble signorm, IssmDouble yts,
+				 IssmDouble h, IssmDouble s, IssmDouble desfac,IssmDouble s0t,
+				 IssmDouble s0p, IssmDouble rlaps, IssmDouble rlapslgm,
+				 IssmDouble TdiffTime,IssmDouble sealevTime,
+				 IssmDouble rho_water, IssmDouble rho_ice);
 void ComputeDelta18oTemperaturePrecipitation(IssmDouble Delta18oSurfacePresent, IssmDouble Delta18oSurfaceLgm, IssmDouble Delta18oSurfaceTime,
-				     IssmDouble Delta18oPresent, IssmDouble Delta18oLgm, IssmDouble Delta18oTime, 
-				     IssmDouble* PrecipitationsPresentday,
-				     IssmDouble* TemperaturesLgm, IssmDouble* TemperaturesPresentday, 
-					  IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout);
+					     IssmDouble Delta18oPresent, IssmDouble Delta18oLgm, IssmDouble Delta18oTime,
+					     IssmDouble* PrecipitationsPresentday,
+					     IssmDouble* TemperaturesLgm, IssmDouble* TemperaturesPresentday, 
+					     IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout);
+void ComputeMungsmTemperaturePrecipitation(IssmDouble TdiffTime, IssmDouble PfacTime,
+					   IssmDouble* PrecipitationsLgm,IssmDouble* PrecipitationsPresentday,
+					   IssmDouble* TemperaturesLgm, IssmDouble* TemperaturesPresentday, 
+					   IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout);
 IssmDouble DrainageFunctionWaterfraction(IssmDouble waterfraction, IssmDouble dt=0.);
+IssmDouble StressIntensityIntegralWeight(IssmDouble depth, IssmDouble water_depth, IssmDouble thickness);
 
 /*Print arrays*/
Index: /issm/trunk/src/c/shared/Enum/EnumDefinitions.h
===================================================================
--- /issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 19104)
+++ /issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 19105)
@@ -50,4 +50,5 @@
 	BaseEnum,
 	ConstantsGEnum,
+	ConstantsOmegaEnum,
 	ConstantsReferencetemperatureEnum,
 	ConstantsYtsEnum,
@@ -87,4 +88,5 @@
 	FlowequationFeFSEnum,
 	FlowequationVertexEquationEnum,
+	FrictionAsEnum,
 	FrictionCoefficientEnum,
 	FrictionPEnum,
@@ -93,4 +95,7 @@
 	FrictionCEnum,
 	FrictionLawEnum,
+	FrictionGammaEnum,
+	FrictionWaterLayerEnum,
+	FrictionEffectivePressureEnum,
 	GeometryHydrostaticRatioEnum,
 	HydrologyModelEnum,
@@ -107,4 +112,5 @@
 	EplHeadSlopeXEnum,
 	EplHeadSlopeYEnum,
+	EplZigZagCounterEnum,
 	HydrologydcMaxIterEnum,
 	HydrologydcRelTolEnum,
@@ -121,7 +127,9 @@
 	HydrologydcEplPorosityEnum,
 	HydrologydcEplInitialThicknessEnum,
+	HydrologydcEplColapseThicknessEnum,
 	HydrologydcEplMaxThicknessEnum,
 	HydrologydcEplThicknessEnum,
 	HydrologydcEplThicknessOldEnum,
+	HydrologydcEplThickCompEnum,
 	HydrologydcEplConductivityEnum,
 	HydrologydcIsefficientlayerEnum,
@@ -132,4 +140,5 @@
 	HydrologydcPenaltyFactorEnum,
 	HydrologydcPenaltyLockEnum,
+	HydrologydcEplflipLockEnum,
 	HydrologydcBasalMoulinInputEnum,
 	HydrologyLayerEnum,
@@ -139,4 +148,5 @@
 	IndependentObjectEnum,
 	InversionControlParametersEnum,
+	InversionControlScalingFactorsEnum,
 	InversionCostFunctionThresholdEnum,
 	InversionCostFunctionsCoefficientsEnum,
@@ -163,4 +173,5 @@
 	InversionStepThresholdEnum,
 	InversionThicknessObsEnum,
+	InversionSurfaceObsEnum,
 	InversionVxObsEnum,
 	InversionVyObsEnum,
@@ -198,5 +209,26 @@
 	DamageEvolutionNumRequestedOutputsEnum,
 	DamageEvolutionRequestedOutputsEnum,
+	DamageEnum,
 	NewDamageEnum,
+	StressIntensityFactorEnum,
+	CalvingLawEnum,
+	CalvingCalvingrateEnum,
+	CalvingMeltingrateEnum,
+	CalvingLevermannEnum,
+	CalvingPiEnum,
+	CalvingDevEnum,
+	DefaultCalvingEnum,
+	CalvingRequestedOutputsEnum,
+	CalvinglevermannCoeffEnum,
+	CalvinglevermannMeltingrateEnum,
+	CalvingpiCoeffEnum,
+	CalvingpiMeltingrateEnum,
+	CalvingratexEnum,
+	CalvingrateyEnum,
+	CalvingratexAverageEnum,
+	CalvingrateyAverageEnum,
+	StrainRateparallelEnum,
+	StrainRateperpendicularEnum,
+	StrainRateeffectiveEnum,
 	MaterialsRhoIceEnum,
 	MaterialsRhoSeawaterEnum,
@@ -238,5 +270,4 @@
 	MasstransportPenaltyFactorEnum,
 	MasstransportSpcthicknessEnum,
-	MasstransportCalvingrateEnum,
 	MasstransportStabilizationEnum,
 	MasstransportVertexPairingEnum,
@@ -271,4 +302,5 @@
 	ThermalIsenthalpyEnum,
 	ThermalIsdynamicbasalspcEnum,
+	ThermalReltolEnum,
 	ThermalMaxiterEnum,
 	ThermalPenaltyFactorEnum,
@@ -295,4 +327,5 @@
 	TransientIsdamageevolutionEnum,
 	TransientIshydrologyEnum,
+	TransientIscalvingEnum,
 	TransientNumRequestedOutputsEnum,
 	TransientRequestedOutputsEnum,
@@ -301,9 +334,8 @@
 	BalancethicknessApparentMassbalanceEnum,
 	Balancethickness2MisfitEnum,
-	BalancethicknessNuxEnum,
-	BalancethicknessNuyEnum,
-	BalancethicknessVxObsEnum,
-	BalancethicknessVyObsEnum,
-	BalancethicknessThicknessObsEnum,
+	BalancethicknessDiffusionCoefficientEnum,
+	BalancethicknessCmuEnum,
+	BalancethicknessOmegaEnum,
+	BalancethicknessD0Enum,
 	/*}}}*/
 	/*Surfaceforcings{{{*/
@@ -315,5 +347,7 @@
 	SurfaceforcingsDelta18oSurfaceEnum,
 	SurfaceforcingsIsdelta18oEnum,
+	SurfaceforcingsIsmungsmEnum,
 	SurfaceforcingsPrecipitationsPresentdayEnum,
+	SurfaceforcingsPrecipitationsLgmEnum,
 	SurfaceforcingsTemperaturesPresentdayEnum,
 	SurfaceforcingsTemperaturesLgmEnum,
@@ -321,4 +355,10 @@
 	SurfaceforcingsDesfacEnum,
 	SurfaceforcingsS0pEnum,
+	SurfaceforcingsS0tEnum,
+	SurfaceforcingsRlapsEnum,
+	SurfaceforcingsRlapslgmEnum,
+	SurfaceforcingsPfacEnum,
+	SurfaceforcingsTdiffEnum,
+	SurfaceforcingsSealevEnum,
 	SMBgradientsEnum,
 	SurfaceforcingsMonthlytemperaturesEnum,
@@ -383,6 +423,5 @@
 	SteadystateSolutionEnum,
 	SurfaceSlopeSolutionEnum,
-	SmoothedSurfaceSlopeXAnalysisEnum,
-	SmoothedSurfaceSlopeYAnalysisEnum,
+	SmoothAnalysisEnum,
 	ThermalAnalysisEnum,
 	ThermalSolutionEnum,
@@ -394,4 +433,5 @@
 	MeshdeformationAnalysisEnum,
 	LevelsetAnalysisEnum,
+	LevelsetStabilizationEnum,
 	ExtrapolationAnalysisEnum,
 	LsfReinitializationAnalysisEnum,
@@ -443,4 +483,6 @@
 	InputToL2ProjectEnum,
 	InputToDepthaverageEnum,
+	InputToSmoothEnum,
+	SmoothThicknessMultiplierEnum,
 	IntParamEnum,
 	IntVecParamEnum,
@@ -457,4 +499,15 @@
 	ProfilerEnum,
 	MatrixParamEnum,
+	MassconEnum,
+	MassconNameEnum,
+	MassconDefinitionenumEnum,
+	MassconLevelsetEnum,
+	MassconaxpbyEnum,
+	MassconaxpbyNameEnum,
+	MassconaxpbyDefinitionenumEnum,
+	MassconaxpbyNamexEnum,
+	MassconaxpbyNameyEnum,
+	MassconaxpbyAlphaEnum,
+	MassconaxpbyBetaEnum,
 	NodeSIdEnum,
 	VectorParamEnum,
@@ -524,4 +577,5 @@
 	TemperaturePicardEnum,
 	ThicknessAbsMisfitEnum,
+	SurfaceAbsMisfitEnum,
 	VelEnum,
 	VelocityEnum,
@@ -547,4 +601,5 @@
 	IntMatParamEnum,
 	RheologyBbarAbsGradientEnum,
+	RheologyBAbsGradientEnum,
 	DragCoefficientAbsGradientEnum,
 	TransientInputEnum,
@@ -555,4 +610,6 @@
 	HydrologyWaterVxEnum,
 	HydrologyWaterVyEnum,
+	DrivingStressXEnum,
+	DrivingStressYEnum,
 	SigmaNNEnum,
 	StressTensorEnum,
@@ -563,4 +620,5 @@
 	StressTensoryzEnum,
 	StressTensorzzEnum,
+	StressMaxPrincipalEnum,
 	DeviatoricStressEnum,
 	DeviatoricStressxxEnum,
@@ -578,4 +636,5 @@
 	StrainRatezzEnum,
 	DivergenceEnum,
+	MaxDivergenceEnum,
 	GiaCrossSectionShapeEnum,
 	GiadWdtEnum,
@@ -604,4 +663,5 @@
 	OneLayerP4zEnum,
 	CrouzeixRaviartEnum,
+	LACrouzeixRaviartEnum,
 	/*}}}*/
 	/*Results{{{*/
@@ -619,12 +679,115 @@
 	/*Output Definitions{{{*/
 	OutputdefinitionEnum,
+	Outputdefinition1Enum,
+	Outputdefinition2Enum,
+	Outputdefinition3Enum,
+	Outputdefinition4Enum,
+	Outputdefinition5Enum,
+	Outputdefinition6Enum,
+	Outputdefinition7Enum,
+	Outputdefinition8Enum,
+	Outputdefinition9Enum,
+	Outputdefinition10Enum,
+	Outputdefinition11Enum,
+	Outputdefinition12Enum,
+	Outputdefinition13Enum,
+	Outputdefinition14Enum,
+	Outputdefinition15Enum,
+	Outputdefinition16Enum,
+	Outputdefinition17Enum,
+	Outputdefinition18Enum,
+	Outputdefinition19Enum,
+	Outputdefinition20Enum,
+	Outputdefinition21Enum,
+	Outputdefinition22Enum,
+	Outputdefinition23Enum,
+	Outputdefinition24Enum,
+	Outputdefinition25Enum,
+	Outputdefinition26Enum,
+	Outputdefinition27Enum,
+	Outputdefinition28Enum,
+	Outputdefinition29Enum,
+	Outputdefinition30Enum,
+	Outputdefinition31Enum,
+	Outputdefinition32Enum,
+	Outputdefinition33Enum,
+	Outputdefinition34Enum,
+	Outputdefinition35Enum,
+	Outputdefinition36Enum,
+	Outputdefinition37Enum,
+	Outputdefinition38Enum,
+	Outputdefinition39Enum,
+	Outputdefinition40Enum,
+	Outputdefinition41Enum,
+	Outputdefinition42Enum,
+	Outputdefinition43Enum,
+	Outputdefinition44Enum,
+	Outputdefinition45Enum,
+	Outputdefinition46Enum,
+	Outputdefinition47Enum,
+	Outputdefinition48Enum,
+	Outputdefinition49Enum,
+	Outputdefinition50Enum,
+	Outputdefinition51Enum,
+	Outputdefinition52Enum,
+	Outputdefinition53Enum,
+	Outputdefinition54Enum,
+	Outputdefinition55Enum,
+	Outputdefinition56Enum,
+	Outputdefinition57Enum,
+	Outputdefinition58Enum,
+	Outputdefinition59Enum,
+	Outputdefinition60Enum,
+	Outputdefinition61Enum,
+	Outputdefinition62Enum,
+	Outputdefinition63Enum,
+	Outputdefinition64Enum,
+	Outputdefinition65Enum,
+	Outputdefinition66Enum,
+	Outputdefinition67Enum,
+	Outputdefinition68Enum,
+	Outputdefinition69Enum,
+	Outputdefinition70Enum,
+	Outputdefinition71Enum,
+	Outputdefinition72Enum,
+	Outputdefinition73Enum,
+	Outputdefinition74Enum,
+	Outputdefinition75Enum,
+	Outputdefinition76Enum,
+	Outputdefinition77Enum,
+	Outputdefinition78Enum,
+	Outputdefinition79Enum,
+	Outputdefinition80Enum,
+	Outputdefinition81Enum,
+	Outputdefinition82Enum,
+	Outputdefinition83Enum,
+	Outputdefinition84Enum,
+	Outputdefinition85Enum,
+	Outputdefinition86Enum,
+	Outputdefinition87Enum,
+	Outputdefinition88Enum,
+	Outputdefinition89Enum,
+	Outputdefinition90Enum,
+	Outputdefinition91Enum,
+	Outputdefinition92Enum,
+	Outputdefinition93Enum,
+	Outputdefinition94Enum,
+	Outputdefinition95Enum,
+	Outputdefinition96Enum,
+	Outputdefinition97Enum,
+	Outputdefinition98Enum,
+	Outputdefinition99Enum,
+	Outputdefinition100Enum,   
 	OutputdefinitionListEnum,
 	MassfluxatgateEnum,
 	MassfluxatgateNameEnum,
+	MassfluxatgateDefinitionenumEnum,
 	MassfluxatgateSegmentsEnum,
 	MisfitNameEnum,
+	MisfitDefinitionenumEnum,
 	MisfitModelEnumEnum,
 	MisfitObservationEnum,
 	MisfitObservationEnumEnum,
+	MisfitLocalEnum,
 	MisfitTimeinterpolationEnum,
 	MisfitWeightsEnum,
@@ -632,4 +795,8 @@
 	SurfaceObservationEnum,
 	WeightsSurfaceObservationEnum,
+	VxObsEnum,
+	WeightsVxObsEnum,
+	VyObsEnum,
+	WeightsVyObsEnum,
 	/*}}}*/
 	/*Responses{{{*/
@@ -645,4 +812,5 @@
 	MaxVzEnum,
 	MaxAbsVzEnum,
+	IceMassEnum,
 	IceVolumeEnum,
 	IceVolumeAboveFloatationEnum,
@@ -665,4 +833,5 @@
 	SubelementMigration2Enum,
 	ContactEnum,
+	GroundingOnlyEnum,
 	MaskGroundediceLevelsetEnum,
 	/*}}}*/
@@ -693,5 +862,8 @@
 	OldGradientEnum,
 	OutputFilePointerEnum,
+	ToolkitsFileNameEnum,
+	RootPathEnum,
 	OutputFileNameEnum,
+	InputFileNameEnum,
 	LockFileNameEnum,
 	ToolkitsOptionsAnalysesEnum,
Index: /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp
===================================================================
--- /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 19104)
+++ /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 19105)
@@ -58,4 +58,5 @@
 		case BaseEnum : return "Base";
 		case ConstantsGEnum : return "ConstantsG";
+		case ConstantsOmegaEnum : return "ConstantsOmega";
 		case ConstantsReferencetemperatureEnum : return "ConstantsReferencetemperature";
 		case ConstantsYtsEnum : return "ConstantsYts";
@@ -95,4 +96,5 @@
 		case FlowequationFeFSEnum : return "FlowequationFeFS";
 		case FlowequationVertexEquationEnum : return "FlowequationVertexEquation";
+		case FrictionAsEnum : return "FrictionAs";
 		case FrictionCoefficientEnum : return "FrictionCoefficient";
 		case FrictionPEnum : return "FrictionP";
@@ -101,4 +103,7 @@
 		case FrictionCEnum : return "FrictionC";
 		case FrictionLawEnum : return "FrictionLaw";
+		case FrictionGammaEnum : return "FrictionGamma";
+		case FrictionWaterLayerEnum : return "FrictionWaterLayer";
+		case FrictionEffectivePressureEnum : return "FrictionEffectivePressure";
 		case GeometryHydrostaticRatioEnum : return "GeometryHydrostaticRatio";
 		case HydrologyModelEnum : return "HydrologyModel";
@@ -115,4 +120,5 @@
 		case EplHeadSlopeXEnum : return "EplHeadSlopeX";
 		case EplHeadSlopeYEnum : return "EplHeadSlopeY";
+		case EplZigZagCounterEnum : return "EplZigZagCounter";
 		case HydrologydcMaxIterEnum : return "HydrologydcMaxIter";
 		case HydrologydcRelTolEnum : return "HydrologydcRelTol";
@@ -129,7 +135,9 @@
 		case HydrologydcEplPorosityEnum : return "HydrologydcEplPorosity";
 		case HydrologydcEplInitialThicknessEnum : return "HydrologydcEplInitialThickness";
+		case HydrologydcEplColapseThicknessEnum : return "HydrologydcEplColapseThickness";
 		case HydrologydcEplMaxThicknessEnum : return "HydrologydcEplMaxThickness";
 		case HydrologydcEplThicknessEnum : return "HydrologydcEplThickness";
 		case HydrologydcEplThicknessOldEnum : return "HydrologydcEplThicknessOld";
+		case HydrologydcEplThickCompEnum : return "HydrologydcEplThickComp";
 		case HydrologydcEplConductivityEnum : return "HydrologydcEplConductivity";
 		case HydrologydcIsefficientlayerEnum : return "HydrologydcIsefficientlayer";
@@ -140,4 +148,5 @@
 		case HydrologydcPenaltyFactorEnum : return "HydrologydcPenaltyFactor";
 		case HydrologydcPenaltyLockEnum : return "HydrologydcPenaltyLock";
+		case HydrologydcEplflipLockEnum : return "HydrologydcEplflipLock";
 		case HydrologydcBasalMoulinInputEnum : return "HydrologydcBasalMoulinInput";
 		case HydrologyLayerEnum : return "HydrologyLayer";
@@ -147,4 +156,5 @@
 		case IndependentObjectEnum : return "IndependentObject";
 		case InversionControlParametersEnum : return "InversionControlParameters";
+		case InversionControlScalingFactorsEnum : return "InversionControlScalingFactors";
 		case InversionCostFunctionThresholdEnum : return "InversionCostFunctionThreshold";
 		case InversionCostFunctionsCoefficientsEnum : return "InversionCostFunctionsCoefficients";
@@ -171,4 +181,5 @@
 		case InversionStepThresholdEnum : return "InversionStepThreshold";
 		case InversionThicknessObsEnum : return "InversionThicknessObs";
+		case InversionSurfaceObsEnum : return "InversionSurfaceObs";
 		case InversionVxObsEnum : return "InversionVxObs";
 		case InversionVyObsEnum : return "InversionVyObs";
@@ -206,5 +217,26 @@
 		case DamageEvolutionNumRequestedOutputsEnum : return "DamageEvolutionNumRequestedOutputs";
 		case DamageEvolutionRequestedOutputsEnum : return "DamageEvolutionRequestedOutputs";
+		case DamageEnum : return "Damage";
 		case NewDamageEnum : return "NewDamage";
+		case StressIntensityFactorEnum : return "StressIntensityFactor";
+		case CalvingLawEnum : return "CalvingLaw";
+		case CalvingCalvingrateEnum : return "CalvingCalvingrate";
+		case CalvingMeltingrateEnum : return "CalvingMeltingrate";
+		case CalvingLevermannEnum : return "CalvingLevermann";
+		case CalvingPiEnum : return "CalvingPi";
+		case CalvingDevEnum : return "CalvingDev";
+		case DefaultCalvingEnum : return "DefaultCalving";
+		case CalvingRequestedOutputsEnum : return "CalvingRequestedOutputs";
+		case CalvinglevermannCoeffEnum : return "CalvinglevermannCoeff";
+		case CalvinglevermannMeltingrateEnum : return "CalvinglevermannMeltingrate";
+		case CalvingpiCoeffEnum : return "CalvingpiCoeff";
+		case CalvingpiMeltingrateEnum : return "CalvingpiMeltingrate";
+		case CalvingratexEnum : return "Calvingratex";
+		case CalvingrateyEnum : return "Calvingratey";
+		case CalvingratexAverageEnum : return "CalvingratexAverage";
+		case CalvingrateyAverageEnum : return "CalvingrateyAverage";
+		case StrainRateparallelEnum : return "StrainRateparallel";
+		case StrainRateperpendicularEnum : return "StrainRateperpendicular";
+		case StrainRateeffectiveEnum : return "StrainRateeffective";
 		case MaterialsRhoIceEnum : return "MaterialsRhoIce";
 		case MaterialsRhoSeawaterEnum : return "MaterialsRhoSeawater";
@@ -246,5 +278,4 @@
 		case MasstransportPenaltyFactorEnum : return "MasstransportPenaltyFactor";
 		case MasstransportSpcthicknessEnum : return "MasstransportSpcthickness";
-		case MasstransportCalvingrateEnum : return "MasstransportCalvingrate";
 		case MasstransportStabilizationEnum : return "MasstransportStabilization";
 		case MasstransportVertexPairingEnum : return "MasstransportVertexPairing";
@@ -279,4 +310,5 @@
 		case ThermalIsenthalpyEnum : return "ThermalIsenthalpy";
 		case ThermalIsdynamicbasalspcEnum : return "ThermalIsdynamicbasalspc";
+		case ThermalReltolEnum : return "ThermalReltol";
 		case ThermalMaxiterEnum : return "ThermalMaxiter";
 		case ThermalPenaltyFactorEnum : return "ThermalPenaltyFactor";
@@ -303,4 +335,5 @@
 		case TransientIsdamageevolutionEnum : return "TransientIsdamageevolution";
 		case TransientIshydrologyEnum : return "TransientIshydrology";
+		case TransientIscalvingEnum : return "TransientIscalving";
 		case TransientNumRequestedOutputsEnum : return "TransientNumRequestedOutputs";
 		case TransientRequestedOutputsEnum : return "TransientRequestedOutputs";
@@ -309,9 +342,8 @@
 		case BalancethicknessApparentMassbalanceEnum : return "BalancethicknessApparentMassbalance";
 		case Balancethickness2MisfitEnum : return "Balancethickness2Misfit";
-		case BalancethicknessNuxEnum : return "BalancethicknessNux";
-		case BalancethicknessNuyEnum : return "BalancethicknessNuy";
-		case BalancethicknessVxObsEnum : return "BalancethicknessVxObs";
-		case BalancethicknessVyObsEnum : return "BalancethicknessVyObs";
-		case BalancethicknessThicknessObsEnum : return "BalancethicknessThicknessObs";
+		case BalancethicknessDiffusionCoefficientEnum : return "BalancethicknessDiffusionCoefficient";
+		case BalancethicknessCmuEnum : return "BalancethicknessCmu";
+		case BalancethicknessOmegaEnum : return "BalancethicknessOmega";
+		case BalancethicknessD0Enum : return "BalancethicknessD0";
 		case SurfaceforcingsEnum : return "Surfaceforcings";
 		case SMBEnum : return "SMB";
@@ -321,5 +353,7 @@
 		case SurfaceforcingsDelta18oSurfaceEnum : return "SurfaceforcingsDelta18oSurface";
 		case SurfaceforcingsIsdelta18oEnum : return "SurfaceforcingsIsdelta18o";
+		case SurfaceforcingsIsmungsmEnum : return "SurfaceforcingsIsmungsm";
 		case SurfaceforcingsPrecipitationsPresentdayEnum : return "SurfaceforcingsPrecipitationsPresentday";
+		case SurfaceforcingsPrecipitationsLgmEnum : return "SurfaceforcingsPrecipitationsLgm";
 		case SurfaceforcingsTemperaturesPresentdayEnum : return "SurfaceforcingsTemperaturesPresentday";
 		case SurfaceforcingsTemperaturesLgmEnum : return "SurfaceforcingsTemperaturesLgm";
@@ -327,4 +361,10 @@
 		case SurfaceforcingsDesfacEnum : return "SurfaceforcingsDesfac";
 		case SurfaceforcingsS0pEnum : return "SurfaceforcingsS0p";
+		case SurfaceforcingsS0tEnum : return "SurfaceforcingsS0t";
+		case SurfaceforcingsRlapsEnum : return "SurfaceforcingsRlaps";
+		case SurfaceforcingsRlapslgmEnum : return "SurfaceforcingsRlapslgm";
+		case SurfaceforcingsPfacEnum : return "SurfaceforcingsPfac";
+		case SurfaceforcingsTdiffEnum : return "SurfaceforcingsTdiff";
+		case SurfaceforcingsSealevEnum : return "SurfaceforcingsSealev";
 		case SMBgradientsEnum : return "SMBgradients";
 		case SurfaceforcingsMonthlytemperaturesEnum : return "SurfaceforcingsMonthlytemperatures";
@@ -386,6 +426,5 @@
 		case SteadystateSolutionEnum : return "SteadystateSolution";
 		case SurfaceSlopeSolutionEnum : return "SurfaceSlopeSolution";
-		case SmoothedSurfaceSlopeXAnalysisEnum : return "SmoothedSurfaceSlopeXAnalysis";
-		case SmoothedSurfaceSlopeYAnalysisEnum : return "SmoothedSurfaceSlopeYAnalysis";
+		case SmoothAnalysisEnum : return "SmoothAnalysis";
 		case ThermalAnalysisEnum : return "ThermalAnalysis";
 		case ThermalSolutionEnum : return "ThermalSolution";
@@ -397,4 +436,5 @@
 		case MeshdeformationAnalysisEnum : return "MeshdeformationAnalysis";
 		case LevelsetAnalysisEnum : return "LevelsetAnalysis";
+		case LevelsetStabilizationEnum : return "LevelsetStabilization";
 		case ExtrapolationAnalysisEnum : return "ExtrapolationAnalysis";
 		case LsfReinitializationAnalysisEnum : return "LsfReinitializationAnalysis";
@@ -440,4 +480,6 @@
 		case InputToL2ProjectEnum : return "InputToL2Project";
 		case InputToDepthaverageEnum : return "InputToDepthaverage";
+		case InputToSmoothEnum : return "InputToSmooth";
+		case SmoothThicknessMultiplierEnum : return "SmoothThicknessMultiplier";
 		case IntParamEnum : return "IntParam";
 		case IntVecParamEnum : return "IntVecParam";
@@ -454,4 +496,15 @@
 		case ProfilerEnum : return "Profiler";
 		case MatrixParamEnum : return "MatrixParam";
+		case MassconEnum : return "Masscon";
+		case MassconNameEnum : return "MassconName";
+		case MassconDefinitionenumEnum : return "MassconDefinitionenum";
+		case MassconLevelsetEnum : return "MassconLevelset";
+		case MassconaxpbyEnum : return "Massconaxpby";
+		case MassconaxpbyNameEnum : return "MassconaxpbyName";
+		case MassconaxpbyDefinitionenumEnum : return "MassconaxpbyDefinitionenum";
+		case MassconaxpbyNamexEnum : return "MassconaxpbyNamex";
+		case MassconaxpbyNameyEnum : return "MassconaxpbyNamey";
+		case MassconaxpbyAlphaEnum : return "MassconaxpbyAlpha";
+		case MassconaxpbyBetaEnum : return "MassconaxpbyBeta";
 		case NodeSIdEnum : return "NodeSId";
 		case VectorParamEnum : return "VectorParam";
@@ -515,4 +568,5 @@
 		case TemperaturePicardEnum : return "TemperaturePicard";
 		case ThicknessAbsMisfitEnum : return "ThicknessAbsMisfit";
+		case SurfaceAbsMisfitEnum : return "SurfaceAbsMisfit";
 		case VelEnum : return "Vel";
 		case VelocityEnum : return "Velocity";
@@ -538,4 +592,5 @@
 		case IntMatParamEnum : return "IntMatParam";
 		case RheologyBbarAbsGradientEnum : return "RheologyBbarAbsGradient";
+		case RheologyBAbsGradientEnum : return "RheologyBAbsGradient";
 		case DragCoefficientAbsGradientEnum : return "DragCoefficientAbsGradient";
 		case TransientInputEnum : return "TransientInput";
@@ -546,4 +601,6 @@
 		case HydrologyWaterVxEnum : return "HydrologyWaterVx";
 		case HydrologyWaterVyEnum : return "HydrologyWaterVy";
+		case DrivingStressXEnum : return "DrivingStressX";
+		case DrivingStressYEnum : return "DrivingStressY";
 		case SigmaNNEnum : return "SigmaNN";
 		case StressTensorEnum : return "StressTensor";
@@ -554,4 +611,5 @@
 		case StressTensoryzEnum : return "StressTensoryz";
 		case StressTensorzzEnum : return "StressTensorzz";
+		case StressMaxPrincipalEnum : return "StressMaxPrincipal";
 		case DeviatoricStressEnum : return "DeviatoricStress";
 		case DeviatoricStressxxEnum : return "DeviatoricStressxx";
@@ -569,4 +627,5 @@
 		case StrainRatezzEnum : return "StrainRatezz";
 		case DivergenceEnum : return "Divergence";
+		case MaxDivergenceEnum : return "MaxDivergence";
 		case GiaCrossSectionShapeEnum : return "GiaCrossSectionShape";
 		case GiadWdtEnum : return "GiadWdt";
@@ -593,4 +652,5 @@
 		case OneLayerP4zEnum : return "OneLayerP4z";
 		case CrouzeixRaviartEnum : return "CrouzeixRaviart";
+		case LACrouzeixRaviartEnum : return "LACrouzeixRaviart";
 		case SaveResultsEnum : return "SaveResults";
 		case BoolExternalResultEnum : return "BoolExternalResult";
@@ -604,12 +664,115 @@
 		case WaterColumnOldEnum : return "WaterColumnOld";
 		case OutputdefinitionEnum : return "Outputdefinition";
+		case Outputdefinition1Enum : return "Outputdefinition1";
+		case Outputdefinition2Enum : return "Outputdefinition2";
+		case Outputdefinition3Enum : return "Outputdefinition3";
+		case Outputdefinition4Enum : return "Outputdefinition4";
+		case Outputdefinition5Enum : return "Outputdefinition5";
+		case Outputdefinition6Enum : return "Outputdefinition6";
+		case Outputdefinition7Enum : return "Outputdefinition7";
+		case Outputdefinition8Enum : return "Outputdefinition8";
+		case Outputdefinition9Enum : return "Outputdefinition9";
+		case Outputdefinition10Enum : return "Outputdefinition10";
+		case Outputdefinition11Enum : return "Outputdefinition11";
+		case Outputdefinition12Enum : return "Outputdefinition12";
+		case Outputdefinition13Enum : return "Outputdefinition13";
+		case Outputdefinition14Enum : return "Outputdefinition14";
+		case Outputdefinition15Enum : return "Outputdefinition15";
+		case Outputdefinition16Enum : return "Outputdefinition16";
+		case Outputdefinition17Enum : return "Outputdefinition17";
+		case Outputdefinition18Enum : return "Outputdefinition18";
+		case Outputdefinition19Enum : return "Outputdefinition19";
+		case Outputdefinition20Enum : return "Outputdefinition20";
+		case Outputdefinition21Enum : return "Outputdefinition21";
+		case Outputdefinition22Enum : return "Outputdefinition22";
+		case Outputdefinition23Enum : return "Outputdefinition23";
+		case Outputdefinition24Enum : return "Outputdefinition24";
+		case Outputdefinition25Enum : return "Outputdefinition25";
+		case Outputdefinition26Enum : return "Outputdefinition26";
+		case Outputdefinition27Enum : return "Outputdefinition27";
+		case Outputdefinition28Enum : return "Outputdefinition28";
+		case Outputdefinition29Enum : return "Outputdefinition29";
+		case Outputdefinition30Enum : return "Outputdefinition30";
+		case Outputdefinition31Enum : return "Outputdefinition31";
+		case Outputdefinition32Enum : return "Outputdefinition32";
+		case Outputdefinition33Enum : return "Outputdefinition33";
+		case Outputdefinition34Enum : return "Outputdefinition34";
+		case Outputdefinition35Enum : return "Outputdefinition35";
+		case Outputdefinition36Enum : return "Outputdefinition36";
+		case Outputdefinition37Enum : return "Outputdefinition37";
+		case Outputdefinition38Enum : return "Outputdefinition38";
+		case Outputdefinition39Enum : return "Outputdefinition39";
+		case Outputdefinition40Enum : return "Outputdefinition40";
+		case Outputdefinition41Enum : return "Outputdefinition41";
+		case Outputdefinition42Enum : return "Outputdefinition42";
+		case Outputdefinition43Enum : return "Outputdefinition43";
+		case Outputdefinition44Enum : return "Outputdefinition44";
+		case Outputdefinition45Enum : return "Outputdefinition45";
+		case Outputdefinition46Enum : return "Outputdefinition46";
+		case Outputdefinition47Enum : return "Outputdefinition47";
+		case Outputdefinition48Enum : return "Outputdefinition48";
+		case Outputdefinition49Enum : return "Outputdefinition49";
+		case Outputdefinition50Enum : return "Outputdefinition50";
+		case Outputdefinition51Enum : return "Outputdefinition51";
+		case Outputdefinition52Enum : return "Outputdefinition52";
+		case Outputdefinition53Enum : return "Outputdefinition53";
+		case Outputdefinition54Enum : return "Outputdefinition54";
+		case Outputdefinition55Enum : return "Outputdefinition55";
+		case Outputdefinition56Enum : return "Outputdefinition56";
+		case Outputdefinition57Enum : return "Outputdefinition57";
+		case Outputdefinition58Enum : return "Outputdefinition58";
+		case Outputdefinition59Enum : return "Outputdefinition59";
+		case Outputdefinition60Enum : return "Outputdefinition60";
+		case Outputdefinition61Enum : return "Outputdefinition61";
+		case Outputdefinition62Enum : return "Outputdefinition62";
+		case Outputdefinition63Enum : return "Outputdefinition63";
+		case Outputdefinition64Enum : return "Outputdefinition64";
+		case Outputdefinition65Enum : return "Outputdefinition65";
+		case Outputdefinition66Enum : return "Outputdefinition66";
+		case Outputdefinition67Enum : return "Outputdefinition67";
+		case Outputdefinition68Enum : return "Outputdefinition68";
+		case Outputdefinition69Enum : return "Outputdefinition69";
+		case Outputdefinition70Enum : return "Outputdefinition70";
+		case Outputdefinition71Enum : return "Outputdefinition71";
+		case Outputdefinition72Enum : return "Outputdefinition72";
+		case Outputdefinition73Enum : return "Outputdefinition73";
+		case Outputdefinition74Enum : return "Outputdefinition74";
+		case Outputdefinition75Enum : return "Outputdefinition75";
+		case Outputdefinition76Enum : return "Outputdefinition76";
+		case Outputdefinition77Enum : return "Outputdefinition77";
+		case Outputdefinition78Enum : return "Outputdefinition78";
+		case Outputdefinition79Enum : return "Outputdefinition79";
+		case Outputdefinition80Enum : return "Outputdefinition80";
+		case Outputdefinition81Enum : return "Outputdefinition81";
+		case Outputdefinition82Enum : return "Outputdefinition82";
+		case Outputdefinition83Enum : return "Outputdefinition83";
+		case Outputdefinition84Enum : return "Outputdefinition84";
+		case Outputdefinition85Enum : return "Outputdefinition85";
+		case Outputdefinition86Enum : return "Outputdefinition86";
+		case Outputdefinition87Enum : return "Outputdefinition87";
+		case Outputdefinition88Enum : return "Outputdefinition88";
+		case Outputdefinition89Enum : return "Outputdefinition89";
+		case Outputdefinition90Enum : return "Outputdefinition90";
+		case Outputdefinition91Enum : return "Outputdefinition91";
+		case Outputdefinition92Enum : return "Outputdefinition92";
+		case Outputdefinition93Enum : return "Outputdefinition93";
+		case Outputdefinition94Enum : return "Outputdefinition94";
+		case Outputdefinition95Enum : return "Outputdefinition95";
+		case Outputdefinition96Enum : return "Outputdefinition96";
+		case Outputdefinition97Enum : return "Outputdefinition97";
+		case Outputdefinition98Enum : return "Outputdefinition98";
+		case Outputdefinition99Enum : return "Outputdefinition99";
+		case Outputdefinition100Enum : return "Outputdefinition100";
 		case OutputdefinitionListEnum : return "OutputdefinitionList";
 		case MassfluxatgateEnum : return "Massfluxatgate";
 		case MassfluxatgateNameEnum : return "MassfluxatgateName";
+		case MassfluxatgateDefinitionenumEnum : return "MassfluxatgateDefinitionenum";
 		case MassfluxatgateSegmentsEnum : return "MassfluxatgateSegments";
 		case MisfitNameEnum : return "MisfitName";
+		case MisfitDefinitionenumEnum : return "MisfitDefinitionenum";
 		case MisfitModelEnumEnum : return "MisfitModelEnum";
 		case MisfitObservationEnum : return "MisfitObservation";
 		case MisfitObservationEnumEnum : return "MisfitObservationEnum";
+		case MisfitLocalEnum : return "MisfitLocal";
 		case MisfitTimeinterpolationEnum : return "MisfitTimeinterpolation";
 		case MisfitWeightsEnum : return "MisfitWeights";
@@ -617,4 +780,8 @@
 		case SurfaceObservationEnum : return "SurfaceObservation";
 		case WeightsSurfaceObservationEnum : return "WeightsSurfaceObservation";
+		case VxObsEnum : return "VxObs";
+		case WeightsVxObsEnum : return "WeightsVxObs";
+		case VyObsEnum : return "VyObs";
+		case WeightsVyObsEnum : return "WeightsVyObs";
 		case MinVelEnum : return "MinVel";
 		case MaxVelEnum : return "MaxVel";
@@ -628,4 +795,5 @@
 		case MaxVzEnum : return "MaxVz";
 		case MaxAbsVzEnum : return "MaxAbsVz";
+		case IceMassEnum : return "IceMass";
 		case IceVolumeEnum : return "IceVolume";
 		case IceVolumeAboveFloatationEnum : return "IceVolumeAboveFloatation";
@@ -644,4 +812,5 @@
 		case SubelementMigration2Enum : return "SubelementMigration2";
 		case ContactEnum : return "Contact";
+		case GroundingOnlyEnum : return "GroundingOnly";
 		case MaskGroundediceLevelsetEnum : return "MaskGroundediceLevelset";
 		case GaussSegEnum : return "GaussSeg";
@@ -666,5 +835,8 @@
 		case OldGradientEnum : return "OldGradient";
 		case OutputFilePointerEnum : return "OutputFilePointer";
+		case ToolkitsFileNameEnum : return "ToolkitsFileName";
+		case RootPathEnum : return "RootPath";
 		case OutputFileNameEnum : return "OutputFileName";
+		case InputFileNameEnum : return "InputFileName";
 		case LockFileNameEnum : return "LockFileName";
 		case ToolkitsOptionsAnalysesEnum : return "ToolkitsOptionsAnalyses";
Index: /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp
===================================================================
--- /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 19104)
+++ /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 19105)
@@ -58,4 +58,5 @@
 	      else if (strcmp(name,"Base")==0) return BaseEnum;
 	      else if (strcmp(name,"ConstantsG")==0) return ConstantsGEnum;
+	      else if (strcmp(name,"ConstantsOmega")==0) return ConstantsOmegaEnum;
 	      else if (strcmp(name,"ConstantsReferencetemperature")==0) return ConstantsReferencetemperatureEnum;
 	      else if (strcmp(name,"ConstantsYts")==0) return ConstantsYtsEnum;
@@ -95,4 +96,5 @@
 	      else if (strcmp(name,"FlowequationFeFS")==0) return FlowequationFeFSEnum;
 	      else if (strcmp(name,"FlowequationVertexEquation")==0) return FlowequationVertexEquationEnum;
+	      else if (strcmp(name,"FrictionAs")==0) return FrictionAsEnum;
 	      else if (strcmp(name,"FrictionCoefficient")==0) return FrictionCoefficientEnum;
 	      else if (strcmp(name,"FrictionP")==0) return FrictionPEnum;
@@ -101,4 +103,7 @@
 	      else if (strcmp(name,"FrictionC")==0) return FrictionCEnum;
 	      else if (strcmp(name,"FrictionLaw")==0) return FrictionLawEnum;
+	      else if (strcmp(name,"FrictionGamma")==0) return FrictionGammaEnum;
+	      else if (strcmp(name,"FrictionWaterLayer")==0) return FrictionWaterLayerEnum;
+	      else if (strcmp(name,"FrictionEffectivePressure")==0) return FrictionEffectivePressureEnum;
 	      else if (strcmp(name,"GeometryHydrostaticRatio")==0) return GeometryHydrostaticRatioEnum;
 	      else if (strcmp(name,"HydrologyModel")==0) return HydrologyModelEnum;
@@ -115,4 +120,5 @@
 	      else if (strcmp(name,"EplHeadSlopeX")==0) return EplHeadSlopeXEnum;
 	      else if (strcmp(name,"EplHeadSlopeY")==0) return EplHeadSlopeYEnum;
+	      else if (strcmp(name,"EplZigZagCounter")==0) return EplZigZagCounterEnum;
 	      else if (strcmp(name,"HydrologydcMaxIter")==0) return HydrologydcMaxIterEnum;
 	      else if (strcmp(name,"HydrologydcRelTol")==0) return HydrologydcRelTolEnum;
@@ -129,7 +135,12 @@
 	      else if (strcmp(name,"HydrologydcEplPorosity")==0) return HydrologydcEplPorosityEnum;
 	      else if (strcmp(name,"HydrologydcEplInitialThickness")==0) return HydrologydcEplInitialThicknessEnum;
+	      else if (strcmp(name,"HydrologydcEplColapseThickness")==0) return HydrologydcEplColapseThicknessEnum;
 	      else if (strcmp(name,"HydrologydcEplMaxThickness")==0) return HydrologydcEplMaxThicknessEnum;
-	      else if (strcmp(name,"HydrologydcEplThickness")==0) return HydrologydcEplThicknessEnum;
+         else stage=2;
+   }
+   if(stage==2){
+	      if (strcmp(name,"HydrologydcEplThickness")==0) return HydrologydcEplThicknessEnum;
 	      else if (strcmp(name,"HydrologydcEplThicknessOld")==0) return HydrologydcEplThicknessOldEnum;
+	      else if (strcmp(name,"HydrologydcEplThickComp")==0) return HydrologydcEplThickCompEnum;
 	      else if (strcmp(name,"HydrologydcEplConductivity")==0) return HydrologydcEplConductivityEnum;
 	      else if (strcmp(name,"HydrologydcIsefficientlayer")==0) return HydrologydcIsefficientlayerEnum;
@@ -137,10 +148,8 @@
 	      else if (strcmp(name,"HydrologydcSedimentlimit")==0) return HydrologydcSedimentlimitEnum;
 	      else if (strcmp(name,"HydrologydcTransferFlag")==0) return HydrologydcTransferFlagEnum;
-         else stage=2;
-   }
-   if(stage==2){
-	      if (strcmp(name,"HydrologydcLeakageFactor")==0) return HydrologydcLeakageFactorEnum;
+	      else if (strcmp(name,"HydrologydcLeakageFactor")==0) return HydrologydcLeakageFactorEnum;
 	      else if (strcmp(name,"HydrologydcPenaltyFactor")==0) return HydrologydcPenaltyFactorEnum;
 	      else if (strcmp(name,"HydrologydcPenaltyLock")==0) return HydrologydcPenaltyLockEnum;
+	      else if (strcmp(name,"HydrologydcEplflipLock")==0) return HydrologydcEplflipLockEnum;
 	      else if (strcmp(name,"HydrologydcBasalMoulinInput")==0) return HydrologydcBasalMoulinInputEnum;
 	      else if (strcmp(name,"HydrologyLayer")==0) return HydrologyLayerEnum;
@@ -150,4 +159,5 @@
 	      else if (strcmp(name,"IndependentObject")==0) return IndependentObjectEnum;
 	      else if (strcmp(name,"InversionControlParameters")==0) return InversionControlParametersEnum;
+	      else if (strcmp(name,"InversionControlScalingFactors")==0) return InversionControlScalingFactorsEnum;
 	      else if (strcmp(name,"InversionCostFunctionThreshold")==0) return InversionCostFunctionThresholdEnum;
 	      else if (strcmp(name,"InversionCostFunctionsCoefficients")==0) return InversionCostFunctionsCoefficientsEnum;
@@ -174,4 +184,5 @@
 	      else if (strcmp(name,"InversionStepThreshold")==0) return InversionStepThresholdEnum;
 	      else if (strcmp(name,"InversionThicknessObs")==0) return InversionThicknessObsEnum;
+	      else if (strcmp(name,"InversionSurfaceObs")==0) return InversionSurfaceObsEnum;
 	      else if (strcmp(name,"InversionVxObs")==0) return InversionVxObsEnum;
 	      else if (strcmp(name,"InversionVyObs")==0) return InversionVyObsEnum;
@@ -209,5 +220,26 @@
 	      else if (strcmp(name,"DamageEvolutionNumRequestedOutputs")==0) return DamageEvolutionNumRequestedOutputsEnum;
 	      else if (strcmp(name,"DamageEvolutionRequestedOutputs")==0) return DamageEvolutionRequestedOutputsEnum;
+	      else if (strcmp(name,"Damage")==0) return DamageEnum;
 	      else if (strcmp(name,"NewDamage")==0) return NewDamageEnum;
+	      else if (strcmp(name,"StressIntensityFactor")==0) return StressIntensityFactorEnum;
+	      else if (strcmp(name,"CalvingLaw")==0) return CalvingLawEnum;
+	      else if (strcmp(name,"CalvingCalvingrate")==0) return CalvingCalvingrateEnum;
+	      else if (strcmp(name,"CalvingMeltingrate")==0) return CalvingMeltingrateEnum;
+	      else if (strcmp(name,"CalvingLevermann")==0) return CalvingLevermannEnum;
+	      else if (strcmp(name,"CalvingPi")==0) return CalvingPiEnum;
+	      else if (strcmp(name,"CalvingDev")==0) return CalvingDevEnum;
+	      else if (strcmp(name,"DefaultCalving")==0) return DefaultCalvingEnum;
+	      else if (strcmp(name,"CalvingRequestedOutputs")==0) return CalvingRequestedOutputsEnum;
+	      else if (strcmp(name,"CalvinglevermannCoeff")==0) return CalvinglevermannCoeffEnum;
+	      else if (strcmp(name,"CalvinglevermannMeltingrate")==0) return CalvinglevermannMeltingrateEnum;
+	      else if (strcmp(name,"CalvingpiCoeff")==0) return CalvingpiCoeffEnum;
+	      else if (strcmp(name,"CalvingpiMeltingrate")==0) return CalvingpiMeltingrateEnum;
+	      else if (strcmp(name,"Calvingratex")==0) return CalvingratexEnum;
+	      else if (strcmp(name,"Calvingratey")==0) return CalvingrateyEnum;
+	      else if (strcmp(name,"CalvingratexAverage")==0) return CalvingratexAverageEnum;
+	      else if (strcmp(name,"CalvingrateyAverage")==0) return CalvingrateyAverageEnum;
+	      else if (strcmp(name,"StrainRateparallel")==0) return StrainRateparallelEnum;
+	      else if (strcmp(name,"StrainRateperpendicular")==0) return StrainRateperpendicularEnum;
+	      else if (strcmp(name,"StrainRateeffective")==0) return StrainRateeffectiveEnum;
 	      else if (strcmp(name,"MaterialsRhoIce")==0) return MaterialsRhoIceEnum;
 	      else if (strcmp(name,"MaterialsRhoSeawater")==0) return MaterialsRhoSeawaterEnum;
@@ -228,5 +260,8 @@
 	      else if (strcmp(name,"MeshNumberofelements")==0) return MeshNumberofelementsEnum;
 	      else if (strcmp(name,"MeshNumberoflayers")==0) return MeshNumberoflayersEnum;
-	      else if (strcmp(name,"MeshNumberofvertices2d")==0) return MeshNumberofvertices2dEnum;
+         else stage=3;
+   }
+   if(stage==3){
+	      if (strcmp(name,"MeshNumberofvertices2d")==0) return MeshNumberofvertices2dEnum;
 	      else if (strcmp(name,"MeshNumberofvertices")==0) return MeshNumberofverticesEnum;
 	      else if (strcmp(name,"MeshUpperelements")==0) return MeshUpperelementsEnum;
@@ -249,5 +284,4 @@
 	      else if (strcmp(name,"MasstransportPenaltyFactor")==0) return MasstransportPenaltyFactorEnum;
 	      else if (strcmp(name,"MasstransportSpcthickness")==0) return MasstransportSpcthicknessEnum;
-	      else if (strcmp(name,"MasstransportCalvingrate")==0) return MasstransportCalvingrateEnum;
 	      else if (strcmp(name,"MasstransportStabilization")==0) return MasstransportStabilizationEnum;
 	      else if (strcmp(name,"MasstransportVertexPairing")==0) return MasstransportVertexPairingEnum;
@@ -260,8 +294,5 @@
 	      else if (strcmp(name,"QmuNumberofpartitions")==0) return QmuNumberofpartitionsEnum;
 	      else if (strcmp(name,"QmuNumberofresponses")==0) return QmuNumberofresponsesEnum;
-         else stage=3;
-   }
-   if(stage==3){
-	      if (strcmp(name,"QmuPartition")==0) return QmuPartitionEnum;
+	      else if (strcmp(name,"QmuPartition")==0) return QmuPartitionEnum;
 	      else if (strcmp(name,"QmuResponsedescriptors")==0) return QmuResponsedescriptorsEnum;
 	      else if (strcmp(name,"QmuVariabledescriptors")==0) return QmuVariabledescriptorsEnum;
@@ -285,4 +316,5 @@
 	      else if (strcmp(name,"ThermalIsenthalpy")==0) return ThermalIsenthalpyEnum;
 	      else if (strcmp(name,"ThermalIsdynamicbasalspc")==0) return ThermalIsdynamicbasalspcEnum;
+	      else if (strcmp(name,"ThermalReltol")==0) return ThermalReltolEnum;
 	      else if (strcmp(name,"ThermalMaxiter")==0) return ThermalMaxiterEnum;
 	      else if (strcmp(name,"ThermalPenaltyFactor")==0) return ThermalPenaltyFactorEnum;
@@ -309,4 +341,5 @@
 	      else if (strcmp(name,"TransientIsdamageevolution")==0) return TransientIsdamageevolutionEnum;
 	      else if (strcmp(name,"TransientIshydrology")==0) return TransientIshydrologyEnum;
+	      else if (strcmp(name,"TransientIscalving")==0) return TransientIscalvingEnum;
 	      else if (strcmp(name,"TransientNumRequestedOutputs")==0) return TransientNumRequestedOutputsEnum;
 	      else if (strcmp(name,"TransientRequestedOutputs")==0) return TransientRequestedOutputsEnum;
@@ -315,9 +348,8 @@
 	      else if (strcmp(name,"BalancethicknessApparentMassbalance")==0) return BalancethicknessApparentMassbalanceEnum;
 	      else if (strcmp(name,"Balancethickness2Misfit")==0) return Balancethickness2MisfitEnum;
-	      else if (strcmp(name,"BalancethicknessNux")==0) return BalancethicknessNuxEnum;
-	      else if (strcmp(name,"BalancethicknessNuy")==0) return BalancethicknessNuyEnum;
-	      else if (strcmp(name,"BalancethicknessVxObs")==0) return BalancethicknessVxObsEnum;
-	      else if (strcmp(name,"BalancethicknessVyObs")==0) return BalancethicknessVyObsEnum;
-	      else if (strcmp(name,"BalancethicknessThicknessObs")==0) return BalancethicknessThicknessObsEnum;
+	      else if (strcmp(name,"BalancethicknessDiffusionCoefficient")==0) return BalancethicknessDiffusionCoefficientEnum;
+	      else if (strcmp(name,"BalancethicknessCmu")==0) return BalancethicknessCmuEnum;
+	      else if (strcmp(name,"BalancethicknessOmega")==0) return BalancethicknessOmegaEnum;
+	      else if (strcmp(name,"BalancethicknessD0")==0) return BalancethicknessD0Enum;
 	      else if (strcmp(name,"Surfaceforcings")==0) return SurfaceforcingsEnum;
 	      else if (strcmp(name,"SMB")==0) return SMBEnum;
@@ -327,5 +359,7 @@
 	      else if (strcmp(name,"SurfaceforcingsDelta18oSurface")==0) return SurfaceforcingsDelta18oSurfaceEnum;
 	      else if (strcmp(name,"SurfaceforcingsIsdelta18o")==0) return SurfaceforcingsIsdelta18oEnum;
+	      else if (strcmp(name,"SurfaceforcingsIsmungsm")==0) return SurfaceforcingsIsmungsmEnum;
 	      else if (strcmp(name,"SurfaceforcingsPrecipitationsPresentday")==0) return SurfaceforcingsPrecipitationsPresentdayEnum;
+	      else if (strcmp(name,"SurfaceforcingsPrecipitationsLgm")==0) return SurfaceforcingsPrecipitationsLgmEnum;
 	      else if (strcmp(name,"SurfaceforcingsTemperaturesPresentday")==0) return SurfaceforcingsTemperaturesPresentdayEnum;
 	      else if (strcmp(name,"SurfaceforcingsTemperaturesLgm")==0) return SurfaceforcingsTemperaturesLgmEnum;
@@ -333,4 +367,10 @@
 	      else if (strcmp(name,"SurfaceforcingsDesfac")==0) return SurfaceforcingsDesfacEnum;
 	      else if (strcmp(name,"SurfaceforcingsS0p")==0) return SurfaceforcingsS0pEnum;
+	      else if (strcmp(name,"SurfaceforcingsS0t")==0) return SurfaceforcingsS0tEnum;
+	      else if (strcmp(name,"SurfaceforcingsRlaps")==0) return SurfaceforcingsRlapsEnum;
+	      else if (strcmp(name,"SurfaceforcingsRlapslgm")==0) return SurfaceforcingsRlapslgmEnum;
+	      else if (strcmp(name,"SurfaceforcingsPfac")==0) return SurfaceforcingsPfacEnum;
+	      else if (strcmp(name,"SurfaceforcingsTdiff")==0) return SurfaceforcingsTdiffEnum;
+	      else if (strcmp(name,"SurfaceforcingsSealev")==0) return SurfaceforcingsSealevEnum;
 	      else if (strcmp(name,"SMBgradients")==0) return SMBgradientsEnum;
 	      else if (strcmp(name,"SurfaceforcingsMonthlytemperatures")==0) return SurfaceforcingsMonthlytemperaturesEnum;
@@ -343,5 +383,8 @@
 	      else if (strcmp(name,"SurfaceforcingsAccumulation")==0) return SurfaceforcingsAccumulationEnum;
 	      else if (strcmp(name,"SurfaceforcingsEvaporation")==0) return SurfaceforcingsEvaporationEnum;
-	      else if (strcmp(name,"SurfaceforcingsRunoff")==0) return SurfaceforcingsRunoffEnum;
+         else stage=4;
+   }
+   if(stage==4){
+	      if (strcmp(name,"SurfaceforcingsRunoff")==0) return SurfaceforcingsRunoffEnum;
 	      else if (strcmp(name,"SMBmeltcomponents")==0) return SMBmeltcomponentsEnum;
 	      else if (strcmp(name,"SurfaceforcingsMelt")==0) return SurfaceforcingsMeltEnum;
@@ -383,8 +426,5 @@
 	      else if (strcmp(name,"MeltingAnalysis")==0) return MeltingAnalysisEnum;
 	      else if (strcmp(name,"MasstransportAnalysis")==0) return MasstransportAnalysisEnum;
-         else stage=4;
-   }
-   if(stage==4){
-	      if (strcmp(name,"MasstransportSolution")==0) return MasstransportSolutionEnum;
+	      else if (strcmp(name,"MasstransportSolution")==0) return MasstransportSolutionEnum;
 	      else if (strcmp(name,"FreeSurfaceBaseAnalysis")==0) return FreeSurfaceBaseAnalysisEnum;
 	      else if (strcmp(name,"FreeSurfaceTopAnalysis")==0) return FreeSurfaceTopAnalysisEnum;
@@ -395,6 +435,5 @@
 	      else if (strcmp(name,"SteadystateSolution")==0) return SteadystateSolutionEnum;
 	      else if (strcmp(name,"SurfaceSlopeSolution")==0) return SurfaceSlopeSolutionEnum;
-	      else if (strcmp(name,"SmoothedSurfaceSlopeXAnalysis")==0) return SmoothedSurfaceSlopeXAnalysisEnum;
-	      else if (strcmp(name,"SmoothedSurfaceSlopeYAnalysis")==0) return SmoothedSurfaceSlopeYAnalysisEnum;
+	      else if (strcmp(name,"SmoothAnalysis")==0) return SmoothAnalysisEnum;
 	      else if (strcmp(name,"ThermalAnalysis")==0) return ThermalAnalysisEnum;
 	      else if (strcmp(name,"ThermalSolution")==0) return ThermalSolutionEnum;
@@ -406,4 +445,5 @@
 	      else if (strcmp(name,"MeshdeformationAnalysis")==0) return MeshdeformationAnalysisEnum;
 	      else if (strcmp(name,"LevelsetAnalysis")==0) return LevelsetAnalysisEnum;
+	      else if (strcmp(name,"LevelsetStabilization")==0) return LevelsetStabilizationEnum;
 	      else if (strcmp(name,"ExtrapolationAnalysis")==0) return ExtrapolationAnalysisEnum;
 	      else if (strcmp(name,"LsfReinitializationAnalysis")==0) return LsfReinitializationAnalysisEnum;
@@ -449,4 +489,6 @@
 	      else if (strcmp(name,"InputToL2Project")==0) return InputToL2ProjectEnum;
 	      else if (strcmp(name,"InputToDepthaverage")==0) return InputToDepthaverageEnum;
+	      else if (strcmp(name,"InputToSmooth")==0) return InputToSmoothEnum;
+	      else if (strcmp(name,"SmoothThicknessMultiplier")==0) return SmoothThicknessMultiplierEnum;
 	      else if (strcmp(name,"IntParam")==0) return IntParamEnum;
 	      else if (strcmp(name,"IntVecParam")==0) return IntVecParamEnum;
@@ -463,4 +505,18 @@
 	      else if (strcmp(name,"Profiler")==0) return ProfilerEnum;
 	      else if (strcmp(name,"MatrixParam")==0) return MatrixParamEnum;
+	      else if (strcmp(name,"Masscon")==0) return MassconEnum;
+         else stage=5;
+   }
+   if(stage==5){
+	      if (strcmp(name,"MassconName")==0) return MassconNameEnum;
+	      else if (strcmp(name,"MassconDefinitionenum")==0) return MassconDefinitionenumEnum;
+	      else if (strcmp(name,"MassconLevelset")==0) return MassconLevelsetEnum;
+	      else if (strcmp(name,"Massconaxpby")==0) return MassconaxpbyEnum;
+	      else if (strcmp(name,"MassconaxpbyName")==0) return MassconaxpbyNameEnum;
+	      else if (strcmp(name,"MassconaxpbyDefinitionenum")==0) return MassconaxpbyDefinitionenumEnum;
+	      else if (strcmp(name,"MassconaxpbyNamex")==0) return MassconaxpbyNamexEnum;
+	      else if (strcmp(name,"MassconaxpbyNamey")==0) return MassconaxpbyNameyEnum;
+	      else if (strcmp(name,"MassconaxpbyAlpha")==0) return MassconaxpbyAlphaEnum;
+	      else if (strcmp(name,"MassconaxpbyBeta")==0) return MassconaxpbyBetaEnum;
 	      else if (strcmp(name,"NodeSId")==0) return NodeSIdEnum;
 	      else if (strcmp(name,"VectorParam")==0) return VectorParamEnum;
@@ -506,8 +562,5 @@
 	      else if (strcmp(name,"Internal")==0) return InternalEnum;
 	      else if (strcmp(name,"MassFlux")==0) return MassFluxEnum;
-         else stage=5;
-   }
-   if(stage==5){
-	      if (strcmp(name,"MeltingOffset")==0) return MeltingOffsetEnum;
+	      else if (strcmp(name,"MeltingOffset")==0) return MeltingOffsetEnum;
 	      else if (strcmp(name,"Misfit")==0) return MisfitEnum;
 	      else if (strcmp(name,"Pressure")==0) return PressureEnum;
@@ -527,4 +580,5 @@
 	      else if (strcmp(name,"TemperaturePicard")==0) return TemperaturePicardEnum;
 	      else if (strcmp(name,"ThicknessAbsMisfit")==0) return ThicknessAbsMisfitEnum;
+	      else if (strcmp(name,"SurfaceAbsMisfit")==0) return SurfaceAbsMisfitEnum;
 	      else if (strcmp(name,"Vel")==0) return VelEnum;
 	      else if (strcmp(name,"Velocity")==0) return VelocityEnum;
@@ -550,4 +604,5 @@
 	      else if (strcmp(name,"IntMatParam")==0) return IntMatParamEnum;
 	      else if (strcmp(name,"RheologyBbarAbsGradient")==0) return RheologyBbarAbsGradientEnum;
+	      else if (strcmp(name,"RheologyBAbsGradient")==0) return RheologyBAbsGradientEnum;
 	      else if (strcmp(name,"DragCoefficientAbsGradient")==0) return DragCoefficientAbsGradientEnum;
 	      else if (strcmp(name,"TransientInput")==0) return TransientInputEnum;
@@ -558,4 +613,6 @@
 	      else if (strcmp(name,"HydrologyWaterVx")==0) return HydrologyWaterVxEnum;
 	      else if (strcmp(name,"HydrologyWaterVy")==0) return HydrologyWaterVyEnum;
+	      else if (strcmp(name,"DrivingStressX")==0) return DrivingStressXEnum;
+	      else if (strcmp(name,"DrivingStressY")==0) return DrivingStressYEnum;
 	      else if (strcmp(name,"SigmaNN")==0) return SigmaNNEnum;
 	      else if (strcmp(name,"StressTensor")==0) return StressTensorEnum;
@@ -566,4 +623,5 @@
 	      else if (strcmp(name,"StressTensoryz")==0) return StressTensoryzEnum;
 	      else if (strcmp(name,"StressTensorzz")==0) return StressTensorzzEnum;
+	      else if (strcmp(name,"StressMaxPrincipal")==0) return StressMaxPrincipalEnum;
 	      else if (strcmp(name,"DeviatoricStress")==0) return DeviatoricStressEnum;
 	      else if (strcmp(name,"DeviatoricStressxx")==0) return DeviatoricStressxxEnum;
@@ -571,5 +629,8 @@
 	      else if (strcmp(name,"DeviatoricStressxz")==0) return DeviatoricStressxzEnum;
 	      else if (strcmp(name,"DeviatoricStressyy")==0) return DeviatoricStressyyEnum;
-	      else if (strcmp(name,"DeviatoricStressyz")==0) return DeviatoricStressyzEnum;
+         else stage=6;
+   }
+   if(stage==6){
+	      if (strcmp(name,"DeviatoricStressyz")==0) return DeviatoricStressyzEnum;
 	      else if (strcmp(name,"DeviatoricStresszz")==0) return DeviatoricStresszzEnum;
 	      else if (strcmp(name,"StrainRate")==0) return StrainRateEnum;
@@ -581,4 +642,5 @@
 	      else if (strcmp(name,"StrainRatezz")==0) return StrainRatezzEnum;
 	      else if (strcmp(name,"Divergence")==0) return DivergenceEnum;
+	      else if (strcmp(name,"MaxDivergence")==0) return MaxDivergenceEnum;
 	      else if (strcmp(name,"GiaCrossSectionShape")==0) return GiaCrossSectionShapeEnum;
 	      else if (strcmp(name,"GiadWdt")==0) return GiadWdtEnum;
@@ -605,4 +667,5 @@
 	      else if (strcmp(name,"OneLayerP4z")==0) return OneLayerP4zEnum;
 	      else if (strcmp(name,"CrouzeixRaviart")==0) return CrouzeixRaviartEnum;
+	      else if (strcmp(name,"LACrouzeixRaviart")==0) return LACrouzeixRaviartEnum;
 	      else if (strcmp(name,"SaveResults")==0) return SaveResultsEnum;
 	      else if (strcmp(name,"BoolExternalResult")==0) return BoolExternalResultEnum;
@@ -616,12 +679,118 @@
 	      else if (strcmp(name,"WaterColumnOld")==0) return WaterColumnOldEnum;
 	      else if (strcmp(name,"Outputdefinition")==0) return OutputdefinitionEnum;
+	      else if (strcmp(name,"Outputdefinition1")==0) return Outputdefinition1Enum;
+	      else if (strcmp(name,"Outputdefinition2")==0) return Outputdefinition2Enum;
+	      else if (strcmp(name,"Outputdefinition3")==0) return Outputdefinition3Enum;
+	      else if (strcmp(name,"Outputdefinition4")==0) return Outputdefinition4Enum;
+	      else if (strcmp(name,"Outputdefinition5")==0) return Outputdefinition5Enum;
+	      else if (strcmp(name,"Outputdefinition6")==0) return Outputdefinition6Enum;
+	      else if (strcmp(name,"Outputdefinition7")==0) return Outputdefinition7Enum;
+	      else if (strcmp(name,"Outputdefinition8")==0) return Outputdefinition8Enum;
+	      else if (strcmp(name,"Outputdefinition9")==0) return Outputdefinition9Enum;
+	      else if (strcmp(name,"Outputdefinition10")==0) return Outputdefinition10Enum;
+	      else if (strcmp(name,"Outputdefinition11")==0) return Outputdefinition11Enum;
+	      else if (strcmp(name,"Outputdefinition12")==0) return Outputdefinition12Enum;
+	      else if (strcmp(name,"Outputdefinition13")==0) return Outputdefinition13Enum;
+	      else if (strcmp(name,"Outputdefinition14")==0) return Outputdefinition14Enum;
+	      else if (strcmp(name,"Outputdefinition15")==0) return Outputdefinition15Enum;
+	      else if (strcmp(name,"Outputdefinition16")==0) return Outputdefinition16Enum;
+	      else if (strcmp(name,"Outputdefinition17")==0) return Outputdefinition17Enum;
+	      else if (strcmp(name,"Outputdefinition18")==0) return Outputdefinition18Enum;
+	      else if (strcmp(name,"Outputdefinition19")==0) return Outputdefinition19Enum;
+	      else if (strcmp(name,"Outputdefinition20")==0) return Outputdefinition20Enum;
+	      else if (strcmp(name,"Outputdefinition21")==0) return Outputdefinition21Enum;
+	      else if (strcmp(name,"Outputdefinition22")==0) return Outputdefinition22Enum;
+	      else if (strcmp(name,"Outputdefinition23")==0) return Outputdefinition23Enum;
+	      else if (strcmp(name,"Outputdefinition24")==0) return Outputdefinition24Enum;
+	      else if (strcmp(name,"Outputdefinition25")==0) return Outputdefinition25Enum;
+	      else if (strcmp(name,"Outputdefinition26")==0) return Outputdefinition26Enum;
+	      else if (strcmp(name,"Outputdefinition27")==0) return Outputdefinition27Enum;
+	      else if (strcmp(name,"Outputdefinition28")==0) return Outputdefinition28Enum;
+	      else if (strcmp(name,"Outputdefinition29")==0) return Outputdefinition29Enum;
+	      else if (strcmp(name,"Outputdefinition30")==0) return Outputdefinition30Enum;
+	      else if (strcmp(name,"Outputdefinition31")==0) return Outputdefinition31Enum;
+	      else if (strcmp(name,"Outputdefinition32")==0) return Outputdefinition32Enum;
+	      else if (strcmp(name,"Outputdefinition33")==0) return Outputdefinition33Enum;
+	      else if (strcmp(name,"Outputdefinition34")==0) return Outputdefinition34Enum;
+	      else if (strcmp(name,"Outputdefinition35")==0) return Outputdefinition35Enum;
+	      else if (strcmp(name,"Outputdefinition36")==0) return Outputdefinition36Enum;
+	      else if (strcmp(name,"Outputdefinition37")==0) return Outputdefinition37Enum;
+	      else if (strcmp(name,"Outputdefinition38")==0) return Outputdefinition38Enum;
+	      else if (strcmp(name,"Outputdefinition39")==0) return Outputdefinition39Enum;
+	      else if (strcmp(name,"Outputdefinition40")==0) return Outputdefinition40Enum;
+	      else if (strcmp(name,"Outputdefinition41")==0) return Outputdefinition41Enum;
+	      else if (strcmp(name,"Outputdefinition42")==0) return Outputdefinition42Enum;
+	      else if (strcmp(name,"Outputdefinition43")==0) return Outputdefinition43Enum;
+	      else if (strcmp(name,"Outputdefinition44")==0) return Outputdefinition44Enum;
+	      else if (strcmp(name,"Outputdefinition45")==0) return Outputdefinition45Enum;
+	      else if (strcmp(name,"Outputdefinition46")==0) return Outputdefinition46Enum;
+	      else if (strcmp(name,"Outputdefinition47")==0) return Outputdefinition47Enum;
+	      else if (strcmp(name,"Outputdefinition48")==0) return Outputdefinition48Enum;
+	      else if (strcmp(name,"Outputdefinition49")==0) return Outputdefinition49Enum;
+	      else if (strcmp(name,"Outputdefinition50")==0) return Outputdefinition50Enum;
+	      else if (strcmp(name,"Outputdefinition51")==0) return Outputdefinition51Enum;
+	      else if (strcmp(name,"Outputdefinition52")==0) return Outputdefinition52Enum;
+	      else if (strcmp(name,"Outputdefinition53")==0) return Outputdefinition53Enum;
+	      else if (strcmp(name,"Outputdefinition54")==0) return Outputdefinition54Enum;
+	      else if (strcmp(name,"Outputdefinition55")==0) return Outputdefinition55Enum;
+	      else if (strcmp(name,"Outputdefinition56")==0) return Outputdefinition56Enum;
+	      else if (strcmp(name,"Outputdefinition57")==0) return Outputdefinition57Enum;
+	      else if (strcmp(name,"Outputdefinition58")==0) return Outputdefinition58Enum;
+	      else if (strcmp(name,"Outputdefinition59")==0) return Outputdefinition59Enum;
+	      else if (strcmp(name,"Outputdefinition60")==0) return Outputdefinition60Enum;
+	      else if (strcmp(name,"Outputdefinition61")==0) return Outputdefinition61Enum;
+	      else if (strcmp(name,"Outputdefinition62")==0) return Outputdefinition62Enum;
+	      else if (strcmp(name,"Outputdefinition63")==0) return Outputdefinition63Enum;
+	      else if (strcmp(name,"Outputdefinition64")==0) return Outputdefinition64Enum;
+	      else if (strcmp(name,"Outputdefinition65")==0) return Outputdefinition65Enum;
+	      else if (strcmp(name,"Outputdefinition66")==0) return Outputdefinition66Enum;
+	      else if (strcmp(name,"Outputdefinition67")==0) return Outputdefinition67Enum;
+	      else if (strcmp(name,"Outputdefinition68")==0) return Outputdefinition68Enum;
+	      else if (strcmp(name,"Outputdefinition69")==0) return Outputdefinition69Enum;
+	      else if (strcmp(name,"Outputdefinition70")==0) return Outputdefinition70Enum;
+	      else if (strcmp(name,"Outputdefinition71")==0) return Outputdefinition71Enum;
+	      else if (strcmp(name,"Outputdefinition72")==0) return Outputdefinition72Enum;
+	      else if (strcmp(name,"Outputdefinition73")==0) return Outputdefinition73Enum;
+         else stage=7;
+   }
+   if(stage==7){
+	      if (strcmp(name,"Outputdefinition74")==0) return Outputdefinition74Enum;
+	      else if (strcmp(name,"Outputdefinition75")==0) return Outputdefinition75Enum;
+	      else if (strcmp(name,"Outputdefinition76")==0) return Outputdefinition76Enum;
+	      else if (strcmp(name,"Outputdefinition77")==0) return Outputdefinition77Enum;
+	      else if (strcmp(name,"Outputdefinition78")==0) return Outputdefinition78Enum;
+	      else if (strcmp(name,"Outputdefinition79")==0) return Outputdefinition79Enum;
+	      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 if (strcmp(name,"Outputdefinition83")==0) return Outputdefinition83Enum;
+	      else if (strcmp(name,"Outputdefinition84")==0) return Outputdefinition84Enum;
+	      else if (strcmp(name,"Outputdefinition85")==0) return Outputdefinition85Enum;
+	      else if (strcmp(name,"Outputdefinition86")==0) return Outputdefinition86Enum;
+	      else if (strcmp(name,"Outputdefinition87")==0) return Outputdefinition87Enum;
+	      else if (strcmp(name,"Outputdefinition88")==0) return Outputdefinition88Enum;
+	      else if (strcmp(name,"Outputdefinition89")==0) return Outputdefinition89Enum;
+	      else if (strcmp(name,"Outputdefinition90")==0) return Outputdefinition90Enum;
+	      else if (strcmp(name,"Outputdefinition91")==0) return Outputdefinition91Enum;
+	      else if (strcmp(name,"Outputdefinition92")==0) return Outputdefinition92Enum;
+	      else if (strcmp(name,"Outputdefinition93")==0) return Outputdefinition93Enum;
+	      else if (strcmp(name,"Outputdefinition94")==0) return Outputdefinition94Enum;
+	      else if (strcmp(name,"Outputdefinition95")==0) return Outputdefinition95Enum;
+	      else if (strcmp(name,"Outputdefinition96")==0) return Outputdefinition96Enum;
+	      else if (strcmp(name,"Outputdefinition97")==0) return Outputdefinition97Enum;
+	      else if (strcmp(name,"Outputdefinition98")==0) return Outputdefinition98Enum;
+	      else if (strcmp(name,"Outputdefinition99")==0) return Outputdefinition99Enum;
+	      else if (strcmp(name,"Outputdefinition100")==0) return Outputdefinition100Enum;
 	      else if (strcmp(name,"OutputdefinitionList")==0) return OutputdefinitionListEnum;
 	      else if (strcmp(name,"Massfluxatgate")==0) return MassfluxatgateEnum;
 	      else if (strcmp(name,"MassfluxatgateName")==0) return MassfluxatgateNameEnum;
+	      else if (strcmp(name,"MassfluxatgateDefinitionenum")==0) return MassfluxatgateDefinitionenumEnum;
 	      else if (strcmp(name,"MassfluxatgateSegments")==0) return MassfluxatgateSegmentsEnum;
 	      else if (strcmp(name,"MisfitName")==0) return MisfitNameEnum;
+	      else if (strcmp(name,"MisfitDefinitionenum")==0) return MisfitDefinitionenumEnum;
 	      else if (strcmp(name,"MisfitModelEnum")==0) return MisfitModelEnumEnum;
 	      else if (strcmp(name,"MisfitObservation")==0) return MisfitObservationEnum;
 	      else if (strcmp(name,"MisfitObservationEnum")==0) return MisfitObservationEnumEnum;
+	      else if (strcmp(name,"MisfitLocal")==0) return MisfitLocalEnum;
 	      else if (strcmp(name,"MisfitTimeinterpolation")==0) return MisfitTimeinterpolationEnum;
 	      else if (strcmp(name,"MisfitWeights")==0) return MisfitWeightsEnum;
@@ -629,8 +798,9 @@
 	      else if (strcmp(name,"SurfaceObservation")==0) return SurfaceObservationEnum;
 	      else if (strcmp(name,"WeightsSurfaceObservation")==0) return WeightsSurfaceObservationEnum;
-         else stage=6;
-   }
-   if(stage==6){
-	      if (strcmp(name,"MinVel")==0) return MinVelEnum;
+	      else if (strcmp(name,"VxObs")==0) return VxObsEnum;
+	      else if (strcmp(name,"WeightsVxObs")==0) return WeightsVxObsEnum;
+	      else if (strcmp(name,"VyObs")==0) return VyObsEnum;
+	      else if (strcmp(name,"WeightsVyObs")==0) return WeightsVyObsEnum;
+	      else if (strcmp(name,"MinVel")==0) return MinVelEnum;
 	      else if (strcmp(name,"MaxVel")==0) return MaxVelEnum;
 	      else if (strcmp(name,"MinVx")==0) return MinVxEnum;
@@ -643,4 +813,5 @@
 	      else if (strcmp(name,"MaxVz")==0) return MaxVzEnum;
 	      else if (strcmp(name,"MaxAbsVz")==0) return MaxAbsVzEnum;
+	      else if (strcmp(name,"IceMass")==0) return IceMassEnum;
 	      else if (strcmp(name,"IceVolume")==0) return IceVolumeEnum;
 	      else if (strcmp(name,"IceVolumeAboveFloatation")==0) return IceVolumeAboveFloatationEnum;
@@ -659,4 +830,5 @@
 	      else if (strcmp(name,"SubelementMigration2")==0) return SubelementMigration2Enum;
 	      else if (strcmp(name,"Contact")==0) return ContactEnum;
+	      else if (strcmp(name,"GroundingOnly")==0) return GroundingOnlyEnum;
 	      else if (strcmp(name,"MaskGroundediceLevelset")==0) return MaskGroundediceLevelsetEnum;
 	      else if (strcmp(name,"GaussSeg")==0) return GaussSegEnum;
@@ -681,5 +853,8 @@
 	      else if (strcmp(name,"OldGradient")==0) return OldGradientEnum;
 	      else if (strcmp(name,"OutputFilePointer")==0) return OutputFilePointerEnum;
+	      else if (strcmp(name,"ToolkitsFileName")==0) return ToolkitsFileNameEnum;
+	      else if (strcmp(name,"RootPath")==0) return RootPathEnum;
 	      else if (strcmp(name,"OutputFileName")==0) return OutputFileNameEnum;
+	      else if (strcmp(name,"InputFileName")==0) return InputFileNameEnum;
 	      else if (strcmp(name,"LockFileName")==0) return LockFileNameEnum;
 	      else if (strcmp(name,"ToolkitsOptionsAnalyses")==0) return ToolkitsOptionsAnalysesEnum;
@@ -700,5 +875,8 @@
 	      else if (strcmp(name,"Dense")==0) return DenseEnum;
 	      else if (strcmp(name,"MpiDense")==0) return MpiDenseEnum;
-	      else if (strcmp(name,"MpiSparse")==0) return MpiSparseEnum;
+         else stage=8;
+   }
+   if(stage==8){
+	      if (strcmp(name,"MpiSparse")==0) return MpiSparseEnum;
 	      else if (strcmp(name,"Seq")==0) return SeqEnum;
 	      else if (strcmp(name,"Mpi")==0) return MpiEnum;
@@ -720,5 +898,5 @@
 	      else if (strcmp(name,"LevelsetfunctionPicard")==0) return LevelsetfunctionPicardEnum;
 	      else if (strcmp(name,"MaximumNumberOfDefinitions")==0) return MaximumNumberOfDefinitionsEnum;
-         else stage=7;
+         else stage=9;
    }
 	/*If we reach this point, the string provided has not been found*/
Index: /issm/trunk/src/c/shared/Enum/Synchronize.sh
===================================================================
--- /issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 19104)
+++ /issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 19105)
@@ -74,5 +74,5 @@
 if test \"x$"  toupper($1)"\" = \"xyes\"; then\n\
 	HAVE_"  toupper($1)"=yes\n\
-	AC_DEFINE([_HAVE_"  toupper($1)"_],[1],[with " $1"capability])\n\
+	AC_DEFINE([_HAVE_"  toupper($1)"_],[1],[with " $1" capability])\n\
 fi\n\
 AM_CONDITIONAL([" toupper($1)"], [test x$HAVE_" toupper($1)" = xyes])\n\
Index: /issm/trunk/src/c/shared/FSanalyticals/fsanalyticals.cpp
===================================================================
--- /issm/trunk/src/c/shared/FSanalyticals/fsanalyticals.cpp	(revision 19104)
+++ /issm/trunk/src/c/shared/FSanalyticals/fsanalyticals.cpp	(revision 19105)
@@ -51,7 +51,16 @@
 			z=y;
 			return 32.0/5.0*pow(PI, 2)*sin(8*PI*z);
+		case 13:
+			z=y;
+			return 8.0*pow(PI, 2)*pow(x, 2)*(z - 2)*sin(4*PI*x*z) - 4.0*PI*x*cos(4*PI*x*z) + 16.0*pow(PI, 2)*pow(z, 2)*(z - 2)*sin(4*PI*x*z) - 0.25*PI*((16*pow(PI, 2)*x*z*(PI*x*z - PI*x)*cos(4*PI*x*z) + 4*pow(PI, 2)*x*z*(8*pow(PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(PI, 2)*pow(x, 2)*z - 1)*sin(4*PI*x*z) + 4*pow(PI, 2)*x*z*sin(4*PI*x*z) - 4*PI*x*(-PI*z + PI)*sin(4*PI*x*z) - 16*PI*x*(pow(PI, 2)*x*pow(z, 2) - 2*pow(PI, 2)*x*z)*cos(4*PI*x*z) - 16*PI*z*(pow(PI, 2)*pow(x, 2)*z - pow(PI, 2)*pow(x, 2))*cos(4*PI*x*z) + 4*PI*(PI*x*z - PI*x)*sin(4*PI*x*z) - 8*(pow(PI, 2)*x*z - pow(PI, 2)*x)*sin(4*PI*x*z) - PI*(8*pow(PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(PI, 2)*pow(x, 2)*z - 1)*cos(4*PI*x*z) - PI*cos(4*PI*x*z))/(pow(PI, 3)*pow(x, 3)) + 3*(-4*PI*x*(PI*x*z - PI*x)*sin(4*PI*x*z) + PI*x*(8*pow(PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(PI, 2)*pow(x, 2)*z - 1)*cos(4*PI*x*z) + PI*x*cos(4*PI*x*z) + 4*(pow(PI, 2)*pow(x, 2)*z - pow(PI, 2)*pow(x, 2))*sin(4*PI*x*z))/(pow(PI, 3)*pow(x, 4))) + 4*PI*sin(4*PI*z)*cos(4*PI*x);
+		case 14:
+			z=y;
+			return 8.0*pow(2, 1.0L/3.0L)*pow(M_PI, 2)*pow(z, 2)*(z - 2)*sin(4*M_PI*x*z)/pow(4.0*pow(M_PI, 2)*pow(z, 2)*pow(z - 2, 2)*pow(cos(4*M_PI*x*z), 2) + (1.0L/2.0L)*pow(2.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) - 0.0625*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) + 0.5*sin(4*M_PI*x*z) + (2.0L/5.0L)*M_PI*cos(4*M_PI*x), 2) + pow(M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 0.25*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*x*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z), 2)/(pow(M_PI, 4)*pow(x, 6)), 1.0L/3.0L) - 0.0266666666666667*pow(2, 1.0L/3.0L)*M_PI*z*(z - 2)*(800.0*pow(M_PI, 3)*pow(z, 3)*pow(z - 2, 2)*sin(4*M_PI*x*z)*cos(4*M_PI*x*z) - (-10.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) + 0.3125*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) - 2.5*sin(4*M_PI*x*z) - 2*M_PI*cos(4*M_PI*x))*(40.0*pow(M_PI, 2)*x*z*(z - 2)*sin(4*M_PI*x*z) - 10.0*M_PI*z*cos(4*M_PI*x*z) - 10.0*M_PI*(z - 2)*cos(4*M_PI*x*z) + 1.25*M_PI*(32*cos(4*M_PI*x)/pow(x, 2) - 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(M_PI*pow(x, 3)) - 4*(4*pow(M_PI, 2)*pow(z, 2)*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + pow(M_PI, 2)*pow(z, 2)*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z) - 2*M_PI*z*(-M_PI*z + M_PI)*sin(4*M_PI*x*z) - 8*M_PI*z*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(z, 2) - 2*pow(M_PI, 2)*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 20*sin(4*M_PI*x)/(M_PI*pow(x, 3)) - 6*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 4)) - 6*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4)) + 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 5)) + 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 5))) + 8*pow(M_PI, 2)*sin(4*M_PI*x)) - (50*M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 12.5*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 12.5*M_PI*x*cos(4*M_PI*x*z) - 50*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z))*(4*pow(M_PI, 2)*x*z*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + pow(M_PI, 2)*x*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z) + pow(M_PI, 2)*x*z*sin(4*M_PI*x*z) - M_PI*x*(-M_PI*z + M_PI)*sin(4*M_PI*x*z) - 4.0*M_PI*x*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*cos(4*M_PI*x*z) - 4*M_PI*z*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*cos(4*M_PI*x*z) + M_PI*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 2*(pow(M_PI, 2)*x*z - pow(M_PI, 2)*x)*sin(4*M_PI*x*z) - 0.25*M_PI*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*cos(4*M_PI*x*z))/(pow(M_PI, 4)*pow(x, 6)) + 150*pow(M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 0.25*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*x*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z), 2)/(pow(M_PI, 4)*pow(x, 7)))*cos(4*M_PI*x*z)/pow(4.0*pow(M_PI, 2)*pow(z, 2)*pow(z - 2, 2)*pow(cos(4*M_PI*x*z), 2) + (1.0L/2.0L)*pow(2.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) - 0.0625*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) + 0.5*sin(4*M_PI*x*z) + (2.0L/5.0L)*M_PI*cos(4*M_PI*x), 2) + pow(M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 0.25*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*x*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z), 2)/(pow(M_PI, 4)*pow(x, 6)), 4.0L/3.0L) + (1.0L/10.0L)*pow(2, 1.0L/3.0L)*(40.0*pow(M_PI, 2)*pow(x, 2)*(z - 2)*sin(4*M_PI*x*z) - 20.0*M_PI*x*cos(4*M_PI*x*z) - 1.25*M_PI*((16*pow(M_PI, 2)*x*z*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + 4*pow(M_PI, 2)*x*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z) + 4*pow(M_PI, 2)*x*z*sin(4*M_PI*x*z) - 4*M_PI*x*(-M_PI*z + M_PI)*sin(4*M_PI*x*z) - 16*M_PI*x*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*cos(4*M_PI*x*z) - 16*M_PI*z*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*cos(4*M_PI*x*z) + 4*M_PI*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 8*(pow(M_PI, 2)*x*z - pow(M_PI, 2)*x)*sin(4*M_PI*x*z) - M_PI*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - M_PI*cos(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) + 3*(-4*M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) + M_PI*x*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))))/pow(4.0*pow(M_PI, 2)*pow(z, 2)*pow(z - 2, 2)*pow(cos(4*M_PI*x*z), 2) + (1.0L/2.0L)*pow(2.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) - 0.0625*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) + 0.5*sin(4*M_PI*x*z) + (2.0L/5.0L)*M_PI*cos(4*M_PI*x), 2) + pow(M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 0.25*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*x*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z), 2)/(pow(M_PI, 4)*pow(x, 6)), 1.0L/3.0L) + 4*M_PI*sin(4*M_PI*z)*cos(4*M_PI*x) + (1.0L/150.0L)*pow(2, 1.0L/3.0L)*(-10.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) + 0.3125*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) - 2.5*sin(4*M_PI*x*z) - 2*M_PI*cos(4*M_PI*x))*(160.0*pow(M_PI, 3)*x*pow(z, 2)*pow(z - 2, 2)*sin(4*M_PI*x*z)*cos(4*M_PI*x*z) - 40.0*pow(M_PI, 2)*pow(z, 2)*(z - 2)*pow(cos(4*M_PI*x*z), 2) - 40.0*pow(M_PI, 2)*z*pow(z - 2, 2)*pow(cos(4*M_PI*x*z), 2) + (-8.0*pow(M_PI, 2)*pow(x, 2)*(z - 2)*sin(4*M_PI*x*z) + 4.0*M_PI*x*cos(4*M_PI*x*z) + 0.25*M_PI*((16*pow(M_PI, 2)*x*z*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + 4*pow(M_PI, 2)*x*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z) + 4*pow(M_PI, 2)*x*z*sin(4*M_PI*x*z) - 4*M_PI*x*(-M_PI*z + M_PI)*sin(4*M_PI*x*z) - 16*M_PI*x*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*cos(4*M_PI*x*z) - 16*M_PI*z*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*cos(4*M_PI*x*z) + 4*M_PI*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 8*(pow(M_PI, 2)*x*z - pow(M_PI, 2)*x)*sin(4*M_PI*x*z) - M_PI*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - M_PI*cos(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) + 3*(-4*M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) + M_PI*x*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))))*(-10.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) + 0.3125*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) - 2.5*sin(4*M_PI*x*z) - 2*M_PI*cos(4*M_PI*x)) - (10*M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 2.5*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 2.5*M_PI*x*cos(4*M_PI*x*z) - 10*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z))*(4*pow(M_PI, 2)*pow(x, 2)*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + pow(M_PI, 2)*pow(x, 2)*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z) + pow(M_PI, 2)*pow(x, 2)*sin(4*M_PI*x*z) - 8.0*M_PI*x*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*cos(4*M_PI*x*z))/(pow(M_PI, 4)*pow(x, 6)))/pow(4.0*pow(M_PI, 2)*pow(z, 2)*pow(z - 2, 2)*pow(cos(4*M_PI*x*z), 2) + (1.0L/2.0L)*pow(2.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) - 0.0625*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) + 0.5*sin(4*M_PI*x*z) + (2.0L/5.0L)*M_PI*cos(4*M_PI*x), 2) + pow(M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 0.25*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*x*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z), 2)/(pow(M_PI, 4)*pow(x, 6)), 4.0L/3.0L);
 		case 21:
 			z=y;
-			return z - 4.0L/3.0L*pow(2, 1.0L/3.0L)*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*x*z*(x - 1)*(z - 1)*(2*z - 1) + z*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) + z*(6*pow(x, 2) - 6*x + 1))*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 3*pow(z, 4)*(2*x - 1) + 6*pow(z, 3)*(2*x - 1) - 3*pow(z, 2)*(2*x - 1)))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) - 1.0L/3.0L*pow(2, 1.0L/3.0L)*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x))*(2*pow(x, 3) - 3*pow(x, 2) + x + 6*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 6*z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2) + 2*pow(x, 2)*pow(x - 1, 2)*(z - 1) + pow(x, 2)*pow(x - 1, 2)*(2*z - 1) - 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) - z*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1)))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) + 2*pow(2, 1.0L/3.0L)*(pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*x*z*(x - 1)*(z - 1)*(2*z - 1) + z*pow(x - 1, 2)*(z - 1)*(2*z - 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L) - 1.0L/2.0L + pow(2, 1.0L/3.0L)*(2*pow(x, 2)*z*pow(x - 1, 2) + 2*pow(x, 2)*pow(x - 1, 2)*(z - 1) + pow(x, 2)*pow(x - 1, 2)*(2*z - 1) - 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) - z*(6*pow(x, 2) - 6*x + 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L);
+			return z - 4.0L/3.0L*pow(2, 1.0L/3.0L)*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*x*z*(x - 1)*(z - 1)*(2*z - 1) + z*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) + z*(6*pow(x, 2) - 6*x + 1))*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 3*pow(z, 4)*(2*x - 1) + 6*pow(z, 3)*(2*x - 1) - 3*pow(z, 2)*(2*x - 1)))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) - 1.0L/3.0L*pow(2, 1.0L/3.0L)*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x))*(2*pow(x, 3) - 3*pow(x, 2) + x + 6*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 6*z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2) + 2*pow(x, 2)*pow(x - 1, 2)*(z - 1) + pow(x, 2)*pow(x - 1, 2)*(2*z - 1) - 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) - z*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1)))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) + 2*pow(2, 1.0L/3.0L)*(pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*x*z*(x - 1)*(z - 1)*(2*z - 1) + z*pow(x - 1, 2)*(z - 1)*(2*z - 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L) - 0.5 + pow(2, 1.0L/3.0L)*(2*pow(x, 2)*z*pow(x - 1, 2) + 2*pow(x, 2)*pow(x - 1, 2)*(z - 1) + pow(x, 2)*pow(x - 1, 2)*(2*z - 1) - 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) - z*(6*pow(x, 2) - 6*x + 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L);
+		case 22:
+			z=y;
+			return -2*pow(2, 1.0L/3.0L)*(pow(x, 2)*z*pow(z - 2, 2) + 4*x*z*(x - 2)*pow(z - 2, 2) + z*pow(x - 2, 2)*pow(z - 2, 2))/pow(8*pow(x, 8) - 64*pow(x, 7) + 192*pow(x, 6) - 256*pow(x, 5) + 128*pow(x, 4) + (1.0L/2.0L)*pow(z, 8)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) - 16.0L/3.0L*pow(z, 7)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) + (1.0L/9.0L)*pow(z, 6)*(207*pow(x, 6) - 1242*pow(x, 5) + 4518*pow(x, 4) - 9792*pow(x, 3) + 10536*pow(x, 2) - 4800*x + 800) - 8.0L/3.0L*pow(z, 5)*(69*pow(x, 6) - 414*pow(x, 5) + 1050*pow(x, 4) - 1440*pow(x, 3) + 1080*pow(x, 2) - 384*x + 64) + (1.0L/6.0L)*pow(z, 4)*(27*pow(x, 8) - 216*pow(x, 7) + 3984*pow(x, 6) - 20880*pow(x, 5) + 45952*pow(x, 4) - 48640*pow(x, 3) + 24256*pow(x, 2) - 4608*x + 768) - 8.0L/3.0L*pow(z, 3)*(9*pow(x, 8) - 72*pow(x, 7) + 504*pow(x, 6) - 2016*pow(x, 5) + 3920*pow(x, 4) - 3590*pow(x, 3) + 1298*pow(x, 2) - 12*x) + 4*pow(z, 2)*(11*pow(x, 8) - 88*pow(x, 7) + 368*pow(x, 6) - 976*pow(x, 5) + 1536*pow(x, 4) - 1296*pow(x, 3) + 496*pow(x, 2) - 32*x) - 32*z*(pow(x, 8) - 8*pow(x, 7) + 24*pow(x, 6) - 32*pow(x, 5) + 16*pow(x, 4) - 2*pow(x, 3) + 6*pow(x, 2) - 4*x) + 2, 1.0L/3.0L) + (2.0L/9.0L)*pow(2, 1.0L/3.0L)*(2*pow(x, 2)*z*(x - 2)*pow(z - 2, 2) + 2*x*z*pow(x - 2, 2)*pow(z - 2, 2) + 1)*(96*pow(x, 7) - 672*pow(x, 6) + 1728*pow(x, 5) - 1920*pow(x, 4) + 768*pow(x, 3) + 9*pow(z, 8)*(3*pow(x, 3) - 9*pow(x, 2) + 8*x - 2) - 96*pow(z, 7)*(3*pow(x, 3) - 9*pow(x, 2) + 8*x - 2) + pow(z, 6)*(207*pow(x, 5) - 1035*pow(x, 4) + 3012*pow(x, 3) - 4896*pow(x, 2) + 3512*x - 800) - 24*pow(z, 5)*(69*pow(x, 5) - 345*pow(x, 4) + 700*pow(x, 3) - 720*pow(x, 2) + 360*x - 64) + 2*pow(z, 4)*(27*pow(x, 7) - 189*pow(x, 6) + 2988*pow(x, 5) - 13050*pow(x, 4) + 22976*pow(x, 3) - 18240*pow(x, 2) + 6064*x - 576) - 8*pow(z, 3)*(36*pow(x, 7) - 252*pow(x, 6) + 1512*pow(x, 5) - 5040*pow(x, 4) + 7840*pow(x, 3) - 5385*pow(x, 2) + 1298*x - 6) + 48*pow(z, 2)*(11*pow(x, 7) - 77*pow(x, 6) + 276*pow(x, 5) - 610*pow(x, 4) + 768*pow(x, 3) - 486*pow(x, 2) + 124*x - 4) - 96*z*(4*pow(x, 7) - 28*pow(x, 6) + 72*pow(x, 5) - 80*pow(x, 4) + 32*pow(x, 3) - 3*pow(x, 2) + 6*x - 2))/pow(8*pow(x, 8) - 64*pow(x, 7) + 192*pow(x, 6) - 256*pow(x, 5) + 128*pow(x, 4) + (1.0L/2.0L)*pow(z, 8)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) - 16.0L/3.0L*pow(z, 7)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) + (1.0L/9.0L)*pow(z, 6)*(207*pow(x, 6) - 1242*pow(x, 5) + 4518*pow(x, 4) - 9792*pow(x, 3) + 10536*pow(x, 2) - 4800*x + 800) - 8.0L/3.0L*pow(z, 5)*(69*pow(x, 6) - 414*pow(x, 5) + 1050*pow(x, 4) - 1440*pow(x, 3) + 1080*pow(x, 2) - 384*x + 64) + (1.0L/6.0L)*pow(z, 4)*(27*pow(x, 8) - 216*pow(x, 7) + 3984*pow(x, 6) - 20880*pow(x, 5) + 45952*pow(x, 4) - 48640*pow(x, 3) + 24256*pow(x, 2) - 4608*x + 768) - 8.0L/3.0L*pow(z, 3)*(9*pow(x, 8) - 72*pow(x, 7) + 504*pow(x, 6) - 2016*pow(x, 5) + 3920*pow(x, 4) - 3590*pow(x, 3) + 1298*pow(x, 2) - 12*x) + 4*pow(z, 2)*(11*pow(x, 8) - 88*pow(x, 7) + 368*pow(x, 6) - 976*pow(x, 5) + 1536*pow(x, 4) - 1296*pow(x, 3) + 496*pow(x, 2) - 32*x) - 32*z*(pow(x, 8) - 8*pow(x, 7) + 24*pow(x, 6) - 32*pow(x, 5) + 16*pow(x, 4) - 2*pow(x, 3) + 6*pow(x, 2) - 4*x) + 2, 4.0L/3.0L) - pow(2, 1.0L/3.0L)*(pow(x, 2)*z*pow(x - 2, 2) + 2*pow(x, 2)*pow(x - 2, 2)*(z - 2) - 2*pow(z, 3)*(3*pow(x, 2) - 6*x + 2) + 8*pow(z, 2)*(3*pow(x, 2) - 6*x + 2) - 8*z*(3*pow(x, 2) - 6*x + 2))/pow(8*pow(x, 8) - 64*pow(x, 7) + 192*pow(x, 6) - 256*pow(x, 5) + 128*pow(x, 4) + (1.0L/2.0L)*pow(z, 8)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) - 16.0L/3.0L*pow(z, 7)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) + (1.0L/9.0L)*pow(z, 6)*(207*pow(x, 6) - 1242*pow(x, 5) + 4518*pow(x, 4) - 9792*pow(x, 3) + 10536*pow(x, 2) - 4800*x + 800) - 8.0L/3.0L*pow(z, 5)*(69*pow(x, 6) - 414*pow(x, 5) + 1050*pow(x, 4) - 1440*pow(x, 3) + 1080*pow(x, 2) - 384*x + 64) + (1.0L/6.0L)*pow(z, 4)*(27*pow(x, 8) - 216*pow(x, 7) + 3984*pow(x, 6) - 20880*pow(x, 5) + 45952*pow(x, 4) - 48640*pow(x, 3) + 24256*pow(x, 2) - 4608*x + 768) - 8.0L/3.0L*pow(z, 3)*(9*pow(x, 8) - 72*pow(x, 7) + 504*pow(x, 6) - 2016*pow(x, 5) + 3920*pow(x, 4) - 3590*pow(x, 3) + 1298*pow(x, 2) - 12*x) + 4*pow(z, 2)*(11*pow(x, 8) - 88*pow(x, 7) + 368*pow(x, 6) - 976*pow(x, 5) + 1536*pow(x, 4) - 1296*pow(x, 3) + 496*pow(x, 2) - 32*x) - 32*z*(pow(x, 8) - 8*pow(x, 7) + 24*pow(x, 6) - 32*pow(x, 5) + 16*pow(x, 4) - 2*pow(x, 3) + 6*pow(x, 2) - 4*x) + 2, 1.0L/3.0L) - 1.0L/27.0L*pow(2, 1.0L/3.0L)*(6*pow(x, 2)*z*pow(x - 2, 2)*(z - 2) + 3*pow(x, 2)*pow(x - 2, 2)*pow(z - 2, 2) - 3*pow(z, 4)*(3*pow(x, 2) - 6*x + 2) + 16*pow(z, 3)*(3*pow(x, 2) - 6*x + 2) - 24*pow(z, 2)*(3*pow(x, 2) - 6*x + 2))*(48*pow(x, 8) - 384*pow(x, 7) + 1152*pow(x, 6) - 1536*pow(x, 5) + 768*pow(x, 4) - 96*pow(x, 3) + 288*pow(x, 2) - 192*x - 6*pow(z, 7)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) + 56*pow(z, 6)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) - pow(z, 5)*(207*pow(x, 6) - 1242*pow(x, 5) + 4518*pow(x, 4) - 9792*pow(x, 3) + 10536*pow(x, 2) - 4800*x + 800) + 20*pow(z, 4)*(69*pow(x, 6) - 414*pow(x, 5) + 1050*pow(x, 4) - 1440*pow(x, 3) + 1080*pow(x, 2) - 384*x + 64) - pow(z, 3)*(27*pow(x, 8) - 216*pow(x, 7) + 3984*pow(x, 6) - 20880*pow(x, 5) + 45952*pow(x, 4) - 48640*pow(x, 3) + 24256*pow(x, 2) - 4608*x + 768) + 12*pow(z, 2)*(9*pow(x, 8) - 72*pow(x, 7) + 504*pow(x, 6) - 2016*pow(x, 5) + 3920*pow(x, 4) - 3590*pow(x, 3) + 1298*pow(x, 2) - 12*x) - 12*z*(11*pow(x, 8) - 88*pow(x, 7) + 368*pow(x, 6) - 976*pow(x, 5) + 1536*pow(x, 4) - 1296*pow(x, 3) + 496*pow(x, 2) - 32*x))/pow(8*pow(x, 8) - 64*pow(x, 7) + 192*pow(x, 6) - 256*pow(x, 5) + 128*pow(x, 4) + (1.0L/2.0L)*pow(z, 8)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) - 16.0L/3.0L*pow(z, 7)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) + (1.0L/9.0L)*pow(z, 6)*(207*pow(x, 6) - 1242*pow(x, 5) + 4518*pow(x, 4) - 9792*pow(x, 3) + 10536*pow(x, 2) - 4800*x + 800) - 8.0L/3.0L*pow(z, 5)*(69*pow(x, 6) - 414*pow(x, 5) + 1050*pow(x, 4) - 1440*pow(x, 3) + 1080*pow(x, 2) - 384*x + 64) + (1.0L/6.0L)*pow(z, 4)*(27*pow(x, 8) - 216*pow(x, 7) + 3984*pow(x, 6) - 20880*pow(x, 5) + 45952*pow(x, 4) - 48640*pow(x, 3) + 24256*pow(x, 2) - 4608*x + 768) - 8.0L/3.0L*pow(z, 3)*(9*pow(x, 8) - 72*pow(x, 7) + 504*pow(x, 6) - 2016*pow(x, 5) + 3920*pow(x, 4) - 3590*pow(x, 3) + 1298*pow(x, 2) - 12*x) + 4*pow(z, 2)*(11*pow(x, 8) - 88*pow(x, 7) + 368*pow(x, 6) - 976*pow(x, 5) + 1536*pow(x, 4) - 1296*pow(x, 3) + 496*pow(x, 2) - 32*x) - 32*z*(pow(x, 8) - 8*pow(x, 7) + 24*pow(x, 6) - 32*pow(x, 5) + 16*pow(x, 4) - 2*pow(x, 3) + 6*pow(x, 2) - 4*x) + 2, 4.0L/3.0L) + 4*M_PI*cos(4*M_PI*x + (1.0L/3.0L)*M_PI);
 		case 24:
 			return 2*pow(2, 1.0L/3.0L)*pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L) - 2.0L/3.0L*pow(2, 1.0L/3.0L)*PI*p*(12*pow(PI, 3)*pow(p, 3)*sin(PI*p*x)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2)*cos(PI*p*x) - (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*cos(PI*p*x)*cos(PI*p*y) + pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*cos(PI*p*x)*cos(PI*p*z)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z)))*sin(PI*p*x)*sin(PI*p*y)*sin(PI*p*z)/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) + PI*q*sin(PI*q*y)*sin(PI*q*z)*cos(PI*q*x) - 1.0L/6.0L*pow(2, 1.0L/3.0L)*(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(12*pow(PI, 3)*pow(p, 3)*pow(sin(PI*p*x), 2)*sin(PI*p*y)*pow(sin(PI*p*z), 2)*cos(PI*p*y) + (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*cos(PI*p*x)*cos(PI*p*y) - 2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*cos(PI*p*y)*cos(PI*p*z)))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) - 1.0L/6.0L*pow(2, 1.0L/3.0L)*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(12*pow(PI, 3)*pow(p, 3)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*sin(PI*p*z)*cos(PI*p*z) + (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(-2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*cos(PI*p*y)*cos(PI*p*z) + pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*cos(PI*p*x)*cos(PI*p*z)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) + pow(2, 1.0L/3.0L)*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L);
@@ -99,7 +108,16 @@
 			z=y;
 			return 32.0/5.0*pow(PI, 2)*sin(8*PI*x) - 100;
+		case 13:
+			z=y;
+			return 8.0*pow(PI, 2)*x*z*(z - 2)*sin(4*PI*x*z) - 2.0*PI*z*cos(4*PI*x*z) - 2.0*PI*(z - 2)*cos(4*PI*x*z) + 0.25*PI*(32*cos(4*PI*x)/pow(x, 2) - 4*(8*pow(PI, 2)*pow(x, 2) + 1)*sin(4*PI*x)/(PI*pow(x, 3)) - 4*(4*pow(PI, 2)*pow(z, 2)*(PI*x*z - PI*x)*cos(4*PI*x*z) + pow(PI, 2)*pow(z, 2)*(8*pow(PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(PI, 2)*pow(x, 2)*z - 1)*sin(4*PI*x*z) - 2*PI*z*(-PI*z + PI)*sin(4*PI*x*z) - 8*PI*z*(pow(PI, 2)*x*pow(z, 2) - 2*pow(PI, 2)*x*z)*cos(4*PI*x*z) - (pow(PI, 2)*pow(z, 2) - 2*pow(PI, 2)*z)*sin(4*PI*x*z))/(pow(PI, 3)*pow(x, 3)) - 20*sin(4*PI*x)/(PI*pow(x, 3)) - 6*(8*pow(PI, 2)*pow(x, 2) + 1)*cos(4*PI*x)/(pow(PI, 2)*pow(x, 4)) - 6*(-4*PI*z*(PI*x*z - PI*x)*sin(4*PI*x*z) + PI*z*(8*pow(PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(PI, 2)*pow(x, 2)*z - 1)*cos(4*PI*x*z) - (-PI*z + PI)*cos(4*PI*x*z) + 4*(pow(PI, 2)*x*pow(z, 2) - 2*pow(PI, 2)*x*z)*sin(4*PI*x*z))/(pow(PI, 3)*pow(x, 4)) + 3*(8*pow(PI, 2)*pow(x, 2) + 1)*sin(4*PI*x)/(pow(PI, 3)*pow(x, 5)) + 3*(4*(PI*x*z - PI*x)*cos(4*PI*x*z) + (8*pow(PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(PI, 2)*pow(x, 2)*z - 1)*sin(4*PI*x*z))/(pow(PI, 3)*pow(x, 5))) + 4*PI*sin(4*PI*x)*cos(4*PI*z) + (8.0L/5.0L)*pow(PI, 2)*sin(4*PI*x) + 2*(-4.0*pow(PI, 2)*pow(x, 2)*(PI*x*z - PI*x)*cos(4*PI*x*z) - 1.0*pow(PI, 2)*pow(x, 2)*(8*pow(PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(PI, 2)*pow(x, 2)*z - 1)*sin(4*PI*x*z) - 1.0*pow(PI, 2)*pow(x, 2)*sin(4*PI*x*z) + 8.0*PI*x*(pow(PI, 2)*pow(x, 2)*z - pow(PI, 2)*pow(x, 2))*cos(4*PI*x*z))/(pow(PI, 2)*pow(x, 3));
+		case 14:
+			z=y;
+			return 4*M_PI*sin(4*M_PI*x)*cos(4*M_PI*z) + (1.0L/10.0L)*pow(2, 1.0L/3.0L)*(40.0*pow(M_PI, 2)*x*z*(z - 2)*sin(4*M_PI*x*z) - 10.0*M_PI*z*cos(4*M_PI*x*z) - 10.0*M_PI*(z - 2)*cos(4*M_PI*x*z) + 1.25*M_PI*(32*cos(4*M_PI*x)/pow(x, 2) - 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(M_PI*pow(x, 3)) - 4*(4*pow(M_PI, 2)*pow(z, 2)*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + pow(M_PI, 2)*pow(z, 2)*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z) - 2*M_PI*z*(-M_PI*z + M_PI)*sin(4*M_PI*x*z) - 8*M_PI*z*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(z, 2) - 2*pow(M_PI, 2)*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 20*sin(4*M_PI*x)/(M_PI*pow(x, 3)) - 6*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 4)) - 6*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4)) + 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 5)) + 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 5))) + 8*pow(M_PI, 2)*sin(4*M_PI*x))/pow(4.0*pow(M_PI, 2)*pow(z, 2)*pow(z - 2, 2)*pow(cos(4*M_PI*x*z), 2) + (1.0L/2.0L)*pow(2.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) - 0.0625*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) + 0.5*sin(4*M_PI*x*z) + (2.0L/5.0L)*M_PI*cos(4*M_PI*x), 2) + pow(M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 0.25*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*x*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z), 2)/(pow(M_PI, 4)*pow(x, 6)), 1.0L/3.0L) + (1.0L/750.0L)*pow(2, 1.0L/3.0L)*(-10.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) + 0.3125*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) - 2.5*sin(4*M_PI*x*z) - 2*M_PI*cos(4*M_PI*x))*(800.0*pow(M_PI, 3)*pow(z, 3)*pow(z - 2, 2)*sin(4*M_PI*x*z)*cos(4*M_PI*x*z) - (-10.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) + 0.3125*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) - 2.5*sin(4*M_PI*x*z) - 2*M_PI*cos(4*M_PI*x))*(40.0*pow(M_PI, 2)*x*z*(z - 2)*sin(4*M_PI*x*z) - 10.0*M_PI*z*cos(4*M_PI*x*z) - 10.0*M_PI*(z - 2)*cos(4*M_PI*x*z) + 1.25*M_PI*(32*cos(4*M_PI*x)/pow(x, 2) - 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(M_PI*pow(x, 3)) - 4*(4*pow(M_PI, 2)*pow(z, 2)*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + pow(M_PI, 2)*pow(z, 2)*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z) - 2*M_PI*z*(-M_PI*z + M_PI)*sin(4*M_PI*x*z) - 8*M_PI*z*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(z, 2) - 2*pow(M_PI, 2)*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 20*sin(4*M_PI*x)/(M_PI*pow(x, 3)) - 6*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 4)) - 6*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4)) + 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 5)) + 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 5))) + 8*pow(M_PI, 2)*sin(4*M_PI*x)) - (50*M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 12.5*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 12.5*M_PI*x*cos(4*M_PI*x*z) - 50*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z))*(4*pow(M_PI, 2)*x*z*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + pow(M_PI, 2)*x*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z) + pow(M_PI, 2)*x*z*sin(4*M_PI*x*z) - M_PI*x*(-M_PI*z + M_PI)*sin(4*M_PI*x*z) - 4.0*M_PI*x*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*cos(4*M_PI*x*z) - 4*M_PI*z*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*cos(4*M_PI*x*z) + M_PI*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 2*(pow(M_PI, 2)*x*z - pow(M_PI, 2)*x)*sin(4*M_PI*x*z) - 0.25*M_PI*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*cos(4*M_PI*x*z))/(pow(M_PI, 4)*pow(x, 6)) + 150*pow(M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 0.25*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*x*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z), 2)/(pow(M_PI, 4)*pow(x, 7)))/pow(4.0*pow(M_PI, 2)*pow(z, 2)*pow(z - 2, 2)*pow(cos(4*M_PI*x*z), 2) + (1.0L/2.0L)*pow(2.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) - 0.0625*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) + 0.5*sin(4*M_PI*x*z) + (2.0L/5.0L)*M_PI*cos(4*M_PI*x), 2) + pow(M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 0.25*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*x*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z), 2)/(pow(M_PI, 4)*pow(x, 6)), 4.0L/3.0L) - pow(2, 1.0L/3.0L)*(4.0*pow(M_PI, 2)*pow(x, 2)*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + pow(M_PI, 2)*pow(x, 2)*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z) + pow(M_PI, 2)*pow(x, 2)*sin(4*M_PI*x*z) - 8.0*M_PI*x*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*cos(4*M_PI*x*z))/(pow(M_PI, 2)*pow(x, 3)*pow(4.0*pow(M_PI, 2)*pow(z, 2)*pow(z - 2, 2)*pow(cos(4*M_PI*x*z), 2) + (1.0L/2.0L)*pow(2.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) - 0.0625*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) + 0.5*sin(4*M_PI*x*z) + (2.0L/5.0L)*M_PI*cos(4*M_PI*x), 2) + pow(M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 0.25*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*x*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z), 2)/(pow(M_PI, 4)*pow(x, 6)), 1.0L/3.0L)) - 1.0L/15.0L*pow(2, 1.0L/3.0L)*(M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 0.25*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*x*cos(4*M_PI*x*z) + (-1.0*pow(M_PI, 2)*pow(x, 2)*z + pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z))*(160.0*pow(M_PI, 3)*x*pow(z, 2)*pow(z - 2, 2)*sin(4*M_PI*x*z)*cos(4*M_PI*x*z) - 40.0*pow(M_PI, 2)*pow(z, 2)*(z - 2)*pow(cos(4*M_PI*x*z), 2) - 40.0*pow(M_PI, 2)*z*pow(z - 2, 2)*pow(cos(4*M_PI*x*z), 2) + (-8.0*pow(M_PI, 2)*pow(x, 2)*(z - 2)*sin(4*M_PI*x*z) + 4.0*M_PI*x*cos(4*M_PI*x*z) + 0.25*M_PI*((16*pow(M_PI, 2)*x*z*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + 4*pow(M_PI, 2)*x*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z) + 4*pow(M_PI, 2)*x*z*sin(4*M_PI*x*z) - 4*M_PI*x*(-M_PI*z + M_PI)*sin(4*M_PI*x*z) - 16*M_PI*x*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*cos(4*M_PI*x*z) - 16*M_PI*z*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*cos(4*M_PI*x*z) + 4*M_PI*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 8*(pow(M_PI, 2)*x*z - pow(M_PI, 2)*x)*sin(4*M_PI*x*z) - M_PI*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - M_PI*cos(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) + 3*(-4*M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) + M_PI*x*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))))*(-10.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) + 0.3125*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) - 2.5*sin(4*M_PI*x*z) - 2*M_PI*cos(4*M_PI*x)) - (10*M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 2.5*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 2.5*M_PI*x*cos(4*M_PI*x*z) - 10*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z))*(4*pow(M_PI, 2)*pow(x, 2)*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + pow(M_PI, 2)*pow(x, 2)*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z) + pow(M_PI, 2)*pow(x, 2)*sin(4*M_PI*x*z) - 8.0*M_PI*x*(pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*cos(4*M_PI*x*z))/(pow(M_PI, 4)*pow(x, 6)))/(pow(M_PI, 2)*pow(x, 3)*pow(4.0*pow(M_PI, 2)*pow(z, 2)*pow(z - 2, 2)*pow(cos(4*M_PI*x*z), 2) + (1.0L/2.0L)*pow(2.0*M_PI*x*(z - 2)*cos(4*M_PI*x*z) - 0.0625*M_PI*(16*sin(4*M_PI*x)/(M_PI*pow(x, 2)) + 4*(8*pow(M_PI, 2)*pow(x, 2) + 1)*cos(4*M_PI*x)/(pow(M_PI, 2)*pow(x, 3)) + 4*(-4*M_PI*z*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) + M_PI*z*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - (-M_PI*z + M_PI)*cos(4*M_PI*x*z) + 4*(pow(M_PI, 2)*x*pow(z, 2) - 2*pow(M_PI, 2)*x*z)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 3)) - 3*(8*pow(M_PI, 2)*pow(x, 2) + 1)*sin(4*M_PI*x)/(pow(M_PI, 3)*pow(x, 4)) - 3*(4*(M_PI*x*z - M_PI*x)*cos(4*M_PI*x*z) + (8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*sin(4*M_PI*x*z))/(pow(M_PI, 3)*pow(x, 4))) + 0.5*sin(4*M_PI*x*z) + (2.0L/5.0L)*M_PI*cos(4*M_PI*x), 2) + pow(M_PI*x*(M_PI*x*z - M_PI*x)*sin(4*M_PI*x*z) - 0.25*M_PI*x*(8*pow(M_PI, 2)*pow(x, 2)*pow(z, 2) - 16*pow(M_PI, 2)*pow(x, 2)*z - 1)*cos(4*M_PI*x*z) - 0.25*M_PI*x*cos(4*M_PI*x*z) - (pow(M_PI, 2)*pow(x, 2)*z - pow(M_PI, 2)*pow(x, 2))*sin(4*M_PI*x*z), 2)/(pow(M_PI, 4)*pow(x, 6)), 4.0L/3.0L));
 		case 21:
 			z=y;
-			return x + (4.0L/3.0L)*pow(2, 1.0L/3.0L)*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x))*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x))*(2*pow(x, 3) - 3*pow(x, 2) + x + 6*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 6*z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2) + 2*pow(x, 2)*pow(x - 1, 2)*(z - 1) + pow(x, 2)*pow(x - 1, 2)*(2*z - 1) - 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) - z*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1)))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) - 1.0L/3.0L*pow(2, 1.0L/3.0L)*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*x*z*(x - 1)*(z - 1)*(2*z - 1) + z*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) + z*(6*pow(x, 2) - 6*x + 1))*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 3*pow(z, 4)*(2*x - 1) + 6*pow(z, 3)*(2*x - 1) - 3*pow(z, 2)*(2*x - 1)))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) - 1.0L/2.0L - 2*pow(2, 1.0L/3.0L)*(2*pow(x, 3) - 3*pow(x, 2) + x + 6*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 6*z*(2*pow(x, 3) - 3*pow(x, 2) + x))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L) + pow(2, 1.0L/3.0L)*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 3*pow(z, 4)*(2*x - 1) + 6*pow(z, 3)*(2*x - 1) - 3*pow(z, 2)*(2*x - 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L);
+			return x + (4.0L/3.0L)*pow(2, 1.0L/3.0L)*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x))*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x))*(2*pow(x, 3) - 3*pow(x, 2) + x + 6*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 6*z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2) + 2*pow(x, 2)*pow(x - 1, 2)*(z - 1) + pow(x, 2)*pow(x - 1, 2)*(2*z - 1) - 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) + 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) - z*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1)))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) - 1.0L/3.0L*pow(2, 1.0L/3.0L)*(4*(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1))*(pow(x, 2)*z*(z - 1)*(2*z - 1) + 4*x*z*(x - 1)*(z - 1)*(2*z - 1) + z*pow(x - 1, 2)*(z - 1)*(2*z - 1)) + 4*(2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - 3*pow(z, 2)*(6*pow(x, 2) - 6*x + 1) + z*(6*pow(x, 2) - 6*x + 1))*(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x)) + (2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 3*pow(z, 4)*(2*x - 1) + 6*pow(z, 3)*(2*x - 1) - 3*pow(z, 2)*(2*x - 1)))*(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 4.0L/3.0L) - 0.5 - 2*pow(2, 1.0L/3.0L)*(2*pow(x, 3) - 3*pow(x, 2) + x + 6*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 6*z*(2*pow(x, 3) - 3*pow(x, 2) + x))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L) + pow(2, 1.0L/3.0L)*(2*pow(x, 2)*z*(x - 1)*(z - 1) + pow(x, 2)*z*(x - 1)*(2*z - 1) + pow(x, 2)*(x - 1)*(z - 1)*(2*z - 1) + 2*x*z*pow(x - 1, 2)*(z - 1) + x*z*pow(x - 1, 2)*(2*z - 1) + x*pow(x - 1, 2)*(z - 1)*(2*z - 1) - 3*pow(z, 4)*(2*x - 1) + 6*pow(z, 3)*(2*x - 1) - 3*pow(z, 2)*(2*x - 1))/pow(4*pow(pow(x, 2)*z*(x - 1)*(z - 1)*(2*z - 1) + x*z*pow(x - 1, 2)*(z - 1)*(2*z - 1), 2) + 4*pow(2*pow(z, 3)*(2*pow(x, 3) - 3*pow(x, 2) + x) - 3*pow(z, 2)*(2*pow(x, 3) - 3*pow(x, 2) + x) + z*(2*pow(x, 3) - 3*pow(x, 2) + x), 2) + (1.0L/2.0L)*pow(2*pow(x, 2)*z*pow(x - 1, 2)*(z - 1) + pow(x, 2)*z*pow(x - 1, 2)*(2*z - 1) + pow(x, 2)*pow(x - 1, 2)*(z - 1)*(2*z - 1) - pow(z, 4)*(6*pow(x, 2) - 6*x + 1) + 2*pow(z, 3)*(6*pow(x, 2) - 6*x + 1) - pow(z, 2)*(6*pow(x, 2) - 6*x + 1), 2), 1.0L/3.0L);
+		case 22:
+			z=y;
+			return (2.0L/9.0L)*pow(2, 1.0L/3.0L)*(4*pow(z, 3)*(pow(x, 3) - 3*pow(x, 2) + 2*x) - 16*pow(z, 2)*(pow(x, 3) - 3*pow(x, 2) + 2*x) + 16*z*(pow(x, 3) - 3*pow(x, 2) + 2*x) + 1)*(48*pow(x, 8) - 384*pow(x, 7) + 1152*pow(x, 6) - 1536*pow(x, 5) + 768*pow(x, 4) - 96*pow(x, 3) + 288*pow(x, 2) - 192*x - 6*pow(z, 7)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) + 56*pow(z, 6)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) - pow(z, 5)*(207*pow(x, 6) - 1242*pow(x, 5) + 4518*pow(x, 4) - 9792*pow(x, 3) + 10536*pow(x, 2) - 4800*x + 800) + 20*pow(z, 4)*(69*pow(x, 6) - 414*pow(x, 5) + 1050*pow(x, 4) - 1440*pow(x, 3) + 1080*pow(x, 2) - 384*x + 64) - pow(z, 3)*(27*pow(x, 8) - 216*pow(x, 7) + 3984*pow(x, 6) - 20880*pow(x, 5) + 45952*pow(x, 4) - 48640*pow(x, 3) + 24256*pow(x, 2) - 4608*x + 768) + 12*pow(z, 2)*(9*pow(x, 8) - 72*pow(x, 7) + 504*pow(x, 6) - 2016*pow(x, 5) + 3920*pow(x, 4) - 3590*pow(x, 3) + 1298*pow(x, 2) - 12*x) - 12*z*(11*pow(x, 8) - 88*pow(x, 7) + 368*pow(x, 6) - 976*pow(x, 5) + 1536*pow(x, 4) - 1296*pow(x, 3) + 496*pow(x, 2) - 32*x))/pow(8*pow(x, 8) - 64*pow(x, 7) + 192*pow(x, 6) - 256*pow(x, 5) + 128*pow(x, 4) + (1.0L/2.0L)*pow(z, 8)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) - 16.0L/3.0L*pow(z, 7)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) + (1.0L/9.0L)*pow(z, 6)*(207*pow(x, 6) - 1242*pow(x, 5) + 4518*pow(x, 4) - 9792*pow(x, 3) + 10536*pow(x, 2) - 4800*x + 800) - 8.0L/3.0L*pow(z, 5)*(69*pow(x, 6) - 414*pow(x, 5) + 1050*pow(x, 4) - 1440*pow(x, 3) + 1080*pow(x, 2) - 384*x + 64) + (1.0L/6.0L)*pow(z, 4)*(27*pow(x, 8) - 216*pow(x, 7) + 3984*pow(x, 6) - 20880*pow(x, 5) + 45952*pow(x, 4) - 48640*pow(x, 3) + 24256*pow(x, 2) - 4608*x + 768) - 8.0L/3.0L*pow(z, 3)*(9*pow(x, 8) - 72*pow(x, 7) + 504*pow(x, 6) - 2016*pow(x, 5) + 3920*pow(x, 4) - 3590*pow(x, 3) + 1298*pow(x, 2) - 12*x) + 4*pow(z, 2)*(11*pow(x, 8) - 88*pow(x, 7) + 368*pow(x, 6) - 976*pow(x, 5) + 1536*pow(x, 4) - 1296*pow(x, 3) + 496*pow(x, 2) - 32*x) - 32*z*(pow(x, 8) - 8*pow(x, 7) + 24*pow(x, 6) - 32*pow(x, 5) + 16*pow(x, 4) - 2*pow(x, 3) + 6*pow(x, 2) - 4*x) + 2, 4.0L/3.0L) + 4*pow(2, 1.0L/3.0L)*(4*pow(x, 3) - 12*pow(x, 2) + 8*x + 3*pow(z, 2)*(pow(x, 3) - 3*pow(x, 2) + 2*x) - 8*z*(pow(x, 3) - 3*pow(x, 2) + 2*x))/pow(8*pow(x, 8) - 64*pow(x, 7) + 192*pow(x, 6) - 256*pow(x, 5) + 128*pow(x, 4) + (1.0L/2.0L)*pow(z, 8)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) - 16.0L/3.0L*pow(z, 7)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) + (1.0L/9.0L)*pow(z, 6)*(207*pow(x, 6) - 1242*pow(x, 5) + 4518*pow(x, 4) - 9792*pow(x, 3) + 10536*pow(x, 2) - 4800*x + 800) - 8.0L/3.0L*pow(z, 5)*(69*pow(x, 6) - 414*pow(x, 5) + 1050*pow(x, 4) - 1440*pow(x, 3) + 1080*pow(x, 2) - 384*x + 64) + (1.0L/6.0L)*pow(z, 4)*(27*pow(x, 8) - 216*pow(x, 7) + 3984*pow(x, 6) - 20880*pow(x, 5) + 45952*pow(x, 4) - 48640*pow(x, 3) + 24256*pow(x, 2) - 4608*x + 768) - 8.0L/3.0L*pow(z, 3)*(9*pow(x, 8) - 72*pow(x, 7) + 504*pow(x, 6) - 2016*pow(x, 5) + 3920*pow(x, 4) - 3590*pow(x, 3) + 1298*pow(x, 2) - 12*x) + 4*pow(z, 2)*(11*pow(x, 8) - 88*pow(x, 7) + 368*pow(x, 6) - 976*pow(x, 5) + 1536*pow(x, 4) - 1296*pow(x, 3) + 496*pow(x, 2) - 32*x) - 32*z*(pow(x, 8) - 8*pow(x, 7) + 24*pow(x, 6) - 32*pow(x, 5) + 16*pow(x, 4) - 2*pow(x, 3) + 6*pow(x, 2) - 4*x) + 2, 1.0L/3.0L) + (1.0L/27.0L)*pow(2, 1.0L/3.0L)*(6*pow(x, 2)*z*pow(x - 2, 2)*(z - 2) + 3*pow(x, 2)*pow(x - 2, 2)*pow(z - 2, 2) - 3*pow(z, 4)*(3*pow(x, 2) - 6*x + 2) + 16*pow(z, 3)*(3*pow(x, 2) - 6*x + 2) - 24*pow(z, 2)*(3*pow(x, 2) - 6*x + 2))*(96*pow(x, 7) - 672*pow(x, 6) + 1728*pow(x, 5) - 1920*pow(x, 4) + 768*pow(x, 3) + 9*pow(z, 8)*(3*pow(x, 3) - 9*pow(x, 2) + 8*x - 2) - 96*pow(z, 7)*(3*pow(x, 3) - 9*pow(x, 2) + 8*x - 2) + pow(z, 6)*(207*pow(x, 5) - 1035*pow(x, 4) + 3012*pow(x, 3) - 4896*pow(x, 2) + 3512*x - 800) - 24*pow(z, 5)*(69*pow(x, 5) - 345*pow(x, 4) + 700*pow(x, 3) - 720*pow(x, 2) + 360*x - 64) + 2*pow(z, 4)*(27*pow(x, 7) - 189*pow(x, 6) + 2988*pow(x, 5) - 13050*pow(x, 4) + 22976*pow(x, 3) - 18240*pow(x, 2) + 6064*x - 576) - 8*pow(z, 3)*(36*pow(x, 7) - 252*pow(x, 6) + 1512*pow(x, 5) - 5040*pow(x, 4) + 7840*pow(x, 3) - 5385*pow(x, 2) + 1298*x - 6) + 48*pow(z, 2)*(11*pow(x, 7) - 77*pow(x, 6) + 276*pow(x, 5) - 610*pow(x, 4) + 768*pow(x, 3) - 486*pow(x, 2) + 124*x - 4) - 96*z*(4*pow(x, 7) - 28*pow(x, 6) + 72*pow(x, 5) - 80*pow(x, 4) + 32*pow(x, 3) - 3*pow(x, 2) + 6*x - 2))/pow(8*pow(x, 8) - 64*pow(x, 7) + 192*pow(x, 6) - 256*pow(x, 5) + 128*pow(x, 4) + (1.0L/2.0L)*pow(z, 8)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) - 16.0L/3.0L*pow(z, 7)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) + (1.0L/9.0L)*pow(z, 6)*(207*pow(x, 6) - 1242*pow(x, 5) + 4518*pow(x, 4) - 9792*pow(x, 3) + 10536*pow(x, 2) - 4800*x + 800) - 8.0L/3.0L*pow(z, 5)*(69*pow(x, 6) - 414*pow(x, 5) + 1050*pow(x, 4) - 1440*pow(x, 3) + 1080*pow(x, 2) - 384*x + 64) + (1.0L/6.0L)*pow(z, 4)*(27*pow(x, 8) - 216*pow(x, 7) + 3984*pow(x, 6) - 20880*pow(x, 5) + 45952*pow(x, 4) - 48640*pow(x, 3) + 24256*pow(x, 2) - 4608*x + 768) - 8.0L/3.0L*pow(z, 3)*(9*pow(x, 8) - 72*pow(x, 7) + 504*pow(x, 6) - 2016*pow(x, 5) + 3920*pow(x, 4) - 3590*pow(x, 3) + 1298*pow(x, 2) - 12*x) + 4*pow(z, 2)*(11*pow(x, 8) - 88*pow(x, 7) + 368*pow(x, 6) - 976*pow(x, 5) + 1536*pow(x, 4) - 1296*pow(x, 3) + 496*pow(x, 2) - 32*x) - 32*z*(pow(x, 8) - 8*pow(x, 7) + 24*pow(x, 6) - 32*pow(x, 5) + 16*pow(x, 4) - 2*pow(x, 3) + 6*pow(x, 2) - 4*x) + 2, 4.0L/3.0L) - pow(2, 1.0L/3.0L)*(2*pow(x, 2)*z*(x - 2)*(z - 2) + pow(x, 2)*(x - 2)*pow(z - 2, 2) + 2*x*z*pow(x - 2, 2)*(z - 2) + x*pow(x - 2, 2)*pow(z - 2, 2) - 3*pow(z, 4)*(x - 1) + 16*pow(z, 3)*(x - 1) - 24*pow(z, 2)*(x - 1))/pow(8*pow(x, 8) - 64*pow(x, 7) + 192*pow(x, 6) - 256*pow(x, 5) + 128*pow(x, 4) + (1.0L/2.0L)*pow(z, 8)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) - 16.0L/3.0L*pow(z, 7)*(9*pow(x, 4) - 36*pow(x, 3) + 48*pow(x, 2) - 24*x + 4) + (1.0L/9.0L)*pow(z, 6)*(207*pow(x, 6) - 1242*pow(x, 5) + 4518*pow(x, 4) - 9792*pow(x, 3) + 10536*pow(x, 2) - 4800*x + 800) - 8.0L/3.0L*pow(z, 5)*(69*pow(x, 6) - 414*pow(x, 5) + 1050*pow(x, 4) - 1440*pow(x, 3) + 1080*pow(x, 2) - 384*x + 64) + (1.0L/6.0L)*pow(z, 4)*(27*pow(x, 8) - 216*pow(x, 7) + 3984*pow(x, 6) - 20880*pow(x, 5) + 45952*pow(x, 4) - 48640*pow(x, 3) + 24256*pow(x, 2) - 4608*x + 768) - 8.0L/3.0L*pow(z, 3)*(9*pow(x, 8) - 72*pow(x, 7) + 504*pow(x, 6) - 2016*pow(x, 5) + 3920*pow(x, 4) - 3590*pow(x, 3) + 1298*pow(x, 2) - 12*x) + 4*pow(z, 2)*(11*pow(x, 8) - 88*pow(x, 7) + 368*pow(x, 6) - 976*pow(x, 5) + 1536*pow(x, 4) - 1296*pow(x, 3) + 496*pow(x, 2) - 32*x) - 32*z*(pow(x, 8) - 8*pow(x, 7) + 24*pow(x, 6) - 32*pow(x, 5) + 16*pow(x, 4) - 2*pow(x, 3) + 6*pow(x, 2) - 4*x) + 2, 1.0L/3.0L) - 10;
 		case 24:
 			return -pow(2, 1.0L/3.0L)*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L) + (1.0L/3.0L)*pow(2, 1.0L/3.0L)*PI*p*(12*pow(PI, 3)*pow(p, 3)*pow(sin(PI*p*x), 2)*sin(PI*p*y)*pow(sin(PI*p*z), 2)*cos(PI*p*y) + (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*cos(PI*p*x)*cos(PI*p*y) - 2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*cos(PI*p*y)*cos(PI*p*z)))*sin(PI*p*x)*sin(PI*p*y)*sin(PI*p*z)/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) + PI*q*sin(PI*q*x)*sin(PI*q*z)*cos(PI*q*y) - 1.0L/6.0L*pow(2, 1.0L/3.0L)*(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(12*pow(PI, 3)*pow(p, 3)*sin(PI*p*x)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2)*cos(PI*p*x) - (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*cos(PI*p*x)*cos(PI*p*y) + pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*cos(PI*p*x)*cos(PI*p*z)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(pow(PI, 3)*pow(p, 3)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*sin(PI*p*y) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*y)*cos(PI*p*z)))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) - 1.0L/6.0L*pow(2, 1.0L/3.0L)*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(12*pow(PI, 3)*pow(p, 3)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*sin(PI*p*z)*cos(PI*p*z) + (-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x))*(-2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*cos(PI*p*y)*cos(PI*p*z) + pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*cos(PI*p*x)*cos(PI*p*z)) - (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z))*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y)) + (pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z))*(2*pow(PI, 2)*pow(p, 2)*(cos(PI*p*x) - 1)*sin(PI*p*y)*sin(PI*p*z) - pow(PI, 2)*pow(p, 2)*sin(PI*p*y)*sin(PI*p*z)*cos(PI*p*x)))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 4.0L/3.0L) - 1.0L/2.0L*pow(2, 1.0L/3.0L)*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) - 2*pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L) - 1.0L/2.0L*pow(2, 1.0L/3.0L)*(pow(PI, 2)*pow(p, 2)*(cos(PI*p*y) - 1)*sin(PI*p*x)*sin(PI*p*z) + pow(PI, 2)*pow(p, 2)*sin(PI*p*x)*sin(PI*p*z)*cos(PI*p*y))/pow(6*pow(PI, 2)*pow(p, 2)*pow(sin(PI*p*x), 2)*pow(sin(PI*p*y), 2)*pow(sin(PI*p*z), 2) + (1.0L/2.0L)*pow(-2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*z)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*z)*cos(PI*p*x), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*x)*cos(PI*p*y) + PI*p*(cos(PI*p*y) - 1)*sin(PI*p*x)*cos(PI*p*z), 2) + (1.0L/2.0L)*pow(pow(PI, 2)*pow(p, 2)*(cos(PI*p*z)/(PI*p) - 1/(PI*p))*sin(PI*p*y)*cos(PI*p*x) - 2*PI*p*(cos(PI*p*x) - 1)*sin(PI*p*y)*cos(PI*p*z), 2), 1.0L/3.0L); 
@@ -118,5 +136,5 @@
 
 	switch(testid){
-		case 1: case 2: case 7: case 8: case 11:  case 12: case 18: case 21:
+		case 1: case 2: case 7: case 8: case 11:  case 12: case 13: case 14: case 18: case 21: case 22:
 			return 0.;
 		case 3: 
@@ -144,5 +162,5 @@
 
 	switch(testid){
-		case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 21:
+		case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 21: case 22:
 			return 0.;
 		case 18:
Index: /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp
===================================================================
--- /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 19104)
+++ /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 19105)
@@ -333,4 +333,87 @@
 
 }/*}}}*/
+void Matrix2x2Eigen(IssmDouble* plambda1,IssmDouble* plambda2,IssmDouble* pvx, IssmDouble* pvy,IssmDouble a11, IssmDouble a21,IssmDouble a22){/*{{{*/
+	/*From symetric matrix (a11,a21;a21,a22), get eigen values lambda1 and lambda2 and one eigen vector v*/
+
+	/*Output*/
+	IssmDouble lambda1,lambda2;
+	IssmDouble vx,vy;
+
+	/*To get the eigen values, we must solve the following equation:
+	 *     | a11 - lambda    a21        |
+	 * det |                            | = 0
+	 *     | a21             a22-lambda |
+	 *
+	 * We have to solve the following polynom:
+	 *  lamda^2 + ( -a11 -a22)*lambda + (a11*a22-a21*a21) = 0*/
+
+	/*Compute polynom determinant*/
+	IssmDouble b=-a11-a22;
+	IssmDouble delta=b*b - 4*(a11*a22-a21*a21);
+
+	/*Compute norm of M to avoid round off errors*/
+	IssmDouble normM=a11*a11 + a22*a22 + a21*a21;
+
+	/*1: normM too small: eigen values = 0*/
+	if(normM<1.e-30){
+		lambda1=0.;
+		lambda2=0.;
+		vx=1.;
+		vy=0.;
+	}
+	/*2: delta is small -> double root*/
+	else if (delta < 1.e-5*normM){
+		lambda1=-b/2.;
+		lambda2=-b/2.;
+		vx=1.;
+		vy=0.;
+	}
+	/*3: general case -> two roots*/
+	else{
+		delta   = sqrt(delta);
+		lambda1 = (-b-delta)/2.;
+		lambda2 = (-b+delta)/2.;
+
+		/*Now, one must find the eigen vectors. For that we use the following property of the inner product
+		 *    <Ax,y> = <x,tAy>
+		 * Here, M'(M-lambda*Id) is symmetrical, which gives:
+		 *    ∀(x,y)∈R²xR² <M'x,y> = <M'y,x>
+		 * And we have the following:
+		 *    if y∈Ker(M'), ∀x∈R² <M'x,y> = <x,M'y> = 0
+		 * We have shown that
+		 *    Im(M') ⊥ Ker(M')
+		 *
+		 * To find the eigen vectors of M, we only have to find two vectors
+		 * of the image of M' and take their perpendicular as long as they are
+		 * not 0.
+		 * To do that, we take the images (1,0) and (0,1):
+		 *  x1 = (a11 - lambda)      x2 = a21
+		 *  y1 = a21                 y2 = (a22-lambda)
+		 *
+		 * We take the vector that has the larger norm and take its perpendicular.*/
+
+		IssmDouble norm1 = (a11-lambda1)*(a11-lambda1) + a21*a21; 
+		IssmDouble norm2 = a21*a21 + (a22-lambda1)*(a22-lambda1);
+
+		if(norm2<norm1){
+			norm1=sqrt(norm1);
+			vx = - a21/norm1;
+			vy = (a11-lambda1)/norm1;
+		}
+		else{
+			norm2=sqrt(norm2);
+			vx = - (a22-lambda1)/norm2;
+			vy = a21/norm2;
+		}
+	}
+
+	/*Assign output*/
+	*plambda1 = lambda1;
+	*plambda2 = lambda2;
+	*pvx      = vx;
+	*pvy      = vy;
+
+
+}/*}}}*/
 
 void Matrix3x3Determinant(IssmDouble* Adet,IssmDouble* A){/*{{{*/
Index: /issm/trunk/src/c/shared/Matrix/matrix.h
===================================================================
--- /issm/trunk/src/c/shared/Matrix/matrix.h	(revision 19104)
+++ /issm/trunk/src/c/shared/Matrix/matrix.h	(revision 19105)
@@ -14,4 +14,5 @@
 void Matrix2x2Invert(IssmDouble* Ainv, IssmDouble* A);
 void Matrix2x2Determinant(IssmDouble* Adet,IssmDouble* A);
+void Matrix2x2Eigen(IssmDouble* plambda1,IssmDouble* plambda2,IssmDouble* pvx, IssmDouble* pvy,IssmDouble a11, IssmDouble a21,IssmDouble a22);
 
 void Matrix3x3Invert(IssmDouble* Ainv, IssmDouble* A);
Index: /issm/trunk/src/c/shared/Numerics/numerics.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/numerics.h	(revision 19104)
+++ /issm/trunk/src/c/shared/Numerics/numerics.h	(revision 19105)
@@ -33,5 +33,5 @@
 void        cross(IssmDouble *result,IssmDouble*vector1,IssmDouble*vector2);
 void        XZvectorsToCoordinateSystem(IssmDouble *T,IssmDouble*xzvectors);
-int         cubic(IssmDouble a, IssmDouble b, IssmDouble c, IssmDouble d, double X[3], int *num);
+int         cubic(IssmDouble a, IssmDouble b, IssmDouble c, IssmDouble d,IssmDouble X[3], int *num);
 
 int         NewtonSolveDnorm(IssmDouble* pdnorm,IssmDouble c1,IssmDouble c2,IssmDouble c3,IssmDouble n,IssmDouble dnorm);
Index: /issm/trunk/src/c/shared/Numerics/recast.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/recast.h	(revision 19104)
+++ /issm/trunk/src/c/shared/Numerics/recast.h	(revision 19105)
@@ -40,3 +40,14 @@
 #endif
 
+/*Morlighem's change: we do not want dynamic_casts because of performance
+ * issue, so for now, we just use C-like cast*/
+template<class To,class From> To xDynamicCast(const From& from) {
+
+	/*C-like cast (fast but not safe)*/
+	return (To) from;
+
+	/*C++ dynamic_cast, poor performance but safer*/
+	//return dynamic_cast<To>(from);
+}
+
 #endif
Index: /issm/trunk/src/c/solutionsequences/convergence.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/convergence.cpp	(revision 19104)
+++ /issm/trunk/src/c/solutionsequences/convergence.cpp	(revision 19105)
@@ -7,5 +7,5 @@
 #include "../shared/shared.h"
 
-void convergence(bool* pconverged, Matrix<IssmDouble>* Kff,Vector<IssmDouble>* pf,Vector<IssmDouble>* uf,Vector<IssmDouble>* old_uf,Parameters* parameters){
+void convergence(bool* pconverged, Matrix<IssmDouble>* Kff,Vector<IssmDouble>* pf,Vector<IssmDouble>* uf,Vector<IssmDouble>* old_uf,IssmDouble eps_res,IssmDouble eps_rel,IssmDouble eps_abs){
 
 	/*output*/
@@ -23,10 +23,5 @@
 	IssmDouble nF;
 	IssmDouble solver_residue,res;
-
-	/*convergence options*/
-	IssmDouble eps_res;
-	IssmDouble eps_rel;
-	IssmDouble eps_abs;
-	IssmDouble yts;
+	int analysis_type;
 
 	if(VerboseModule()) _printf0_("   checking convergence\n");
@@ -38,10 +33,4 @@
 		return;
 	}
-
-	/*get convergence options*/
-	parameters->FindParam(&eps_res,StressbalanceRestolEnum);
-	parameters->FindParam(&eps_rel,StressbalanceReltolEnum);
-	parameters->FindParam(&eps_abs,StressbalanceAbstolEnum);
-	parameters->FindParam(&yts,ConstantsYtsEnum);
 
 	/*Display solver caracteristics*/
@@ -130,13 +119,13 @@
 		//print
 		if (!xIsNan<IssmDouble>(eps_abs)){
-			if ((nduinf*yts)<eps_abs){
-				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " < " << eps_abs << " m/yr\n");
+			if ((nduinf)<eps_abs){
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf << " < " << eps_abs << "\n");
 			}
 			else{
-				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " > " << eps_abs << " m/yr\n");
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf << " > " << eps_abs << "\n");
 				converged=false;
 			}
 		}
-		else  _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf*yts << " m/yr\n");
+		else  _printf0_(setw(50) << left << "   Convergence criterion: max(du)" << nduinf << "\n");
 
 	}
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_fct.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_fct.cpp	(revision 19105)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_fct.cpp	(revision 19105)
@@ -0,0 +1,444 @@
+/*!\file: solutionsequence_linear.cpp
+ * \brief: numerical core of linear solutions
+ */ 
+
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+
+#ifdef _HAVE_PETSC_
+void CreateDMatrix(Mat* pD,Mat K){/*{{{*/
+	/*Create D matrix such that:
+	 *
+	 * d_ij = max( -k_ij,0,-k_ji) off diagonal
+	 *
+	 * d_ii = - sum_{i!=j} d_ij for the diagonal
+	 *
+	 */
+
+	/*Intermediaries*/
+	int        ncols,ncols2,rstart,rend;
+	double     d,diagD;
+	Mat        D        = NULL;
+	Mat        K_transp = NULL;
+	int*       cols  = NULL;
+	int*       cols2 = NULL;
+	double*    vals  = NULL;
+	double*    vals2 = NULL;
+
+	/*First, we need to transpose K so that we access both k_ij and k_ji*/
+	MatTranspose(K,MAT_INITIAL_MATRIX,&K_transp);
+
+	/*Initialize output (D has the same non zero pattern as K)*/
+	MatDuplicate(K,MAT_SHARE_NONZERO_PATTERN,&D);
+
+	/*Go through the rows of K an K' and build D*/
+	MatGetOwnershipRange(K,&rstart,&rend);
+	for(int row=rstart; row<rend; row++){
+		diagD = 0.;
+		MatGetRow(K       ,row,&ncols, (const int**)&cols, (const double**)&vals);
+		MatGetRow(K_transp,row,&ncols2,(const int**)&cols2,(const double**)&vals2);
+		_assert_(ncols==ncols2);
+		for(int j=0; j<ncols; j++) {
+			_assert_(cols[j]==cols2[j]);
+			d = max(max(-vals[j],-vals2[j]),0.);
+			MatSetValue(D,row,cols[j],d,INSERT_VALUES);
+			if(cols[j]!=row) diagD -= d;
+		}
+		MatSetValue(D,row,row,diagD,INSERT_VALUES);
+		MatRestoreRow(K       ,row,&ncols, (const int**)&cols, (const double**)&vals);
+		MatRestoreRow(K_transp,row,&ncols2,(const int**)&cols2,(const double**)&vals2);
+	}
+	MatAssemblyBegin(D,MAT_FINAL_ASSEMBLY);
+	MatAssemblyEnd(  D,MAT_FINAL_ASSEMBLY);
+
+	/*Clean up and assign output pointer*/
+	MatFree(&K_transp);
+	*pD = D;
+}/*}}}*/
+void CreateLHS(Mat* pLHS,IssmDouble* pdmax,Mat K,Mat D,Vec Ml,IssmDouble theta,IssmDouble deltat,FemModel* femmodel,int configuration_type){/*{{{*/
+	/*Create Left Hand side of Lower order solution
+	 *
+	 * LHS = [ML − theta*detlat *(K+D)^n+1]
+	 *
+	 */
+
+	/*Intermediaries*/
+	int        dof,ncols,ncols2,rstart,rend;
+	double     d,mi,dmax = 0.;
+	Mat        LHS   = NULL;
+	int*       cols  = NULL;
+	int*       cols2 = NULL;
+	double*    vals  = NULL;
+	double*    vals2 = NULL;
+
+	MatDuplicate(K,MAT_SHARE_NONZERO_PATTERN,&LHS);
+	MatGetOwnershipRange(K,&rstart,&rend);
+	for(int row=rstart; row<rend; row++){
+		MatGetRow(K,row,&ncols, (const int**)&cols, (const double**)&vals);
+		MatGetRow(D,row,&ncols2,(const int**)&cols2,(const double**)&vals2);
+		_assert_(ncols==ncols2);
+		for(int j=0; j<ncols; j++) {
+			_assert_(cols[j]==cols2[j]);
+			d = -theta*deltat*(vals[j] + vals2[j]);
+			if(cols[j]==row){
+				VecGetValues(Ml,1,(const int*)&cols[j],&mi);
+				d += mi;
+			}
+			if(fabs(d)>dmax) dmax = fabs(d);
+			MatSetValue(LHS,row,cols[j],d,INSERT_VALUES);
+		}
+		MatRestoreRow(K,row,&ncols, (const int**)&cols, (const double**)&vals);
+		MatRestoreRow(D,row,&ncols2,(const int**)&cols2,(const double**)&vals2);
+	}
+
+	/*Broadcast max(dmax)*/
+	IssmDouble dmax_all;
+	ISSM_MPI_Reduce(&dmax,&dmax_all,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&dmax_all,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
+	dmax = dmax_all;
+
+	/*Penalize Dirichlet boundary*/
+	dmax = dmax * 1.e+3;
+	for(int i=0;i<femmodel->constraints->Size();i++){
+		Constraint* constraint=(Constraint*)femmodel->constraints->GetObjectByOffset(i);
+		if(constraint->InAnalysis(configuration_type)){
+			constraint->PenaltyDofAndValue(&dof,&d,femmodel->nodes,femmodel->parameters);
+			if(dof!=-1){
+				MatSetValue(LHS,dof,dof,dmax,INSERT_VALUES);
+			}
+		}
+	}
+	MatAssemblyBegin(LHS,MAT_FINAL_ASSEMBLY);
+	MatAssemblyEnd(  LHS,MAT_FINAL_ASSEMBLY);
+
+	/*Clean up and assign output pointer*/
+	*pdmax = dmax;
+	*pLHS  = LHS;
+}/*}}}*/
+void CreateRHS(Vec* pRHS,Mat K,Mat D,Vec Ml,Vec u,IssmDouble theta,IssmDouble deltat,IssmDouble dmax,FemModel* femmodel,int configuration_type){/*{{{*/
+	/*Create Left Hand side of Lower order solution
+	 *
+	 * RHS = [ML + (1 − theta) deltaT L^n] u^n
+	 *
+	 * where L = K + D
+	 *
+	 */
+
+	/*Intermediaries*/
+	Vec         Ku  = NULL;
+	Vec         Du  = NULL;
+	Vec         RHS = NULL;
+	int         dof;
+	IssmDouble  d;
+
+	/*Initialize vectors*/
+	VecDuplicate(u,&Ku);
+	VecDuplicate(u,&Du);
+	VecDuplicate(u,&RHS);
+
+	/*Create RHS = M*u + (1-theta)*deltat*K*u + (1-theta)*deltat*D*u*/
+	MatMult(K,u,Ku);
+	MatMult(D,u,Du);
+	VecPointwiseMult(RHS,Ml,u);
+	VecAXPBYPCZ(RHS,(1-theta)*deltat,(1-theta)*deltat,1,Ku,Du);
+	VecFree(&Ku);
+	VecFree(&Du);
+
+	/*Penalize Dirichlet boundary*/
+	for(int i=0;i<femmodel->constraints->Size();i++){
+		Constraint* constraint=(Constraint*)femmodel->constraints->GetObjectByOffset(i);
+		if(constraint->InAnalysis(configuration_type)){
+			constraint->PenaltyDofAndValue(&dof,&d,femmodel->nodes,femmodel->parameters);
+			d = d*dmax;
+			if(dof!=-1){
+				VecSetValues(RHS,1,&dof,(const double*)&d,INSERT_VALUES);
+			}
+		}
+	}
+	VecAssemblyBegin(RHS);
+	VecAssemblyEnd(  RHS);
+
+	/*Assign output pointer*/
+	*pRHS = RHS;
+
+}/*}}}*/
+void RichardsonUdot(Vec* pudot,Vec u,Vec Ml,Mat K,Mat Mc){/*{{{*/
+	/*Use Richardson's formulato get udot using 5 steps and an initial guess of 0
+	 *
+	 * udot_new = udot_old + Ml^-1 (K^(n+1) u - Mc udot_old)
+	 *
+	 * */
+
+	/*Intermediaries*/
+	Vec udot  = NULL;
+	Vec temp1 = NULL;
+	Vec temp2 = NULL;
+
+	/*Initialize vectors*/
+	VecDuplicate(u,&udot);
+	VecDuplicate(u,&temp1);
+	VecDuplicate(u,&temp2);
+
+	/*Initial guess*/
+	VecZeroEntries(udot);
+	
+	/*Richardson's iterations*/
+	for(int i=0;i<5;i++){
+		MatMult(Mc,udot,temp1);
+		MatMult(K, u,   temp2);
+		VecAXPBY(temp2,-1.,1.,temp1);       // temp2 = (K^(n+1) u -- Mc udot_old)
+		VecPointwiseDivide(temp1,temp2,Ml); // temp1 = Ml^-1 temp2
+		VecAXPBY(udot,1.,1.,temp1);
+	}
+
+	/*Clean up and assign output pointer*/
+	VecFree(&temp1);
+	VecFree(&temp2);
+	*pudot=udot;
+
+}/*}}}*/
+void CreateRis(IssmDouble** pRi_plus_serial,IssmDouble** pRi_minus_serial,Mat Mc,Mat D,IssmDouble* ml_serial,Vec uvec,IssmDouble* u,IssmDouble* udot,IssmDouble* ulmin,IssmDouble* ulmax,IssmDouble deltat){/*{{{*/
+
+	/*Intermediaries*/
+	Vec         Ri_plus  = NULL;
+	Vec         Ri_minus = NULL;
+	int         ncols,ncols2,rstart,rend;
+	double      d;
+	int        *cols     = NULL;
+	int        *cols2    = NULL;
+	double     *vals     = NULL;
+	double     *vals2    = NULL;
+
+	/*Initialize vectors*/
+	VecDuplicate(uvec,&Ri_plus);
+	VecDuplicate(uvec,&Ri_minus);
+
+	/*Get global extremas*/
+	IssmDouble uLmin_global =  ulmin[0];
+	IssmDouble uLmax_global =  ulmax[0];
+	VecGetSize(uvec,&ncols);
+	for(int i=1;i<ncols;i++) if(ulmin[i]<uLmin_global) uLmin_global = ulmin[i];
+	for(int i=1;i<ncols;i++) if(ulmax[i]>uLmax_global) uLmax_global = ulmax[i];
+	//printf("%g %g\n",uLmin_global,uLmax_global);
+
+	/*Go through D and calculate Ris*/
+	MatGetOwnershipRange(D,&rstart,&rend);
+	for(int row=rstart; row<rend; row++){
+		double Pi_plus  = 0.;
+		double Pi_minus = 0.;
+		MatGetRow(Mc,row,&ncols, (const int**)&cols, (const double**)&vals);
+		MatGetRow(D ,row,&ncols2,(const int**)&cols2,(const double**)&vals2);
+		_assert_(ncols==ncols2);
+		for(int j=0; j<ncols; j++) {
+			_assert_(cols[j]==cols2[j]);
+			d = vals[j]*(udot[row] - udot[cols[j]]) + vals2[j]*(u[row] - u[cols[j]]);
+			if(row!=cols[j]){
+				if(d>0.){
+					Pi_plus  += d;
+				}
+				else{
+					Pi_minus += d;
+				}
+			}
+		}
+
+		/*Compute Qis and Ris*/
+		//double Qi_plus  = ml_serial[row]/deltat*(3. - u[row]);
+		//double Qi_minus = ml_serial[row]/deltat*(2. - u[row]);
+		double Qi_plus  = ml_serial[row]/deltat*(ulmax[row] - u[row]);
+		double Qi_minus = ml_serial[row]/deltat*(ulmin[row] - u[row]);
+		//double Qi_plus  = ml_serial[row]/deltat*(uLmax_global - u[row]);
+		//double Qi_minus = ml_serial[row]/deltat*(uLmin_global - u[row]);
+		_assert_(Qi_plus  >= 0.);
+		_assert_(Qi_minus <= 0.);
+		d = 1.;
+		if(Pi_plus!=0.) d = min(1.,Qi_plus/Pi_plus);
+		VecSetValue(Ri_plus,row,d,INSERT_VALUES);
+		d = 1.;
+		if(Pi_minus!=0.) d = min(1.,Qi_minus/Pi_minus);
+		VecSetValue(Ri_minus,row,d,INSERT_VALUES);
+
+		MatRestoreRow(Mc,row,&ncols, (const int**)&cols, (const double**)&vals);
+		MatRestoreRow(D ,row,&ncols2,(const int**)&cols2,(const double**)&vals2);
+	}
+	VecAssemblyBegin(Ri_plus);
+	VecAssemblyEnd(  Ri_plus);
+	VecAssemblyBegin(Ri_minus);
+	VecAssemblyEnd(  Ri_minus);
+
+	/*Serialize Ris*/
+	IssmDouble* Ri_plus_serial  = NULL;
+	IssmDouble* Ri_minus_serial = NULL;
+	VecToMPISerial(&Ri_plus_serial,Ri_plus,IssmComm::GetComm());
+	VecToMPISerial(&Ri_minus_serial,Ri_minus,IssmComm::GetComm());
+	VecFree(&Ri_plus);
+	VecFree(&Ri_minus);
+
+	/*Assign output pointer*/
+	*pRi_plus_serial  = Ri_plus_serial;
+	*pRi_minus_serial = Ri_minus_serial;
+}/*}}}*/
+void CreateFbar(Vec* pFbar,IssmDouble* Ri_plus,IssmDouble* Ri_minus,Mat Mc,Mat D,IssmDouble* udot,IssmDouble* u,Vec uvec){/*{{{*/
+
+	/*Intermediaries*/
+	Vec         Fbar = NULL;
+	int         ncols,ncols2,rstart,rend;
+	double      d,f_ij;
+	int        *cols     = NULL;
+	int        *cols2    = NULL;
+	double     *vals     = NULL;
+	double     *vals2    = NULL;
+
+	/*Build fbar*/
+	VecDuplicate(uvec,&Fbar);
+	MatGetOwnershipRange(D,&rstart,&rend);
+	for(int row=rstart; row<rend; row++){
+		MatGetRow(Mc,row,&ncols, (const int**)&cols, (const double**)&vals);
+		MatGetRow(D ,row,&ncols2,(const int**)&cols2,(const double**)&vals2);
+		_assert_(ncols==ncols2);
+		d = 0.;
+		for(int j=0; j<ncols; j++) {
+			_assert_(cols[j]==cols2[j]);
+			if(row==cols[j]) continue;
+			f_ij = vals[j]*(udot[row] - udot[cols[j]]) + vals2[j]*(u[row] - u[cols[j]]);
+			if(f_ij>0){
+				d += min(Ri_plus[row],Ri_minus[cols[j]]) * f_ij;
+			}
+			else{
+				d += min(Ri_minus[row],Ri_plus[cols[j]]) * f_ij;
+			}
+		}
+		VecSetValue(Fbar,row,d,INSERT_VALUES);
+		MatRestoreRow(Mc,row,&ncols, (const int**)&cols, (const double**)&vals);
+		MatRestoreRow(D ,row,&ncols2,(const int**)&cols2,(const double**)&vals2);
+	}
+	VecAssemblyBegin(Fbar);
+	VecAssemblyEnd(  Fbar);
+
+	/*Assign output pointer*/
+	*pFbar = Fbar;
+}/*}}}*/
+void UpdateSolution(Vec u,Vec udot,Vec Ml,Vec Fbar,IssmDouble deltat){/*{{{*/
+
+	/*Intermediary*/
+	Vec temp1 = NULL;
+
+	/*Compute solution u^n+1 = u_L + deltat Ml^-1 fbar*/
+	VecDuplicate(u,&temp1);
+	VecPointwiseDivide(temp1,Fbar,Ml); //temp1 = Ml^-1 temp2
+	VecAXPBY(udot,1.,1.,temp1);
+	VecAXPY(u,deltat,temp1);
+
+	/*CLean up and return*/
+	VecFree(&temp1);
+}/*}}}*/
+#endif
+void solutionsequence_fct(FemModel* femmodel){
+
+	/*intermediary: */
+	IssmDouble           theta,deltat,dmax;
+	int                  configuration_type;
+	Vector<IssmDouble>*  Ml = NULL;
+	Matrix<IssmDouble>*  K  = NULL;
+	Matrix<IssmDouble>*  Mc = NULL;
+	Vector<IssmDouble>*  ug = NULL;
+	Vector<IssmDouble>*  uf = NULL;
+
+	/*Create analysis*/
+	MasstransportAnalysis* analysis = new MasstransportAnalysis();
+
+	/*Recover parameters: */
+	femmodel->parameters->FindParam(&deltat,TimesteppingTimeStepEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->UpdateConstraintsx();
+	theta = 0.5;
+
+	/*Create lumped mass matrix*/
+	analysis->LumpedMassMatrix(&Ml,femmodel);
+	analysis->MassMatrix(&Mc,femmodel);
+	analysis->FctKMatrix(&K,NULL,femmodel);
+	delete analysis;
+
+	#ifdef _HAVE_PETSC_
+
+	/*Convert matrices to PETSc matrices*/
+	Mat D_petsc  = NULL;
+	Mat LHS      = NULL;
+	Vec RHS      = NULL;
+	Vec u        = NULL;
+	Vec udot     = NULL;
+	Mat K_petsc  = K->pmatrix->matrix;
+	Vec Ml_petsc = Ml->pvector->vector;
+	Mat Mc_petsc = Mc->pmatrix->matrix;
+
+	/*Create D Matrix*/
+	CreateDMatrix(&D_petsc,K_petsc);
+
+	/*Create LHS: [ML − theta*detlat *(K+D)^n+1]*/
+	CreateLHS(&LHS,&dmax,K_petsc,D_petsc,Ml_petsc,theta,deltat,femmodel,configuration_type);
+
+	/*Get previous solution u^n*/
+	GetSolutionFromInputsx(&ug,femmodel);
+	Reducevectorgtofx(&uf, ug, femmodel->nodes,femmodel->parameters);
+	delete ug;
+
+	/*Create RHS: [ML + (1 − theta) deltaT L^n] u^n */
+	CreateRHS(&RHS,K_petsc,D_petsc,Ml_petsc,uf->pvector->vector,theta,deltat,dmax,femmodel,configuration_type);
+	delete uf;
+	
+	/*Go solve lower order solution*/
+	SolverxPetsc(&u,LHS,RHS,NULL,NULL, femmodel->parameters); 
+	MatFree(&LHS);
+	VecFree(&RHS);
+
+	/*Richardson to calculate udot*/
+	RichardsonUdot(&udot,u,Ml_petsc,K_petsc,Mc_petsc);
+	delete K;
+
+	/*Serialize u and udot*/
+	IssmDouble* udot_serial = NULL;
+	IssmDouble* u_serial    = NULL;
+	IssmDouble* ml_serial   = NULL;
+	VecToMPISerial(&udot_serial,udot    ,IssmComm::GetComm());
+	VecToMPISerial(&u_serial   ,u       ,IssmComm::GetComm());
+	VecToMPISerial(&ml_serial  ,Ml_petsc,IssmComm::GetComm());
+
+	/*Anti diffusive fluxes*/
+	Vec         Fbar            = NULL;
+	IssmDouble *Ri_minus_serial = NULL;
+	IssmDouble *Ri_plus_serial  = NULL;
+	IssmDouble *ulmin           = NULL;
+	IssmDouble *ulmax           = NULL;
+	femmodel->GetInputLocalMinMaxOnNodesx(&ulmin,&ulmax,u_serial);
+	CreateRis(&Ri_plus_serial,&Ri_minus_serial,Mc_petsc,D_petsc,ml_serial,u,u_serial,udot_serial,ulmin,ulmax,deltat);
+	CreateFbar(&Fbar,Ri_plus_serial,Ri_minus_serial,Mc_petsc,D_petsc,udot_serial,u_serial,u);
+	xDelete<IssmDouble>(Ri_plus_serial);
+	xDelete<IssmDouble>(Ri_minus_serial);
+	xDelete<IssmDouble>(ulmin);
+	xDelete<IssmDouble>(ulmax);
+
+	/*Clean up*/
+	MatFree(&D_petsc);
+	delete Mc;
+	xDelete<IssmDouble>(udot_serial);
+	xDelete<IssmDouble>(u_serial);
+	xDelete<IssmDouble>(ml_serial);
+
+	/*Compute solution u^n+1 = u_L + deltat Ml^-1 fbar*/
+	UpdateSolution(u,udot,Ml_petsc,Fbar,deltat);
+	uf =new Vector<IssmDouble>(u);
+	VecFree(&u);
+	VecFree(&Fbar);
+	VecFree(&udot);
+	delete Ml;
+
+	/*Update Element inputs*/
+	InputUpdateFromSolutionx(femmodel,uf); 
+	delete uf;
+
+	#else
+	_error_("PETSc needs to be installed");
+	#endif
+}
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 19104)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 19105)
@@ -46,5 +46,6 @@
 	IssmDouble ndu_sed,nu_sed;
 	IssmDouble ndu_epl,nu_epl;
-
+	IssmDouble ThickCount,L2Count;
+	
 	/*Recover parameters: */
 	femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
@@ -69,4 +70,5 @@
 		/*Initialize the element mask*/
 		inefanalysis->ElementizeEplMask(femmodel);
+		effanalysis->InitZigZagCounter(femmodel);
 	}
 	/*The real computation starts here, outermost loop is on the two layer system*/
@@ -90,15 +92,15 @@
 		femmodel->parameters->SetParam(HydrologySedimentEnum,HydrologyLayerEnum);
 		
-		/*Reset constraint on the ZigZag Lock, this thing doesn't work, it have to disapear*/
+		/*Reset constraint on the ZigZag Lock*/
 		ResetConstraintsx(femmodel);
 
-		/* {{{ *//*Treating the sediment*/
+		/*{{{*//*Treating the sediment*/
 		for(;;){
 			sedconverged=false;
 			uf_sed_sub_iter=uf_sed->Duplicate();_assert_(uf_sed_sub_iter);
 			uf_sed->Copy(uf_sed_sub_iter);
-			/* {{{ *//*Loop on the sediment layer to deal with the penalization*/
+			/*{{{*//*Loop on the sediment layer to deal with the penalization*/
 			for(;;){
-				/* {{{ *//*Core of the computation*/
+				/*{{{*/ /*Core of the computation*/
 				if(VerboseSolution()) _printf0_("Building Sediment Matrix...\n");
 				SystemMatricesx(&Kff,&Kfs,&pf,&df,&sediment_kmax,femmodel);
@@ -112,5 +114,5 @@
 				InputUpdateFromSolutionx(femmodel,ug_sed);
 				ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
-				/* }}} */
+				/*}}}*/
 				if (!sedconverged){
 					if(VerboseConvergence()) _printf0_("   # Sediment unstable constraints = " << num_unstable_constraints << "\n");
@@ -125,9 +127,5 @@
 			}
 		
-			/* }}} *//*End of the sediment penalization loop*/
-			/*Update EPL mask*/
-			if(isefficientlayer){
-				inefanalysis->ElementizeEplMask(femmodel);
-			}
+			/*}}}*//*End of the sediment penalization loop*/
 			sedconverged=false;
 			
@@ -155,10 +153,11 @@
 			}
 		}
-		/* }}} *//*End of the global sediment loop*/
-		/* {{{ *//*Now dealing with the EPL in the same way*/
+		/*}}}*//*End of the global sediment loop*/
+		/*{{{*//*Now dealing with the EPL in the same way*/
 		if(isefficientlayer){
 			femmodel->SetCurrentConfiguration(HydrologyDCEfficientAnalysisEnum);
 			/*updating mask*/
-			femmodel->HydrologyEPLupdateDomainx();
+			femmodel->HydrologyEPLupdateDomainx(&ThickCount);
+			inefanalysis->ElementizeEplMask(femmodel);
 			InputUpdateFromConstantx(femmodel,true,ResetPenaltiesEnum);
 			InputUpdateFromConstantx(femmodel,false,ConvergedEnum);
@@ -169,21 +168,21 @@
 				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*/
+				/*{{{*//*Retrieve the EPL head slopes and compute EPL Thickness*/
 				if(VerboseSolution()) _printf0_("computing EPL Head slope...\n");
+				//inefanalysis->ElementizeEplMask(femmodel);
+				femmodel->SetCurrentConfiguration(L2ProjectionEPLAnalysisEnum);
+				femmodel->UpdateConstraintsL2ProjectionEPLx(&L2Count);
 				inefanalysis->ElementizeEplMask(femmodel);
-				femmodel->SetCurrentConfiguration(L2ProjectionEPLAnalysisEnum);
-				femmodel->UpdateConstraintsL2ProjectionEPLx();
 				femmodel->parameters->SetParam(EplHeadSlopeXEnum,InputToL2ProjectEnum);
 				solutionsequence_linear(femmodel);
 				femmodel->parameters->SetParam(EplHeadSlopeYEnum,InputToL2ProjectEnum);
 				solutionsequence_linear(femmodel);
+
 				femmodel->SetCurrentConfiguration(HydrologyDCEfficientAnalysisEnum);
-
 				effanalysis->ComputeEPLThickness(femmodel);
-
 				//updating mask after the computation of the epl thickness (Allow to close too thin EPL)
-				femmodel->HydrologyEPLupdateDomainx();
+				femmodel->HydrologyEPLupdateDomainx(&ThickCount);
 				inefanalysis->ElementizeEplMask(femmodel);
-				/* }}} */
+				/*}}}*/
 					
 				if(VerboseSolution()) _printf0_("Building EPL Matrix...\n");
@@ -215,4 +214,6 @@
 					_error_("   maximum number of EPL iterations (" << hydro_maxiter << ") exceeded");
 				}
+				//If there is some colapse go through sediment again
+				if(ThickCount<L2Count)eplconverged=true;
 				eplcount++;
 				
@@ -222,11 +223,12 @@
 					InputUpdateFromConstantx(femmodel,eplconverged,ConvergedEnum);
 					InputUpdateFromSolutionx(femmodel,ug_epl);
+					effanalysis->ResetCounter(femmodel);
 					break;
 				}
 			}
 		}
-		/* }}} */ /*End of the global EPL loop*/
-
-		/* {{{ */ /*Now dealing with the convergence of the whole system*/
+		/*}}}*/ /*End of the global EPL loop*/
+
+		/*{{{*/ /*Now dealing with the convergence of the whole system*/
 		if(!hydroconverged){
 			//compute norm(du)/norm(u)
@@ -268,5 +270,5 @@
 		if(hydroconverged)break;
 	}
-	/* }}} */
+	/*}}}*/
 	if(isefficientlayer)InputUpdateFromSolutionx(femmodel,ug_epl);
 	femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_la.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_la.cpp	(revision 19104)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_la.cpp	(revision 19105)
@@ -39,9 +39,11 @@
 
 	/*Convergence criterion*/
-	int  count = 0;
-	Vector<IssmDouble>* vel     = NULL;
-	Vector<IssmDouble>* vel_old = NULL;
-	GetVectorFromInputsx(&vel,femmodel,VxEnum,VertexEnum);
-	GetVectorFromInputsx(&pug,femmodel,PressureEnum,VertexEnum);
+	int  count       = 0;
+	int  count_local = 0;
+	Vector<IssmDouble>* vel           = NULL;
+	Vector<IssmDouble>* vel_old       = NULL;
+	Vector<IssmDouble>* vel_old_local = NULL;
+	GetVectorFromInputsx(&vel,femmodel,VxEnum,VertexPIdEnum);
+	GetVectorFromInputsx(&pug,femmodel,PressureEnum,VertexPIdEnum);
 
 	while(true){
@@ -49,21 +51,42 @@
 
 		/*save pointer to old velocity*/
-		delete vel_old;vel_old=vel;
+		delete vel_old;vel_old=vel->Duplicate(); vel->Copy(vel_old);
 		delete pug_old;pug_old=pug; 
 		pressure_converged=false; vel_converged=false;
 
-		/*Solve KU=F*/
-		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
-		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-		SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
-		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
-		Reduceloadx(pf, Kfs, ys); delete Kfs;
-		Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
-		delete Kff; delete pf; delete df;
-		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete uf; delete ys;
+		while(true){
+			count_local++;
+			delete vel_old_local;vel_old_local=vel;
+			/*Solve KU=F*/
+			femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+			femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+			SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+			CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
+			Reduceloadx(pf, Kfs, ys); delete Kfs;
+			Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); 
+			delete Kff; delete pf; delete df;
+			Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete uf; delete ys;
 
-		/*Update solution*/
-		InputUpdateFromSolutionx(femmodel,ug); delete ug;
-		GetVectorFromInputsx(&vel,femmodel,VxEnum,VertexEnum);
+			/*Update solution*/
+			InputUpdateFromSolutionx(femmodel,ug); delete ug;
+			GetVectorFromInputsx(&vel,femmodel,VxEnum,VertexPIdEnum);
+			/*Check for convergence*/
+			Vector<IssmDouble>* dvel_local=vel_old_local->Duplicate(); vel_old_local->Copy(dvel_local); dvel_local->AYPX(vel,-1.0);
+			IssmDouble ndu=dvel_local->Norm(NORM_TWO);   delete dvel_local;
+			IssmDouble nu =vel_old_local->Norm(NORM_TWO);
+			if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
+			if((ndu/nu)<eps_rel){
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " < " << eps_rel*100 << " %\n");
+				break;
+			}
+			else{ 
+				if(VerboseConvergence()) _printf0_(setw(50) << left << "   Convergence criterion: norm(du)/norm(u)" << ndu/nu*100 << " > " << eps_rel*100 << " %\n");
+			}
+			if(count_local>=max_nonlinear_iterations){
+				_printf0_("   maximum number of nonlinear iterations (" << max_nonlinear_iterations << ") exceeded\n"); 
+				break;
+			}
+		}
+		count_local=0;
 
 		femmodel->SetCurrentConfiguration(UzawaPressureAnalysisEnum);
@@ -78,10 +101,10 @@
 		/*Update solution*/
 		InputUpdateFromSolutionx(femmodel,pug); delete pug;
-		GetVectorFromInputsx(&pug,femmodel,PressureEnum,VertexEnum);
+		GetVectorFromInputsx(&pug,femmodel,PressureEnum,VertexPIdEnum);
 
 		/*Check for convergence*/
-		Vector<IssmDouble>* dvel=vel_old->Duplicate(); vel_old->Copy(dvel); dvel->AYPX(vel,-1.0);
+		Vector<IssmDouble>* dvel=vel_old_local->Duplicate(); vel_old_local->Copy(dvel); dvel->AYPX(vel,-1.0);
 		IssmDouble ndu=dvel->Norm(NORM_TWO);   delete dvel;
-		IssmDouble nu =vel_old->Norm(NORM_TWO);
+		IssmDouble nu =vel_old_local->Norm(NORM_TWO);
 		if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
 		if((ndu/nu)<eps_rel){
@@ -119,4 +142,5 @@
 	delete vel;  
 	delete vel_old;  
+	delete vel_old_local;  
 	delete stressanalysis;
 	delete pressureanalysis;
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_la_theta.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_la_theta.cpp	(revision 19104)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_la_theta.cpp	(revision 19105)
@@ -41,5 +41,5 @@
 	Vector<IssmDouble>* vx     = NULL;
 	Vector<IssmDouble>* vx_old = NULL;
-	GetVectorFromInputsx(&vx,femmodel,VxEnum,VertexEnum);
+	GetVectorFromInputsx(&vx,femmodel,VxEnum,VertexPIdEnum);
 
 	while(true){
@@ -69,5 +69,5 @@
 		analysis->InputUpdateFromSolutionFSXTH_d(  femmodel->elements,femmodel->parameters);
 		analysis->InputUpdateFromSolutionFSXTH_tau(femmodel->elements,femmodel->parameters);
-		GetVectorFromInputsx(&vx,femmodel,VxEnum,VertexEnum);
+		GetVectorFromInputsx(&vx,femmodel,VxEnum,VertexPIdEnum);
 
 		/*Check for convergence*/
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp	(revision 19104)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp	(revision 19105)
@@ -30,5 +30,6 @@
 	/*parameters:*/
 	int max_nonlinear_iterations;
-	int  configuration_type;
+	int configuration_type;
+	IssmDouble eps_res,eps_rel,eps_abs;
 
 	/*Recover parameters: */
@@ -36,4 +37,7 @@
 	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
 	femmodel->parameters->FindParam(&newton,StressbalanceIsnewtonEnum);
+	femmodel->parameters->FindParam(&eps_res,StressbalanceRestolEnum);
+	femmodel->parameters->FindParam(&eps_rel,StressbalanceReltolEnum);
+	femmodel->parameters->FindParam(&eps_abs,StressbalanceAbstolEnum);
 	femmodel->UpdateConstraintsx();
 
@@ -83,5 +87,5 @@
 
 		/*Check convergence*/
-		convergence(&converged,Kff,pf,uf,old_uf,femmodel->parameters); 
+		convergence(&converged,Kff,pf,uf,old_uf,eps_res,eps_rel,eps_abs); 
 		delete Kff; delete pf;
 		if(converged==true){	
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp	(revision 19104)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp	(revision 19105)
@@ -31,8 +31,13 @@
 	int max_nonlinear_iterations;
 	int configuration_type;
+	IssmDouble eps_res,eps_rel,eps_abs;
+
 
 	/*Recover parameters: */
 	femmodel->parameters->FindParam(&min_mechanical_constraints,StressbalanceRiftPenaltyThresholdEnum);
 	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
+	femmodel->parameters->FindParam(&eps_res,StressbalanceRestolEnum);
+	femmodel->parameters->FindParam(&eps_rel,StressbalanceReltolEnum);
+	femmodel->parameters->FindParam(&eps_abs,StressbalanceAbstolEnum);
 	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
 	femmodel->UpdateConstraintsx();
@@ -66,5 +71,5 @@
 		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
 
-		convergence(&converged,Kff,pf,uf,old_uf,femmodel->parameters); delete Kff; delete pf; delete df;
+		convergence(&converged,Kff,pf,uf,old_uf,eps_res,eps_rel,eps_abs); delete Kff; delete pf; delete df;
 		InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
 		InputUpdateFromSolutionx(femmodel,ug);
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp	(revision 19104)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp	(revision 19105)
@@ -33,8 +33,12 @@
 	int  max_nonlinear_iterations;
 	int  configuration_type;
+	IssmDouble eps_res,eps_rel,eps_abs;
 
 	/*Recover parameters: */
 	femmodel->parameters->FindParam(&min_mechanical_constraints,StressbalanceRiftPenaltyThresholdEnum);
 	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
+	femmodel->parameters->FindParam(&eps_res,StressbalanceRestolEnum);
+	femmodel->parameters->FindParam(&eps_rel,StressbalanceReltolEnum);
+	femmodel->parameters->FindParam(&eps_abs,StressbalanceAbstolEnum);
 	femmodel->UpdateConstraintsx();
 
@@ -68,5 +72,5 @@
 		InputUpdateFromSolutionx(femmodel,ug_horiz);
 
-		convergence(&converged,Kff_horiz,pf_horiz,uf_horiz,old_uf_horiz,femmodel->parameters); delete Kff_horiz; delete pf_horiz; delete df_horiz;
+		convergence(&converged,Kff_horiz,pf_horiz,uf_horiz,old_uf_horiz,eps_res,eps_rel,eps_abs); delete Kff_horiz; delete pf_horiz; delete df_horiz;
 
 		/*Second compute vertical velocity: */
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 19104)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 19105)
@@ -3,4 +3,5 @@
  */ 
 
+#include "./solutionsequences.h"
 #include "../toolkits/toolkits.h"
 #include "../classes/classes.h"
@@ -24,4 +25,5 @@
 
 	bool converged;
+	bool isenthalpy, isdynamicbasalspc;
 	int constraints_converged;
 	int num_unstable_constraints;
@@ -32,47 +34,104 @@
 	/*parameters:*/
 	int  configuration_type;
+	IssmDouble eps_rel;
 
 	/*Recover parameters: */
-	femmodel->parameters->FindParam(&thermal_penalty_threshold,ThermalPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
 	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
 	femmodel->parameters->FindParam(&thermal_maxiter,ThermalMaxiterEnum);
 
+	converged=false;
+	InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+
+	if(isenthalpy){
+		femmodel->parameters->FindParam(&isdynamicbasalspc,ThermalIsdynamicbasalspcEnum);
+		femmodel->parameters->FindParam(&eps_rel,ThermalReltolEnum);
+		femmodel->UpdateConstraintsx();
+
+		//Update the solution to make sure that tf and tf_old are similar (for next step in transient or steadystate)
+		GetSolutionFromInputsx(&tg,femmodel);
+		Reducevectorgtofx(&tf, tg, femmodel->nodes,femmodel->parameters);
+		InputUpdateFromSolutionx(femmodel,tg);
+	}
+	else{
+		femmodel->parameters->FindParam(&thermal_penalty_threshold,ThermalPenaltyThresholdEnum);
+		InputUpdateFromConstantx(femmodel,true,ResetPenaltiesEnum);
+		femmodel->UpdateConstraintsx();
+	}
+
 	count=1;
-	converged=false;
+	
+	for(;;){
+		delete tf_old;tf_old=tf;
 
-	InputUpdateFromConstantx(femmodel,true,ResetPenaltiesEnum);
-	InputUpdateFromConstantx(femmodel,false,ConvergedEnum);
-	femmodel->UpdateConstraintsx();
-
-	for(;;){
-
-		delete tf_old; tf_old=tf;
-		SystemMatricesx(&Kff, &Kfs, &pf,&df, &melting_offset,femmodel);
+		if(isenthalpy){ 
+			SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
+			/*Update old solution, such that sizes of tf_old and tf are comparable*/
+			if(isdynamicbasalspc){
+				delete tf_old;
+				Reducevectorgtofx(&tf_old, tg, femmodel->nodes,femmodel->parameters);
+			}
+		}
+		else SystemMatricesx(&Kff, &Kfs, &pf,&df, &melting_offset,femmodel);
+		delete tg;
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf, Kfs, ys); delete Kfs;
-		Solverx(&tf, Kff, pf,tf_old, df, femmodel->parameters);
-		delete Kff;delete pf;delete tg; delete df;
+		Solverx(&tf, Kff, pf, tf_old, df, femmodel->parameters);
 		Mergesolutionfromftogx(&tg, tf,ys,femmodel->nodes,femmodel->parameters); delete ys;
+		if(isenthalpy){ 
+			convergence(&converged,Kff,pf,tf,tf_old,0.05,eps_rel,NAN); 
+			InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+		}
+		delete Kff; delete pf; delete df;
 		InputUpdateFromSolutionx(femmodel,tg);
+		ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
+		if(VerboseConvergence()) _printf0_("   number of unstable constraints: " << num_unstable_constraints << "\n");
 
-		ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
+		if(isenthalpy){ // enthalpy method
+			IssmDouble dt;
+			femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
 
-		if (!converged){
-			if(VerboseConvergence()) _printf0_("   #unstable constraints = " << num_unstable_constraints << "\n");
-			if (num_unstable_constraints <= thermal_penalty_threshold)converged=true;
-			if (count>=thermal_maxiter){
+			count++;
+			bool max_iteration_state=false;
+			if(count>=thermal_maxiter){
+				_printf0_("   maximum number of nonlinear iterations (" << thermal_maxiter << ") exceeded\n"); 
 				converged=true;
-				_printf0_("   maximum number of iterations (" << thermal_maxiter << ") exceeded\n"); 
+				InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+				InputUpdateFromSolutionx(femmodel,tg);		
+				max_iteration_state=true;
+			}
+			if(converged==true){
+				int step; IssmDouble time;
+				femmodel->parameters->FindParam(&time,TimeEnum);
+				femmodel->parameters->FindParam(&step,StepEnum);
+				femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, step, time));
+				break;
+			}
+			else if(dt==0.){
+				EnthalpyAnalysis::ComputeBasalMeltingrate(femmodel);
+				EnthalpyAnalysis::UpdateBasalConstraints(femmodel);
 			}
 		}
-		count++;
-
-		InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
-
-		if(converged)break;
+		else{ // dry ice method
+			if(!converged){
+				if(num_unstable_constraints<=thermal_penalty_threshold) converged=true;
+				if(count>=thermal_maxiter){
+					converged=true;
+					_printf0_("   maximum number of iterations (" << thermal_maxiter << ") exceeded\n"); 
+				}
+			}
+			count++;
+			InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+			if(converged)break;
+		}
 	}
 
-	InputUpdateFromSolutionx(femmodel,tg);
-	femmodel->parameters->SetParam(melting_offset,MeltingOffsetEnum);
+	if(isenthalpy){
+		if(VerboseConvergence()) _printf0_("\n   total number of iterations: " << count-1 << "\n");
+	}
+	else{
+		InputUpdateFromSolutionx(femmodel,tg);
+		femmodel->parameters->SetParam(melting_offset,MeltingOffsetEnum);
+	}
 
 	/*Free ressources: */
Index: /issm/trunk/src/c/solutionsequences/solutionsequences.h
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 19104)
+++ /issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 19105)
@@ -16,4 +16,5 @@
 void solutionsequence_nonlinear(FemModel* femmodel,bool conserve_loads);
 void solutionsequence_newton(FemModel* femmodel);
+void solutionsequence_fct(FemModel* femmodel);
 void solutionsequence_FScoupling_nonlinear(FemModel* femmodel,bool conserve_loads);
 void solutionsequence_linear(FemModel* femmodel);
@@ -23,5 +24,5 @@
 
 /*convergence*/
-void convergence(bool* pconverged, Matrix<IssmDouble>* K_ff,Vector<IssmDouble>* p_f,Vector<IssmDouble>* u_f,Vector<IssmDouble>* u_f_old,Parameters* parameters);
+void convergence(bool* pconverged, Matrix<IssmDouble>* K_ff,Vector<IssmDouble>* p_f,Vector<IssmDouble>* u_f,Vector<IssmDouble>* u_f_old,IssmDouble eps_res,IssmDouble eps_rel,IssmDouble eps_abs);
 
 #endif
Index: /issm/trunk/src/c/toolkits/gsl/DenseGslSolve.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/gsl/DenseGslSolve.cpp	(revision 19104)
+++ /issm/trunk/src/c/toolkits/gsl/DenseGslSolve.cpp	(revision 19105)
@@ -235,5 +235,5 @@
 	IssmPDouble* pdoubleEDFout=xNew<IssmPDouble>(n);           // provide space to transfer outputs during call_ext_fct
 	// call the wrapped solver through the registry entry we retrieve from parameters
-	call_ext_fct(dynamic_cast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
+	call_ext_fct(xDynamicCast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
 	             n*(n+1), pdoubleEDFin, adoubleEDFin,
 	             n, pdoubleEDFout,X);
Index: /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp	(revision 19104)
+++ /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp	(revision 19105)
@@ -244,5 +244,5 @@
   IssmPDouble *passiveSol=xNew<IssmPDouble>(n);
   IssmDouble *sol=xNew<IssmDouble>(n);
-  call_ext_fct(dynamic_cast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
+  call_ext_fct(xDynamicCast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
 	       packedDimsSparseArrLength, packedDimsSparseArr,
 	       local_nnz+n, passivePack_A_rhs, pack_A_rhs, 
Index: /issm/trunk/src/c/toolkits/mumps/MumpsSolve.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mumps/MumpsSolve.cpp	(revision 19104)
+++ /issm/trunk/src/c/toolkits/mumps/MumpsSolve.cpp	(revision 19105)
@@ -324,5 +324,5 @@
   IssmPDouble *passiveSol=xNew<IssmPDouble>(n);
   IssmDouble *sol=xNew<IssmDouble>(n);
-  call_ext_fct(dynamic_cast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
+  call_ext_fct(xDynamicCast<GenericParam<Adolc_edf> * >(parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p,
 	       packedDimsSparseArrLength, packedDimsSparseArr,
 	       local_nnz+n, passivePack_A_rhs, pack_A_rhs, 
Index: /issm/trunk/src/dox/issm.dox
===================================================================
--- /issm/trunk/src/dox/issm.dox	(revision 19104)
+++ /issm/trunk/src/dox/issm.dox	(revision 19105)
@@ -47,23 +47,17 @@
 </th>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">453</td><td  bgcolor=#FFFFFF style="text-align:right;">15861</td><td  bgcolor=#FFFFFF style="text-align:right;">18188</td><td  bgcolor=#FFFFFF style="text-align:right;">68849</td><td  bgcolor=#FFFFFF style="text-align:right;">102898</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">445</td><td  bgcolor=#FFFFFF style="text-align:right;">15967</td><td  bgcolor=#FFFFFF style="text-align:right;">16145</td><td  bgcolor=#FFFFFF style="text-align:right;">70397</td><td  bgcolor=#FFFFFF style="text-align:right;">102509</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">1378</td><td  bgcolor=#C6E2FF style="text-align:right;">8341</td><td  bgcolor=#C6E2FF style="text-align:right;">16259</td><td  bgcolor=#C6E2FF style="text-align:right;">38645</td><td  bgcolor=#C6E2FF style="text-align:right;">63245</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">1422</td><td  bgcolor=#C6E2FF style="text-align:right;">8497</td><td  bgcolor=#C6E2FF style="text-align:right;">16638</td><td  bgcolor=#C6E2FF style="text-align:right;">39538</td><td  bgcolor=#C6E2FF style="text-align:right;">64673</td>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">421</td><td  bgcolor=#FFFFFF style="text-align:right;">3504</td><td  bgcolor=#FFFFFF style="text-align:right;">3753</td><td  bgcolor=#FFFFFF style="text-align:right;">15489</td><td  bgcolor=#FFFFFF style="text-align:right;">22746</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">411</td><td  bgcolor=#FFFFFF style="text-align:right;">3443</td><td  bgcolor=#FFFFFF style="text-align:right;">3528</td><td  bgcolor=#FFFFFF style="text-align:right;">15243</td><td  bgcolor=#FFFFFF style="text-align:right;">22214</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> m4 </th><td  bgcolor=#C6E2FF style="text-align:right;">9</td><td  bgcolor=#C6E2FF style="text-align:right;">1588</td><td  bgcolor=#C6E2FF style="text-align:right;">151</td><td  bgcolor=#C6E2FF style="text-align:right;">11565</td><td  bgcolor=#C6E2FF style="text-align:right;">13304</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> m4 </th><td  bgcolor=#C6E2FF style="text-align:right;">8</td><td  bgcolor=#C6E2FF style="text-align:right;">1036</td><td  bgcolor=#C6E2FF style="text-align:right;">149</td><td  bgcolor=#C6E2FF style="text-align:right;">9756</td><td  bgcolor=#C6E2FF style="text-align:right;">10941</td>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> Python </th><td  bgcolor=#FFFFFF style="text-align:right;">144</td><td  bgcolor=#FFFFFF style="text-align:right;">2330</td><td  bgcolor=#FFFFFF style="text-align:right;">2559</td><td  bgcolor=#FFFFFF style="text-align:right;">9348</td><td  bgcolor=#FFFFFF style="text-align:right;">14237</td>
-</tr>
-<tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> XML </th><td  bgcolor=#C6E2FF style="text-align:right;">4</td><td  bgcolor=#C6E2FF style="text-align:right;">160</td><td  bgcolor=#C6E2FF style="text-align:right;">92</td><td  bgcolor=#C6E2FF style="text-align:right;">3075</td><td  bgcolor=#C6E2FF style="text-align:right;">3327</td>
-</tr>
-<tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> Java </th><td  bgcolor=#FFFFFF style="text-align:right;">18</td><td  bgcolor=#FFFFFF style="text-align:right;">719</td><td  bgcolor=#FFFFFF style="text-align:right;">891</td><td  bgcolor=#FFFFFF style="text-align:right;">2321</td><td  bgcolor=#FFFFFF style="text-align:right;">3931</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Python </th><td  bgcolor=#FFFFFF style="text-align:right;">151</td><td  bgcolor=#FFFFFF style="text-align:right;">2421</td><td  bgcolor=#FFFFFF style="text-align:right;">2623</td><td  bgcolor=#FFFFFF style="text-align:right;">9733</td><td  bgcolor=#FFFFFF style="text-align:right;">14777</td>
 </tr>
 <tr>
@@ -71,17 +65,8 @@
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#FFFFFF style="text-align:right;">3</td><td  bgcolor=#FFFFFF style="text-align:right;">61</td><td  bgcolor=#FFFFFF style="text-align:right;">88</td><td  bgcolor=#FFFFFF style="text-align:right;">266</td><td  bgcolor=#FFFFFF style="text-align:right;">415</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#FFFFFF style="text-align:right;">2</td><td  bgcolor=#FFFFFF style="text-align:right;">59</td><td  bgcolor=#FFFFFF style="text-align:right;">84</td><td  bgcolor=#FFFFFF style="text-align:right;">262</td><td  bgcolor=#FFFFFF style="text-align:right;">405</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> XSD </th><td  bgcolor=#C6E2FF style="text-align:right;">2</td><td  bgcolor=#C6E2FF style="text-align:right;">30</td><td  bgcolor=#C6E2FF style="text-align:right;">36</td><td  bgcolor=#C6E2FF style="text-align:right;">229</td><td  bgcolor=#C6E2FF style="text-align:right;">295</td>
-</tr>
-<tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> Perl </th><td  bgcolor=#FFFFFF style="text-align:right;">1</td><td  bgcolor=#FFFFFF style="text-align:right;">6</td><td  bgcolor=#FFFFFF style="text-align:right;">9</td><td  bgcolor=#FFFFFF style="text-align:right;">196</td><td  bgcolor=#FFFFFF style="text-align:right;">211</td>
-</tr>
-<tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> Ant </th><td  bgcolor=#C6E2FF style="text-align:right;">1</td><td  bgcolor=#C6E2FF style="text-align:right;">16</td><td  bgcolor=#C6E2FF style="text-align:right;">7</td><td  bgcolor=#C6E2FF style="text-align:right;">103</td><td  bgcolor=#C6E2FF style="text-align:right;">126</td>
-</tr>
-<tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">2441</td><td  bgcolor=#FFFFFF style="text-align:right;">32620</td><td  bgcolor=#FFFFFF style="text-align:right;">42335</td><td  bgcolor=#FFFFFF style="text-align:right;">150451</td><td  bgcolor=#FFFFFF style="text-align:right;">225406</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> SUM: </th><td  bgcolor=#C6E2FF style="text-align:right;">2446</td><td  bgcolor=#C6E2FF style="text-align:right;">31427</td><td  bgcolor=#C6E2FF style="text-align:right;">39469</td><td  bgcolor=#C6E2FF style="text-align:right;">145294</td><td  bgcolor=#C6E2FF style="text-align:right;">216190</td>
 </tr>
 </table>
Index: /issm/trunk/src/m/classes/SMB.m
===================================================================
--- /issm/trunk/src/m/classes/SMB.m	(revision 19104)
+++ /issm/trunk/src/m/classes/SMB.m	(revision 19105)
@@ -9,11 +9,11 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
+        function createxml(self,fid) % {{{
             fprintf(fid, '\n\n');
             fprintf(fid, '%s\n', '<!-- surfaceforcings(SMB) -->');
-			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="mass_balance" type="',class(obj.mass_balance),'" default="',obj.mass_balance,'">','     <section name="surfaceforcings(SMB)" />','     <help> surface mass balance [m/yr ice eq] </help>','</parameter>');
+			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="mass_balance" type="',class(self.mass_balance),'" default="',self.mass_balance,'">','     <section name="surfaceforcings(SMB)" />','     <help> surface mass balance [m/yr ice eq] </help>','</parameter>');
            
         end % }}}
-		function obj = SMB(varargin) % {{{
+		function self = SMB(varargin) % {{{
 			switch nargin
 				case 0
@@ -35,8 +35,8 @@
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			if ismember(MasstransportAnalysisEnum(),analyses),
-				md = checkfield(md,'fieldname','surfaceforcings.mass_balance','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.mass_balance','timeseries',1,'NaN',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum(),analyses),
@@ -44,14 +44,14 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   surface forcings parameters:'));
-			fielddisplay(obj,'mass_balance','surface mass balance [m/yr ice eq]');
+			fielddisplay(self,'mass_balance','surface mass balance [m/yr ice eq]');
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
 			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/SMB.py
===================================================================
--- /issm/trunk/src/m/classes/SMB.py	(revision 19104)
+++ /issm/trunk/src/m/classes/SMB.py	(revision 19105)
@@ -38,5 +38,5 @@
 
 		if MasstransportAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','surfaceforcings.mass_balance','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.mass_balance','timeseries',1,'NaN',1)
 
 		if BalancethicknessAnalysisEnum() in analyses:
@@ -50,4 +50,4 @@
 
 		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBEnum(),'format','Integer');
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
 	# }}}
Index: /issm/trunk/src/m/classes/SMBcomponents.m
===================================================================
--- /issm/trunk/src/m/classes/SMBcomponents.m	(revision 19104)
+++ /issm/trunk/src/m/classes/SMBcomponents.m	(revision 19105)
@@ -11,5 +11,5 @@
 	end
 	methods
-		function obj = SMBcomponents(varargin) % {{{
+		function self = SMBcomponents(varargin) % {{{
 			switch nargin
 				case 0
@@ -41,8 +41,8 @@
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			if ismember(MasstransportAnalysisEnum(),analyses),
-				md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.accumulation','timeseries',1,'NaN',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum(),analyses),
@@ -50,5 +50,5 @@
 			end
 			if ismember(MasstransportAnalysisEnum(),analyses),
-				md = checkfield(md,'fieldname','surfaceforcings.runoff','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.runoff','timeseries',1,'NaN',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum(),analyses),
@@ -56,5 +56,5 @@
 			end
 			if ismember(MasstransportAnalysisEnum(),analyses),
-				md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.evaporation','timeseries',1,'NaN',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum(),analyses),
@@ -62,18 +62,18 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   surface forcings parameters (SMB=accumulation-runoff-evaporation) :'));
-			fielddisplay(obj,'accumulation','accumulated snow [m/yr ice eq]');
-			fielddisplay(obj,'runoff','amount of ice melt lost from the ice column [m/yr ice eq]');
-			fielddisplay(obj,'evaporation','amount of ice lost to evaporative processes [m/yr ice eq]');
+			fielddisplay(self,'accumulation','accumulated snow [m/yr ice eq]');
+			fielddisplay(self,'runoff','amount of ice melt lost from the ice column [m/yr ice eq]');
+			fielddisplay(self,'evaporation','amount of ice lost to evaporative processes [m/yr ice eq]');
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
 			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBcomponentsEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/SMBcomponents.py
===================================================================
--- /issm/trunk/src/m/classes/SMBcomponents.py	(revision 19104)
+++ /issm/trunk/src/m/classes/SMBcomponents.py	(revision 19105)
@@ -51,5 +51,5 @@
 
 		if MasstransportAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.accumulation','timeseries',1,'NaN',1)
 
 		if BalancethicknessAnalysisEnum() in analyses:
@@ -57,5 +57,5 @@
 
 		if MasstransportAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','surfaceforcings.runoff','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.runoff','timeseries',1,'NaN',1)
 
 		if BalancethicknessAnalysisEnum() in analyses:
@@ -63,5 +63,5 @@
 
 		if MasstransportAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.evaporation','timeseries',1,'NaN',1)
 
 		if BalancethicknessAnalysisEnum() in analyses:
@@ -75,6 +75,6 @@
 
 		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBcomponentsEnum(),'format','Integer');
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
 	# }}}
Index: /issm/trunk/src/m/classes/SMBgradients.m
===================================================================
--- /issm/trunk/src/m/classes/SMBgradients.m	(revision 19104)
+++ /issm/trunk/src/m/classes/SMBgradients.m	(revision 19105)
@@ -12,8 +12,8 @@
 	end
 	methods
-		function obj = SMBgradients(varargin) % {{{
+		function self = SMBgradients(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
@@ -30,37 +30,37 @@
 
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%Nothing for now
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			if ismember(MasstransportAnalysisEnum(),analyses),
-				md = checkfield(md,'fieldname','surfaceforcings.href','forcing',1,'NaN',1);
-				md = checkfield(md,'fieldname','surfaceforcings.smbref','forcing',1,'NaN',1);
-				md = checkfield(md,'fieldname','surfaceforcings.b_pos','forcing',1,'NaN',1);
-				md = checkfield(md,'fieldname','surfaceforcings.b_neg','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.href','timeseries',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.smbref','timeseries',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.b_pos','timeseries',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.b_neg','timeseries',1,'NaN',1);
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   surface forcings parameters:'));
 
 			disp(sprintf('\n   SMB gradients parameters:'));
-			fielddisplay(obj,'href',' reference elevation from which deviation is used to calculate SMB adjustment in smb gradients method [m]');
-			fielddisplay(obj,'smbref',' reference smb from which deviation is calculated in smb gradients method [mm/yr water equiv]');
-			fielddisplay(obj,'b_pos',' slope of hs - smb regression line for accumulation regime required if smb gradients is activated');
-			fielddisplay(obj,'b_neg',' slope of hs - smb regression line for ablation regime required if smb gradients is activated');
+			fielddisplay(self,'href',' reference elevation from which deviation is used to calculate SMB adjustment in smb gradients method [m]');
+			fielddisplay(self,'smbref',' reference smb from which deviation is calculated in smb gradients method [mm/yr water equiv]');
+			fielddisplay(self,'b_pos',' slope of hs - smb regression line for accumulation regime required if smb gradients is activated');
+			fielddisplay(self,'b_neg',' slope of hs - smb regression line for ablation regime required if smb gradients is activated');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
 			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBgradientsEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','href','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','href','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
 
 		end % }}}
Index: /issm/trunk/src/m/classes/SMBgradients.py
===================================================================
--- /issm/trunk/src/m/classes/SMBgradients.py	(revision 19104)
+++ /issm/trunk/src/m/classes/SMBgradients.py	(revision 19105)
@@ -44,8 +44,8 @@
 
 		if MasstransportAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','surfaceforcings.href','forcing',1,'NaN',1)
-			md = checkfield(md,'fieldname','surfaceforcings.smbref','forcing',1,'NaN',1)
-			md = checkfield(md,'fieldname','surfaceforcings.b_pos','forcing',1,'NaN',1)
-			md = checkfield(md,'fieldname','surfaceforcings.b_neg','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.href','timeseries',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.smbref','timeseries',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.b_pos','timeseries',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.b_neg','timeseries',1,'NaN',1)
 
 		return md
@@ -56,7 +56,7 @@
 
 		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBgradientsEnum(),'format','Integer');
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','href','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','href','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
 	# }}}
Index: /issm/trunk/src/m/classes/SMBhenning.m
===================================================================
--- /issm/trunk/src/m/classes/SMBhenning.m	(revision 19104)
+++ /issm/trunk/src/m/classes/SMBhenning.m	(revision 19105)
@@ -9,5 +9,5 @@
 	end
 	methods
-		function obj = SMBhenning(varargin) % {{{
+		function self = SMBhenning(varargin) % {{{
 			switch nargin
 				case 0
@@ -29,8 +29,8 @@
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			if ismember(MasstransportAnalysisEnum(),analyses),
-				md = checkfield(md,'fieldname','surfaceforcings.smbref','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.smbref','timeseries',1,'NaN',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum(),analyses),
@@ -38,14 +38,14 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   surface forcings parameters:'));
-			fielddisplay(obj,'smbref','reference smb from which deviation is calculated [m/yr ice eq]');
+			fielddisplay(self,'smbref','reference smb from which deviation is calculated [m/yr ice eq]');
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
 			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBhenningEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/SMBmeltcomponents.m
===================================================================
--- /issm/trunk/src/m/classes/SMBmeltcomponents.m	(revision 19104)
+++ /issm/trunk/src/m/classes/SMBmeltcomponents.m	(revision 19105)
@@ -12,5 +12,5 @@
 	end
 	methods
-		function obj = SMBmeltcomponents(varargin) % {{{
+		function self = SMBmeltcomponents(varargin) % {{{
 			switch nargin
 				case 0
@@ -47,8 +47,8 @@
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			if ismember(MasstransportAnalysisEnum(),analyses),
-				md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.accumulation','timeseries',1,'NaN',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum(),analyses),
@@ -56,5 +56,5 @@
 			end
 			if ismember(MasstransportAnalysisEnum(),analyses),
-				md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.evaporation','timeseries',1,'NaN',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum(),analyses),
@@ -62,5 +62,5 @@
 			end
 			if ismember(MasstransportAnalysisEnum(),analyses),
-				md = checkfield(md,'fieldname','surfaceforcings.refreeze','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.refreeze','timeseries',1,'NaN',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum(),analyses),
@@ -68,5 +68,5 @@
 			end
 			if ismember(MasstransportAnalysisEnum(),analyses),
-				md = checkfield(md,'fieldname','surfaceforcings.melt','forcing',1,'NaN',1);
+				md = checkfield(md,'fieldname','surfaceforcings.melt','timeseries',1,'NaN',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum(),analyses),
@@ -74,20 +74,20 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   surface forcings parameters with melt (SMB=accumulation-evaporation-melt+refreeze) :'));
-			fielddisplay(obj,'accumulation','accumulated snow [m/yr ice eq]');
-			fielddisplay(obj,'evaporation','amount of ice lost to evaporative processes [m/yr ice eq]');
-			fielddisplay(obj,'melt','amount of ice melt in ice column [m/yr ice eq]');
-			fielddisplay(obj,'refreeze','amount of ice melt refrozen in ice column [m/yr ice eq]');
+			fielddisplay(self,'accumulation','accumulated snow [m/yr ice eq]');
+			fielddisplay(self,'evaporation','amount of ice lost to evaporative processes [m/yr ice eq]');
+			fielddisplay(self,'melt','amount of ice melt in ice column [m/yr ice eq]');
+			fielddisplay(self,'refreeze','amount of ice melt refrozen in ice column [m/yr ice eq]');
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
 			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBmeltcomponentsEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/SMBmeltcomponents.py
===================================================================
--- /issm/trunk/src/m/classes/SMBmeltcomponents.py	(revision 19104)
+++ /issm/trunk/src/m/classes/SMBmeltcomponents.py	(revision 19105)
@@ -57,5 +57,5 @@
 
 		if MasstransportAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','surfaceforcings.accumulation','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.accumulation','timeseries',1,'NaN',1)
 
 		if BalancethicknessAnalysisEnum() in analyses:
@@ -63,5 +63,5 @@
 
 		if MasstransportAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','surfaceforcings.melt','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.melt','timeseries',1,'NaN',1)
 
 		if BalancethicknessAnalysisEnum() in analyses:
@@ -69,5 +69,5 @@
 
 		if MasstransportAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','surfaceforcings.refreeze','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.refreeze','timeseries',1,'NaN',1)
 
 		if BalancethicknessAnalysisEnum() in analyses:
@@ -75,5 +75,5 @@
 
 		if MasstransportAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','surfaceforcings.evaporation','forcing',1,'NaN',1)
+			md = checkfield(md,'fieldname','surfaceforcings.evaporation','timeseries',1,'NaN',1)
 
 		if BalancethicknessAnalysisEnum() in analyses:
@@ -87,7 +87,7 @@
 
 		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBmeltcomponentsEnum(),'format','Integer');
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
 	# }}}
Index: /issm/trunk/src/m/classes/SMBpdd.m
===================================================================
--- /issm/trunk/src/m/classes/SMBpdd.m	(revision 19104)
+++ /issm/trunk/src/m/classes/SMBpdd.m	(revision 19105)
@@ -8,7 +8,14 @@
 		precipitation             = NaN;
 		monthlytemperatures       = NaN;
-		desfac                    = 0.5;
+		desfac                    = 0;
 		s0p                       = 0;
+		s0t                       = 0;
+		rlaps                     = 0;
+		rlapslgm                  = 0;                
+		Pfac                      = NaN;
+		Tdiff                     = NaN;
+		sealev                    = NaN;
 		isdelta18o                = 0;
+		ismungsm                  = 0;
 		delta18o                  = NaN;
 		delta18o_surface          = NaN;
@@ -16,10 +23,11 @@
 		temperatures_lgm          = NaN;
 		precipitations_presentday = NaN;
+		precipitations_lgm        = NaN;
 	end
 	methods
-		function obj = SMBpdd(varargin) % {{{
+		function self = SMBpdd(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
@@ -27,36 +35,47 @@
 		end % }}}
 		function self = extrude(self,md) % {{{
-
-			self.precipitation=project3d(md,'vector',self.precipitation,'type','node');
-			self.monthlytemperatures=project3d(md,'vector',self.monthlytemperatures,'type','node');
+			if(self.isdelta18o==0 & self.ismungsm==0),self.precipitation=project3d(md,'vector',self.precipitation,'type','node');end
+			if(self.isdelta18o==0 & self.ismungsm==0),self.monthlytemperatures=project3d(md,'vector',self.monthlytemperatures,'type','node');end
 			if(self.isdelta18o),self.temperatures_lgm=project3d(md,'vector',self.temperatures_lgm,'type','node');end
 			if(self.isdelta18o),self.temperatures_presentday=project3d(md,'vector',self.temperatures_presentday,'type','node');end
 			if(self.isdelta18o),self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node');end
-
+			if(self.isdelta18o),self.precipitations_lgm=project3d(md,'vector',self.precipitations_lgm,'type','node');end
+			if(self.ismungsm),self.temperatures_lgm=project3d(md,'vector',self.temperatures_lgm,'type','node');end
+			if(self.ismungsm),self.temperatures_presentday=project3d(md,'vector',self.temperatures_presentday,'type','node');end
+			if(self.ismungsm),self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node');end
+			if(self.ismungsm),self.precipitations_lgm=project3d(md,'vector',self.precipitations_lgm,'type','node');end
 
 		end % }}}
 		function self = initialize(self,md) % {{{
-
-			if isnan(self.precipitation),
-				self.precipitation=zeros(md.mesh.numberofvertices,1);
-				disp('      no SMBpdd.precipitation specified: values set as zero');
-			end
+                    
+			% if isnan(self.precipitation),
+			% 	self.precipitation=zeros(md.mesh.numberofvertices,1);
+			% 	disp('      no SMBpdd.precipitation specified: values set as zero');
+			% end
 
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
-		  obj.isdelta18o = 0;
-		  obj.desfac     = 0.5;
-		  obj.s0p        = 0;
+		  self.isdelta18o = 0;
+		  self.ismungsm   = 0;
+		  self.desfac     = 0.5;
+		  self.s0p        = 0;
+		  self.s0t        = 0;
+		  self.rlaps      = 6.5;
+		  self.rlapslgm   = 6.5;
+                  
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			if ismember(MasstransportAnalysisEnum(),analyses),
 				md = checkfield(md,'fieldname','surfaceforcings.desfac','<=',1,'numel',1);
 				md = checkfield(md,'fieldname','surfaceforcings.s0p','>=',0,'numel',1);
-				if(obj.isdelta18o==0)
-					md = checkfield(md,'fieldname','surfaceforcings.monthlytemperatures','forcing',1,'NaN',1);
-					md = checkfield(md,'fieldname','surfaceforcings.precipitation','forcing',1,'NaN',1);
-				else
+				md = checkfield(md,'fieldname','surfaceforcings.s0t','>=',0,'numel',1);
+				md = checkfield(md,'fieldname','surfaceforcings.rlaps','>=',0,'numel',1);
+				md = checkfield(md,'fieldname','surfaceforcings.rlapslgm','>=',0,'numel',1);
+				if(self.isdelta18o==0 & self.ismungsm==0)
+					md = checkfield(md,'fieldname','surfaceforcings.monthlytemperatures','timeseries',1,'NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.precipitation','timeseries',1,'NaN',1);
+				elseif(self.isdelta18o==1) 
 					md = checkfield(md,'fieldname','surfaceforcings.delta18o','NaN',1);
 					md = checkfield(md,'fieldname','surfaceforcings.delta18o_surface','NaN',1);
@@ -64,24 +83,52 @@
 					md = checkfield(md,'fieldname','surfaceforcings.temperatures_lgm','size',[md.mesh.numberofvertices+1 12],'NaN',1);
 					md = checkfield(md,'fieldname','surfaceforcings.precipitations_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.precipitations_lgm','size',[md.mesh.numberofvertices+1 12],'NaN',1);                                       
+					md = checkfield(md,'fieldname','surfaceforcings.Tdiff','NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.sealev','NaN',1);
+				elseif(self.ismungsm==1) 
+					md = checkfield(md,'fieldname','surfaceforcings.temperatures_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.temperatures_lgm','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.precipitations_presentday','size',[md.mesh.numberofvertices+1 12],'NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.precipitations_lgm','size',[md.mesh.numberofvertices+1 12],'NaN',1);                                       
+					md = checkfield(md,'fieldname','surfaceforcings.Pfac','NaN',1,'size',[2,NaN]);
+					md = checkfield(md,'fieldname','surfaceforcings.Tdiff','NaN',1);
+					md = checkfield(md,'fieldname','surfaceforcings.sealev','NaN',1);
 				end
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   surface forcings parameters:'));
 
 			disp(sprintf('\n   PDD and deltaO18 parameters:'));
-			fielddisplay(obj,'isdelta18o','is temperature and precipitation delta18o parametrisation activated (0 or 1, default is 0)');
-			fielddisplay(obj,'desfac','desertification elevation factor (between 0 and 1, default is 0.5) [m]');
-			fielddisplay(obj,'s0p','should be set to elevation from precip source (between 0 and a few 1000s m, default is 0) [m]');
-			fielddisplay(obj,'monthlytemperatures','monthly surface temperatures [K], required if pdd is activated and delta18o not activated');
-			fielddisplay(obj,'precipitation','surface precipitation [m/yr water eq]');
-			fielddisplay(obj,'temperatures_presentday','monthly present day surface temperatures [K], required if pdd is activated and delta18o activated');
-			fielddisplay(obj,'temperatures_lgm','monthly LGM surface temperatures [K], required if pdd is activated and delta18o activated');
-			fielddisplay(obj,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if pdd is activated and delta18o activated');
-			fielddisplay(obj,'delta18o','delta18o, required if pdd is activated and delta18o activated');
-			fielddisplay(obj,'delta18o_surface','surface elevation of the delta18o site, required if pdd is activated and delta18o activated');
-
+			fielddisplay(self,'isdelta18o','is temperature and precipitation delta18o parametrisation activated (0 or 1, default is 0)');
+			fielddisplay(self,'ismungsm','is temperature and precipitation mungsm parametrisation activated (0 or 1, default is 0)');
+			fielddisplay(self,'desfac','desertification elevation factor (between 0 and 1, default is 0.5) [m]');
+			fielddisplay(self,'s0p','should be set to elevation from precip source (between 0 and a few 1000s m, default is 0) [m]');
+			fielddisplay(self,'s0t','should be set to elevation from temperature source (between 0 and a few 1000s m, default is 0) [m]');
+			fielddisplay(self,'rlaps','present day lapse rate [degree/km]');
+			fielddisplay(self,'rlapslgm','LGM lapse rate [degree/km]');
+                        if(self.isdelta18o==0 & self.ismungsm==0)
+                            fielddisplay(self,'monthlytemperatures',['monthly surface temperatures [K], required if pdd is activated and delta18o not activated']);
+                            fielddisplay(self,'precipitation',['monthly surface precipitation [m/yr water eq], required if pdd is activated and delta18o or mungsm not activated']);
+                        elseif(self.isdelta18o==1)
+                            fielddisplay(self,'delta18o','delta18o, required if pdd is activated and delta18o activated');
+                            fielddisplay(self,'delta18o_surface','surface elevation of the delta18o site, required if pdd is activated and delta18o activated');
+                            fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [K], required if delta18o/mungsm is activated');
+                            fielddisplay(self,'temperatures_lgm','monthly LGM surface temperatures [K], required if delta18o or mungsm is activated');
+                            fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if delta18o or mungsm is activated');
+                            fielddisplay(self,'precipitations_lgm','monthly surface precipitation [m/yr water eq], required if delta18o or mungsm is activated');
+                            fielddisplay(self,'Tdiff','time interpolation parameter for temperature, 1D(year), required if mungsm is activated');
+                            fielddisplay(self,'sealev','sea level [m], 1D(year), required if mungsm is activated');
+                        elseif(self.ismungsm==1)
+                            fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [K], required if delta18o/mungsm is activated');
+                            fielddisplay(self,'temperatures_lgm','monthly LGM surface temperatures [K], required if delta18o or mungsm is activated');
+                            fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if delta18o or mungsm is activated');
+                            fielddisplay(self,'precipitations_lgm','monthly surface precipitation [m/yr water eq], required if delta18o or mungsm is activated');
+                            fielddisplay(self,'Pfac','time interpolation parameter for precipitation, 1D(year), required if mungsm is activated');
+                            fielddisplay(self,'Tdiff','time interpolation parameter for temperature, 1D(year), required if mungsm is activated');
+                            fielddisplay(self,'sealev','sea level [m], 1D(year), required if mungsm is activated');
+                        end
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
@@ -89,16 +136,33 @@
 			WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBpddEnum(),'format','Integer');
 
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','desfac','format','Double');
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','s0p','format','Double');
-			WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','isdelta18o','format','Boolean');
-			if obj.isdelta18o
-				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','temperatures_presentday','format','DoubleMat','mattype',1);
-				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','temperatures_lgm','format','DoubleMat','mattype',1);
-				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','precipitations_presentday','format','DoubleMat','mattype',1);
-				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','delta18o_surface','format','DoubleMat','mattype',1);
-				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','delta18o','format','DoubleMat','mattype',1);
-			else
-				WriteData(fid,'object',obj,'class','surfaceforcings','fieldname','monthlytemperatures','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','isdelta18o','format','Boolean');
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','ismungsm','format','Boolean');
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','desfac','format','Double');
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','s0p','format','Double');
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','s0t','format','Double');
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','rlaps','format','Double');
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','rlapslgm','format','Double');
+
+			if(self.isdelta18o==0 & self.ismungsm==0)
+				%WriteData(fid,'object',self,'class','surfaceforcings','fieldname','monthlytemperatures','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','monthlytemperatures','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			elseif self.isdelta18o
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','temperatures_presentday','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','temperatures_lgm','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitations_presentday','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitations_lgm','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','delta18o_surface','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','delta18o','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','Tdiff','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','sealev','format','DoubleMat','mattype',1);
+			elseif self.ismungsm
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','temperatures_presentday','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','temperatures_lgm','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitations_presentday','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitations_lgm','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','Pfac','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','Tdiff','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'class','surfaceforcings','fieldname','sealev','format','DoubleMat','mattype',1);
 			end
 		end % }}}
Index: /issm/trunk/src/m/classes/SMBpdd.py
===================================================================
--- /issm/trunk/src/m/classes/SMBpdd.py	(revision 19104)
+++ /issm/trunk/src/m/classes/SMBpdd.py	(revision 19105)
@@ -19,5 +19,12 @@
 		self.desfac                    = 0.
 		self.s0p                       = 0.
+		self.s0t                       = 0.
+		self.rlaps                     = 0.
+		self.rlapslgm                  = 0.
+		self.Pfac                      = float('NaN')
+		self.Tdiff                     = float('NaN')
+		self.sealev                    = float('NaN')
 		self.isdelta18o                = 0
+		self.ismungsm                  = 0
 		self.delta18o                  = float('NaN')
 		self.delta18o_surface          = float('NaN')
@@ -25,4 +32,5 @@
 		self.temperatures_lgm          = float('NaN')
 		self.precipitations_presentday = float('NaN')
+		self.precipitations_lgm        = float('NaN')
 
 		#set defaults
@@ -32,40 +40,66 @@
 		string="   surface forcings parameters:"
 
-		string="%s\n%s"%(string,fielddisplay(self,'precipitation','surface precipitation [m/yr water eq]'))
+		string="%s\n%s"%(string,fielddisplay(self,'isdelta18o','is temperature and precipitation delta18o parametrisation activated (0 or 1, default is 0)'))
+		string="%s\n%s"%(string,fielddisplay(self,'ismungsm','is temperature and precipitation mungsm parametrisation activated (0 or 1, default is 0)'))
 		string="%s\n%s"%(string,fielddisplay(self,'desfac','desertification elevation factor (between 0 and 1, default is 0.5) [m]'))
-		string="%s\n%s"%(string,fielddisplay(self,'isdelta18o','is temperature and precipitation delta18o parametrisation activated (0 or 1, default is 0)'))
 		string="%s\n%s"%(string,fielddisplay(self,'s0p','should be set to elevation from precip source (between 0 and a few 1000s m, default is 0) [m]'))
-		string="%s\n%s"%(string,fielddisplay(self,'monthlytemperatures','monthly surface temperatures [K], required if pdd is activated and delta18o not activated'))
-		string="%s\n%s"%(string,fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [K], required if pdd is activated and delta18o activated'))
-		string="%s\n%s"%(string,fielddisplay(self,'temperatures_lgm','monthly LGM surface temperatures [K], required if pdd is activated and delta18o activated'))
-		string="%s\n%s"%(string,fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if pdd is activated and delta18o activated'))
-		string="%s\n%s"%(string,fielddisplay(self,'delta18o','delta18o, required if pdd is activated and delta18o activated'))
-		string="%s\n%s"%(string,fielddisplay(self,'delta18o_surface','surface elevation of the delta18o site, required if pdd is activated and delta18o activated'))
-
+		string="%s\n%s"%(string,fielddisplay(self,'s0t','should be set to elevation from temperature source (between 0 and a few 1000s m, default is 0) [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'rlaps','present day lapse rate [degree/km]'))
+		string="%s\n%s"%(string,fielddisplay(self,'rlapslgm','LGM lapse rate [degree/km]'))
+		if not (self.isdelta18o and self.ismungsm):
+			string="%s\n%s"%(string,fielddisplay(self,'monthlytemperatures',['monthly surface temperatures [K], required if pdd is activated and delta18o not activated']))
+			string="%s\n%s"%(string,fielddisplay(self,'precipitation',['monthly surface precipitation [m/yr water eq], required if pdd is activated and delta18o or mungsm not activated']))
+			if self.isdelta18o:
+				string="%s\n%s"%(string,fielddisplay(self,'delta18o','delta18o, required if pdd is activated and delta18o activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'delta18o_surface','surface elevation of the delta18o site, required if pdd is activated and delta18o activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [K], required if delta18o/mungsm is activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'temperatures_lgm','monthly LGM surface temperatures [K], required if delta18o or mungsm is activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if delta18o or mungsm is activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'precipitations_lgm','monthly surface precipitation [m/yr water eq], required if delta18o or mungsm is activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'Tdiff','time interpolation parameter for temperature, 1D(year), required if mungsm is activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'sealev','sea level [m], 1D(year), required if mungsm is activated'))
+			if self.ismungsm:
+				string="%s\n%s"%(string,fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [K], required if delta18o/mungsm is activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'temperatures_lgm','monthly LGM surface temperatures [K], required if delta18o or mungsm is activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if delta18o or mungsm is activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'precipitations_lgm','monthly surface precipitation [m/yr water eq], required if delta18o or mungsm is activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'Pfac','time interpolation parameter for precipitation, 1D(year), required if mungsm is activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'Tdiff','time interpolation parameter for temperature, 1D(year), required if mungsm is activated'))
+				string="%s\n%s"%(string,fielddisplay(self,'sealev','sea level [m], 1D(year), required if mungsm is activated'))
 		return string
 		#}}}
 	def extrude(self,md): # {{{
 
-		self.precipitation=project3d(md,'vector',self.precipitation,'type','node');
-		self.monthlytemperatures=project3d(md,'vector',self.monthlytemperatures,'type','node');
+		if not (self.isdelta18o and self.ismungsm):
+			self.precipitation=project3d(md,'vector',self.precipitation,'type','node')
+			self.monthlytemperatures=project3d(md,'vector',self.monthlytemperatures,'type','node')
 		if self.isdelta18o: self.temperatures_lgm=project3d(md,'vector',self.temperatures_lgm,'type','node')
 		if self.isdelta18o: self.temperatures_presentday=project3d(md,'vector',self.temperatures_presentday,'type','node')
 		if self.isdelta18o: self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node')
+		if self.isdelta18o: self.precipitations_lgm=project3d(md,'vector',self.precipitations_lgm,'type','node')
+		if self.ismungsm: self.temperatures_lgm=project3d(md,'vector',self.temperatures_lgm,'type','node')
+		if self.ismungsm: self.temperatures_presentday=project3d(md,'vector',self.temperatures_presentday,'type','node')
+		if self.ismungsm: self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node')
+		if self.ismungsm: self.precipitations_lgm=project3d(md,'vector',self.precipitations_lgm,'type','node')
 		return self
 	#}}}
 	def initialize(self,md): # {{{
 
-		if numpy.all(numpy.isnan(self.precipitation)):
-			self.precipitation=numpy.zeros((md.mesh.numberofvertices,1))
-			print "      no SMBpdd.precipitation specified: values set as zero"
-
-		return self
+		# if numpy.all(numpy.isnan(self.precipitation)):
+		# 	self.precipitation=numpy.zeros((md.mesh.numberofvertices,1))
+		# 	print "      no SMBpdd.precipitation specified: values set as zero"
+		# 
+		 return self
 	#}}}
 	def setdefaultparameters(self): # {{{
-		  
+
 		#pdd method not used in default mode
 		self.isdelta18o = 0
+		self.ismungsm   = 0
 		self.desfac     = 0.5
 		self.s0p        = 0.
+		self.s0t        = 0.
+		self.rlaps      = 6.5 
+		self.rlapslgm   = 6.5
 
 		return self
@@ -74,10 +108,14 @@
 
 		if MasstransportAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','surfaceforcings.desfac','<=',1,'numel',[1]);
-			md = checkfield(md,'fieldname','surfaceforcings.s0p','>=',0,'numel',[1]);
-			if not self.isdelta18o:
-				md = checkfield(md,'fieldname','surfaceforcings.monthlytemperatures','forcing',1,'NaN',1)
-				md = checkfield(md,'fieldname','surfaceforcings.precipitation','forcing',1,'NaN',1)
-			else:
+			md = checkfield(md,'fieldname','surfaceforcings.desfac','<=',1,'numel',[1])
+			md = checkfield(md,'fieldname','surfaceforcings.s0p','>=',0,'numel',[1])
+			md = checkfield(md,'fieldname','surfaceforcings.s0t','>=',0,'numel',[1])
+			md = checkfield(md,'fieldname','surfaceforcings.rlaps','>=',0,'numel',[1])
+			md = checkfield(md,'fieldname','surfaceforcings.rlapslgm','>=',0,'numel',[1])
+
+			if (self.isdelta18o==0 and self.ismungsm==0):
+				md = checkfield(md,'fieldname','surfaceforcings.monthlytemperatures','NaN',1)
+				md = checkfield(md,'fieldname','surfaceforcings.precipitation','NaN',1)
+			elif self.isdelta18o:
 				md = checkfield(md,'fieldname','surfaceforcings.delta18o','NaN',1)
 				md = checkfield(md,'fieldname','surfaceforcings.delta18o_surface','NaN',1)
@@ -85,4 +123,15 @@
 				md = checkfield(md,'fieldname','surfaceforcings.temperatures_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1)
 				md = checkfield(md,'fieldname','surfaceforcings.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1)
+				md = checkfield(md,'fieldname','surfaceforcings.precipitations_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1)                                       
+				md = checkfield(md,'fieldname','surfaceforcings.Tdiff','NaN',1,'size',[2,numpy.nan])
+				md = checkfield(md,'fieldname','surfaceforcings.sealev','NaN',1,'size',[2,numpy.nan])
+			elif self.ismungsm:
+				md = checkfield(md,'fieldname','surfaceforcings.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1)
+				md = checkfield(md,'fieldname','surfaceforcings.temperatures_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1)
+				md = checkfield(md,'fieldname','surfaceforcings.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1)
+				md = checkfield(md,'fieldname','surfaceforcings.precipitations_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1)                                       
+				md = checkfield(md,'fieldname','surfaceforcings.Pfac','NaN',1,'size',[2,numpy.nan])
+				md = checkfield(md,'fieldname','surfaceforcings.Tdiff','NaN',1,'size',[2,numpy.nan])
+				md = checkfield(md,'fieldname','surfaceforcings.sealev','NaN',1,'size',[2,numpy.nan])
 
 		return md
@@ -92,17 +141,33 @@
 		yts=365.0*24.0*3600.0
 
-		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBpddEnum(),'format','Integer');
+		WriteData(fid,'enum',SurfaceforcingsEnum(),'data',SMBpddEnum(),'format','Integer')
 
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
 		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','isdelta18o','format','Boolean')
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','desfac','format','Double');
-		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','s0p','format','Double');
-		if self.isdelta18o:
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','ismungsm','format','Boolean')
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','desfac','format','Double')
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','s0p','format','Double')
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','s0t','format','Double')
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','rlaps','format','Double')
+		WriteData(fid,'object',self,'class','surfaceforcings','fieldname','rlapslgm','format','Double')
+
+		if (self.isdelta18o==0 and self.ismungsm==0):
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','monthlytemperatures','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		elif self.isdelta18o:
 			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','temperatures_presentday','format','DoubleMat','mattype',1)
 			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','temperatures_lgm','format','DoubleMat','mattype',1)
 			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitations_presentday','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitations_lgm','format','DoubleMat','mattype',1)
 			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','delta18o_surface','format','DoubleMat','mattype',1)
 			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','delta18o','format','DoubleMat','mattype',1)
-		else:
-			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','monthlytemperatures','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','Tdiff','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','sealev','format','DoubleMat','mattype',1)			
+		elif self.ismungsm:
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','temperatures_presentday','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','temperatures_lgm','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitations_presentday','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','precipitations_lgm','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','Pfac','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','Tdiff','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'class','surfaceforcings','fieldname','sealev','format','DoubleMat','mattype',1)
 	# }}}
Index: /issm/trunk/src/m/classes/adinversion.m
===================================================================
--- /issm/trunk/src/m/classes/adinversion.m	(revision 19105)
+++ /issm/trunk/src/m/classes/adinversion.m	(revision 19105)
@@ -0,0 +1,192 @@
+%ADINVERSION class definition
+%
+%   Usage:
+%      adinversion=adinversion();
+
+classdef adinversion
+	properties (SetAccess=public) 
+		iscontrol                   = 0
+		control_parameters          = NaN
+		control_scaling_factors     = NaN
+		maxsteps                    = 0
+		maxiter                     = 0
+		dxmin                       = 0
+		gttol                       = 0
+		cost_functions              = NaN
+		cost_functions_coefficients = NaN
+		min_parameters              = NaN
+		max_parameters              = NaN
+		vx_obs                      = NaN
+		vy_obs                      = NaN
+		vz_obs                      = NaN
+		vel_obs                     = NaN
+		thickness_obs               = NaN
+		surface_obs                 = NaN
+
+	end
+	methods
+		function self = adinversion(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					self=structtoobj(adinversion(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%parameter to be inferred by control methods (only
+			%drag and B are supported yet)
+			self.control_parameters={'FrictionCoefficient'};
+
+			%Scaling factor for each control
+			self.control_scaling_factors=1;
+
+			%number of iterations
+			self.maxsteps=20;
+			self.maxiter=40;
+
+			%several responses can be used:
+			self.cost_functions={'FrictionCoefficient'};
+
+			%m1qn3 parameters
+			self.dxmin  = 0.1;
+			self.gttol = 1e-4;
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			%Early return
+			if ~self.iscontrol, return; end
+
+			if ~IssmConfig('_HAVE_M1QN3_'),
+				md = checkmessage(md,['M1QN3 has not been installed, ISSM needs to be reconfigured and recompiled with AD']);
+			end
+
+			num_controls=numel(md.inversion.control_parameters);
+			num_costfunc=size(md.inversion.cost_functions,2);
+
+			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
+			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
+				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'DamageDbar',...
+				'Vx' 'Vy' 'Thickness' 'BalancethicknessOmega' 'BalancethicknessApparentMassbalance'});
+			md = checkfield(md,'fieldname','inversion.control_scaling_factors','size',[1 num_controls],'>',0,'NaN',1);
+			md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.maxiter','numel',1,'>=',0);
+			md = checkfield(md,'fieldname','inversion.dxmin','numel',1,'>',0);
+			md = checkfield(md,'fieldname','inversion.gttol','numel',1,'>',0);
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:506 601:604 1001:1010]);
+			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
+			md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
+			md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices num_controls]);
+
+			if solution==BalancethicknessSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				md = checkfield(md,'fieldname','inversion.surface_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			elseif solution==BalancethicknessSoftSolutionEnum()
+				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+			else
+				md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				if ~strcmp(domaintype(md.mesh),'2Dvertical'),
+					md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				end
+			end
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   adinversion parameters:'));
+			fielddisplay(self,'iscontrol','is inversion activated?');
+			fielddisplay(self,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(self,'control_scaling_factors','order of magnitude of each control (useful for multi-parameter optimization)');
+			fielddisplay(self,'maxsteps','maximum number of iterations (gradient computation)');
+			fielddisplay(self,'maxiter','maximum number of Function evaluation (forward run)');
+			fielddisplay(self,'dxmin','convergence criterion: two points less than dxmin from eachother (sup-norm) are considered identical');
+			fielddisplay(self,'gttol','convergence criterion: ||g(X)||/||g(X0)|| (g(X0): gradient at initial guess X0)');
+			fielddisplay(self,'cost_functions','indicate the type of response for each optimization step');
+			fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
+			fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(self,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]');
+			fielddisplay(self,'thickness_obs','observed thickness [m]');
+			fielddisplay(self,'surface_obs','observed surface elevation [m]');
+			
+			disp('Available cost functions:');
+			disp('   101: SurfaceAbsVelMisfit');
+			disp('   102: SurfaceRelVelMisfit');
+			disp('   103: SurfaceLogVelMisfit');
+			disp('   104: SurfaceLogVxVyMisfit');
+			disp('   105: SurfaceAverageVelMisfit');
+			disp('   201: ThicknessAbsMisfit');
+			disp('   501: DragCoefficientAbsGradient');
+			disp('   502: RheologyBbarAbsGradient');
+			disp('   503: ThicknessAbsGradient');
+		end % }}}
+		function marshall(self,md,fid) % {{{
+
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean');
+			WriteData(fid,'enum',InversionTypeEnum(),'data',4,'format','Integer');
+			if ~self.iscontrol, return; end
+			WriteData(fid,'object',self,'class','inversion','fieldname','control_scaling_factors','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','inversion','fieldname','maxsteps','format','Integer');
+			WriteData(fid,'object',self,'class','inversion','fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',self,'class','inversion','fieldname','dxmin','format','Double');
+			WriteData(fid,'object',self,'class','inversion','fieldname','gttol','format','Double');
+			WriteData(fid,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			if(numel(self.thickness_obs)==md.mesh.numberofelements),
+				mattype=2;
+			else
+				mattype=1;
+			end
+			WriteData(fid,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
+			WriteData(fid,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',mattype);
+
+			%process control parameters
+			num_control_parameters=numel(self.control_parameters);
+			data=zeros(1,num_control_parameters);
+			for i=1:num_control_parameters,
+				data(i)=StringToEnum(self.control_parameters{i});
+			end
+			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer');
+
+			%process cost functions
+			num_cost_functions=size(self.cost_functions,2);
+			data=self.cost_functions;
+			pos=find(self.cost_functions==101); data(pos)=SurfaceAbsVelMisfitEnum();
+			pos=find(self.cost_functions==102); data(pos)=SurfaceRelVelMisfitEnum();
+			pos=find(self.cost_functions==103); data(pos)=SurfaceLogVelMisfitEnum();
+			pos=find(self.cost_functions==104); data(pos)=SurfaceLogVxVyMisfitEnum();
+			pos=find(self.cost_functions==105); data(pos)=SurfaceAverageVelMisfitEnum();
+			pos=find(self.cost_functions==201); data(pos)=ThicknessAbsMisfitEnum();
+			pos=find(self.cost_functions==501); data(pos)=DragCoefficientAbsGradientEnum();
+			pos=find(self.cost_functions==502); data(pos)=RheologyBbarAbsGradientEnum();
+			pos=find(self.cost_functions==503); data(pos)=ThicknessAbsGradientEnum();
+			pos=find(self.cost_functions==504); data(pos)=ThicknessAlongGradientEnum();
+			pos=find(self.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
+			pos=find(self.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
+			pos=find(self.cost_functions==601); data(pos)=SurfaceAbsMisfitEnum();
+			pos=find(self.cost_functions==1001); data(pos)=Outputdefinition1Enum();
+			pos=find(self.cost_functions==1002); data(pos)=Outputdefinition2Enum();
+			pos=find(self.cost_functions==1003); data(pos)=Outputdefinition3Enum();
+			pos=find(self.cost_functions==1004); data(pos)=Outputdefinition4Enum();
+			pos=find(self.cost_functions==1005); data(pos)=Outputdefinition5Enum();
+			pos=find(self.cost_functions==1006); data(pos)=Outputdefinition6Enum();
+			pos=find(self.cost_functions==1007); data(pos)=Outputdefinition7Enum();
+			pos=find(self.cost_functions==1008); data(pos)=Outputdefinition8Enum();
+			pos=find(self.cost_functions==1009); data(pos)=Outputdefinition8Enum();
+			pos=find(self.cost_functions==1010); data(pos)=Outputdefinition10Enum();
+			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
+			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/autodiff.m
===================================================================
--- /issm/trunk/src/m/classes/autodiff.m	(revision 19104)
+++ /issm/trunk/src/m/classes/autodiff.m	(revision 19105)
@@ -20,44 +20,44 @@
 		%}}}
 	methods
-     	function createxml(obj,fid) % {{{
+     	function createxml(self,fid) % {{{
             fprintf(fid, '<!-- autodiff -->\n');            
                     
             % automatic differentiation parameters 
             fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="automatic differentiation parameters">','<section name="autodiff" />');                    
-                fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="isautodiff" type="',class(obj.isautodiff),'" optional="false">','     <section name="autodiff" />','         <option value="',convert2str(obj.isautodiff),'" type="string" default="true"></option>','     <help> indicates if the automatic differentiation is activated </help>','  </parameter>');
+                fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="isautodiff" type="',class(self.isautodiff),'" optional="false">','     <section name="autodiff" />','         <option value="',convert2str(self.isautodiff),'" type="string" default="true"></option>','     <help> indicates if the automatic differentiation is activated </help>','  </parameter>');
              
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="dependents" type="',class(obj.dependents),'" default="',convert2str(obj.dependents),'">','     <section name="autodiff" />','     <help> list of dependent variables </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="independents" type="',class(obj.independents),'" default="',convert2str(obj.independents),'">','     <section name="autodiff" />','     <help> list of independent variables </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="driver" type="',class(obj.driver),'" default="',convert2str(obj.driver),'">','     <section name="autodiff" />','     <help> ADOLC driver (''fos_forward'' or ''fov_forward'') </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="obufsize" type="',class(obj.obufsize),'" default="',convert2str(obj.obufsize),'">','     <section name="autodiff" />','     <help> Number of operations per buffer (==OBUFSIZE in usrparms.h)  </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lbufsize" type="',class(obj.lbufsize),'" default="',convert2str(obj.lbufsize),'">','     <section name="autodiff" />','     <help> Number of locations per buffer (==LBUFSIZE in usrparms.h) </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cbufsize" type="',class(obj.cbufsize),'" default="',convert2str(obj.cbufsize),'">','     <section name="autodiff" />','     <help> Number of values per buffer (==CBUFSIZE in usrparms.h) </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="tbufsize" type="',class(obj.tbufsize),'" default="',convert2str(obj.tbufsize),'">','     <section name="autodiff" />','     <help> Number of taylors per buffer (&amp;lt;=TBUFSIZE in usrparms.h) </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gcTriggerRatio" type="',class(obj.gcTriggerRatio),'" default="',convert2str(obj.gcTriggerRatio),'">','     <section name="autodiff" />','     <help> free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gcTriggerRatio" type="',class(obj.gcTriggerRatio),'" default="',convert2str(obj.gcTriggerRatio),'">','     <section name="autodiff" />','     <help> free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="dependents" type="',class(self.dependents),'" default="',convert2str(self.dependents),'">','     <section name="autodiff" />','     <help> list of dependent variables </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="independents" type="',class(self.independents),'" default="',convert2str(self.independents),'">','     <section name="autodiff" />','     <help> list of independent variables </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="driver" type="',class(self.driver),'" default="',convert2str(self.driver),'">','     <section name="autodiff" />','     <help> ADOLC driver (''fos_forward'' or ''fov_forward'') </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="obufsize" type="',class(self.obufsize),'" default="',convert2str(self.obufsize),'">','     <section name="autodiff" />','     <help> Number of operations per buffer (==OBUFSIZE in usrparms.h)  </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lbufsize" type="',class(self.lbufsize),'" default="',convert2str(self.lbufsize),'">','     <section name="autodiff" />','     <help> Number of locations per buffer (==LBUFSIZE in usrparms.h) </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cbufsize" type="',class(self.cbufsize),'" default="',convert2str(self.cbufsize),'">','     <section name="autodiff" />','     <help> Number of values per buffer (==CBUFSIZE in usrparms.h) </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="tbufsize" type="',class(self.tbufsize),'" default="',convert2str(self.tbufsize),'">','     <section name="autodiff" />','     <help> Number of taylors per buffer (&amp;lt;=TBUFSIZE in usrparms.h) </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gcTriggerRatio" type="',class(self.gcTriggerRatio),'" default="',convert2str(self.gcTriggerRatio),'">','     <section name="autodiff" />','     <help> free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gcTriggerRatio" type="',class(self.gcTriggerRatio),'" default="',convert2str(self.gcTriggerRatio),'">','     <section name="autodiff" />','     <help> free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize </help>','  </parameter>');
             
             fprintf(fid,'%s\n%s\n','</frame>');    
         
         end % }}}
-		function obj = autodiff(varargin) % {{{
+		function self = autodiff(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
-		obj.obufsize     = 524288;
-		obj.lbufsize     = 524288;
-		obj.cbufsize     = 524288;
-		obj.tbufsize     = 524288;
-		obj.gcTriggerRatio=2.0;
-		obj.gcTriggerMaxSize=65536;
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function self = setdefaultparameters(self) % {{{
+		self.obufsize     = 524288;
+		self.lbufsize     = 524288;
+		self.cbufsize     = 524288;
+		self.tbufsize     = 524288;
+		self.gcTriggerRatio=2.0;
+		self.gcTriggerMaxSize=65536;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return 
-			if ~obj.isautodiff, return; end
+			if ~self.isautodiff, return; end
 
 			%Driver value:
@@ -73,34 +73,34 @@
 
 			%go through our dependents and independents and check consistency: 
-			for i=1:numel(obj.dependents),
-				dep=obj.dependents{i};
+			for i=1:numel(self.dependents),
+				dep=self.dependents{i};
 				md=checkconsistency(dep,md,solution,analyses);
 			end
-			for i=1:numel(obj.independents),
-				indep=obj.independents{i};
-				md=checkconsistency(indep,md,i,solution,analyses,obj.driver);
-			end
-
-		end % }}}
-		function disp(obj) % {{{
+			for i=1:numel(self.independents),
+				indep=self.independents{i};
+				md=checkconsistency(indep,md,i,solution,analyses,self.driver);
+			end
+
+		end % }}}
+		function disp(self) % {{{
 			disp(sprintf('   automatic differentiation parameters:'));
-			fielddisplay(obj,'isautodiff','indicates if the automatic differentiation is activated');
-			fielddisplay(obj,'dependents','list of dependent variables');
-			fielddisplay(obj,'independents','list of independent variables');
-			fielddisplay(obj,'driver','ADOLC driver (''fos_forward'' or ''fov_forward'')');
-			fielddisplay(obj,'obufsize','Number of operations per buffer (==OBUFSIZE in usrparms.h)');
-			fielddisplay(obj,'lbufsize','Number of locations per buffer (==LBUFSIZE in usrparms.h)');
-			fielddisplay(obj,'cbufsize','Number of values per buffer (==CBUFSIZE in usrparms.h)');
-			fielddisplay(obj,'tbufsize','Number of taylors per buffer (<=TBUFSIZE in usrparms.h)');
-			fielddisplay(obj,'gcTriggerRatio','free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio');
-			fielddisplay(obj,'gcTriggerMaxSize','free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize');
-		end % }}}
-		function marshall(obj,md,fid) % {{{
-
-			WriteData(fid,'object',obj,'fieldname','isautodiff','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','driver','format','String');
+			fielddisplay(self,'isautodiff','indicates if the automatic differentiation is activated');
+			fielddisplay(self,'dependents','list of dependent variables');
+			fielddisplay(self,'independents','list of independent variables');
+			fielddisplay(self,'driver','ADOLC driver (''fos_forward'' or ''fov_forward'')');
+			fielddisplay(self,'obufsize','Number of operations per buffer (==OBUFSIZE in usrparms.h)');
+			fielddisplay(self,'lbufsize','Number of locations per buffer (==LBUFSIZE in usrparms.h)');
+			fielddisplay(self,'cbufsize','Number of values per buffer (==CBUFSIZE in usrparms.h)');
+			fielddisplay(self,'tbufsize','Number of taylors per buffer (<=TBUFSIZE in usrparms.h)');
+			fielddisplay(self,'gcTriggerRatio','free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio');
+			fielddisplay(self,'gcTriggerMaxSize','free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize');
+		end % }}}
+		function marshall(self,md,fid) % {{{
+
+			WriteData(fid,'object',self,'fieldname','isautodiff','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','driver','format','String');
 
 			%early return
-			if ~obj.isautodiff,
+			if ~self.isautodiff,
 				WriteData(fid,'data',false,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean');
 				WriteData(fid,'data',false,'enum',AutodiffKeepEnum(),'format','Boolean');
@@ -109,13 +109,13 @@
 
 			%buffer sizes {{{
-			WriteData(fid,'object',obj,'fieldname','obufsize','format','Double');
-			WriteData(fid,'object',obj,'fieldname','lbufsize','format','Double');
-			WriteData(fid,'object',obj,'fieldname','cbufsize','format','Double');
-			WriteData(fid,'object',obj,'fieldname','tbufsize','format','Double');
-			WriteData(fid,'object',obj,'fieldname','gcTriggerRatio','format','Double');
-			WriteData(fid,'object',obj,'fieldname','gcTriggerMaxSize','format','Double');
+			WriteData(fid,'object',self,'fieldname','obufsize','format','Double');
+			WriteData(fid,'object',self,'fieldname','lbufsize','format','Double');
+			WriteData(fid,'object',self,'fieldname','cbufsize','format','Double');
+			WriteData(fid,'object',self,'fieldname','tbufsize','format','Double');
+			WriteData(fid,'object',self,'fieldname','gcTriggerRatio','format','Double');
+			WriteData(fid,'object',self,'fieldname','gcTriggerMaxSize','format','Double');
 			%}}}
 			%process dependent variables {{{
-			num_dependent_objects=numel(obj.dependents);
+			num_dependent_objects=numel(self.dependents);
 			WriteData(fid,'data',num_dependent_objects,'enum',AutodiffNumDependentObjectsEnum(),'format','Integer');
 
@@ -126,5 +126,5 @@
 
 				for i=1:num_dependent_objects,
-					dep=obj.dependents{i};
+					dep=self.dependents{i};
 
 					names{i}=dep.name;
@@ -138,5 +138,5 @@
 			%}}}
 			%process independent variables {{{
-			num_independent_objects=numel(obj.independents);
+			num_independent_objects=numel(self.independents);
 			WriteData(fid,'data',num_independent_objects,'enum',AutodiffNumIndependentObjectsEnum(),'format','Integer');
 
@@ -146,5 +146,5 @@
 
 				for i=1:num_independent_objects,
-					indep=obj.independents{i};
+					indep=self.independents{i};
 
 					names(i)=StringToEnum(indep.name);
@@ -156,9 +156,9 @@
 			%}}}
 			%if driver is fos_forward, build index:  {{{
-			if strcmpi(obj.driver,'fos_forward'),
+			if strcmpi(self.driver,'fos_forward'),
 				index=0;
 
 				for i=1:num_independent_objects,
-					indep=obj.independents{i};
+					indep=self.independents{i};
 					if ~isnan(indep.fos_forward_index),
 						index=index+indep.fos_forward_index;
@@ -177,9 +177,9 @@
 			%}}}
 			%if driver is fos_reverse, build index:  {{{
-			if strcmpi(obj.driver,'fos_reverse'),
+			if strcmpi(self.driver,'fos_reverse'),
 				index=0;
 
 				for i=1:num_dependent_objects,
-					dep=obj.dependents{i};
+					dep=self.dependents{i};
 					if ~isnan(dep.fos_reverse_index),
 						index=index+dep.fos_reverse_index;
@@ -198,9 +198,9 @@
 			%}}}
 			%if driver is fov_forward, build indices:  {{{
-			if strcmpi(obj.driver,'fov_forward'),
+			if strcmpi(self.driver,'fov_forward'),
 				indices=0;
 
 				for i=1:num_independent_objects,
-					indep=obj.independents{i};
+					indep=self.independents{i};
 					if ~isempty(indep.fos_forward_index),
 						indices=indices+indep.fov_forward_indices;
@@ -221,5 +221,5 @@
 			mass_flux_segments=cell(0,1);
 			for i=1:num_dependent_objects,
-				dep=obj.dependents{i};
+				dep=self.dependents{i};
 				if strcmpi(dep.name,'MassFlux'),
 					mass_flux_segments{end+1,1}=dep.segments;
@@ -244,8 +244,8 @@
 			%
 
-			if length(obj.driver)<=3,
+			if length(self.driver)<=3,
 				keep=false; %there is no "_reverse" string within the driver string: 
 			else
-				if strncmpi(obj.driver(4:end),'_reverse',8),
+				if strncmpi(self.driver(4:end),'_reverse',8),
 					keep=true;
 				else
Index: /issm/trunk/src/m/classes/balancethickness.m
===================================================================
--- /issm/trunk/src/m/classes/balancethickness.m	(revision 19104)
+++ /issm/trunk/src/m/classes/balancethickness.m	(revision 19105)
@@ -9,35 +9,23 @@
 		thickening_rate   = NaN;
 		stabilization     = 0;
+
+		omega             = NaN;
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- balancethickness -->');
-            
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcthickness" type="',   	class(obj.spcthickness),'" default="',        convert2str(obj.spcthickness),'">',	'     <section name="balancethickness" />','     <help> thickness constraints (NaN means no constraint) [m] </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="thickening_rate" type="', 	class(obj.thickening_rate),'" default="',            convert2str(obj.thickening_rate),'">',     '     <section name="balancethickness" />','     <help> ice thickening rate used in the mass conservation (dh/dt) [m/yr] </help>','</parameter>');
-            
-            % balancethickness drop-down (1,2, or 3)
-            fprintf(fid,'%s\n%s\n%s\n',        '<parameter key ="stabilization" type="alternative" optional="false">','     <section name="balancethickness" />','     <help> 0: None, 1: SU, 2: SSAs artificial diffusivity, 3:DG </help>');
-            fprintf(fid,'%s\n','       <option value="1" type="string" default="true"> </option>');
-            fprintf(fid,'%s\n','       <option value="2" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n%s\n','       <option value="3" type="string" default="false"> </option>','</parameter>');
-
-        end % }}}
-		function obj = balancethickness(varargin) % {{{
+		function self = balancethickness(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%Type of stabilization used
-			obj.stabilization=1;
+			self.stabilization=1;
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 			%Early return
 			if solution~=BalancethicknessSolutionEnum(), return; end
@@ -46,20 +34,24 @@
 			md = checkfield(md,'fieldname','balancethickness.thickening_rate','size',[md.mesh.numberofvertices 1],'NaN',1);
 			md = checkfield(md,'fieldname','balancethickness.stabilization','size',[1 1],'values',[0 1 2 3]);
+
+			%md = checkfield(md,'fieldname','balancethickness.omega','size',[md.mesh.numberofvertices 1],'NaN',1,'>=',0);
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   balance thickness solution parameters:'));
 
-			fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint) [m]');
-			fielddisplay(obj,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt) [m/yr]');
-			fielddisplay(obj,'stabilization','0: None, 1: SU, 2: SSA''s artificial diffusivity, 3:DG');
+			fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint) [m]');
+			fielddisplay(self,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt) [m/yr]');
+			fielddisplay(self,'stabilization','0: None, 1: SU, 2: SSA''s artificial diffusivity, 3:DG');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
-			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','thickening_rate','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
+			WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','thickening_rate','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'fieldname','stabilization','format','Integer');
+
+			WriteData(fid,'object',self,'fieldname','omega','format','DoubleMat','mattype',1);
 		end % }}}
 	end
Index: sm/trunk/src/m/classes/balancethickness2.m
===================================================================
--- /issm/trunk/src/m/classes/balancethickness2.m	(revision 19104)
+++ 	(revision )
@@ -1,62 +1,0 @@
-%BALANCETHICKNESS2 class definition
-%
-%   Usage:
-%      balancethickness2=balancethickness2();
-
-classdef balancethickness2
-	properties (SetAccess=public) 
-		spcpotential         = NaN;
-		apparent_massbalance = NaN;
-		nux                  = NaN;
-		nuy                  = NaN;
-		vx_obs               = NaN;
-		vy_obs               = NaN;
-		thickness_obs        = NaN;
-	end
-	methods
-		function obj = balancethickness2(varargin) % {{{
-			switch nargin
-				case 0
-					obj=setdefaultparameters(obj);
-				otherwise
-					error('constructor not supported');
-			end
-		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
-
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
-			%Early return
-			if solution~=Balancethickness2SolutionEnum(), return; end
-
-			md = checkfield(md,'fieldname','balancethickness.spcpotential','size',[md.mesh.numberofvertices 1]);
-			md = checkfield(md,'fieldname','balancethickness.apparent_massbalance','size',[md.mesh.numberofvertices 1],'NaN',1);
-			md = checkfield(md,'fieldname','balancethickness.nux','size',[md.mesh.numberofvertices 1],'NaN',1,'>',0,'<=',1);
-			md = checkfield(md,'fieldname','balancethickness.nuy','size',[md.mesh.numberofvertices 1],'NaN',1,'>',0,'<=',1);
-			md = checkfield(md,'fieldname','balancethickness.vx_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
-			md = checkfield(md,'fieldname','balancethickness.vy_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
-			md = checkfield(md,'fieldname','balancethickness.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1,'>=',0);
-		end % }}}
-		function disp(obj) % {{{
-			disp(sprintf('   balance thickness solution parameters:'));
-
-			fielddisplay(obj,'spcpotential','potential constraints (NaN means no constraint)');
-			fielddisplay(obj,'apparent_massbalance','Apparent mass balance [m/yr]');
-			fielddisplay(obj,'nux','vx_bar = nux vx_s (in ]0 1])');
-			fielddisplay(obj,'nuy','vy_bar = nuy vy_s (in ]0 1])');
-			fielddisplay(obj,'vx_obs','observed vx');
-			fielddisplay(obj,'vy_obs','observed vy');
-			fielddisplay(obj,'thickness_obs','observed H');
-
-		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','spcpotential','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','apparent_massbalance','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','nux','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','nuy','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','vx_obs','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','vy_obs','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','Balancethickness','fieldname','thickness_obs','format','DoubleMat','mattype',1);
-		end % }}}
-	end
-end
Index: /issm/trunk/src/m/classes/bamgmesh.m
===================================================================
--- /issm/trunk/src/m/classes/bamgmesh.m	(revision 19104)
+++ /issm/trunk/src/m/classes/bamgmesh.m	(revision 19105)
@@ -23,4 +23,5 @@
 		CrackedVertices=[];
 		CrackedEdges=[];
+		PreviousNumbering=[];
 		% }}}
 	end
Index: /issm/trunk/src/m/classes/basalforcings.m
===================================================================
--- /issm/trunk/src/m/classes/basalforcings.m	(revision 19104)
+++ /issm/trunk/src/m/classes/basalforcings.m	(revision 19105)
@@ -11,15 +11,20 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- basalforcings -->');
-			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="melting_rate" type="',            class(obj.melting_rate),'" default="',              num2str(obj.melting_rate),'">',              '     <section name="basalforcings" />','     <help> basal melting rate (positive if melting) [m/yr] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="geothermalflux" type="',          class(obj.geothermalflux),'" default="',            num2str(obj.geothermalflux),'">',            '     <section name="basalforcings" />','     <help> geothermal heat flux [W/m^2] </help>','</parameter>');
-             
-        end % }}}
-		function obj = basalforcings(varargin) % {{{
+		function createxml(self,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- basalforcings -->');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="melting_rate" type="',            class(self.melting_rate),'" default="',              num2str(self.melting_rate),'">',              '     <section name="basalforcings" />','     <help> basal melting rate (positive if melting) [m/yr] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="geothermalflux" type="',          class(self.geothermalflux),'" default="',            num2str(self.geothermalflux),'">',            '     <section name="basalforcings" />','     <help> geothermal heat flux [W/m^2] </help>','</parameter>');
+
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.groundedice_melting_rate=project3d(md,'vector',self.groundedice_melting_rate,'type','node','layer',1); 
+			self.floatingice_melting_rate=project3d(md,'vector',self.floatingice_melting_rate,'type','node','layer',1); 
+			self.geothermalflux=project3d(md,'vector',self.geothermalflux,'type','node','layer',1); %bedrock only gets geothermal flux
+		end % }}}
+		function self = basalforcings(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
@@ -39,12 +44,12 @@
 
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			if ismember(MasstransportAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.ismasstransport==0),
-				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
-				md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'timeseries',1);
+				md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'timeseries',1);
 			end
 			if ismember(BalancethicknessAnalysisEnum(),analyses),
@@ -53,25 +58,25 @@
 			end
 			if ismember(ThermalAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.isthermal==0),
-				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
-				md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1);
-				md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0);
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'timeseries',1);
+				md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'timeseries',1);
+				md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'timeseries',1,'>=',0);
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   basal forcings parameters:'));
 
-			fielddisplay(obj,'groundedice_melting_rate','basal melting rate (positive if melting) [m/yr]');
-			fielddisplay(obj,'floatingice_melting_rate','basal melting rate (positive if melting) [m/yr]');
-			fielddisplay(obj,'geothermalflux','geothermal heat flux [W/m^2]');
+			fielddisplay(self,'groundedice_melting_rate','basal melting rate (positive if melting) [m/yr]');
+			fielddisplay(self,'floatingice_melting_rate','basal melting rate (positive if melting) [m/yr]');
+			fielddisplay(self,'geothermalflux','geothermal heat flux [W/m^2]');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
 			WriteData(fid,'enum',BasalforcingsEnum(),'data',FloatingMeltRateEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-			WriteData(fid,'object',obj,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-			WriteData(fid,'object',obj,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',self,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/basalforcings.py
===================================================================
--- /issm/trunk/src/m/classes/basalforcings.py	(revision 19104)
+++ /issm/trunk/src/m/classes/basalforcings.py	(revision 19105)
@@ -1,3 +1,4 @@
 from fielddisplay import fielddisplay
+from project3d import project3d
 from EnumDefinitions import *
 from checkfield import checkfield
@@ -30,4 +31,10 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.groundedice_melting_rate=project3d(md,'vector',self.groundedice_melting_rate,'type','node','layer',1)
+		self.floatingice_melting_rate=project3d(md,'vector',self.floatingice_melting_rate,'type','node','layer',1)
+		self.geothermalflux=project3d(md,'vector',self.geothermalflux,'type','node','layer',1)    #bedrock only gets geothermal flux
+		return self
+	#}}}
 	def initialize(self,md): # {{{
 
@@ -48,6 +55,6 @@
 
 		if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
-			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
-			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'timeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'timeseries',1)
 
 		if BalancethicknessAnalysisEnum() in analyses:
@@ -56,7 +63,7 @@
 
 		if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isthermal):
-			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
-			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'forcing',1)
-			md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0)
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'timeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'timeseries',1)
+			md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'timeseries',1,'>=',0)
 
 		return md
@@ -67,6 +74,6 @@
 
 		WriteData(fid,'enum',BasalforcingsEnum(),'data',FloatingMeltRateEnum(),'format','Integer');
-		WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
 	# }}}
Index: /issm/trunk/src/m/classes/calving.m
===================================================================
--- /issm/trunk/src/m/classes/calving.m	(revision 19105)
+++ /issm/trunk/src/m/classes/calving.m	(revision 19105)
@@ -0,0 +1,63 @@
+%CALVING class definition
+%
+%   Usage:
+%      calving=calving();
+
+classdef calving
+	properties (SetAccess=public) 
+		stabilization = 0;
+		calvingrate   = NaN;
+		meltingrate   = NaN;
+	end
+	methods
+		function self = calving(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('calving');
+					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.calvingrate=project3d(md,'vector',self.calvingrate,'type','node');
+			self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node');
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%stabilization = 2 by default
+			self.stabilization = 2;
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+			%Early return
+			if (solution~=TransientSolutionEnum() | md.transient.iscalving==0), return; end
+
+			md = checkfield(md,'fieldname','calving.stabilization','values',[0 1 2]);
+			md = checkfield(md,'fieldname','calving.calvingrate(1:md.mesh.numberofvertices,:)','>=',0,'timeseries',1,'NaN',1);
+			md = checkfield(md,'fieldname','calving.meltingrate(1:md.mesh.numberofvertices,:)','>=',0,'timeseries',1,'NaN',1);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   Calving parameters:'));
+			fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding');
+			fielddisplay(self,'calvingrate','calving rate at given location [m/a]');
+			fielddisplay(self,'meltingrate','melting rate at given location [m/a]');
+		end % }}}
+		function marshall(self,md,fid) % {{{
+			yts=365.0*24.0*3600.0;
+			WriteData(fid,'enum',CalvingLawEnum(),'data',DefaultCalvingEnum(),'format','Integer');
+			WriteData(fid,'enum',LevelsetStabilizationEnum(),'data',self.stabilization,'format','Integer');
+			WriteData(fid,'object',self,'fieldname','calvingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts);
+			WriteData(fid,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/calving.py
===================================================================
--- /issm/trunk/src/m/classes/calving.py	(revision 19105)
+++ /issm/trunk/src/m/classes/calving.py	(revision 19105)
@@ -0,0 +1,66 @@
+from fielddisplay import fielddisplay
+from project3d import project3d
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import checkfield
+from WriteData import WriteData
+
+class calving(object):
+	"""
+	CALVING class definition
+
+	   Usage:
+	      calving=calving();
+	"""
+
+	def __init__(self): # {{{
+
+		self.stabilization = 0
+		self.calvingrate   = float('NaN')
+		self.meltingrate   = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   Calving parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding'))
+		string="%s\n%s"%(string,fielddisplay(self,'calvingrate','calving rate at given location [m/a]'))
+		string="%s\n%s"%(string,fielddisplay(self,'meltingrate','melting rate at given location [m/a]'))
+
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+		self.calvingrate=project3d(md,'vector',self.calvingrate,'type','node')
+		self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node')
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+
+		#stabilization = 2 by default
+		self.stabilization = 2
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if (solution!=TransientSolutionEnum()) or (not md.transient.iscalving):
+			return md
+
+		md = checkfield(md,'fieldname','calving.stabilization','values',[0,1,2]);
+		md = checkfield(md,'fieldname','calving.calvingrate','>=',0,'timeseries',1,'NaN',1);
+		md = checkfield(md,'fieldname','calving.meltingrate','>=',0,'timeseries',1,'NaN',1);
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		yts=365.*24.*3600.
+
+		WriteData(fid,'enum',CalvingLawEnum(),'data',DefaultCalvingEnum(),'format','Integer');
+		WriteData(fid,'enum',LevelsetStabilizationEnum(),'data',self.stabilization,'format','Integer');
+		WriteData(fid,'object',self,'fieldname','calvingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts)
+	# }}}
Index: /issm/trunk/src/m/classes/calvingdev.m
===================================================================
--- /issm/trunk/src/m/classes/calvingdev.m	(revision 19105)
+++ /issm/trunk/src/m/classes/calvingdev.m	(revision 19105)
@@ -0,0 +1,62 @@
+%CALVINGDEV class definition
+%
+%   Usage:
+%      calvingdev=calvingdev();
+
+classdef calvingdev
+	properties (SetAccess=public) 
+		stabilization = 0;
+		coeff         = NaN;
+		meltingrate   = NaN;
+	end
+	methods
+		function self = calvingdev(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('calvingdev');
+					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 = setdefaultparameters(self) % {{{
+
+			%stabilization = 2 by default
+			self.stabilization = 2;
+
+			%Proportionality coefficient in Pi model
+			self.coeff=2e13;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+			%Early return
+			if (solution~=TransientSolutionEnum() | md.transient.iscalving==0), return; end
+
+			md = checkfield(md,'fieldname','calving.stabilization','values',[0 1 2]);
+			md = checkfield(md,'fieldname','calving.coeff','>',0,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'size',[md.mesh.numberofvertices 1],'>=',0);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   Calving Pi parameters:'));
+			fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding');
+			fielddisplay(self,'coeff','proportionality coefficient in Pi model');
+			fielddisplay(self,'meltingrate','melting rate at given location [m/a]');
+
+		end % }}}
+		function marshall(self,md,fid) % {{{
+			yts=365.0*24.0*3600.0;
+			WriteData(fid,'enum',CalvingLawEnum(),'data',CalvingDevEnum(),'format','Integer');
+			WriteData(fid,'enum',LevelsetStabilizationEnum(),'data',self.stabilization,'format','Integer');
+			WriteData(fid,'enum',CalvingpiCoeffEnum(),'data',self.coeff,'format','DoubleMat','mattype',1);
+			WriteData(fid,'class','calving','object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1,'scale',1./yts);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/calvinglevermann.m
===================================================================
--- /issm/trunk/src/m/classes/calvinglevermann.m	(revision 19105)
+++ /issm/trunk/src/m/classes/calvinglevermann.m	(revision 19105)
@@ -0,0 +1,66 @@
+%CALVINGLEVERMANN class definition
+%
+%   Usage:
+%      calvinglevermann=calvinglevermann();
+
+classdef calvinglevermann
+	properties (SetAccess=public) 
+		stabilization = 0;
+		coeff         = NaN;
+		meltingrate   = NaN;
+	end
+	methods
+		function self = calvinglevermann(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('calvinglevermann');
+					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.coeff=project3d(md,'vector',self.coeff,'type','node');
+			self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node');
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%stabilization = 2 by default
+			self.stabilization = 2;
+
+			%Proportionality coefficient in Levermann model
+			self.coeff=2e13;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+			%Early return
+			if (solution~=TransientSolutionEnum() | md.transient.iscalving==0), return; end
+
+			md = checkfield(md,'fieldname','calving.stabilization','values',[0 1 2]);
+			md = checkfield(md,'fieldname','calving.coeff','>',0,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'size',[md.mesh.numberofvertices 1],'>=',0);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   Calving Levermann parameters:'));
+			fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding');
+			fielddisplay(self,'coeff','proportionality coefficient in Levermann model');
+			fielddisplay(self,'meltingrate','melting rate at given location [m/a]');
+
+		end % }}}
+		function marshall(self,md,fid) % {{{
+			yts=365.0*24.0*3600.0;
+			WriteData(fid,'enum',CalvingLawEnum(),'data',CalvingLevermannEnum(),'format','Integer');
+			WriteData(fid,'enum',LevelsetStabilizationEnum(),'data',self.stabilization,'format','Integer');
+			WriteData(fid,'enum',CalvinglevermannCoeffEnum(),'data',self.coeff,'format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/calvinglevermann.py
===================================================================
--- /issm/trunk/src/m/classes/calvinglevermann.py	(revision 19105)
+++ /issm/trunk/src/m/classes/calvinglevermann.py	(revision 19105)
@@ -0,0 +1,62 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import checkfield
+from WriteData import WriteData
+
+class calvinglevermann(object):
+	"""
+	CALVINGLEVERMANN class definition
+
+	   Usage:
+	      calvinglevermann=calvinglevermann();
+	"""
+
+	def __init__(self): # {{{
+		self.stabilization = 0
+		self.coeff         = float('NaN')
+		self.meltingrate   = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		string='   Calving Levermann parameters:'
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding'))
+		string="%s\n%s"%(string,fielddisplay(self,'coeff','proportionality coefficient in Levermann model'))
+		string="%s\n%s"%(string,fielddisplay(self,'meltingrate','melting rate at given location [m/a]'))
+
+		return string
+		#}}}
+	def extrude(self,md): # {{{
+		self.coeff=project3d(md,'vector',self.coeff,'type','node')
+		self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node')
+		return self
+	#}}}
+	def setdefaultparameters(self): # {{{
+
+		#stabilization = 2 by default
+		self.stabilization = 2
+
+		#Proportionality coefficient in Levermann model
+		self.coeff=2e13;
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if (solution!=TransientSolutionEnum()) or (not md.transient.iscalving):
+			return md
+
+		md = checkfield(md,'fieldname','calving.stabilization','values',[0,1,2]);
+		md = checkfield(md,'fieldname','calving.coeff','size',[md.mesh.numberofvertices],'>',0)
+		md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'size',[md.mesh.numberofvertices],'>=',0)
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		yts=365.*24.*3600.
+		WriteData(fid,'enum',CalvingLawEnum(),'data',CalvingLevermannEnum(),'format','Integer');
+		WriteData(fid,'enum',LevelsetStabilizationEnum(),'data',self.stabilization,'format','Integer');
+		WriteData(fid,'enum',CalvinglevermannCoeffEnum(),'data',self.coeff,'format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts)
+	# }}}
Index: /issm/trunk/src/m/classes/calvingpi.m
===================================================================
--- /issm/trunk/src/m/classes/calvingpi.m	(revision 19105)
+++ /issm/trunk/src/m/classes/calvingpi.m	(revision 19105)
@@ -0,0 +1,66 @@
+%CALVINGPI class definition
+%
+%   Usage:
+%      calvingpi=calvingpi();
+
+classdef calvingpi
+	properties (SetAccess=public) 
+		stabilization = 0;
+		coeff         = NaN;
+		meltingrate   = NaN;
+	end
+	methods
+		function self = calvingpi(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('calvingpi');
+					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.coeff=project3d(md,'vector',self.coeff,'type','node');
+			self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node');
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%stabilization = 2 by default
+			self.stabilization = 2;
+
+			%Proportionality coefficient in Pi model
+			self.coeff=2e13;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+			%Early return
+			if (solution~=TransientSolutionEnum() | md.transient.iscalving==0), return; end
+
+			md = checkfield(md,'fieldname','calving.stabilization','values',[0 1 2]);
+			md = checkfield(md,'fieldname','calving.coeff','>',0,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'size',[md.mesh.numberofvertices 1],'>=',0);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   Calving Pi parameters:'));
+			fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding');
+			fielddisplay(self,'coeff','proportionality coefficient in Pi model');
+			fielddisplay(self,'meltingrate','melting rate at given location [m/a]');
+
+		end % }}}
+		function marshall(self,md,fid) % {{{
+			yts=365.0*24.0*3600.0;
+			WriteData(fid,'enum',CalvingLawEnum(),'data',CalvingPiEnum(),'format','Integer');
+			WriteData(fid,'enum',LevelsetStabilizationEnum(),'data',self.stabilization,'format','Integer');
+			WriteData(fid,'enum',CalvingpiCoeffEnum(),'data',self.coeff,'format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/clusters/acenet.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/acenet.m	(revision 19104)
+++ /issm/trunk/src/m/classes/clusters/acenet.m	(revision 19105)
@@ -9,6 +9,6 @@
     properties (SetAccess=public) 
 		 % {{{
-		 name='glacdyn.ace-net.ca'
-		 %name='placentia.ace-net.ca'
+		 %name='glacdyn.ace-net.ca'
+		 name='placentia.ace-net.ca'
 		 %name='brasdor.ace-net.ca'
 		 login='klemorza';
@@ -19,5 +19,7 @@
 		 % codepath='/usr/local/issm-r11321/bin'; % this one is for issm on acenet global
 		 codepath='/home/klemorza/issm/trunk-jpl/bin'; % this one is for issm on my acenet directory
-		 executionpath='/home/klemorza/issm/trunk-jpl/execution';
+		 %executionpath='/home/klemorza/issm/trunk-jpl/execution';
+		 %executionpath='/home/klemorza/scratch/issmres.dir';
+		 executionpath='/net/glacdyn-data/glacdyn/1/klemorza/issm.dir';
 		 %}}}
 	 end
@@ -50,5 +52,5 @@
 
 			 available_queues={'debug','shortq','longq'};
-			 queue_requirements_time=[60*1 60*3 60*17];
+			 queue_requirements_time=[48*1 48*2 48*5];
 			 queue_requirements_np=[32 128 256];
 
@@ -66,15 +68,30 @@
 			 fprintf(fid,'#$ -cwd\n');
           fprintf(fid,'#$ -N issm\n');
-          fprintf(fid,'#$ -l h_rt=96:0:0\n');
+          %fprintf(fid,'#$ -l h_rt=25:00:0\n');
+          %fprintf(fid,'#$ -l h_rt=47:59:00\n');
+          %fprintf(fid,'#$ -l h_rt=72:00:0\n');
+          fprintf(fid,'#$ -l h_rt=96:00:0\n');
+	  fprintf(fid,'#$ -l h_vmem=4G\n');
           fprintf(fid,'#$ -pe ompi* %i\n',cluster.np);
           fprintf(fid,'#$ -j y\n');
+          fprintf(fid,'#$ -l h=cl27*|cl28*|cl29*|cl30*|cl31*|cl320|cl267|cl268|cl269|cl338 \n');
+          %fprintf(fid,'#$ -l h=cl338 \n');
+          %fprintf(fid,'#$ -pe openmp 20 \n');
+          %fprintf(fid,'#$ -q !tarasov.q\n'); %
+          fprintf(fid,'#$ -pe openmp 8\n');
           fprintf(fid,'module purge\n');
-          fprintf(fid,'module load gcc openmpi/gcc\n');
-          fprintf(fid,'module load issm\n');
-			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
-			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
+          %fprintf(fid,'module load gcc openmpi/gcc\n');
+          %fprintf(fid,'module unload openmpi\n');
+          fprintf(fid,'module load intel/12.1.7.367\n');
+          fprintf(fid,'module load openmpi/intel/1.2.9\n');
+
+          fprintf(fid,'module load gsl\n');
+          %fprintf(fid,'module load issm\n');
+          fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+          fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
           fprintf(fid,'\n');
-          fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
-                   cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+          fprintf(fid,'mpiexec %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog\n',...
+                   cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+          %fprintf(fid,'echo $HOSTNAME >>%s.outlog',modelname);
 			 fclose(fid);
 
@@ -95,5 +112,5 @@
 			 disp('launching solution sequence on remote cluster');
 			 launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
-				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub ' modelname '.queue '];
+				 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz && qsub ' modelname '.queue '];
 			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
 		 end %}}}
Index: /issm/trunk/src/m/classes/clusters/discover.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/discover.m	(revision 19104)
+++ /issm/trunk/src/m/classes/clusters/discover.m	(revision 19105)
@@ -58,17 +58,14 @@
 		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
 
-			 available_queues={'general_long','general','general_small','debug'};
-			 queue_requirements_time=[24*60 12*60 12*60 60];
-			 queue_requirements_np=[516 1024 16 32];
+			 available_queues={'general_long','general','debug'};
+			 queue_requirements_time=[24*60 12*60 60];
+			 queue_requirements_np=[516 1024 32];
 
 			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
 
-			 if ( strcmpi(cluster.queue,'general') & cluster.cpuspernode*cluster.numnodes < 17)
-				 md = checkmessage(md,'cpus must be greater than 17 for general queue');
-			 end
 			 %now, check cluster.cpuspernode according to processor type
-			 if ( strcmpi(cluster.processor,'neha')),
-				 if ((cluster.cpuspernode>8 ) | (cluster.cpuspernode<1)),
-					 md = checkmessage(md,'cpuspernode should be between 1 and 8 for ''neha'' processors');
+			 if ( strcmpi(cluster.processor,'sand')),
+				 if ((cluster.cpuspernode>16 ) | (cluster.cpuspernode<1)),
+					 md = checkmessage(md,'cpuspernode should be between 1 and 16 for ''sand'' processors');
 				 end
 			 elseif strcmpi(cluster.processor,'west'),
@@ -77,5 +74,5 @@
 				 end
 			 else
-				 md = checkmessage(md,'unknown processor type, should be ''neha'' or ''west'' ');
+				 md = checkmessage(md,'unknown processor type, should be ''sand'' or ''west'' ');
 			 end
 
@@ -100,5 +97,7 @@
 			 fprintf(fid,'#PBS -l select=%i:mpiprocs=%i:proc=%s\n',cluster.numnodes,cluster.cpuspernode,cluster.processor);
 			 fprintf(fid,'#PBS -l walltime=%i:00\n',cluster.time); %SLURM walltime is in minutes:
-			 fprintf(fid,'#PBS -q %s \n',cluster.queue);
+			 if ~strcmp(cluster.queue,'general'),
+				 fprintf(fid,'#PBS -q %s \n',cluster.queue);
+			 end
 			 fprintf(fid,'#PBS -W group_list=s1010\n');
 			 fprintf(fid,'#PBS -m e\n');
Index: /issm/trunk/src/m/classes/clusters/generic.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/generic.m	(revision 19104)
+++ /issm/trunk/src/m/classes/clusters/generic.m	(revision 19105)
@@ -24,23 +24,30 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
+        function createxml(self,fid) % {{{
             fprintf(fid, '\n\n');
             fprintf(fid, '%s\n', '<!-- generic -->');
             
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="name" type="',class(obj.name),'" default="',convert2str(obj.name),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="login" type="',class(obj.login),'" default="',convert2str(obj.login),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',	'<parameter key ="np" type="',class(obj.np),'" default="',convert2str(obj.np),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="port" type="',class(obj.port),'" default="',convert2str(obj.port),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="codepath" type="',class(obj.codepath),'" default="',convert2str(obj.codepath),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="name" type="',class(self.name),'" default="',convert2str(self.name),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="login" type="',class(self.login),'" default="',convert2str(self.login),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',	'<parameter key ="np" type="',class(self.np),'" default="',convert2str(self.np),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="port" type="',class(self.port),'" default="',convert2str(self.port),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="codepath" type="',class(self.codepath),'" default="',convert2str(self.codepath),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
              
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="executionpath" type="',class(obj.executionpath),'" default="',convert2str(obj.executionpath),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="etcpath" type="',class(obj.etcpath),'" default="',convert2str(obj.etcpath),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="valgrind" type="',class(obj.valgrind),'" default="',convert2str(obj.valgrind),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="valgrindlib" type="',class(obj.valgrindlib),'" default="',convert2str(obj.valgrindlib),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="valgrindsup" type="',class(obj.valgrindsup),'" default="',convert2str(obj.valgrindsup),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',    	'<parameter key ="verbose" type="',class(obj.verbose),'" default="',convert2str(obj.verbose),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="executionpath" type="',class(self.executionpath),'" default="',convert2str(self.executionpath),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="etcpath" type="',class(self.etcpath),'" default="',convert2str(self.etcpath),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="valgrind" type="',class(self.valgrind),'" default="',convert2str(self.valgrind),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="valgrindlib" type="',class(self.valgrindlib),'" default="',convert2str(self.valgrindlib),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="valgrindsup" type="',class(self.valgrindsup),'" default="',convert2str(self.valgrindsup),'">',     '     <section name="cluster" />','     <help> N/A </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',    	'<parameter key ="verbose" type="',class(self.verbose),'" default="',convert2str(self.verbose),'">',	'     <section name="cluster" />','     <help> N/A </help>','</parameter>');
              
         end % }}}
 		function cluster=generic(varargin) % {{{
+
+			%Change the defaults if ispc
+			if ispc,
+				cluster.codepath      = [issmdir() '\bin'];
+				cluster.etcpath       = [issmdir() '\etc'];
+				cluster.executionpath = [issmdir() '\execution'];
+			end
 
 			%use provided options to change fields
Index: /issm/trunk/src/m/classes/clusters/generic_static.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/generic_static.m	(revision 19105)
+++ /issm/trunk/src/m/classes/clusters/generic_static.m	(revision 19105)
@@ -0,0 +1,87 @@
+%GENERIC cluster class definition
+%
+%   Usage:
+%      cluster=generic_static('name','astrid','np',3);
+
+classdef generic_static
+	properties (SetAccess=public) 
+		% {{{
+		name='';
+		np=1;
+		codepath=fileparts(which('issm.exe'));
+		executionpath = '.';
+		interactive = 1;
+		shell='/bin/sh';
+		%}}}
+	end
+	methods
+		function cluster=generic_static(varargin) % {{{
+
+			%use provided options to change fields
+			options=pairoptions(varargin{:});
+
+			%get name
+			cluster.name=getfieldvalue(options,'name',oshostname());
+
+			%initialize cluster using user settings if provided
+			if (exist([cluster.name '_settings'])==2), eval([cluster.name '_settings']); end
+
+			%OK get other fields
+			cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		end
+		%}}}
+		function disp(cluster) % {{{
+			%  display the object
+			disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			disp(sprintf('    name: %s',cluster.name));
+			disp(sprintf('    np: %i',cluster.np));
+			disp(sprintf('    codepath: %s',cluster.codepath));
+			disp(sprintf('    shell: %s',cluster.shell));
+		end
+		%}}}
+		function md = checkconsistency(cluster,md,solution,analyses) % {{{
+			if cluster.np<1
+				md = checkmessage(md,['number of processors should be at least 1']);
+			end
+			if isnan(cluster.np),
+				md = checkmessage(md,'number of processors should not be NaN!');
+			end
+		end
+		%}}}
+		function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			%write queuing script 
+			fid=fopen([modelname '.queue'],'w');
+			fprintf(fid,'#!%s\n',cluster.shell);
+			fprintf(fid,[cluster.codepath '/mpiexec -np %i %s/issm.exe %s %s %s \n'],cluster.np,cluster.codepath,EnumToString(solution),'./',modelname);
+			fclose(fid);
+
+			%in interactive mode, create a run file, and errlog and outlog file
+			fid=fopen([modelname '.errlog'],'w'); fclose(fid);
+			fid=fopen([modelname '.outlog'],'w'); fclose(fid);
+		end
+		%}}}
+		function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			if ~ispc,
+
+				%figure out what shell extension we will use:
+				if isempty(strfind(cluster.shell,'csh')),
+					shellext='sh';
+				else
+					shellext='csh';
+				end
+
+				disp('launching solution sequence');
+				launchcommand=['source  ' modelname '.queue '];
+				issmssh(cluster.name,'',0,launchcommand);
+			else
+				system([modelname '.bat']);
+			end
+		end %}}}
+		function Download(cluster,dirname,filelist)% {{{
+				%do nothing
+				return;
+		end %}}}
+	end
+end
Index: /issm/trunk/src/m/classes/clusters/greenplanet.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/greenplanet.m	(revision 19104)
+++ /issm/trunk/src/m/classes/clusters/greenplanet.m	(revision 19105)
@@ -9,15 +9,15 @@
     properties (SetAccess=public)  
 		 % {{{
-		 name='greenplanet'
-		 login='';
-		 numnodes=20;
-		 cpuspernode=8; 
-		 port=8000;
-		 queue='c6145';
-		 codepath='';
-		 executionpath='';
-		 interactive=0;
-		 time=24*60;
-		 memory=2;
+		 name          = 'greenplanet'
+		 login         = '';
+		 numnodes      = 20;
+		 cpuspernode   = 8;
+		 port          = 8000;
+		 queue         = 'c6145';
+		 codepath      = '';
+		 executionpath = '';
+		 interactive   = 0;
+		 time          = 24*60;
+		 memory        = 2;
 	 end
 	 properties (SetAccess=private) 
@@ -87,5 +87,7 @@
 			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
 			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
-			 %fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,dirname);
+			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
+			 fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,modelname);
 			 fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
 			 if ~io_gather, %concatenate the output files:
Index: /issm/trunk/src/m/classes/clusters/hpc.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/hpc.m	(revision 19105)
+++ /issm/trunk/src/m/classes/clusters/hpc.m	(revision 19105)
@@ -0,0 +1,162 @@
+%PFE class definition
+%
+%   Usage:
+%      cluster=hpc();
+%      cluster=hpc('np',3);
+%      cluster=hpc('np',3,'login','username');
+
+classdef hpc
+    properties (SetAccess=public)  
+		 % {{{
+		 name='hpc.oit.uci.edu'
+		 login='';
+		 numnodes=1;
+		 cpuspernode=4; 
+		 port=0;
+		 queue='pub64';
+		 codepath='';
+		 executionpath='';
+		 interactive=0;
+	 end
+	 properties (SetAccess=private) 
+		 np=20*8;
+		 % }}}
+	 end
+	 methods
+		 function cluster=hpc(varargin) % {{{
+
+			 %initialize cluster using default settings if provided
+			 if (exist('hpc_settings')==2), hpc_settings; end
+
+			 %use provided options to change fields
+			 cluster=AssignObjectFields(pairoptions(varargin{:}),cluster);
+		 end
+		 %}}}
+		 function disp(cluster) % {{{
+			 %  display the object
+			 disp(sprintf('class ''%s'' object ''%s'' = ',class(cluster),inputname(1)));
+			 disp(sprintf('    name: %s',cluster.name));
+			 disp(sprintf('    login: %s',cluster.login));
+			 disp(sprintf('    port: %i',cluster.port));
+			 disp(sprintf('    numnodes: %i',cluster.numnodes));
+			 disp(sprintf('    cpuspernode: %i',cluster.cpuspernode));
+			 disp(sprintf('    np: %i',cluster.cpuspernode*cluster.numnodes));
+			 disp(sprintf('    queue: %s',cluster.queue));
+			 disp(sprintf('    codepath: %s',cluster.codepath));
+			 disp(sprintf('    executionpath: %s',cluster.executionpath));
+			 disp(sprintf('    interactive: %i',cluster.interactive));
+		 end
+		 %}}}
+		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
+
+			 available_queues={'pub64','free64','free48','free*,pub64','free*'};
+			 queue_requirements_time=[Inf Inf Inf Inf Inf];
+			 queue_requirements_np=[64 64 48 48 48];
+
+			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,1)
+
+			 %Miscelaneous
+			 if isempty(cluster.login), md = checkmessage(md,'login empty'); end
+			 if isempty(cluster.codepath), md = checkmessage(md,'codepath empty'); end
+			 if isempty(cluster.executionpath), md = checkmessage(md,'executionpath empty'); end
+
+		 end
+		 %}}}
+		 function BuildKrigingQueueScript(cluster,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %compute number of processors
+			 cluster.np=cluster.numnodes*cluster.cpuspernode;
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#!/bin/bash\n');
+			 fprintf(fid,'#$ -N %s\n',modelname);
+			 fprintf(fid,'#$ -q %s \n',cluster.queue);
+			 fprintf(fid,'#$ -pe one-node-mpi 2-64\n');
+			 fprintf(fid,'#$ -R y\n');
+			 fprintf(fid,'#$ -m beas\n');
+			 fprintf(fid,'#$ -o %s.outlog \n',modelname);
+			 fprintf(fid,'#$ -e %s.errlog \n\n',modelname);
+			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
+			 fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,modelname);
+			 fprintf(fid,'mpiexec -np %i %s/kriging.exe %s %s\n',cluster.np,cluster.codepath,[cluster.executionpath '/' modelname],modelname);
+			 if ~io_gather, %concatenate the output files:
+				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			 end
+			 fclose(fid);
+		 end
+		 %}}}
+		 function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			 if(isvalgrind), disp('valgrind not supported by cluster, ignoring...'); end
+			 if(isgprof),    disp('gprof not supported by cluster, ignoring...'); end
+
+			 %compute number of processors
+			 cluster.np=cluster.numnodes*cluster.cpuspernode;
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#!/bin/bash\n');
+			 fprintf(fid,'#$ -N %s\n',modelname);
+			 fprintf(fid,'#$ -q %s \n',cluster.queue);
+			 fprintf(fid,'#$ -pe one-node-mpi 2-64\n');
+			 fprintf(fid,'#$ -R y\n');
+			 %fprintf(fid,'#$ -m beas\n');
+			 fprintf(fid,'#$ -o %s.outlog \n',modelname);
+			 fprintf(fid,'#$ -e %s.errlog \n\n',modelname);
+			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
+			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
+			 fprintf(fid,'cd %s/%s\n\n',cluster.executionpath,dirname);
+			 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 if ~io_gather, %concatenate the output files:
+				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+			 end
+			 fclose(fid);
+
+			 %in interactive mode, create a run file, and errlog and outlog file
+			 if cluster.interactive,
+				 fid=fopen([modelname '.run'],'w');
+				 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+				 if ~io_gather, %concatenate the output files:
+					 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+				 end
+				 fclose(fid);
+				 fid=fopen([modelname '.errlog'],'w');
+				 fclose(fid);
+				 fid=fopen([modelname '.outlog'],'w');
+				 fclose(fid);
+			 end
+		 end %}}}
+		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
+
+			 %compress the files into one zip.
+			 compressstring=['tar -zcf ' dirname '.tar.gz '];
+			 for i=1:numel(filelist),
+				 compressstring = [compressstring ' ' filelist{i}];
+			 end
+			 if cluster.interactive,
+				 compressstring = [compressstring ' ' modelname '.errlog ' modelname '.outlog '];
+			 end
+			 system(compressstring);
+
+			 disp('uploading input file and queueing script');
+			 issmscpout(cluster.name,cluster.executionpath,cluster.login,cluster.port,{[dirname '.tar.gz']});
+
+			 disp('launching solution sequence on remote cluster');
+			  launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+											 ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && hostname && qsub ' modelname '.queue '];
+			 issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
+		 end %}}}
+		 function Download(cluster,dirname,filelist)% {{{
+
+			 %copy files from cluster to current directory
+			 directory=[cluster.executionpath '/' dirname '/'];
+			 issmscpin(cluster.name,cluster.login,cluster.port,directory,filelist);
+
+		 end %}}}
+	end
+end
Index: /issm/trunk/src/m/classes/clusters/pfe.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/pfe.m	(revision 19104)
+++ /issm/trunk/src/m/classes/clusters/pfe.m	(revision 19105)
@@ -16,5 +16,5 @@
 		 queue          = 'long';
 		 time           = 12*60;
-		 processor      = 'neh';
+		 processor      = 'wes';
 		 codepath       = '';
 		 executionpath  = '';
@@ -126,9 +126,9 @@
 			 fprintf(fid,'#PBS -W group_list=%s\n',cluster.grouplist);
 			 fprintf(fid,'#PBS -m e\n');
-			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
-			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
+			 fprintf(fid,'#PBS -o %s.outlog \n',[cluster.executionpath '/' dirname '/' modelname]);
+			 fprintf(fid,'#PBS -e %s.errlog \n\n',[cluster.executionpath '/' dirname '/' modelname]);
 			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
-			 fprintf(fid,'module load comp-intel/2013.1.117\n');
-			 fprintf(fid,'module load mpi-sgi/mpt.2.06rp16\n');
+			 fprintf(fid,'module load comp-intel/2015.0.090\n');
+			 fprintf(fid,'module load mpi-sgi/mpt.2.11r13\n');
 			 fprintf(fid,'export PATH="$PATH:."\n\n');
 			 fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
@@ -136,5 +136,9 @@
 			 fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
 			 fprintf(fid,'cd %s/%s/\n\n',cluster.executionpath,dirname);
-			 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 if ~isvalgrind,
+				 fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 else
+				 fprintf(fid,'mpiexec -np %i valgrind --leak-check=full %s/issm.exe %s %s %s\n',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			 end
 			 if ~io_gather, %concatenate the output files:
 				 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
@@ -179,6 +183,6 @@
 			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
 			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
-			 fprintf(fid,'module load comp-intel/2013.1.117\n');
-			 fprintf(fid,'module load mpi-sgi/mpt.2.06rp16\n');
+			 fprintf(fid,'module load comp-intel/2015.0.090\n');
+			 fprintf(fid,'module load mpi-sgi/mpt.2.11r13\n');
 			 fprintf(fid,'export PATH="$PATH:."\n');
 			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
@@ -210,4 +214,32 @@
 			 end
 		 end %}}}
+		 function BuildOceanQueueScript(np,cluster,modelname) % {{{
+
+			 %write queuing script 
+			 fid=fopen([modelname '.queue'],'w');
+			 fprintf(fid,'#PBS -S /bin/bash\n');
+			 fprintf(fid,'#PBS -l select=1:ncpus=%i:model=%s\n',np,cluster.processor);
+			 fprintf(fid,'#PBS -l walltime=%i\n',cluster.time); %walltime is in seconds.
+			 fprintf(fid,'#PBS -q %s \n',cluster.queue);
+			 fprintf(fid,'#PBS -W group_list=%s\n',cluster.grouplist);
+			 fprintf(fid,'#PBS -m e\n');
+			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
+			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
+			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
+			 fprintf(fid,'module load comp-intel/2015.0.090\n');
+			 fprintf(fid,'module load test/mpt.2.11r8\n');
+			 fprintf(fid,'module load netcdf/4.0\n');
+			 fprintf(fid,'module load mpi-mvapich2/1.4.1/gcc\n');
+			 fprintf(fid,'module load gcc/4.4.4\n');
+			 fprintf(fid,'export PATH="$PATH:."\n');
+			 fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
+			 fprintf(fid,['cd ' pwd() ' \n\n']);
+			 fprintf(fid,'mpiexec -np %i ./mitgcmuv\n',np); 
+		%	 if ~io_gather, %concatenate the output files:
+		%		 fprintf(fid,'cat %s.outbin.* > %s.outbin',modelname,modelname);
+		%	 end
+			 fclose(fid);
+
+		 end %}}}
 		 function LaunchQueueJob(cluster,modelname,dirname,filelist)% {{{
 
Index: /issm/trunk/src/m/classes/constants.m
===================================================================
--- /issm/trunk/src/m/classes/constants.m	(revision 19104)
+++ /issm/trunk/src/m/classes/constants.m	(revision 19105)
@@ -6,55 +6,62 @@
 classdef constants
 	properties (SetAccess=public) 
-		g                    = 0;
-		yts                  = 0;
-		referencetemperature = 0;
+		g                    = 0.;
+		omega                = 0.;
+		yts                  = 0.;
+		referencetemperature = 0.;
 	end
 	methods
-        function createxml(obj,fid) % {{{
+        function createxml(self,fid) % {{{
             fprintf(fid, '\n\n');
             fprintf(fid, '%s\n', '<!-- constants -->');
-			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="g" type="',class(obj.g),'" default="',num2str(obj.g),'">','     <section name="constants" />','     <help> gravitational acceleration [m/s^2] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="yts" type="',class(obj.yts),'" default="',num2str(obj.yts),'">','     <section name="constants" />','     <help> number of seconds in a year [s/yr] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="referencetemperature" type="',class(obj.referencetemperature),'" default="',num2str(obj.referencetemperature),'">','     <section name="constants" />','     <help> reference temperature used in the enthalpy model [K] </help>','</parameter>');
+			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="g" type="',class(self.g),'" default="',num2str(self.g),'">','     <section name="constants" />','     <help> gravitational acceleration [m/s^2] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="yts" type="',class(self.yts),'" default="',num2str(self.yts),'">','     <section name="constants" />','     <help> number of seconds in a year [s/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="referencetemperature" type="',class(self.referencetemperature),'" default="',num2str(self.referencetemperature),'">','     <section name="constants" />','     <help> reference temperature used in the enthalpy model [K] </help>','</parameter>');
 		end % }}}
-		function obj = constants(varargin) % {{{
+		function self = constants(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%acceleration due to gravity (m/s^2)
-			obj.g=9.81;
+			self.g=9.81;
+
+			%Earth's rotation speed 
+			self.omega = 7.292*1e-5;
 
 			%converstion from year to seconds
-			obj.yts=365*24*3600;
+			self.yts=365*24*3600;
 
 			%the reference temperature for enthalpy model (cf Aschwanden)
-			obj.referencetemperature=223.15;
+			self.referencetemperature=223.15;
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
-%			md = checkfield(md,'fieldname','constants.g','>',0,'size',[1 1]);
+			md = checkfield(md,'fieldname','constants.g','>=',0,'size',[1 1]); %We allow 0 for validation tests
+			md = checkfield(md,'fieldname','constants.omega','>=',0,'size',[1 1]);
 			md = checkfield(md,'fieldname','constants.yts','>',0,'size',[1 1]);
 			md = checkfield(md,'fieldname','constants.referencetemperature','size',[1 1]);
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   constants parameters:'));
 
-			fielddisplay(obj,'g','gravitational acceleration [m/s^2]');
-			fielddisplay(obj,'yts','number of seconds in a year [s/yr]');
-			fielddisplay(obj,'referencetemperature','reference temperature used in the enthalpy model [K]');
+			fielddisplay(self,'g','gravitational acceleration [m/s^2]');
+			fielddisplay(self,'omega','angular velocity of Earth [rad/s]');
+			fielddisplay(self,'yts','number of seconds in a year [s/yr]');
+			fielddisplay(self,'referencetemperature','reference temperature used in the enthalpy model [K]');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','g','format','Double');
-			WriteData(fid,'object',obj,'fieldname','yts','format','Double');
-			WriteData(fid,'object',obj,'fieldname','referencetemperature','format','Double');
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','g','format','Double');
+			WriteData(fid,'object',self,'fieldname','omega','format','Double');
+			WriteData(fid,'object',self,'fieldname','yts','format','Double');
+			WriteData(fid,'object',self,'fieldname','referencetemperature','format','Double');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/damage.m
===================================================================
--- /issm/trunk/src/m/classes/damage.m	(revision 19104)
+++ /issm/trunk/src/m/classes/damage.m	(revision 19105)
@@ -32,10 +32,10 @@
 	end
 	methods
-		function createxml(obj,fid) % {{{
+		function createxml(self,fid) % {{{
 			fprintf(fid, '\n\n');
 			fprintf(fid, '%s\n', '<!-- damage -->');
 			fprintf(fid, '%s\n', '<!-- Note: this class depends on different input of law -->');
 
-			%fprintf(fid,'%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="law" type="logical"',           '" default="',                num2str(obj.law),'">',   '     <section name="damage" />','     <help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
+			%fprintf(fid,'%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="law" type="logical"',           '" default="',                num2str(self.law),'">',   '     <section name="damage" />','     <help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
 			% drop-down 
 			fprintf(fid,'%s%s%s%s%s\n\t%s\n','<parameter key ="law" type="','alternative','" optional="','false','">','<section name="damage" />');
@@ -49,12 +49,12 @@
 			fprintf(fid,'\t%s%s%s%s%s\n\t\t%s\n','<option value="pralong" type="','string','" default="','false','">','<help> law = pralong </help>');
 
-			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',   '<parameter key ="stress_threshold" type="',class(obj.stress_threshold),'" default="',num2str(obj.stress_threshold),'">','<help> damage stress threshold [Pa] </help>','</parameter>');
-			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',	'<parameter key ="c1" type="', class(obj.c1),'" default="',   num2str(obj.c1),'">',   '<help> damage parameter 1 </help>','</parameter>');
-			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c2" type="',          class(obj.c2),'" default="',            num2str(obj.c2),'">','<help> damage parameter 2 </help>','</parameter>');
-			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c3" type="',          class(obj.c3),'" default="',            num2str(obj.c3),'">','<help> damage parameter 3 [W/m^2] </help>','</parameter>');
-			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c4" type="',            class(obj.c4),'" default="',              num2str(obj.c4),'">','<help> damage parameter 4 </help>','</parameter>');
-			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="healing" type="', class(obj.healing),'" default="',   num2str(obj.healing),'">','<help> damage healing parameter 1 </help>','</parameter>');
-			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="equiv_stress" type="',          class(obj.equiv_stress),'" default="',convert2str(obj.equiv_stress),'">','<help> 0: von Mises </help>','</parameter>');
-			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="requested_outputs" type="',          class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','<help> additional outputs requested </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',   '<parameter key ="stress_threshold" type="',class(self.stress_threshold),'" default="',num2str(self.stress_threshold),'">','<help> damage stress threshold [Pa] </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',	'<parameter key ="c1" type="', class(self.c1),'" default="',   num2str(self.c1),'">',   '<help> damage parameter 1 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c2" type="',          class(self.c2),'" default="',            num2str(self.c2),'">','<help> damage parameter 2 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c3" type="',          class(self.c3),'" default="',            num2str(self.c3),'">','<help> damage parameter 3 [W/m^2] </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="c4" type="',            class(self.c4),'" default="',              num2str(self.c4),'">','<help> damage parameter 4 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="healing" type="', class(self.healing),'" default="',   num2str(self.healing),'">','<help> damage healing parameter 1 </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="equiv_stress" type="',          class(self.equiv_stress),'" default="',convert2str(self.equiv_stress),'">','<help> 0: von Mises </help>','</parameter>');
+			fprintf(fid,'\t\t%s%s%s%s%s\n\t\t\t%s\n\t\t%s\n',  	'<parameter key ="requested_outputs" type="',          class(self.requested_outputs),'" default="',convert2str(self.requested_outputs),'">','<help> additional outputs requested </help>','</parameter>');
 
 
@@ -67,8 +67,8 @@
 
 
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="D" type="',              class(obj.D),'" default="',                  num2str(obj.D),'">',              '     <section name="damage" />','     <help> damage tensor (scalar) </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="law" type="',            class(obj.law),'" default="',                num2str(obj.law),'">',   '     <section name="damage" />','     <help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="spcdamage" type="',      class(obj.spcdamage),'" default="',          num2str(obj.spcdamage),'">',            '     <section name="damage" />','     <help> damage constraints (NaN means no constraint) </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="max_damage" type="',     class(obj.max_damage),'" default="',         num2str(obj.max_damage),'">',            '     <section name="damage" />','     <help> maximum possible damage (0&amp;lt;=max_damage&amp;lt;1) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="D" type="',              class(self.D),'" default="',                  num2str(self.D),'">',              '     <section name="damage" />','     <help> damage tensor (scalar) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="law" type="',            class(self.law),'" default="',                num2str(self.law),'">',   '     <section name="damage" />','     <help> damage law (string) from {"undamaged","pralong"} </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="spcdamage" type="',      class(self.spcdamage),'" default="',          num2str(self.spcdamage),'">',            '     <section name="damage" />','     <help> damage constraints (NaN means no constraint) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="max_damage" type="',     class(self.max_damage),'" default="',         num2str(self.max_damage),'">',            '     <section name="damage" />','     <help> maximum possible damage (0&amp;lt;=max_damage&amp;lt;1) </help>','</parameter>');
 
 			% stabilization (0,1, or 2) drop-down
@@ -79,15 +79,14 @@
 			fprintf(fid, '%s\n','</parameter>');
 
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="maxiter" type="',             class(obj.maxiter),'" default="',   num2str(obj.maxiter),'">',   '     <section name="damage" />','     <help> maximum number of non linear iterations </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_lock" type="',        class(obj.penalty_lock),'" default="',            num2str(obj.penalty_lock),'">',            '     <section name="damage" />','     <help> stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_threshold" type="',   class(obj.penalty_threshold),'" default="',            num2str(obj.penalty_threshold),'">',            '     <section name="damage" />','     <help> threshold to declare convergence of damage evolution solution (default is 0) </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_factor" type="',      class(obj.penalty_factor),'" default="',            num2str(obj.penalty_factor),'">',            '     <section name="damage" />','     <help> scaling exponent (default is 3) </help>','</parameter>');
-
-		end % }}}
-        
-		function obj = damage(varargin) % {{{
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="maxiter" type="',             class(self.maxiter),'" default="',   num2str(self.maxiter),'">',   '     <section name="damage" />','     <help> maximum number of non linear iterations </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_lock" type="',        class(self.penalty_lock),'" default="',            num2str(self.penalty_lock),'">',            '     <section name="damage" />','     <help> stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_threshold" type="',   class(self.penalty_threshold),'" default="',            num2str(self.penalty_threshold),'">',            '     <section name="damage" />','     <help> threshold to declare convergence of damage evolution solution (default is 0) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="penalty_factor" type="',      class(self.penalty_factor),'" default="',            num2str(self.penalty_factor),'">',            '     <section name="damage" />','     <help> scaling exponent (default is 3) </help>','</parameter>');
+
+		end % }}}
+		function self = damage(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
 					inputstruct=varargin{1};
@@ -97,5 +96,5 @@
 						fieldname = list1{i};
 						if ismember(fieldname,list2),
-							obj.(fieldname) = inputstruct.(fieldname);
+							self.(fieldname) = inputstruct.(fieldname);
 						end
 					end
@@ -104,51 +103,55 @@
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = extrude(self,md) % {{{
+			self.D=project3d(md,'vector',self.D,'type','node');
+			self.spcdamage=project3d(md,'vector',self.spcdamage,'type','node');
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
 
 			%damage parameters: 
-			obj.isdamage=0;
-			obj.D=0;
-			obj.law=0;
-			
-			obj.max_damage=1-1e-5; %if damage reaches 1, solve becomes singular, as viscosity becomes nil
+			self.isdamage=0;
+			self.D=0;
+			self.law=0;
+			
+			self.max_damage=1-1e-5; %if damage reaches 1, solve becomes singular, as viscosity becomes nil
 		
 			%Type of stabilization used
-			obj.stabilization=2;
+			self.stabilization=2;
 			
 			%Maximum number of iterations
-			obj.maxiter=100;
+			self.maxiter=100;
 
 			%finite element interpolation
-			obj.elementinterp='P1';
+			self.elementinterp='P1';
 
 			%factor used to compute the values of the penalties: kappa=max(stiffness matrix)*10^penalty_factor
-			obj.penalty_factor=3;
+			self.penalty_factor=3;
 			
 			%stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization)
-			obj.penalty_lock=0;
+			self.penalty_lock=0;
 			
 			%threshold to declare convergence of thermal solution (default is 0)
-			obj.penalty_threshold=0;
+			self.penalty_threshold=0;
 		
 			%damage evolution parameters 
-			obj.stress_threshold=0;
-			obj.healing=0;
-			obj.c1=0;
-			obj.c2=0;
-			obj.c3=0;
-			obj.c4=0;
-			obj.equiv_stress=0;
+			self.stress_threshold=0;
+			self.healing=0;
+			self.c1=0;
+			self.c2=0;
+			self.c3=0;
+			self.c4=0;
+			self.equiv_stress=0;
 
 			 %output default:
-			 obj.requested_outputs={'default'};
-
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			 self.requested_outputs={'default'};
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 			
 			md = checkfield(md,'fieldname','damage.isdamage','values',[1,0]);
-			if obj.isdamage,
+			if self.isdamage,
 				md = checkfield(md,'fieldname','damage.law','numel',[1],'values',[0,1,2]);
-				md = checkfield(md,'fieldname','damage.D','>=',0,'<=',obj.max_damage,'size',[md.mesh.numberofvertices 1]);
-				md = checkfield(md,'fieldname','damage.spcdamage','forcing',1);
+				md = checkfield(md,'fieldname','damage.D','>=',0,'<=',self.max_damage,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','damage.spcdamage','timeseries',1);
 				md = checkfield(md,'fieldname','damage.max_damage','<',1,'>=',0);
 				md = checkfield(md,'fieldname','damage.stabilization','numel',[1],'values',[0 1 2]);
@@ -166,5 +169,5 @@
 				md = checkfield(md,'fieldname','damage.equiv_stress','numel',[1],'values',[0 1]);
 				md = checkfield(md,'fieldname','damage.requested_outputs','stringrow',1);
-			elseif (obj.law~=0),
+			elseif (self.law~=0),
 				if (solution==DamageEvolutionSolutionEnum),
 					error('Invalid evolution law (md.damage.law) for a damage solution');
@@ -180,63 +183,63 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   Damage:\n'));
 
-			fielddisplay(obj,'isdamage','is damage mechanics being used? {true,false}');
-			if obj.isdamage,
-				fielddisplay(obj,'law','damage law {''0: undamaged'',''1: pralong''}');
-				fielddisplay(obj,'D','damage tensor (scalar)');
-				fielddisplay(obj,'spcdamage','damage constraints (NaN means no constraint)');
-				fielddisplay(obj,'max_damage','maximum possible damage (0<=max_damage<1)');
+			fielddisplay(self,'isdamage','is damage mechanics being used? {true,false}');
+			if self.isdamage,
+				fielddisplay(self,'law','damage law {''0: undamaged'',''1: pralong''}');
+				fielddisplay(self,'D','damage tensor (scalar)');
+				fielddisplay(self,'spcdamage','damage constraints (NaN means no constraint)');
+				fielddisplay(self,'max_damage','maximum possible damage (0<=max_damage<1)');
 				
-				fielddisplay(obj,'stabilization','0: no, 1: artificial_diffusivity, 2: SUPG');
-				fielddisplay(obj,'maxiter','maximum number of non linear iterations');
-				fielddisplay(obj,'elementinterp','interpolation scheme for finite elements {''P1'',''P2''}');
-				fielddisplay(obj,'penalty_lock','stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
-				fielddisplay(obj,'penalty_threshold','threshold to declare convergence of damage evolution solution (default is 0)');
-				fielddisplay(obj,'penalty_factor','scaling exponent (default is 3)');
-				fielddisplay(obj,'c1','damage parameter 1');
-				fielddisplay(obj,'c2','damage parameter 2');
-				fielddisplay(obj,'c3','damage parameter 3');
-				fielddisplay(obj,'c4','damage parameter 4');
-				fielddisplay(obj,'healing','damage healing parameter');
-				fielddisplay(obj,'stress_threshold','damage stress threshold [Pa]');
-				fielddisplay(obj,'equiv_stress','0: von Mises, 1: max principal');
-				fielddisplay(obj,'requested_outputs','additional outputs requested');
-			end
-
-		end % }}}
-		function marshall(obj,md,fid) % {{{
-		
-			WriteData(fid,'object',obj,'fieldname','isdamage','format','Boolean');
-			if obj.isdamage,
-				WriteData(fid,'object',obj,'fieldname','law','format','Integer');
-				WriteData(fid,'object',obj,'fieldname','D','format','DoubleMat','mattype',1);
-				WriteData(fid,'object',obj,'fieldname','spcdamage','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-				WriteData(fid,'object',obj,'fieldname','max_damage','format','Double');
-
-				WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
-				WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
-				WriteData(fid,'enum',DamageElementinterpEnum(),'data',StringToEnum(obj.elementinterp),'format','Integer');
-				WriteData(fid,'object',obj,'fieldname','penalty_threshold','format','Integer');
-				WriteData(fid,'object',obj,'fieldname','penalty_lock','format','Integer');
-				WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
-				WriteData(fid,'object',obj,'fieldname','c1','format','Double');
-				WriteData(fid,'object',obj,'fieldname','c2','format','Double');
-				WriteData(fid,'object',obj,'fieldname','c3','format','Double');
-				WriteData(fid,'object',obj,'fieldname','c4','format','Double');
-				WriteData(fid,'object',obj,'fieldname','stress_threshold','format','Double');
-				WriteData(fid,'object',obj,'fieldname','healing','format','Double');
-				WriteData(fid,'object',obj,'fieldname','equiv_stress','format','Integer');
+				fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: SUPG');
+				fielddisplay(self,'maxiter','maximum number of non linear iterations');
+				fielddisplay(self,'elementinterp','interpolation scheme for finite elements {''P1'',''P2''}');
+				fielddisplay(self,'penalty_lock','stabilize unstable damage constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
+				fielddisplay(self,'penalty_threshold','threshold to declare convergence of damage evolution solution (default is 0)');
+				fielddisplay(self,'penalty_factor','scaling exponent (default is 3)');
+				fielddisplay(self,'c1','damage parameter 1');
+				fielddisplay(self,'c2','damage parameter 2');
+				fielddisplay(self,'c3','damage parameter 3');
+				fielddisplay(self,'c4','damage parameter 4');
+				fielddisplay(self,'healing','damage healing parameter');
+				fielddisplay(self,'stress_threshold','damage stress threshold [Pa]');
+				fielddisplay(self,'equiv_stress','0: von Mises, 1: max principal');
+				fielddisplay(self,'requested_outputs','additional outputs requested');
+			end
+
+		end % }}}
+		function marshall(self,md,fid) % {{{
+		
+			WriteData(fid,'object',self,'fieldname','isdamage','format','Boolean');
+			if self.isdamage,
+				WriteData(fid,'object',self,'fieldname','law','format','Integer');
+				WriteData(fid,'object',self,'fieldname','D','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'fieldname','spcdamage','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+				WriteData(fid,'object',self,'fieldname','max_damage','format','Double');
+
+				WriteData(fid,'object',self,'fieldname','stabilization','format','Integer');
+				WriteData(fid,'object',self,'fieldname','maxiter','format','Integer');
+				WriteData(fid,'enum',DamageElementinterpEnum(),'data',StringToEnum(self.elementinterp),'format','Integer');
+				WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer');
+				WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer');
+				WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double');
+				WriteData(fid,'object',self,'fieldname','c1','format','Double');
+				WriteData(fid,'object',self,'fieldname','c2','format','Double');
+				WriteData(fid,'object',self,'fieldname','c3','format','Double');
+				WriteData(fid,'object',self,'fieldname','c4','format','Double');
+				WriteData(fid,'object',self,'fieldname','stress_threshold','format','Double');
+				WriteData(fid,'object',self,'fieldname','healing','format','Double');
+				WriteData(fid,'object',self,'fieldname','equiv_stress','format','Integer');
 			end
 
 			%process requested outputs
-			outputs = obj.requested_outputs;
+			outputs = self.requested_outputs;
 			pos = find(ismember(outputs,'default'));
 			if ~isempty(pos),
 				outputs(pos) = [];                         %remove 'default' from outputs
-				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
-			end
-			if obj.isdamage,
+				outputs      = [outputs defaultoutputs(self,md)]; %add defaults
+			end
+			if self.isdamage,
 				WriteData(fid,'data',outputs,'enum',DamageEvolutionRequestedOutputsEnum,'format','StringArray');
 			end
Index: /issm/trunk/src/m/classes/damage.py
===================================================================
--- /issm/trunk/src/m/classes/damage.py	(revision 19104)
+++ /issm/trunk/src/m/classes/damage.py	(revision 19105)
@@ -1,3 +1,4 @@
 from fielddisplay import fielddisplay
+from project3d import project3d
 from EnumDefinitions import *
 from StringToEnum import StringToEnum
@@ -74,4 +75,9 @@
 		return s
 	# }}}
+	def extrude(self,md): # {{{
+		self.D=project3d(md,'vector',self.D,'type','node')
+		self.spcdamage=project3d(md,'vector',self.spcdamage,'type','node')
+		return self
+	#}}}
 	def setdefaultparameters(self):    # {{{
 
@@ -131,5 +137,5 @@
 			md = checkfield(md,'fieldname','damage.max_damage','<',1,'>=',0)
 			md = checkfield(md,'fieldname','damage.law','numel',[1],'values',[0,1,2,3])
-			md = checkfield(md,'fieldname','damage.spcdamage','forcing',1)
+			md = checkfield(md,'fieldname','damage.spcdamage','timeseries',1)
 			md = checkfield(md,'fieldname','damage.stabilization','numel',[1],'values',[0,1,2])
 			md = checkfield(md,'fieldname','damage.maxiter','>=0',0)
@@ -159,5 +165,5 @@
 			WriteData(fid,'object',self,'fieldname','D','format','DoubleMat','mattype',1)
 			WriteData(fid,'object',self,'fieldname','law','format','Integer')
-			WriteData(fid,'object',self,'fieldname','spcdamage','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',self,'fieldname','spcdamage','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
 			WriteData(fid,'object',self,'fieldname','max_damage','format','Double')
 			WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
Index: /issm/trunk/src/m/classes/debug.m
===================================================================
--- /issm/trunk/src/m/classes/debug.m	(revision 19104)
+++ /issm/trunk/src/m/classes/debug.m	(revision 19105)
@@ -11,5 +11,5 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
+        function createxml(self,fid) % {{{
             fprintf(fid, '\n\n');
             fprintf(fid, '%s\n', '<!-- Debug -->');
@@ -20,28 +20,28 @@
             fprintf(fid,'%s\n%s\n','       <option value="1" type="string" default="false"> </option>','</parameter>');
           
-            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="gprof" type="',              class(obj.gprof),'" optional="false">',              '     <section name="debug" />','        <option value="',convert2str(obj.gprof),'" type="string" default="true"></option>','     <help> use gnu-profiler to find out where the time is spent </help>','</parameter>');
-            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n',    '<parameter key ="profiling" type="',              class(obj.profiling),'" optional="false">',              '     <section name="debug" />','        <option value="',convert2str(obj.profiling),'" type="string" default="true"></option>','     <help> enables profiling (memory, flops, time) </help>','</parameter>');
+            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="gprof" type="',              class(self.gprof),'" optional="false">',              '     <section name="debug" />','        <option value="',convert2str(self.gprof),'" type="string" default="true"></option>','     <help> use gnu-profiler to find out where the time is spent </help>','</parameter>');
+            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n',    '<parameter key ="profiling" type="',              class(self.profiling),'" optional="false">',              '     <section name="debug" />','        <option value="',convert2str(self.profiling),'" type="string" default="true"></option>','     <help> enables profiling (memory, flops, time) </help>','</parameter>');
         end % }}}
-		function obj = debug(varargin) % {{{
+		function self = debug(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 				end
 			end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   debug parameters:'));
 
-			fielddisplay(obj,'valgrind','use Valgrind to debug (0 or 1)');
-			fielddisplay(obj,'gprof','use gnu-profiler to find out where the time is spent');
-			fielddisplay(obj,'profiling','enables profiling (memory, flops, time)');
+			fielddisplay(self,'valgrind','use Valgrind to debug (0 or 1)');
+			fielddisplay(self,'gprof','use gnu-profiler to find out where the time is spent');
+			fielddisplay(self,'profiling','enables profiling (memory, flops, time)');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','profiling','format','Boolean');
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','profiling','format','Boolean');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/dependent.m
===================================================================
--- /issm/trunk/src/m/classes/dependent.m	(revision 19104)
+++ /issm/trunk/src/m/classes/dependent.m	(revision 19105)
@@ -15,45 +15,45 @@
 	end
 	methods
-		function obj = dependent(varargin) % {{{
+		function self = dependent(varargin) % {{{
 
 			%use provided options to change fields
 			options=pairoptions(varargin{:});
 
-			obj.name=getfieldvalue(options,'name','');
-			obj.type=getfieldvalue(options,'type','');
-			obj.exp=getfieldvalue(options,'exp','');
-			obj.segments=getfieldvalue(options,'segments',[]);
-			obj.index=getfieldvalue(options,'index',-1);
-			obj.nods=getfieldvalue(options,'nods',0);
+			self.name=getfieldvalue(options,'name','');
+			self.type=getfieldvalue(options,'type','');
+			self.exp=getfieldvalue(options,'exp','');
+			self.segments=getfieldvalue(options,'segments',[]);
+			self.index=getfieldvalue(options,'index',-1);
+			self.nods=getfieldvalue(options,'nods',0);
 
 			%if name is mass flux: 
-			if strcmpi(obj.name,'MassFlux'),
+			if strcmpi(self.name,'MassFlux'),
 				%make sure that we supplied a file and that it exists! 
-				if exist(obj.exp)~=2,
+				if exist(self.exp)~=2,
 					error('dependent checkconsistency: specified ''exp'' file does not exist!');
 				end
 				%process the file and retrieve segments
 				mesh=getfieldvalue(options,'mesh');
-				obj.segments=MeshProfileIntersection(mesh.elements,mesh.x,mesh.y,obj.exp);
+				self.segments=MeshProfileIntersection(mesh.elements,mesh.x,mesh.y,self.exp);
 			end
 		end
 		%}}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 			%do nothing
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
-			if strcmpi(obj.name,'MassFlux'),
-				if isempty(obj.segments),
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+			if strcmpi(self.name,'MassFlux'),
+				if isempty(self.segments),
 					error('dependent checkconsistency error: need segments to compute this dependent response');
 				end
-				if obj.index<=0,
+				if self.index<=0,
 					error('dependent checkconsistency error: index for segments should be >=1');
 				end
 			end
-			if ~isnan(obj.fos_reverse_index),
+			if ~isnan(self.fos_reverse_index),
 				if ~strcmpi(driver,'fos_reverse'),
 					error('cannot declare a dependent with a fos_reverse_index when the driver is not fos_reverse!');
 				end
-				if obj.nods==0,
+				if self.nods==0,
 					error('dependent checkconsistency error: nods should be set to the size of the independent variable');
 				end
@@ -61,23 +61,23 @@
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   dependent variable:'));
 
-			fielddisplay(obj,'name','variable name (must match corresponding Enum)');
-			fielddisplay(obj,'type','type of variable (''vertex'' or ''scalar'')');
+			fielddisplay(self,'name','variable name (must match corresponding Enum)');
+			fielddisplay(self,'type','type of variable (''vertex'' or ''scalar'')');
 
-			if ~isnan(obj.fos_reverse_index),
-				fielddisplay(obj,'fos_reverse_index','index for fos_reverse driver of ADOLC');
+			if ~isnan(self.fos_reverse_index),
+				fielddisplay(self,'fos_reverse_index','index for fos_reverse driver of ADOLC');
 			end
-			if ~isempty(obj.exp),
-				fielddisplay(obj,'exp','file needed to compute dependent variable');
-				fielddisplay(obj,'segments','mass flux segments');
+			if ~isempty(self.exp),
+				fielddisplay(self,'exp','file needed to compute dependent variable');
+				fielddisplay(self,'segments','mass flux segments');
 			end
 
 		end % }}}
-		function scalar=typetoscalar(obj) % {{{
-			if strcmpi(obj.type,'scalar'),
+		function scalar=typetoscalar(self) % {{{
+			if strcmpi(self.type,'scalar'),
 				scalar=0;
-			elseif strcmpi(obj.type,'vertex'),
+			elseif strcmpi(self.type,'vertex'),
 				scalar=1;
 			end
Index: /issm/trunk/src/m/classes/flaim.m
===================================================================
--- /issm/trunk/src/m/classes/flaim.m	(revision 19104)
+++ /issm/trunk/src/m/classes/flaim.m	(revision 19105)
@@ -21,49 +21,49 @@
 	end
 	methods
-  	 	function createxml(obj,fid) % {{{
+  	 	function createxml(self,fid) % {{{
             fprintf(fid, '<!-- flaim -->\n');            
                     
             % Input
             fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Input:">','<section name="flaim" />');                    
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="targets" type="',class(obj.targets),'" default="',convert2str(obj.targets),'">','     <section name="flaim" />','     <help> name of kml output targets file </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="tracks" type="',class(obj.tracks),'" default="',convert2str(obj.tracks),'">','     <section name="flaim" />','     <help> name of kml input tracks file </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="flightreqs" type="',class(obj.flightreqs),'" default="',convert2str(obj.flightreqs),'">','     <section name="flaim" />','     <help> structure of kml flight requirements (not used yet) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="criterion" type="',class(obj.criterion),'" default="',convert2str(obj.criterion),'">','     <section name="flaim" />','     <help> element or nodal criterion for flight path evaluation (metric) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="targets" type="',class(self.targets),'" default="',convert2str(self.targets),'">','     <section name="flaim" />','     <help> name of kml output targets file </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="tracks" type="',class(self.tracks),'" default="',convert2str(self.tracks),'">','     <section name="flaim" />','     <help> name of kml input tracks file </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="flightreqs" type="',class(self.flightreqs),'" default="',convert2str(self.flightreqs),'">','     <section name="flaim" />','     <help> structure of kml flight requirements (not used yet) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="criterion" type="',class(self.criterion),'" default="',convert2str(self.criterion),'">','     <section name="flaim" />','     <help> element or nodal criterion for flight path evaluation (metric) </help>','  </parameter>');
         	fprintf(fid,'%s\n%s\n','</frame>');    
             
             % Arguments
             fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Arguments:">','<section name="flaim" />');                    
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gridsatequator" type="',class(obj.gridsatequator),'" default="',convert2str(obj.gridsatequator),'">','     <section name="flaim" />','     <help> number of grids at equator (determines resolution) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="usevalueordering" type="',class(obj.usevalueordering),'" optional="false">','     <section name="flaim" />','         <option value="',convert2str(obj.usevalueordering),'" type="string" default="true"></option>','     <help> flag to consider target values for flight path evaluation </help>','  </parameter>');
-            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="split_antimeridian" type="',class(obj.split_antimeridian),'" optional="false">','     <section name="flaim" />','         <option value="',convert2str(obj.split_antimeridian),'" type="string" default="true"></option>','     <help> flag to split polygons on the antimeridian </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gridsatequator" type="',class(self.gridsatequator),'" default="',convert2str(self.gridsatequator),'">','     <section name="flaim" />','     <help> number of grids at equator (determines resolution) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="usevalueordering" type="',class(self.usevalueordering),'" optional="false">','     <section name="flaim" />','         <option value="',convert2str(self.usevalueordering),'" type="string" default="true"></option>','     <help> flag to consider target values for flight path evaluation </help>','  </parameter>');
+            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="split_antimeridian" type="',class(self.split_antimeridian),'" optional="false">','     <section name="flaim" />','         <option value="',convert2str(self.split_antimeridian),'" type="string" default="true"></option>','     <help> flag to split polygons on the antimeridian </help>','  </parameter>');
             fprintf(fid,'%s\n%s\n','</frame>');   
             
             % Optimization
             fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Optimization:">','<section name="flaim" />');                    
-            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="path_optimize" type="',class(obj.path_optimize),'" optional="false">','     <section name="flaim" />','         <option value="',convert2str(obj.path_optimize),'" type="string" default="true"></option>','     <help> optimize? (default false) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="opt_ndir" type="',class(obj.opt_ndir),'" default="',convert2str(obj.opt_ndir),'">','     <section name="flaim" />','     <help> number of directions to test when moving a point.  If this value = 1, a random direction is tested. A value > 1 results in directions equally spaced from [0, 2*PI] being tested. For example, 4 would result in directions [0, PI/2, PI, 3PI/2] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="opt_dist" type="',class(obj.opt_dist),'" default="',convert2str(obj.opt_dist),'">','     <section name="flaim" />','     <help> specifies the distance in km (default 25) to move a randomly selected path point on each iteration </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="opt_niter" type="',class(obj.opt_niter),'" default="',convert2str(obj.opt_niter),'">','     <section name="flaim" />','     <help> number of iterations (default 30,000) to run for flightplan optimization, i.e. the number of times to randomly select a point and move it. </help>','  </parameter>');
+            fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n','  <parameter key ="path_optimize" type="',class(self.path_optimize),'" optional="false">','     <section name="flaim" />','         <option value="',convert2str(self.path_optimize),'" type="string" default="true"></option>','     <help> optimize? (default false) </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="opt_ndir" type="',class(self.opt_ndir),'" default="',convert2str(self.opt_ndir),'">','     <section name="flaim" />','     <help> number of directions to test when moving a point.  If this value = 1, a random direction is tested. A value > 1 results in directions equally spaced from [0, 2*PI] being tested. For example, 4 would result in directions [0, PI/2, PI, 3PI/2] </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="opt_dist" type="',class(self.opt_dist),'" default="',convert2str(self.opt_dist),'">','     <section name="flaim" />','     <help> specifies the distance in km (default 25) to move a randomly selected path point on each iteration </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="opt_niter" type="',class(self.opt_niter),'" default="',convert2str(self.opt_niter),'">','     <section name="flaim" />','     <help> number of iterations (default 30,000) to run for flightplan optimization, i.e. the number of times to randomly select a point and move it. </help>','  </parameter>');
         	fprintf(fid,'%s\n%s\n','</frame>');     
             
             % Output
             fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Output:">','<section name="flaim" />');                    
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="solution" type="',class(obj.solution),'" default="',convert2str(obj.solution),'">','     <section name="flaim" />','     <help> name of kml solution file </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="quality" type="',class(obj.quality),'" default="',convert2str(obj.quality),'">','     <section name="flaim" />','     <help> quality of kml solution </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="solution" type="',class(self.solution),'" default="',convert2str(self.solution),'">','     <section name="flaim" />','     <help> name of kml solution file </help>','  </parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="quality" type="',class(self.quality),'" default="',convert2str(self.quality),'">','     <section name="flaim" />','     <help> quality of kml solution </help>','  </parameter>');
             fprintf(fid,'%s\n%s\n','</frame>');              
         
         end % }}}
-		function obj = flaim(varargin) % {{{
+		function self = flaim(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
@@ -78,31 +78,31 @@
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 
 			disp(sprintf('   FLAIM - Flight Line Adaptation using Ice sheet Modeling:')); 
 
 			disp(sprintf('\n      Input:'));
-			fielddisplay(obj,'targets'            ,'name of kml output targets file ');
-			fielddisplay(obj,'tracks'             ,'name of kml input tracks file ');
-			fielddisplay(obj,'flightreqs'         ,'structure of kml flight requirements (not used yet)');
-			fielddisplay(obj,'criterion'          ,'element or nodal criterion for flight path evaluation (metric)');
+			fielddisplay(self,'targets'            ,'name of kml output targets file ');
+			fielddisplay(self,'tracks'             ,'name of kml input tracks file ');
+			fielddisplay(self,'flightreqs'         ,'structure of kml flight requirements (not used yet)');
+			fielddisplay(self,'criterion'          ,'element or nodal criterion for flight path evaluation (metric)');
 
 			disp(sprintf('\n      Arguments:'));
-			fielddisplay(obj,'gridsatequator'     ,'number of grids at equator (determines resolution)');
-			fielddisplay(obj,'usevalueordering'   ,'flag to consider target values for flight path evaluation');
-			fielddisplay(obj,'split_antimeridian' ,'flag to split polygons on the antimeridian');
+			fielddisplay(self,'gridsatequator'     ,'number of grids at equator (determines resolution)');
+			fielddisplay(self,'usevalueordering'   ,'flag to consider target values for flight path evaluation');
+			fielddisplay(self,'split_antimeridian' ,'flag to split polygons on the antimeridian');
 
 			disp(sprintf('\n      Optimization:'));
-			fielddisplay(obj,'path_optimize'     ,'optimize? (default false)');
-			fielddisplay(obj,'opt_ndir'     ,{'number of directions to test when moving a point.  If this value = 1, a random direction is tested.',...
+			fielddisplay(self,'path_optimize'     ,'optimize? (default false)');
+			fielddisplay(self,'opt_ndir'     ,{'number of directions to test when moving a point.  If this value = 1, a random direction is tested.',...
 											  'A value > 1 results in directions equally spaced from [0, 2*PI] being tested.',...
 											  'For example, 4 would result in directions [0, PI/2, PI, 3PI/2].'});
-			fielddisplay(obj,'opt_dist'     ,'specifies the distance in km (default 25) to move a randomly selected path point on each iteration');
-			fielddisplay(obj,'opt_niter'     ,{'number of iterations (default 30,000) to run for flightplan optimization',...
+			fielddisplay(self,'opt_dist'     ,'specifies the distance in km (default 25) to move a randomly selected path point on each iteration');
+			fielddisplay(self,'opt_niter'     ,{'number of iterations (default 30,000) to run for flightplan optimization',...
 											   'i.e. the number of times to randomly select a point and move it.'});
 
 			disp(sprintf('\n      Output:'));
-			fielddisplay(obj,'solution'           ,'name of kml solution file');
-			fielddisplay(obj,'quality'            ,'quality of kml solution');
+			fielddisplay(self,'solution'           ,'name of kml solution file');
+			fielddisplay(self,'quality'            ,'quality of kml solution');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/flowequation.m
===================================================================
--- /issm/trunk/src/m/classes/flowequation.m	(revision 19104)
+++ /issm/trunk/src/m/classes/flowequation.m	(revision 19105)
@@ -26,5 +26,5 @@
 	end
 	methods (Static)
-		function obj = loadobj(obj) % {{{
+		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
@@ -44,17 +44,17 @@
 			end
 
-			if isstruct(obj)
+			if isstruct(self)
 				disp('Recovering flowequation from older version');
-				objstruct = obj;
-				obj = structtoobj(flowequation(),objstruct);
+				objstruct = self;
+				self = structtoobj(flowequation(),objstruct);
 
 				%2013 July 23rd
-				if isfield(objstruct,'ishutter'),      obj.isSIA     = objstruct.ishutter;       end; 
-				if isfield(objstruct,'ismacayeal'),    obj.isSSA     = objstruct.ismacayeal;     end; 
-				if isfield(objstruct,'ispattyn'),      obj.isHO      = objstruct.ispattyn;       end; 
-				if isfield(objstruct,'isstokes'),      obj.isFS      = objstruct.isstokes;       end; 
-				if isfield(objstruct,'bordermacayeal'),obj.borderSSA = objstruct.bordermacayeal; end; 
-				if isfield(objstruct,'borderpattyn'),  obj.borderHO  = objstruct.borderpattyn;   end; 
-				if isfield(objstruct,'borderstokes'),  obj.borderFS  = objstruct.borderstokes;   end; 
+				if isfield(objstruct,'ishutter'),      self.isSIA     = objstruct.ishutter;       end; 
+				if isfield(objstruct,'ismacayeal'),    self.isSSA     = objstruct.ismacayeal;     end; 
+				if isfield(objstruct,'ispattyn'),      self.isHO      = objstruct.ispattyn;       end; 
+				if isfield(objstruct,'isstokes'),      self.isFS      = objstruct.isstokes;       end; 
+				if isfield(objstruct,'bordermacayeal'),self.borderSSA = objstruct.bordermacayeal; end; 
+				if isfield(objstruct,'borderpattyn'),  self.borderHO  = objstruct.borderpattyn;   end; 
+				if isfield(objstruct,'borderstokes'),  self.borderFS  = objstruct.borderstokes;   end; 
 			end
 
@@ -62,15 +62,15 @@
 	end
 	methods
-		function createxml(obj,fid) % {{{
+		function createxml(self,fid) % {{{
 			fprintf(fid, '\n\n');
 			fprintf(fid, '%s\n', '<!-- flowequation -->');
 			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Flow equation parameters">','<section name="flowequation" />');                    
 
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isSIA" type="',              class(obj.isSIA),'" default="',                  convert2str(obj.isSIA),'">',              '     <section name="flowequation" />','     <help> is the Shallow Ice Approximation (SIA) used ? </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isSSA" type="',            class(obj.isSSA),'" default="',                convert2str(obj.isSSA),'">',   '     <section name="flowequation" />','     <help> is the Shelfy-Stream Approximation (SSA) used ? </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="isL1L2" type="',      class(obj.isL1L2),'" default="',          convert2str(obj.isL1L2),'">',            '     <section name="flowequation" />','     <help> is the L1L2 approximation used ? </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="isHO" type="',     class(obj.isHO),'" default="',         convert2str(obj.isHO),'">',            '     <section name="flowequation" />','     <help> is the Higher-Order (HO) approximation used ? </help>','</parameter>');
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isFS" type="',       class(obj.isFS),'" default="',              convert2str(obj.isFS),'">',              '     <section name="flowequation" />','     <help> are the Full-FS (FS) equations used ? </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isSIA" type="',              class(self.isSIA),'" default="',                  convert2str(self.isSIA),'">',              '     <section name="flowequation" />','     <help> is the Shallow Ice Approximation (SIA) used ? </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isSSA" type="',            class(self.isSSA),'" default="',                convert2str(self.isSSA),'">',   '     <section name="flowequation" />','     <help> is the Shelfy-Stream Approximation (SSA) used ? </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="isL1L2" type="',      class(self.isL1L2),'" default="',          convert2str(self.isL1L2),'">',            '     <section name="flowequation" />','     <help> is the L1L2 approximation used ? </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="isHO" type="',     class(self.isHO),'" default="',         convert2str(self.isHO),'">',            '     <section name="flowequation" />','     <help> is the Higher-Order (HO) approximation used ? </help>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="isFS" type="',       class(self.isFS),'" default="',              convert2str(self.isFS),'">',              '     <section name="flowequation" />','     <help> are the Full-FS (FS) equations used ? </help>','</parameter>');
 
 			% fe_SSA drop-down (P1, P1bubble, P1bubblecondensed, P2)
@@ -98,71 +98,82 @@
 			fprintf(fid,'%s\n%s\n','       <option value="TaylorHood" type="string" default="false"> </option>','</parameter>');
 
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="vertex_equation" type="',      class(obj.vertex_equation),'" default="',            convert2str(obj.vertex_equation),'">',            '     <section name="flowequation" />','     <help> flow equation for each vertex </help>','</parameter>');
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="element_equation" type="',            class(obj.element_equation),'" default="',              convert2str(obj.element_equation),'">',              '     <section name="flowequation" />','     <help> flow equation for each element </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="borderSSA" type="', class(obj.borderSSA),'" default="',   convert2str(obj.borderSSA),'">',   '     <section name="flowequation" />','     <help> vertices on SSAs border (for tiling) </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="borderHO" type="',          class(obj.borderHO),'" default="',            convert2str(obj.borderHO),'">',            '     <section name="flowequation" />','     <help> vertices on HOs border (for tiling) </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="borderFS" type="',          class(obj.borderFS),'" default="',            convert2str(obj.borderFS),'">',            '     <section name="flowequation" />','     <help> vertices on FS border (for tiling) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="vertex_equation" type="',      class(self.vertex_equation),'" default="',            convert2str(self.vertex_equation),'">',            '     <section name="flowequation" />','     <help> flow equation for each vertex </help>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="element_equation" type="',            class(self.element_equation),'" default="',              convert2str(self.element_equation),'">',              '     <section name="flowequation" />','     <help> flow equation for each element </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="borderSSA" type="', class(self.borderSSA),'" default="',   convert2str(self.borderSSA),'">',   '     <section name="flowequation" />','     <help> vertices on SSAs border (for tiling) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="borderHO" type="',          class(self.borderHO),'" default="',            convert2str(self.borderHO),'">',            '     <section name="flowequation" />','     <help> vertices on HOs border (for tiling) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="borderFS" type="',          class(self.borderFS),'" default="',            convert2str(self.borderFS),'">',            '     <section name="flowequation" />','     <help> vertices on FS border (for tiling) </help>','</parameter>');
 
 			fprintf(fid,'%s\n%s\n','</frame>');
 		end % }}}
-		function obj = flowequation(varargin) % {{{
+		function self = extrude(self,md) % {{{
+			self.element_equation=project3d(md,'vector',self.element_equation,'type','element');
+			self.vertex_equation=project3d(md,'vector',self.vertex_equation,'type','node');
+			self.borderSSA=project3d(md,'vector',self.borderSSA,'type','node');
+			self.borderHO=project3d(md,'vector',self.borderHO,'type','node');
+			self.borderFS=project3d(md,'vector',self.borderFS,'type','node');
+		end % }}}
+		function self = flowequation(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%P1 for SSA
-			obj.fe_SSA= 'P1';
+			self.fe_SSA= 'P1';
 
 			%P1 for HO
-			obj.fe_HO= 'P1';
+			self.fe_HO= 'P1';
 
 			%MINI condensed element for FS by default
-			obj.fe_FS = 'MINIcondensed';
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
-
-			if ismember(StressbalanceAnalysisEnum(),analyses),
-
-				md = checkfield(md,'fieldname','flowequation.isSIA','numel',[1],'values',[0 1]);
-				md = checkfield(md,'fieldname','flowequation.isSSA','numel',[1],'values',[0 1]);
-				md = checkfield(md,'fieldname','flowequation.isL1L2','numel',[1],'values',[0 1]);
-				md = checkfield(md,'fieldname','flowequation.isHO','numel',[1],'values',[0 1]);
-				md = checkfield(md,'fieldname','flowequation.isFS','numel',[1],'values',[0 1]);
-				md = checkfield(md,'fieldname','flowequation.fe_SSA','values',{'P1','P1bubble','P1bubblecondensed','P2','P2bubble'});
-				md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',{'P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'});
-				md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',{'P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','LATaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart'});
-				md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_r','numel',[1],'>',0.);
-				md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rlambda','numel',[1],'>',0.);
-				md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rhop','numel',[1],'>',0.);
-				md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rholambda','numel',[1],'>',0.);
-				md = checkfield(md,'fieldname','flowequation.XTH_theta','numel',[1],'>=',0.,'<',0.5);
-				md = checkfield(md,'fieldname','flowequation.borderSSA','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-				md = checkfield(md,'fieldname','flowequation.borderHO','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-				md = checkfield(md,'fieldname','flowequation.borderFS','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-				if strcmp(domaintype(md.mesh),'2Dhorizontal')
-					md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[1:2]);
-					md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[1:2]);
-				elseif strcmp(domaintype(md.mesh),'2Dvertical')
-					md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[2,4,5]);
-					md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[2,4,5]);
-				elseif strcmp(domaintype(md.mesh),'3D'),
-					md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[0:8]);
-					md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[0:8]);
-				else
-					error('Case not supported yet');
-				end
-				if ~(obj.isSIA || obj.isSSA || obj.isL1L2 || obj.isHO || obj.isFS),
-					md = checkmessage(md,['no element types set for this model']);
-				end
+			self.fe_FS = 'MINIcondensed';
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+
+			%Early return
+			if (~ismember(StressbalanceAnalysisEnum(),analyses) & ~ismember(StressbalanceSIAAnalysisEnum(),analyses)) | (solution==TransientSolutionEnum() & md.transient.isstressbalance==0), return; end
+
+			md = checkfield(md,'fieldname','flowequation.isSIA','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','flowequation.isSSA','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','flowequation.isL1L2','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','flowequation.isHO','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','flowequation.isFS','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','flowequation.fe_SSA','values',{'P1','P1bubble','P1bubblecondensed','P2','P2bubble'});
+			md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',{'P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'});
+			md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',{'P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','LATaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart','LACrouzeixRaviart'});
+			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_r','numel',[1],'>',0.);
+			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rlambda','numel',[1],'>',0.);
+			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rhop','numel',[1],'>',0.);
+			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rholambda','numel',[1],'>',0.);
+			md = checkfield(md,'fieldname','flowequation.XTH_theta','numel',[1],'>=',0.,'<',0.5);
+			md = checkfield(md,'fieldname','flowequation.borderSSA','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'fieldname','flowequation.borderHO','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'fieldname','flowequation.borderFS','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			if strcmp(domaintype(md.mesh),'2Dhorizontal')
+				md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[1:2]);
+				md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[1:2]);
+			elseif strcmp(domaintype(md.mesh),'3Dsurface')
+				md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[1:2]);
+				md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[1:2]);
+			elseif strcmp(domaintype(md.mesh),'2Dvertical')
+				md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[2,4,5]);
+				md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[2,4,5]);
+			elseif strcmp(domaintype(md.mesh),'3D'),
+				md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[0:8]);
+				md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[0:8]);
+			else
+				error('Case not supported yet');
+			end
+			if ~(self.isSIA || self.isSSA || self.isL1L2 || self.isHO || self.isFS),
+				md = checkmessage(md,['no element types set for this model']);
 			end
 			if ismember(StressbalanceSIAAnalysisEnum(),analyses),
-				if any(obj.element_equation==1),
-					if(obj.vertex_equation & md.mask.groundedice_levelset<0.),
+				if any(self.element_equation==1),
+					if(self.vertex_equation & md.mask.groundedice_levelset<0.),
 						disp(sprintf('\n !!! Warning: SIA''s model is not consistent on ice shelves !!!\n'));
 					end
@@ -171,41 +182,41 @@
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   flow equation parameters:'));
 
-			fielddisplay(obj,'isSIA','is the Shallow Ice Approximation (SIA) used ?');
-			fielddisplay(obj,'isSSA','is the Shelfy-Stream Approximation (SSA) used ?');
-			fielddisplay(obj,'isL1L2','is the L1L2 approximation used ?');
-			fielddisplay(obj,'isHO','is the Higher-Order (HO) approximation used ?');
-			fielddisplay(obj,'isFS','are the Full-FS (FS) equations used ?');
-			fielddisplay(obj,'fe_SSA','Finite Element for SSA  ''P1'', ''P1bubble'' ''P1bubblecondensed'' ''P2''');
-			fielddisplay(obj,'fe_HO', 'Finite Element for HO   ''P1'' ''P1bubble'' ''P1bubblecondensed'' ''P1xP2'' ''P2xP1'' ''P2''');
-			fielddisplay(obj,'fe_FS', 'Finite Element for FS   ''P1P1'' (debugging only) ''P1P1GLS'' ''MINIcondensed'' ''MINI'' ''TaylorHood'' ''XTaylorHood''');
-			fielddisplay(obj,'vertex_equation','flow equation for each vertex');
-			fielddisplay(obj,'element_equation','flow equation for each element');
-			fielddisplay(obj,'borderSSA','vertices on SSA''s border (for tiling)');
-			fielddisplay(obj,'borderHO','vertices on HO''s border (for tiling)');
-			fielddisplay(obj,'borderFS','vertices on FS'' border (for tiling)');
-
-		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','isSIA','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isSSA','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isL1L2','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isHO','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isFS','format','Boolean');
-			WriteData(fid,'enum',FlowequationFeSSAEnum(),'data',StringToEnum(obj.fe_SSA),'format','Integer');
-			WriteData(fid,'enum',FlowequationFeHOEnum() ,'data',StringToEnum(obj.fe_HO) ,'format','Integer');
-			WriteData(fid,'enum',FlowequationFeFSEnum() ,'data',StringToEnum(obj.fe_FS) ,'format','Integer');
-			WriteData(fid,'enum',AugmentedLagrangianREnum(),'data',obj.augmented_lagrangian_r ,'format','Double');
-			WriteData(fid,'enum',AugmentedLagrangianRhopEnum(),'data',obj.augmented_lagrangian_rhop ,'format','Double');
-			WriteData(fid,'enum',AugmentedLagrangianRlambdaEnum(),'data',obj.augmented_lagrangian_rlambda ,'format','Double');
-			WriteData(fid,'enum',AugmentedLagrangianRholambdaEnum(),'data',obj.augmented_lagrangian_rholambda ,'format','Double');
-			WriteData(fid,'enum',AugmentedLagrangianThetaEnum() ,'data',obj.XTH_theta ,'format','Double');
-			WriteData(fid,'object',obj,'fieldname','borderSSA','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','borderHO','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','borderFS','format','DoubleMat','mattype',1);
+			fielddisplay(self,'isSIA','is the Shallow Ice Approximation (SIA) used ?');
+			fielddisplay(self,'isSSA','is the Shelfy-Stream Approximation (SSA) used ?');
+			fielddisplay(self,'isL1L2','is the L1L2 approximation used ?');
+			fielddisplay(self,'isHO','is the Higher-Order (HO) approximation used ?');
+			fielddisplay(self,'isFS','are the Full-FS (FS) equations used ?');
+			fielddisplay(self,'fe_SSA','Finite Element for SSA  ''P1'', ''P1bubble'' ''P1bubblecondensed'' ''P2''');
+			fielddisplay(self,'fe_HO', 'Finite Element for HO   ''P1'' ''P1bubble'' ''P1bubblecondensed'' ''P1xP2'' ''P2xP1'' ''P2''');
+			fielddisplay(self,'fe_FS', 'Finite Element for FS   ''P1P1'' (debugging only) ''P1P1GLS'' ''MINIcondensed'' ''MINI'' ''TaylorHood'' ''XTaylorHood''');
+			fielddisplay(self,'vertex_equation','flow equation for each vertex');
+			fielddisplay(self,'element_equation','flow equation for each element');
+			fielddisplay(self,'borderSSA','vertices on SSA''s border (for tiling)');
+			fielddisplay(self,'borderHO','vertices on HO''s border (for tiling)');
+			fielddisplay(self,'borderFS','vertices on FS'' border (for tiling)');
+
+		end % }}}
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','isSIA','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','isSSA','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','isL1L2','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','isHO','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','isFS','format','Boolean');
+			WriteData(fid,'enum',FlowequationFeSSAEnum(),'data',StringToEnum(self.fe_SSA),'format','Integer');
+			WriteData(fid,'enum',FlowequationFeHOEnum() ,'data',StringToEnum(self.fe_HO) ,'format','Integer');
+			WriteData(fid,'enum',FlowequationFeFSEnum() ,'data',StringToEnum(self.fe_FS) ,'format','Integer');
+			WriteData(fid,'enum',AugmentedLagrangianREnum(),'data',self.augmented_lagrangian_r ,'format','Double');
+			WriteData(fid,'enum',AugmentedLagrangianRhopEnum(),'data',self.augmented_lagrangian_rhop ,'format','Double');
+			WriteData(fid,'enum',AugmentedLagrangianRlambdaEnum(),'data',self.augmented_lagrangian_rlambda ,'format','Double');
+			WriteData(fid,'enum',AugmentedLagrangianRholambdaEnum(),'data',self.augmented_lagrangian_rholambda ,'format','Double');
+			WriteData(fid,'enum',AugmentedLagrangianThetaEnum() ,'data',self.XTH_theta ,'format','Double');
+			WriteData(fid,'object',self,'fieldname','borderSSA','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','borderHO','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','borderFS','format','DoubleMat','mattype',1);
 			%convert approximations to enums
-			data=obj.vertex_equation;
+			data=self.vertex_equation;
 			pos=find(data==0); data(pos,end)=NoneApproximationEnum();
 			pos=find(data==1); data(pos,end)=SIAApproximationEnum();
@@ -219,5 +230,5 @@
 			pos=find(data==8); data(pos,end)=SSAFSApproximationEnum();
 			WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1);
-			data=obj.element_equation;
+			data=self.element_equation;
 			pos=find(data==0); data(pos,end)=NoneApproximationEnum();
 			pos=find(data==1); data(pos,end)=SIAApproximationEnum();
Index: /issm/trunk/src/m/classes/flowequation.py
===================================================================
--- /issm/trunk/src/m/classes/flowequation.py	(revision 19104)
+++ /issm/trunk/src/m/classes/flowequation.py	(revision 19105)
@@ -1,4 +1,5 @@
 import numpy
 import copy
+from project3d import project3d
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -58,4 +59,12 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.element_equation=project3d(md,'vector',self.element_equation,'type','element')
+		self.vertex_equation=project3d(md,'vector',self.vertex_equation,'type','node')
+		self.borderSSA=project3d(md,'vector',self.borderSSA,'type','node')
+		self.borderHO=project3d(md,'vector',self.borderHO,'type','node')
+		self.borderFS=project3d(md,'vector',self.borderFS,'type','node')
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 
@@ -73,31 +82,34 @@
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
-		if StressbalanceAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','flowequation.isSIA','numel',[1],'values',[0,1])
-			md = checkfield(md,'fieldname','flowequation.isSSA','numel',[1],'values',[0,1])
-			md = checkfield(md,'fieldname','flowequation.isL1L2','numel',[1],'values',[0,1])
-			md = checkfield(md,'fieldname','flowequation.isHO','numel',[1],'values',[0,1])
-			md = checkfield(md,'fieldname','flowequation.isFS','numel',[1],'values',[0,1])
-			md = checkfield(md,'fieldname','flowequation.fe_SSA','values',['P1','P1bubble','P1bubblecondensed','P2','P2bubble'])
-			md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',['P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'])
-			md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart'])
-			md = checkfield(md,'fieldname','flowequation.borderSSA','size',[md.mesh.numberofvertices],'values',[0,1])
-			md = checkfield(md,'fieldname','flowequation.borderHO','size',[md.mesh.numberofvertices],'values',[0,1])
-			md = checkfield(md,'fieldname','flowequation.borderFS','size',[md.mesh.numberofvertices],'values',[0,1])
-			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_r','numel',[1],'>',0.)
-			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rhop','numel',[1],'>',0.)
-			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rlambda','numel',[1],'>',0.)
-			md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rholambda','numel',[1],'>',0.)
-			md = checkfield(md,'fieldname','flowequation.XTH_theta','numel',[1],'>=',0.,'<',.5)
-			if m.strcmp(md.mesh.domaintype(),'2Dhorizontal'):
-				md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[1,2])
-				md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2])
-			elif m.strcmp(md.mesh.domaintype(),'3D'):
-				md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',numpy.arange(0,8+1))
-				md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',numpy.arange(0,8+1))
-			else:
-				raise RuntimeError('mesh type not supported yet')
-			if not (self.isSIA or self.isSSA or self.isL1L2 or self.isHO or self.isFS):
-				md.checkmessage("no element types set for this model")
+		#Early return
+		if (StressbalanceAnalysisEnum() not in analyses and StressbalanceSIAAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.isstressbalance):
+			return md
+
+		md = checkfield(md,'fieldname','flowequation.isSIA','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','flowequation.isSSA','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','flowequation.isL1L2','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','flowequation.isHO','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','flowequation.isFS','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','flowequation.fe_SSA','values',['P1','P1bubble','P1bubblecondensed','P2','P2bubble'])
+		md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',['P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'])
+		md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart'])
+		md = checkfield(md,'fieldname','flowequation.borderSSA','size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'fieldname','flowequation.borderHO','size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'fieldname','flowequation.borderFS','size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_r','numel',[1],'>',0.)
+		md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rhop','numel',[1],'>',0.)
+		md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rlambda','numel',[1],'>',0.)
+		md = checkfield(md,'fieldname','flowequation.augmented_lagrangian_rholambda','numel',[1],'>',0.)
+		md = checkfield(md,'fieldname','flowequation.XTH_theta','numel',[1],'>=',0.,'<',.5)
+		if m.strcmp(md.mesh.domaintype(),'2Dhorizontal'):
+			md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[1,2])
+			md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2])
+		elif m.strcmp(md.mesh.domaintype(),'3D'):
+			md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',numpy.arange(0,8+1))
+			md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',numpy.arange(0,8+1))
+		else:
+			raise RuntimeError('mesh type not supported yet')
+		if not (self.isSIA or self.isSSA or self.isL1L2 or self.isHO or self.isFS):
+			md.checkmessage("no element types set for this model")
 
 		if StressbalanceSIAAnalysisEnum() in analyses:
Index: /issm/trunk/src/m/classes/friction.m
===================================================================
--- /issm/trunk/src/m/classes/friction.m	(revision 19104)
+++ /issm/trunk/src/m/classes/friction.m	(revision 19105)
@@ -11,46 +11,51 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p -->');
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p">','<section name="friction" />');   
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="coefficient" type="',   	class(obj.coefficient),'" default="',     	convert2str(obj.coefficient),'">',              '     <section name="friction" />','     <help> friction coefficient [SI] </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="p" type="',               class(obj.p),'" default="',                 convert2str(obj.p),'">',   '     <section name="friction" />','     <help> p exponent </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="q" type="',               class(obj.q),'" default="',                 convert2str(obj.q),'">',            '     <section name="friction" />','     <help> q exponent </help>','</parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-        end % }}}
-		function obj = friction(varargin) % {{{
+		function createxml(self,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p -->');
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p">','<section name="friction" />');   
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="coefficient" type="',   	class(self.coefficient),'" default="',     	convert2str(self.coefficient),'">',              '     <section name="friction" />','     <help> friction coefficient [SI] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="p" type="',               class(self.p),'" default="',                 convert2str(self.p),'">',   '     <section name="friction" />','     <help> p exponent </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="q" type="',               class(self.q),'" default="',                 convert2str(self.q),'">',            '     <section name="friction" />','     <help> q exponent </help>','</parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.coefficient=project3d(md,'vector',self.coefficient,'type','node','layer',1);
+			self.p=project3d(md,'vector',self.p,'type','element');
+			self.q=project3d(md,'vector',self.q,'type','element');
+		end % }}}
+		function self = friction(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
 			if ~ismember(StressbalanceAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
-			md = checkfield(md,'fieldname','friction.coefficient','forcing',1,'NaN',1);
+			md = checkfield(md,'fieldname','friction.coefficient','timeseries',1,'NaN',1);
 			md = checkfield(md,'fieldname','friction.q','NaN',1,'size',[md.mesh.numberofelements 1]);
 			md = checkfield(md,'fieldname','friction.p','NaN',1,'size',[md.mesh.numberofelements 1]);
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('Basal shear stress parameters: Sigma_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p)'));
-			fielddisplay(obj,'coefficient','friction coefficient [SI]');
-			fielddisplay(obj,'p','p exponent');
-			fielddisplay(obj,'q','q exponent');
+			fielddisplay(self,'coefficient','friction coefficient [SI]');
+			fielddisplay(self,'p','p exponent');
+			fielddisplay(self,'q','q exponent');
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 			yts=365.0*24.0*3600.0;
 
 			WriteData(fid,'enum',FrictionLawEnum,'data',1,'format','Integer');
-			WriteData(fid,'object',obj,'fieldname','coefficient','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			%WriteData(fid,'object',obj,'fieldname','coefficient','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','p','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'fieldname','q','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			%WriteData(fid,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','p','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'fieldname','q','format','DoubleMat','mattype',2);
 			
 
Index: /issm/trunk/src/m/classes/friction.py
===================================================================
--- /issm/trunk/src/m/classes/friction.py	(revision 19104)
+++ /issm/trunk/src/m/classes/friction.py	(revision 19105)
@@ -1,3 +1,4 @@
 from fielddisplay import fielddisplay
+from project3d import project3d
 from EnumDefinitions import *
 from checkfield import checkfield
@@ -29,4 +30,10 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.coefficient=project3d(md,'vector',self.coefficient,'type','node','layer',1)
+		self.p=project3d(md,'vector',self.p,'type','element')
+		self.q=project3d(md,'vector',self.q,'type','element')
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		return self
@@ -38,5 +45,5 @@
 			return md
 
-		md = checkfield(md,'fieldname','friction.coefficient','forcing',1,'NaN',1)
+		md = checkfield(md,'fieldname','friction.coefficient','timeseries',1,'NaN',1)
 		md = checkfield(md,'fieldname','friction.q','NaN',1,'size',[md.mesh.numberofelements])
 		md = checkfield(md,'fieldname','friction.p','NaN',1,'size',[md.mesh.numberofelements])
Index: /issm/trunk/src/m/classes/frictionhydro.m
===================================================================
--- /issm/trunk/src/m/classes/frictionhydro.m	(revision 19105)
+++ /issm/trunk/src/m/classes/frictionhydro.m	(revision 19105)
@@ -0,0 +1,54 @@
+%FRICTIONWEERTMAN class definition
+%
+%   Usage:
+%      friction=frictionhydro();
+
+classdef frictionhydro
+	properties (SetAccess=public) 
+		q                  = NaN;
+		C                  = NaN;
+		As                 = NaN;
+		effective_pressure = NaN; 
+	end
+	methods
+		function self = frictionhydro(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(StressbalanceAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
+			md = checkfield(md,'fieldname','friction.q','NaN',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','friction.C','NaN',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','friction.As','NaN',1,'size',[md.mesh.numberofelements 1]);
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.q=project3d(md,'vector',self.q,'type','element');
+			self.C=project3d(md,'vector',self.C,'type','element');
+			self.As=project3d(md,'vector',self.As,'type','element');
+			self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('Effective Pressure based friction law described in Gagliardini 2007'));
+			fielddisplay(self,'q','friction law exponent q>=1');
+			fielddisplay(self,'C','friction law max value [SI]');
+			fielddisplay(self,'As','Sliding Parameter without cavitation [m Pa^-n s^-1]');
+			fielddisplay(self,'effective_pressure','Effective Pressure [Pa]');
+		end % }}}
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'enum',FrictionLawEnum,'data',3,'format','Integer');
+			WriteData(fid,'class','friction','object',self,'fieldname','q','format','DoubleMat','mattype',2);
+			WriteData(fid,'class','friction','object',self,'fieldname','C','format','DoubleMat','mattype',2);
+			WriteData(fid,'class','friction','object',self,'fieldname','As','format','DoubleMat','mattype',2);
+			WriteData(fid,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/frictiontemp.m
===================================================================
--- /issm/trunk/src/m/classes/frictiontemp.m	(revision 19105)
+++ /issm/trunk/src/m/classes/frictiontemp.m	(revision 19105)
@@ -0,0 +1,60 @@
+%FRICTIONTEMP class definition
+%
+%   Usage:
+%      frictiontemp=frictiontemp();
+
+classdef frictiontemp
+	properties (SetAccess=public) 
+		gamma       = 0;
+		coefficient = NaN;
+		p           = NaN;
+		q           = NaN;
+	end
+	methods
+		function self = frictiontemp(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					self=structtoobj(frictiontemp(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+			%By default gamma = 1;
+			self.gamma = 1;
+
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(StressbalanceAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
+
+			md = checkfield(md,'fieldname','friction.coefficient','timeseries',1,'NaN',1);
+			md = checkfield(md,'fieldname','friction.q','NaN',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','friction.p','NaN',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','friction.gamma','NaN',1,'numel',1,'>',0.);
+
+			%Check that temperature is provided
+			md = checkfield(md,'fieldname','initialization.temperature','NaN',1,'size',[md.mesh.numberofvertices 1]);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('Basal shear stress parameters: tau_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b * 1/f(T)\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p)'));
+			fielddisplay(self,'gamma','submelt sliding parameter f(T) = exp((T-Tpmp)/gamma)');
+			fielddisplay(self,'coefficient','frictiontemp coefficient [SI]');
+			fielddisplay(self,'p','p exponent');
+			fielddisplay(self,'q','q exponent');
+		end % }}}
+		function marshall(self,md,fid) % {{{
+
+			WriteData(fid,'enum',FrictionLawEnum,'data',4,'format','Integer');
+			WriteData(fid,'class','friction','object',self,'fieldname','gamma','format','Double');
+			WriteData(fid,'class','friction','object',self,'fieldname','coefficient','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'class','friction','object',self,'fieldname','p','format','DoubleMat','mattype',2);
+			WriteData(fid,'class','friction','object',self,'fieldname','q','format','DoubleMat','mattype',2);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/frictionwaterlayer.m
===================================================================
--- /issm/trunk/src/m/classes/frictionwaterlayer.m	(revision 19105)
+++ /issm/trunk/src/m/classes/frictionwaterlayer.m	(revision 19105)
@@ -0,0 +1,60 @@
+%FRICTIONWATERLAYER class definition
+%
+%   Usage:
+%      frictionwaterlayer=frictionwaterlayer();
+
+classdef frictionwaterlayer
+	properties (SetAccess=public) 
+		coefficient = NaN;
+		p           = NaN;
+		q           = NaN;
+		water_layer = NaN;
+	end
+	methods
+		function self = frictionwaterlayer(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					self=structtoobj(frictionwaterlayer(),varargin{1});
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(StressbalanceAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
+
+			md = checkfield(md,'fieldname','friction.coefficient','timeseries',1,'NaN',1);
+			md = checkfield(md,'fieldname','friction.q','NaN',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','friction.p','NaN',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','thermal.spctemperature','timeseries',1,'>=',0.);
+
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.coefficient=project3d(md,'vector',self.coefficient,'type','node','layer',1);
+			self.p=project3d(md,'vector',self.p,'type','element');
+			self.q=project3d(md,'vector',self.q,'type','element');
+			self.water_layer=project3d(md,'vector',self.water_layer,'type','node','layer',1);
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('Basal shear stress parameters: tau_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b * 1/f(T)\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*(bed+water_layer), r=q/p and s=1/p)'));
+			fielddisplay(self,'coefficient','frictiontemp coefficient [SI]');
+			fielddisplay(self,'p','p exponent');
+			fielddisplay(self,'q','q exponent');
+			fielddisplay(self,'water_layer','water thickness at the base of the ice (m)');
+		end % }}}
+		function marshall(self,md,fid) % {{{
+
+			WriteData(fid,'enum',FrictionLawEnum,'data',5,'format','Integer');
+			WriteData(fid,'class','friction','object',self,'fieldname','coefficient','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'class','friction','object',self,'fieldname','p','format','DoubleMat','mattype',2);
+			WriteData(fid,'class','friction','object',self,'fieldname','q','format','DoubleMat','mattype',2);
+			WriteData(fid,'class','friction','object',self,'fieldname','water_layer','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/frictionweertman.m
===================================================================
--- /issm/trunk/src/m/classes/frictionweertman.m	(revision 19104)
+++ /issm/trunk/src/m/classes/frictionweertman.m	(revision 19105)
@@ -10,42 +10,51 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p -->');
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p">','<section name="frictionweertman" />');   
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="coefficient" type="',   	class(obj.coefficient),'" default="',     	convert2str(obj.coefficient),'">',              '     <section name="frictionweertman" />','     <help> frictionweertman coefficient [SI] </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="p" type="',               class(obj.p),'" default="',                 convert2str(obj.p),'">',   '     <section name="frictionweertman" />','     <help> p exponent </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="q" type="',               class(obj.q),'" default="',                 convert2str(obj.q),'">',            '     <section name="frictionweertman" />','     <help> q exponent </help>','</parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-        end % }}}
-		function obj = frictionweertman(varargin) % {{{
+		function createxml(self,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p -->');
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Friction: Sigma= drag^2 * Neff ^r * u ^s, with Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p">','<section name="frictionweertman" />');   
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="coefficient" type="',   	class(self.coefficient),'" default="',     	convert2str(self.coefficient),'">',              '     <section name="frictionweertman" />','     <help> frictionweertman coefficient [SI] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="p" type="',               class(self.p),'" default="',                 convert2str(self.p),'">',   '     <section name="frictionweertman" />','     <help> p exponent </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="q" type="',               class(self.q),'" default="',                 convert2str(self.q),'">',            '     <section name="frictionweertman" />','     <help> q exponent </help>','</parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+		end % }}}
+		function self = frictionweertman(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = extrude(self,md) % {{{
+			md.friction.C=project3d(md,'vector',md.friction.C,'type','node','layer',1);
+			md.friction.m=project3d(md,'vector',md.friction.m,'type','element');
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
 			if ~ismember(StressbalanceAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
-			md = checkfield(md,'fieldname','frictionweertman.C','forcing',1,'NaN',1);
-			md = checkfield(md,'fieldname','frictionweertman.m','NaN',1,'size',[md.mesh.numberofelements 1]);
+			md = checkfield(md,'fieldname','friction.C','timeseries',1,'NaN',1);
+			md = checkfield(md,'fieldname','friction.m','NaN',1,'size',[md.mesh.numberofelements 1]);
 		end % }}}
-		function disp(obj) % {{{
-			disp(sprintf('Weertman sliding law parameters: Sigma_b = C^2 * |u_b|^(1/m-1) * u_b'));
-			fielddisplay(obj,'coefficient','friction coefficient [SI]');
-			fielddisplay(obj,'m','m exponent');
+		function disp(self) % {{{
+			disp('Weertman sliding law parameters:');
+			disp('   Weertman''s sliding law reads:');
+			disp('      v_b = C * Sigma_b^m');
+			disp('   In ISSM, this law is rewritten as:');
+			disp('      Sigma_b = C^(-1/m) * |u_b|^(1/m-1)  u_b');
+			disp(' ');
+			fielddisplay(self,'C','friction coefficient [SI]');
+			fielddisplay(self,'m','m exponent');
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 			yts=365.0*24.0*3600.0;
 
-			WriteData(fid,'enum',FrictionLawEnum,'data',1,'format','Integer');
-			WriteData(fid,'class','friction','object',obj,'fieldname','C','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'class','friction','object',obj,'fieldname','m','format','DoubleMat','mattype',2);
+			WriteData(fid,'enum',FrictionLawEnum,'data',2,'format','Integer');
+			WriteData(fid,'class','friction','object',self,'fieldname','C','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'class','friction','object',self,'fieldname','m','format','DoubleMat','mattype',2);
 			
 
Index: /issm/trunk/src/m/classes/frictionweertman.py
===================================================================
--- /issm/trunk/src/m/classes/frictionweertman.py	(revision 19104)
+++ /issm/trunk/src/m/classes/frictionweertman.py	(revision 19105)
@@ -1,3 +1,4 @@
 from fielddisplay import fielddisplay
+from project3d import project3d
 from EnumDefinitions import *
 from checkfield import checkfield
@@ -21,5 +22,5 @@
 		#}}}
 	def __repr__(self): # {{{
-		string="Weertman sliding law parameters: Sigma_b = C^2 * |u_b|^(1/m-1) * u_b"
+		string="Weertman sliding law parameters: Sigma_b = C^(-1/m) * |u_b|^(1/m-1) * u_b"
 
 		string="%s\n%s"%(string,fielddisplay(self,"C","friction coefficient [SI]"))
@@ -36,5 +37,5 @@
 			return md
 
-		md = checkfield(md,'fieldname','friction.C','forcing',1,'NaN',1)
+		md = checkfield(md,'fieldname','friction.C','timeseries',1,'NaN',1)
 		md = checkfield(md,'fieldname','friction.m','NaN',1,'size',[md.mesh.numberofelements])
 
Index: /issm/trunk/src/m/classes/frictionweertmantemp.m
===================================================================
--- /issm/trunk/src/m/classes/frictionweertmantemp.m	(revision 19105)
+++ /issm/trunk/src/m/classes/frictionweertmantemp.m	(revision 19105)
@@ -0,0 +1,50 @@
+%FRICTIONWEERTMAN class definition
+%
+%   Usage:
+%      frictionweertmantemp=frictionweertmantemp();
+
+classdef frictionweertmantemp
+	properties (SetAccess=public) 
+		gamma = 0;
+		C = NaN;
+		m = NaN;
+	end
+	methods
+		function self = frictionweertmantemp(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(StressbalanceAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
+			md = checkfield(md,'fieldname','friction.C','timeseries',1,'NaN',1);
+			md = checkfield(md,'fieldname','friction.m','NaN',1,'size',[md.mesh.numberofelements 1]);
+		end % }}}
+		function disp(self) % {{{
+			disp('Weertman sliding law parameters:');
+			disp('      Sigma_b = C^(-1/m) * |u_b|^(1/m-1)  u_b * 1/f(T)');
+			disp(' ');
+			fielddisplay(self,'gamma','submelt sliding parameter f(T) = exp((T-Tpmp)/gamma)');
+			fielddisplay(self,'C','friction coefficient [SI]');
+			fielddisplay(self,'m','m exponent');
+		end % }}}
+		function marshall(self,md,fid) % {{{
+			yts=365.0*24.0*3600.0;
+
+			WriteData(fid,'enum',FrictionLawEnum,'data',6,'format','Integer');
+			WriteData(fid,'class','friction','object',self,'fieldname','gamma','format','Double');
+			WriteData(fid,'class','friction','object',self,'fieldname','C','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'class','friction','object',self,'fieldname','m','format','DoubleMat','mattype',2);
+			
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/geometry.m
===================================================================
--- /issm/trunk/src/m/classes/geometry.m	(revision 19104)
+++ /issm/trunk/src/m/classes/geometry.m	(revision 19105)
@@ -13,19 +13,19 @@
 	end
 	methods (Static)
-		function obj = loadobj(obj) % {{{
+		function self = loadobj(self) % {{{
 			% This function is directly called by matlab when a model object is
 			% loaded. Update old properties here
 
 			%2014 March 26th
-			if isstruct(obj),
+			if isstruct(self),
 				disp('WARNING: updating geometry');
 				disp('         md.geometry.bed        is now md.geometry.base');
 				disp('         md.geometry.bathymetry is now md.geometry.bed');
-				obj2=obj;
-				obj=geometry();
-				obj.surface    = obj2.surface;
-				obj.thickness  = obj2.thickness;
-				obj.base       = obj2.bed;
-				obj.bed        = obj2.bathymetry;
+				obj2 = self;
+				self = geometry();
+				self.surface    = obj2.surface;
+				self.thickness  = obj2.thickness;
+				self.base       = obj2.bed;
+				self.bed        = obj2.bathymetry;
 			end
 
@@ -33,36 +33,42 @@
 	end
 	methods
-        %function createxml(obj,fid)
-        function createxml(obj, fid)% {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- geometry -->');
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Geometry parameters">','<section name="geometry" />'); 
+		function createxml(self, fid)% {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- geometry -->');
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Geometry parameters">','<section name="geometry" />'); 
 			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="surface" type="','path','" optional="','false','">','     <section name="geometry" />','     <help> surface elevation [m] </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thickness" type="','path','" optional="','false','">','     <section name="geometry" />','     <help> ice thickness [m] </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="bed" type="','path','" optional="','false','">','     <section name="geometry" />','     <help> bed elevation [m] </help>','</parameter>');
-            %fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="bathymetry" type="',class(obj.bathymetry),'" default="',convert2str(obj.bathymetry),'">','     <section name="geometry" />','     <help> bathymetry elevation [m] </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="hydrostatic_ratio" type="',class(obj.hydrostatic_ratio),'" default="',convert2str(obj.hydrostatic_ratio),'">','     <section name="geometry" />','     <help> coefficient for ice shelves; thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro </help>','</parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-        end % }}}
-		function obj = geometry(varargin) % {{{
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thickness" type="','path','" optional="','false','">','     <section name="geometry" />','     <help> ice thickness [m] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="bed" type="','path','" optional="','false','">','     <section name="geometry" />','     <help> bed elevation [m] </help>','</parameter>');
+			%fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="bathymetry" type="',class(self.bathymetry),'" default="',convert2str(self.bathymetry),'">','     <section name="geometry" />','     <help> bathymetry elevation [m] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="hydrostatic_ratio" type="',class(self.hydrostatic_ratio),'" default="',convert2str(self.hydrostatic_ratio),'">','     <section name="geometry" />','     <help> coefficient for ice shelves; thickness correction: hydrostatic_ratio H_obs+ (1-hydrostatic_ratio) H_hydro </help>','</parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.surface=project3d(md,'vector',self.surface,'type','node');
+			self.thickness=project3d(md,'vector',self.thickness,'type','node');
+			self.hydrostatic_ratio=project3d(md,'vector',self.hydrostatic_ratio,'type','node');
+			self.base=project3d(md,'vector',self.base,'type','node');
+			self.bed=project3d(md,'vector',self.bed,'type','node');
+		end % }}}
+		function self = geometry(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			if (solution==TransientSolutionEnum() & md.transient.isgia) | (solution==GiaSolutionEnum()),
-				md = checkfield(md,'fieldname','geometry.thickness','forcing',1,'NaN',1,'>=',0);
+				md = checkfield(md,'fieldname','geometry.thickness','timeseries',1,'NaN',1,'>=',0);
 			else
 				md = checkfield(md,'fieldname','geometry.surface'  ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'fieldname','geometry.base'      ,'NaN',1,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices 1],'>',0);
-				if any((obj.thickness-obj.surface+obj.base)>10^-9),
+				if any((self.thickness-self.surface+self.base)>10^-9),
 					md = checkmessage(md,['equality thickness=surface-base violated']);
 				end 
@@ -72,19 +78,19 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   geometry parameters:'));
 
-			fielddisplay(obj,'surface','ice upper surface elevation [m]');
-			fielddisplay(obj,'thickness','ice thickness [m]');
-			fielddisplay(obj,'base','ice base elevation [m]');
-			fielddisplay(obj,'bed','bed elevation [m]');
+			fielddisplay(self,'surface','ice upper surface elevation [m]');
+			fielddisplay(self,'thickness','ice thickness [m]');
+			fielddisplay(self,'base','ice base elevation [m]');
+			fielddisplay(self,'bed','bed elevation [m]');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'data',obj.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum());
-			WriteData(fid,'data',obj.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum(),'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'data',obj.base,'format','DoubleMat','mattype',1,'enum',BaseEnum());
-			WriteData(fid,'data',obj.bed,'format','DoubleMat','mattype',1,'enum',BedEnum());
-			WriteData(fid,'object',obj,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1);
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'data',self.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum());
+			WriteData(fid,'data',self.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum(),'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'data',self.base,'format','DoubleMat','mattype',1,'enum',BaseEnum());
+			WriteData(fid,'data',self.bed,'format','DoubleMat','mattype',1,'enum',BedEnum());
+			WriteData(fid,'object',self,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/geometry.py
===================================================================
--- /issm/trunk/src/m/classes/geometry.py	(revision 19104)
+++ /issm/trunk/src/m/classes/geometry.py	(revision 19105)
@@ -1,2 +1,3 @@
+from project3d import project3d
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -32,4 +33,12 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.surface=project3d(md,'vector',self.surface,'type','node')
+		self.thickness=project3d(md,'vector',self.thickness,'type','node')
+		self.hydrostatic_ratio=project3d(md,'vector',self.hydrostatic_ratio,'type','node')
+		self.base=project3d(md,'vector',self.base,'type','node')
+		self.bed=project3d(md,'vector',self.bed,'type','node')
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		return self
@@ -39,5 +48,5 @@
 		md = checkfield(md,'fieldname','geometry.surface'  ,'NaN',1,'size',[md.mesh.numberofvertices])
 		md = checkfield(md,'fieldname','geometry.base'      ,'NaN',1,'size',[md.mesh.numberofvertices])
-		md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices],'>',0,'forcing',1)
+		md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'size',[md.mesh.numberofvertices],'>',0,'timeseries',1)
 		if any((self.thickness-self.surface+self.base)>10**-9):
 			md.checkmessage("equality thickness=surface-base violated")
@@ -49,5 +58,5 @@
 	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'data',self.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum())
-		WriteData(fid,'data',self.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum(),'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'data',self.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum(),'timeserieslength',md.mesh.numberofvertices+1)
 		WriteData(fid,'data',self.base,'format','DoubleMat','mattype',1,'enum',BaseEnum())
 		WriteData(fid,'data',self.bed,'format','DoubleMat','mattype',1,'enum',BedEnum())
Index: /issm/trunk/src/m/classes/gia.m
===================================================================
--- /issm/trunk/src/m/classes/gia.m	(revision 19104)
+++ /issm/trunk/src/m/classes/gia.m	(revision 19105)
@@ -11,31 +11,35 @@
 	end
 	methods
-         function createxml(obj,fid) % {{{
-            fprintf(fid, '<!-- gia -->\n');            
-                    
-            % gia solution parameters
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="gia parameters">','<section name="gia" />');                    
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mantle_viscosity" type="',class(obj.mantle_viscosity),'" default="',convert2str(obj.mantle_viscosity),'">','     <section name="gia" />','     <help> mantle viscosity[Pa s] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lithosphere_thickness" type="',class(obj.lithosphere_thickness),'" default="',convert2str(obj.lithosphere_thickness),'">','     <section name="gia" />','     <help> lithosphere thickness (km) </help>','  </parameter>');
-            %cross_section_shape drop-down (1 o r 2)
-            fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="cross_section_shape" type="alternative" optional="false">','     <section name="gia" />','     <help> 1: square-edged (default). 2: elliptical.  See iedge in GiaDeflectionCore </help>');
-            fprintf(fid,'%s\n','       <option value="1" type="string" default="true"> </option>');
-            fprintf(fid,'%s\n%s\n','       <option value="2" type="string" default="false"> </option>','</parameter>');
-            
-            fprintf(fid,'%s\n%s\n','</frame>');    
-        
-        end % }}}
-		function obj = gia(varargin) % {{{
+		function createxml(self,fid) % {{{
+			fprintf(fid, '<!-- gia -->\n');            
+
+			% gia solution parameters
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="gia parameters">','<section name="gia" />');                    
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mantle_viscosity" type="',class(self.mantle_viscosity),'" default="',convert2str(self.mantle_viscosity),'">','     <section name="gia" />','     <help> mantle viscosity[Pa s] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lithosphere_thickness" type="',class(self.lithosphere_thickness),'" default="',convert2str(self.lithosphere_thickness),'">','     <section name="gia" />','     <help> lithosphere thickness (km) </help>','  </parameter>');
+			%cross_section_shape drop-down (1 o r 2)
+			fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="cross_section_shape" type="alternative" optional="false">','     <section name="gia" />','     <help> 1: square-edged (default). 2: elliptical.  See iedge in GiaDeflectionCore </help>');
+			fprintf(fid,'%s\n','       <option value="1" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="2" type="string" default="false"> </option>','</parameter>');
+
+			fprintf(fid,'%s\n%s\n','</frame>');    
+
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.mantle_viscosity=project3d(md,'vector',self.mantle_viscosity,'type','node');
+			self.lithosphere_thickness=project3d(md,'vector',self.lithosphere_thickness,'type','node');
+		end % }}}
+		function self = gia(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
-		obj.cross_section_shape=1; %square as default (see iedge in GiaDeflectionCorex)
+		function self = setdefaultparameters(self) % {{{
+		self.cross_section_shape=1; %square as default (see iedge in GiaDeflectionCorex)
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			if ~ismember(GiaAnalysisEnum(),analyses), return; end
@@ -60,16 +64,16 @@
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   gia parameters:'));
 
-			fielddisplay(obj,'mantle_viscosity','mantle viscosity[Pa s]');
-			fielddisplay(obj,'lithosphere_thickness','lithosphere thickness (km)');
-			fielddisplay(obj,'cross_section_shape','1: square-edged (default). 2: elliptical.  See iedge in GiaDeflectionCore');
+			fielddisplay(self,'mantle_viscosity','mantle viscosity[Pa s]');
+			fielddisplay(self,'lithosphere_thickness','lithosphere thickness (km)');
+			fielddisplay(self,'cross_section_shape','1: square-edged (default). 2: elliptical.  See iedge in GiaDeflectionCore');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','mantle_viscosity','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','lithosphere_thickness','format','DoubleMat','mattype',1,'scale',10^3); %from km to m
-			WriteData(fid,'object',obj,'fieldname','cross_section_shape','format','Integer');
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','mantle_viscosity','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','lithosphere_thickness','format','DoubleMat','mattype',1,'scale',10^3); %from km to m
+			WriteData(fid,'object',self,'fieldname','cross_section_shape','format','Integer');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/gia.py
===================================================================
--- /issm/trunk/src/m/classes/gia.py	(revision 19104)
+++ /issm/trunk/src/m/classes/gia.py	(revision 19105)
@@ -1,3 +1,4 @@
 from fielddisplay import fielddisplay
+from project3d import project3d
 from EnumDefinitions import *
 from checkfield import checkfield
@@ -30,4 +31,9 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.mantle_viscosity=project3d(md,'vector',self.mantle_viscosity,'type','node')
+		self.lithosphere_thickness=project3d(md,'vector',self.lithosphere_thickness,'type','node')
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 
Index: /issm/trunk/src/m/classes/groundingline.m
===================================================================
--- /issm/trunk/src/m/classes/groundingline.m	(revision 19104)
+++ /issm/trunk/src/m/classes/groundingline.m	(revision 19105)
@@ -9,38 +9,38 @@
 	end
 	methods
-         function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- groundingline -->');
-            
-            % Convergence criteria          
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Grounding line migration parameters">','<section name="groundingline" />');  
-			
-            % migration (SoftMigration, AggressiveMigration, or None)drop-down
-            fprintf(fid,'%s\n%s\n%s\n%s\n','<parameter key ="migration" type="alternative" optional="false">','     <section name="groundingline" />','     <help> type of grounding line migration: "SoftMigration","AggressiveMigration" or "None" </help>');
-            fprintf(fid,'%s\n','       <option value="SoftMigration" type="string" default="true"> </option>');
-            fprintf(fid,'%s\n','       <option value="AggressiveMigration" type="string" default="false"> </option>');
-            fprintf(fid, '%s\n%s\n','       <option value="None" type="string" default="false"></option>','</parameter>');
+		function createxml(self,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- groundingline -->');
 
-            fprintf(fid,'%s\n%s\n','</frame>');
-        end % }}}
-		function obj = groundingline(varargin) % {{{
+			% Convergence criteria          
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Grounding line migration parameters">','<section name="groundingline" />');  
+
+			% migration (SoftMigration, AggressiveMigration, or None)drop-down
+			fprintf(fid,'%s\n%s\n%s\n%s\n','<parameter key ="migration" type="alternative" optional="false">','     <section name="groundingline" />','     <help> type of grounding line migration: "SoftMigration","AggressiveMigration" or "None" </help>');
+			fprintf(fid,'%s\n','       <option value="SoftMigration" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="AggressiveMigration" type="string" default="false"> </option>');
+			fprintf(fid, '%s\n%s\n','       <option value="None" type="string" default="false"></option>','</parameter>');
+
+			fprintf(fid,'%s\n%s\n','</frame>');
+		end % }}}
+		function self = groundingline(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%Type of migration
-			obj.migration='None';
+			self.migration='None';
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
-			md = checkfield(md,'fieldname','groundingline.migration','values',{'None' 'AggressiveMigration' 'SoftMigration' 'SubelementMigration' 'SubelementMigration2' 'Contact' 'None'});
+			md = checkfield(md,'fieldname','groundingline.migration','values',{'None' 'AggressiveMigration' 'SoftMigration' 'SubelementMigration' 'SubelementMigration2' 'Contact' 'None' 'GroundingOnly'});
 
-			if ~strcmp(obj.migration,'None'),
+			if ~strcmp(self.migration,'None'),
 				if isnan(md.geometry.bed),
 					md = checkmessage(md,['requesting grounding line migration, but bathymetry is absent!']);
@@ -48,19 +48,19 @@
 				pos=find(md.mask.groundedice_levelset>0.);
 				if any(abs(md.geometry.base(pos)-md.geometry.bed(pos))>10^-10),
-					md = checkmessage(md,['bathymetry not equal to bed on grounded ice!']);
+					md = checkmessage(md,['base not equal to bed on grounded ice!']);
 				end
 				if any(md.geometry.bed - md.geometry.base > 10^-9),
-					md = checkmessage(md,['bathymetry superior to bed on floating ice!']);
+					md = checkmessage(md,['bed superior to base on floating ice!']);
 				end
 			end
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   grounding line migration parameters:'));
-			fielddisplay(obj,'migration','type of grounding line migration: ''SoftMigration'',''AggressiveMigration'' or ''None''');
+			fielddisplay(self,'migration','type of grounding line migration: ''SoftMigration'',''AggressiveMigration'',''SubelementMigration'',''SubelementMigration2'' or ''None''');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'data',StringToEnum(obj.migration),'enum',GroundinglineMigrationEnum(),'format','Integer');
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'data',StringToEnum(self.migration),'enum',GroundinglineMigrationEnum(),'format','Integer');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/groundingline.py
===================================================================
--- /issm/trunk/src/m/classes/groundingline.py	(revision 19104)
+++ /issm/trunk/src/m/classes/groundingline.py	(revision 19105)
@@ -37,5 +37,5 @@
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
-		md = checkfield(md,'fieldname','groundingline.migration','values',['None','AggressiveMigration','SoftMigration','SubelementMigration','SubelementMigration2','Contact'])
+		md = checkfield(md,'fieldname','groundingline.migration','values',['None','AggressiveMigration','SoftMigration','SubelementMigration','SubelementMigration2','Contact','GroundingOnly'])
 
 		if not m.strcmp(self.migration,'None'):
@@ -44,7 +44,7 @@
 			pos=numpy.nonzero(md.mask.groundedice_levelset>0.)[0]
 			if any(numpy.abs(md.geometry.base[pos]-md.geometry.bed[pos])>10**-10):
-				md.checkmessage("bathymetry not equal to bed on grounded ice!")
+				md.checkmessage("base not equal to bed on grounded ice!")
 			if any(md.geometry.bed - md.geometry.base > 10**-9):
-				md.checkmessage("bathymetry superior to bed on floating ice!")
+				md.checkmessage("bed superior to base on floating ice!")
 
 		return md
Index: /issm/trunk/src/m/classes/hydrologydc.m
===================================================================
--- /issm/trunk/src/m/classes/hydrologydc.m	(revision 19104)
+++ /issm/trunk/src/m/classes/hydrologydc.m	(revision 19105)
@@ -30,16 +30,28 @@
 		epl_porosity             = 0;
 		epl_initial_thickness    = 0;
-		epl_max_thickness    = 0;
+		epl_colapse_thickness    = 0;
+		epl_thick_comp           = 0;
+		epl_max_thickness        = 0;
 		epl_conductivity         = 0;
+		eplflip_lock             = 0;
   end
 	methods
-		% {{{ function obj = hydrologydc(varargin) 
-		function obj = hydrologydc(varargin) 
+		function self = extrude(self,md) % {{{
+			self.spcsediment_head=project3d(md,'vector',self.spcsediment_head,'type','node','layer',1);
+			self.mask_eplactive_node=project3d(md,'vector',self.mask_eplactive_node,'type','node','layer',1);
+			self.sediment_transmitivity=project3d(md,'vector',self.sediment_transmitivity,'type','node','layer',1);
+			self.basal_moulin_input=project3d(md,'vector',self.basal_moulin_input,'type','node','layer',1);
+			if(self.isefficientlayer==1);
+				self.spcepl_head=project3d(md,'vector',self.spcepl_head,'type','node','layer',1);
+			end
+		end % }}}
+		% {{{ function self = hydrologydc(varargin) 
+		function self = hydrologydc(varargin) 
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
-	    end
+			end
 		end 
 		% }}}
@@ -51,34 +63,37 @@
 
 		end % }}}
-		% {{{ function obj = setdefaultparameters(obj) 
-		function obj = setdefaultparameters(obj) 
-
-		%Parameters from de Fleurian 2014
-			obj.water_compressibility    = 5.04e-10;
-			obj.isefficientlayer         = 1;
-			obj.penalty_factor           = 3;
-			obj.rel_tol                  = 1.0e-06;
-			obj.max_iter                 = 100;
-			obj.sedimentlimit_flag       = 0;
-			obj.sedimentlimit            = 0;
-			obj.transfer_flag            = 0;
-			obj.leakage_factor           = 10.0;
-
-			obj.sediment_compressibility = 1.0e-08;
-			obj.sediment_porosity        = 0.4;
-			obj.sediment_thickness       = 20.0;
-			obj.sediment_transmitivity   = 8.0e-04;
-
-			obj.epl_compressibility      = 1.0e-08;
-			obj.epl_porosity             = 0.4;
-			obj.epl_initial_thickness    = 1.0;
-			obj.epl_max_thickness    = 5.0;
-			obj.epl_conductivity         = 8.0e-02;
-
-		end 
-		% }}}
-		% {{{ function md = checkconsistency(obj,md,solution,analyses) 
-		function md = checkconsistency(obj,md,solution,analyses) 
-		%Early return
+		% {{{ function self = setdefaultparameters(self) 
+		function self = setdefaultparameters(self) 
+
+			%Parameters from de Fleurian 2014
+			self.water_compressibility    = 5.04e-10;
+			self.isefficientlayer         = 1;
+			self.penalty_factor           = 3;
+			self.penalty_lock             = 0;
+			self.rel_tol                  = 1.0e-06;
+			self.max_iter                 = 100;
+			self.sedimentlimit_flag       = 0;
+			self.sedimentlimit            = 0;
+			self.transfer_flag            = 0;
+			self.leakage_factor           = 10.0;
+
+			self.sediment_compressibility = 1.0e-08;
+			self.sediment_porosity        = 0.4;
+			self.sediment_thickness       = 20.0;
+			self.sediment_transmitivity   = 8.0e-04;
+
+			self.epl_compressibility      = 1.0e-08;
+			self.epl_porosity             = 0.4;
+			self.epl_initial_thickness    = 1.0;
+			self.epl_colapse_thickness    = 1.0e-3;
+			self.epl_thick_comp           = 1;
+			self.epl_max_thickness        = 5.0;
+			self.epl_conductivity         = 8.0e-02;
+			self.eplflip_lock             = 0;
+		end 
+		% }}}
+		% {{{ function md = checkconsistency(self,md,solution,analyses) 
+		function md = checkconsistency(self,md,solution,analyses) 
+			%Early return
 			if ~ismember(HydrologyDCInefficientAnalysisEnum(),analyses) & ~ismember(HydrologyDCEfficientAnalysisEnum(),analyses),
 				return;
@@ -88,17 +103,18 @@
 			md = checkfield(md,'fieldname','hydrology.isefficientlayer','numel',[1],'values',[0 1]);
 			md = checkfield(md,'fieldname','hydrology.penalty_factor','>',0,'numel',1);
+			md = checkfield(md,'fieldname','hydrology.penalty_lock','>=',0,'numel',1);
 			md = checkfield(md,'fieldname','hydrology.rel_tol','>',0,'numel',1);
 			md = checkfield(md,'fieldname','hydrology.max_iter','>',0,'numel',1);
 			md = checkfield(md,'fieldname','hydrology.sedimentlimit_flag','numel',[1],'values',[0 1 2 3]);
 			md = checkfield(md,'fieldname','hydrology.transfer_flag','numel',[1],'values',[0 1]);
-			if obj.sedimentlimit_flag==1,
+			if self.sedimentlimit_flag==1,
 				md = checkfield(md,'fieldname','hydrology.sedimentlimit','>',0,'numel',1);
-	    end
-			if obj.transfer_flag==1,
+			end
+			if self.transfer_flag==1,
 				md = checkfield(md,'fieldname','hydrology.leakage_factor','>',0,'numel',1);
-	    end
-			md = checkfield(md,'fieldname','hydrology.basal_moulin_input','NaN',1,'forcing',1);
-
-			md = checkfield(md,'fieldname','hydrology.spcsediment_head','forcing',1);
+			end
+			md = checkfield(md,'fieldname','hydrology.basal_moulin_input','NaN',1,'timeseries',1);
+
+			md = checkfield(md,'fieldname','hydrology.spcsediment_head','timeseries',1);
 			md = checkfield(md,'fieldname','hydrology.sediment_compressibility','>',0,'numel',1);
 			md = checkfield(md,'fieldname','hydrology.sediment_porosity','>',0,'numel',1);
@@ -106,96 +122,108 @@
 			md = checkfield(md,'fieldname','hydrology.sediment_transmitivity','>=',0,'size',[md.mesh.numberofvertices 1]);
 
-			if obj.isefficientlayer==1,
-				md = checkfield(md,'fieldname','hydrology.spcepl_head','forcing',1);
+			if self.isefficientlayer==1,
+				md = checkfield(md,'fieldname','hydrology.spcepl_head','timeseries',1);
 				md = checkfield(md,'fieldname','hydrology.mask_eplactive_node','size',[md.mesh.numberofvertices 1],'values',[0 1]);
 				md = checkfield(md,'fieldname','hydrology.epl_compressibility','>',0,'numel',1);
 				md = checkfield(md,'fieldname','hydrology.epl_porosity','>',0,'numel',1);
 				md = checkfield(md,'fieldname','hydrology.epl_initial_thickness','>',0,'numel',1);
+				md = checkfield(md,'fieldname','hydrology.epl_colapse_thickness','>',0,'numel',1);
+				md = checkfield(md,'fieldname','hydrology.epl_thick_comp','numel',[1],'values',[0 1]);
 				md = checkfield(md,'fieldname','hydrology.epl_max_thickness','>',0,'numel',1);
 				md = checkfield(md,'fieldname','hydrology.epl_conductivity','>',0,'numel',1);
-	    end
-		end 
-		% }}}
-		% {{{ function disp(obj)
-		function disp(obj) 
+				md = checkfield(md,'fieldname','hydrology.eplflip_lock','>=',0,'numel',1);
+				if (self.epl_colapse_thickness>self.epl_initial_thickness),
+					md = checkmessage(md,'Colapsing thickness for EPL larger than initial thickness');
+				end 
+			end
+		end 
+		% }}}
+		% {{{ function disp(self)
+		function disp(self) 
 			disp(sprintf('   hydrology Dual Porous Continuum Equivalent parameters:'));
 			disp(sprintf('   - general parameters'));
-			fielddisplay(obj,'water_compressibility','compressibility of water [Pa^-1]');
-			fielddisplay(obj,'isefficientlayer','do we use an efficient drainage system [1: true; 0: false]');
-			fielddisplay(obj,'penalty_factor','exponent of the value used in the penalisation method [dimensionless]');
-			fielddisplay(obj,'penalty_lock','stabilize unstable constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
-			fielddisplay(obj,'rel_tol','tolerance of the nonlinear iteration for the transfer between layers [dimensionless]');
-			fielddisplay(obj,'max_iter','maximum number of nonlinear iteration');
-			fielddisplay(obj,'sedimentlimit_flag','what kind of upper limit is applied for the inefficient layer');
+			fielddisplay(self,'water_compressibility','compressibility of water [Pa^-1]');
+			fielddisplay(self,'isefficientlayer','do we use an efficient drainage system [1: true; 0: false]');
+			fielddisplay(self,'penalty_factor','exponent of the value used in the penalisation method [dimensionless]');
+			fielddisplay(self,'penalty_lock','stabilize unstable constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
+			fielddisplay(self,'rel_tol','tolerance of the nonlinear iteration for the transfer between layers [dimensionless]');
+			fielddisplay(self,'max_iter','maximum number of nonlinear iteration');
+			fielddisplay(self,'sedimentlimit_flag','what kind of upper limit is applied for the inefficient layer');
 			disp(sprintf('%55s  0: no limit',' '));
 			disp(sprintf('%55s  1: user defined: %s',' ','sedimentlimit'));
 			disp(sprintf('%55s  2: hydrostatic pressure',' '));
 			disp(sprintf('%55s  3: normal stress',' '));
-			if obj.sedimentlimit_flag==1,
-				fielddisplay(obj,'sedimentlimit','user defined upper limit for the inefficient layer [m]');
-	    end
-			fielddisplay(obj,'transfer_flag',['what kind of transfer method is applied between the layers']);
+			if self.sedimentlimit_flag==1,
+				fielddisplay(self,'sedimentlimit','user defined upper limit for the inefficient layer [m]');
+			end
+			fielddisplay(self,'transfer_flag',['what kind of transfer method is applied between the layers']);
 			disp(sprintf('%55s  0: no transfer',' '));
 			disp(sprintf('%55s  1: constant leakage factor: %s',' ','leakage_factor'));
-			if obj.transfer_flag==1,
-				fielddisplay(obj,'leakage_factor','user defined leakage factor [m]');
-	    end
-			fielddisplay(obj,'basal_moulin_input','Figure out what it is');
+			if self.transfer_flag==1,
+				fielddisplay(self,'leakage_factor','user defined leakage factor [m]');
+			end
+			fielddisplay(self,'basal_moulin_input','water flux at a given point [m3 s-1]');
 			disp(sprintf('   - for the sediment layer'));
-			fielddisplay(obj,'spcsediment_head','sediment water head constraints (NaN means no constraint) [m above MSL]');
-			fielddisplay(obj,'sediment_compressibility','sediment compressibility [Pa^-1]');
-			fielddisplay(obj,'sediment_porosity','sediment [dimensionless]');
-			fielddisplay(obj,'sediment_thickness','sediment thickness [m]');
-			fielddisplay(obj,'sediment_transmitivity','sediment transmitivity [m^2/s]');
-
-			if obj.isefficientlayer==1,
+			fielddisplay(self,'spcsediment_head','sediment water head constraints (NaN means no constraint) [m above MSL]');
+			fielddisplay(self,'sediment_compressibility','sediment compressibility [Pa^-1]');
+			fielddisplay(self,'sediment_porosity','sediment [dimensionless]');
+			fielddisplay(self,'sediment_thickness','sediment thickness [m]');
+			fielddisplay(self,'sediment_transmitivity','sediment transmitivity [m^2/s]');
+
+			if self.isefficientlayer==1,
 				disp(sprintf('   - for the epl layer'));
-				fielddisplay(obj,'spcepl_head','epl water head constraints (NaN means no constraint) [m above MSL]');
-				fielddisplay(obj,'mask_eplactive_node','active (1) or not (0) EPL');
-				fielddisplay(obj,'epl_compressibility','epl compressibility [Pa^-1]');
-				fielddisplay(obj,'epl_porosity','epl [dimensionless]');
-				fielddisplay(obj,'epl_initial_thickness','epl initial thickness [m]');
-				fielddisplay(obj,'epl_max_thickness','epl maximal thickness [m]');
-				fielddisplay(obj,'epl_conductivity','epl conductivity [m^2/s]');
-	    end
-
-		end 
-		% }}}
-		% {{{ function marshall(obj,md,fid) 
-		function marshall(obj,md,fid) 
+				fielddisplay(self,'spcepl_head','epl water head constraints (NaN means no constraint) [m above MSL]');
+				fielddisplay(self,'mask_eplactive_node','active (1) or not (0) EPL');
+				fielddisplay(self,'epl_compressibility','epl compressibility [Pa^-1]');
+				fielddisplay(self,'epl_porosity','epl [dimensionless]');
+				fielddisplay(self,'epl_initial_thickness','epl initial thickness [m]');
+				fielddisplay(self,'epl_colapse_thickness','epl colapsing thickness [m]');
+				fielddisplay(self,'epl_thick_comp','epl thickness computation flag');
+				fielddisplay(self,'epl_max_thickness','epl maximal thickness [m]');
+				fielddisplay(self,'epl_conductivity','epl conductivity [m^2/s]');
+				fielddisplay(self,'eplflip_lock','lock the epl activation to avoid fli-floping (default is 0, no stabilization)');
+			end
+
+		end 
+		% }}}
+		% {{{ function marshall(self,md,fid) 
+		function marshall(self,md,fid) 
 			WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologydcEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'fieldname','water_compressibility','format','Double');
-			WriteData(fid,'object',obj,'fieldname','isefficientlayer','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
-			WriteData(fid,'object',obj,'fieldname','penalty_lock','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','rel_tol','format','Double');
-			WriteData(fid,'object',obj,'fieldname','max_iter','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','sedimentlimit_flag','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','transfer_flag','format','Integer');
-			if obj.sedimentlimit_flag==1,
-				WriteData(fid,'object',obj,'fieldname','sedimentlimit','format','Double');
-	    end
-			if obj.transfer_flag==1,
-				WriteData(fid,'object',obj,'fieldname','leakage_factor','format','Double');
-	    end
-			WriteData(fid,'object',obj,'fieldname','basal_moulin_input','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
-
-			WriteData(fid,'object',obj,'fieldname','spcsediment_head','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'fieldname','sediment_compressibility','format','Double');			
-			WriteData(fid,'object',obj,'fieldname','sediment_porosity','format','Double');			
-			WriteData(fid,'object',obj,'fieldname','sediment_thickness','format','Double');
-			WriteData(fid,'object',obj,'fieldname','sediment_transmitivity','format','DoubleMat','mattype',1');		
-
-			if obj.isefficientlayer==1,	
-				WriteData(fid,'object',obj,'fieldname','spcepl_head','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);	
-				WriteData(fid,'object',obj,'fieldname','mask_eplactive_node','format','DoubleMat','mattype',1);
-				WriteData(fid,'object',obj,'fieldname','epl_compressibility','format','Double');			
-				WriteData(fid,'object',obj,'fieldname','epl_porosity','format','Double');			
-				WriteData(fid,'object',obj,'fieldname','epl_initial_thickness','format','Double');
-				WriteData(fid,'object',obj,'fieldname','epl_max_thickness','format','Double');
-				WriteData(fid,'object',obj,'fieldname','epl_conductivity','format','Double');
-			end
-		end 
-% }}}
-  end
+			WriteData(fid,'object',self,'fieldname','water_compressibility','format','Double');
+			WriteData(fid,'object',self,'fieldname','isefficientlayer','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer');
+			WriteData(fid,'object',self,'fieldname','rel_tol','format','Double');
+			WriteData(fid,'object',self,'fieldname','max_iter','format','Integer');
+			WriteData(fid,'object',self,'fieldname','sedimentlimit_flag','format','Integer');
+			WriteData(fid,'object',self,'fieldname','transfer_flag','format','Integer');
+			if self.sedimentlimit_flag==1,
+				WriteData(fid,'object',self,'fieldname','sedimentlimit','format','Double');
+			end
+			if self.transfer_flag==1,
+				WriteData(fid,'object',self,'fieldname','leakage_factor','format','Double');
+			end
+			WriteData(fid,'object',self,'fieldname','basal_moulin_input','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
+
+			WriteData(fid,'object',self,'fieldname','spcsediment_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'fieldname','sediment_compressibility','format','Double');			
+			WriteData(fid,'object',self,'fieldname','sediment_porosity','format','Double');			
+			WriteData(fid,'object',self,'fieldname','sediment_thickness','format','Double');
+			WriteData(fid,'object',self,'fieldname','sediment_transmitivity','format','DoubleMat','mattype',1');		
+
+			if self.isefficientlayer==1,	
+				WriteData(fid,'object',self,'fieldname','spcepl_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);	
+				WriteData(fid,'object',self,'fieldname','mask_eplactive_node','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',self,'fieldname','epl_compressibility','format','Double');			
+				WriteData(fid,'object',self,'fieldname','epl_porosity','format','Double');			
+				WriteData(fid,'object',self,'fieldname','epl_initial_thickness','format','Double');
+				WriteData(fid,'object',self,'fieldname','epl_colapse_thickness','format','Double');
+				WriteData(fid,'object',self,'fieldname','epl_thick_comp','format','Integer');
+				WriteData(fid,'object',self,'fieldname','epl_max_thickness','format','Double');
+				WriteData(fid,'object',self,'fieldname','epl_conductivity','format','Double');
+				WriteData(fid,'object',self,'fieldname','eplflip_lock','format','Integer');
+			end
+		end 
+		% }}}
+	end
 end
Index: /issm/trunk/src/m/classes/hydrologydc.py
===================================================================
--- /issm/trunk/src/m/classes/hydrologydc.py	(revision 19104)
+++ /issm/trunk/src/m/classes/hydrologydc.py	(revision 19105)
@@ -1,2 +1,4 @@
+import numpy
+from project3d import project3d
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -5,12 +7,12 @@
 
 class hydrologydc(object):
-    """
-    Hydrologydc class definition
-    
-    Usage:
-    hydrologydc=hydrologydc();
-    """
-
-    def __init__(self): # {{{
+	"""
+	Hydrologydc class definition
+
+	Usage:
+		hydrologydc=hydrologydc();
+	"""
+
+	def __init__(self): # {{{
 		self.water_compressibility    = 0
 		self.isefficientlayer         = 0
@@ -23,4 +25,5 @@
 		self.transfer_flag            = 0
 		self.leakage_factor           = 0
+		self.basal_moulin_input       = float('NaN')
 
 		self.spcsediment_head         = float('NaN')
@@ -36,140 +39,181 @@
 		self.epl_porosity             = 0
 		self.epl_initial_thickness    = 0
+		self.epl_colapse_thickness    = 0
+		self.epl_thick_comp           = 0
+		self.epl_max_thickness        = 0
 		self.epl_conductivity         = 0
-                
+		self.eplflip_lock             = 0
+				 
 		#set defaults
 		self.setdefaultparameters()
-                #}}}
-                
+	#}}}
 	def __repr__(self): # {{{
-            string='   hydrology Dual Porous Continuum Equivalent parameters:'
-            string='   - general parameters'
-            string="%s\n%s"%(string,fielddisplay(self,'water_compressibility','compressibility of water [Pa^-1]'))
-            string="%s\n%s"%(string,fielddisplay(self,'isefficientlayer','do we use an efficient drainage system [1: true 0: false]'))
-            string="%s\n%s"%(string,fielddisplay(self,'penalty_factor','exponent of the value used in the penalisation method [dimensionless]'))
-            string="%s\n%s"%(string,fielddisplay(self,'penalty_lock','stabilize unstable constraints that keep zigzagging after n iteration (default is 0, no stabilization)'))
-            string="%s\n%s"%(string,fielddisplay(self,'rel_tol','tolerance of the nonlinear iteration for the transfer between layers [dimensionless]'))
-            string="%s\n%s"%(string,fielddisplay(self,'max_iter','maximum number of nonlinear iteration'))
-            string="%s\n%s"%(string,fielddisplay(self,'sedimentlimit_flag','what kind of upper limit is applied for the inefficient layer'))
-            string='%55s  0: no limit',' '
-            string='%55s  1: user defined: %s',' ','sedimentlimit'
-            string='%55s  2: hydrostatic pressure',' '
-            string='%55s  3: normal stress',' '
-
-            if self.sedimentlimit_flag==1:
-                string="%s\n%s"%(string,fielddisplay(self,'sedimentlimit','user defined upper limit for the inefficient layer [m]'))
-                string="%s\n%s"%(string,fielddisplay(self,'transfer_flag',['what kind of transfer method is applied between the layers']))
-                string='%55s  0: no transfer',' '
-                string='%55s  1: constant leakage factor: %s',' ','leakage_factor'
-                
-            if self.transfer_flag is 1:
-                string="%s\n%s"%(string,fielddisplay(self,'leakage_factor','user defined leakage factor [m]'))
-                string='   - for the sediment layer'
-                string="%s\n%s"%(string,fielddisplay(self,'spcsediment_head','sediment water head constraints (NaN means no constraint) [m above MSL]'))
-                string="%s\n%s"%(string,fielddisplay(self,'sediment_compressibility','sediment compressibility [Pa^-1]'))
-                string="%s\n%s"%(string,fielddisplay(self,'sediment_porosity','sediment [dimensionless]'))
-                string="%s\n%s"%(string,fielddisplay(self,'sediment_thickness','sediment thickness [m]'))
-                string="%s\n%s"%(string,fielddisplay(self,'sediment_transmitivity','sediment transmitivity [m^2/s]'))
-            
-            if self.isefficientlayer==1:
-                string='   - for the epl layer'
-                string="%s\n%s"%(string,fielddisplay(self,'spcepl_head','epl water head constraints (NaN means no constraint) [m above MSL]'))
-                string="%s\n%s"%(string,fielddisplay(self,'mask_eplactive_node','active (1) or not (0) EPL'))
-                string="%s\n%s"%(string,fielddisplay(self,'epl_compressibility','epl compressibility [Pa^-1]'))
-                string="%s\n%s"%(string,fielddisplay(self,'epl_porosity','epl [dimensionless]'))
-                string="%s\n%s"%(string,fielddisplay(self,'epl_initial_thickness','epl initial thickness [m]'))
-                string="%s\n%s"%(string,fielddisplay(self,'epl_conductivity','epl conductivity [m^2/s]'))
-            
-            #}}}
-    def setdefaultparameters(self): #{{{ 
-        
-        #Parameters from de Fleurian 2014
-        self.water_compressibility    = 5.04e-10
-        self.isefficientlayer         = 1
-        self.penalty_factor           = 3
-        self.rel_tol                  = 1.0e-06
-        self.max_iter                 = 100
-        self.sedimentlimit_flag       = 0
-        self.sedimentlimit            = 0
-        self.transfer_flag            = 0
-        self.leakage_factor           = 10.0
-        
-        self.sediment_compressibility = 1.0e-08
-        self.sediment_porosity        = 0.4
-        self.sediment_thickness       = 20.0
-        self.sediment_transmitivity   = 8.0e-04
-        
-        self.epl_compressibility      = 1.0e-08
-        self.epl_porosity             = 0.4
-        self.epl_initial_thickness    = 1.0
-        self.epl_conductivity         = 8.0e-02
-        
-        return self
-    # }}}
-    
-    def checkconsistency(self,md,solution,analyses): #{{{ 
-        
-        #Early return
-        if HydrologyDCInefficientAnalysisEnum() not in analyses:
-            return md
-
-        md = checkfield(md,'fieldname','hydrology.water_compressibility','>',0,'numel',1)
-        md = checkfield(md,'fieldname','hydrology.isefficientlayer','numel',[1],'values',[0 1])
-        md = checkfield(md,'fieldname','hydrology.penalty_factor','>',0,'numel',1)
-        md = checkfield(md,'fieldname','hydrology.rel_tol','>',0,'numel',1)
-        md = checkfield(md,'fieldname','hydrology.max_iter','>',0,'numel',1)
-        md = checkfield(md,'fieldname','hydrology.sedimentlimit_flag','numel',[1],'values',[0 1 2 3])
-        md = checkfield(md,'fieldname','hydrology.transfer_flag','numel',[1],'values',[0 1])
-        
-        if self.sedimentlimit_flag==1:
-            md = checkfield(md,'fieldname','hydrology.sedimentlimit','>',0,'numel',1)
-    
-        if self.transfer_flag==1:
-            md = checkfield(md,'fieldname','hydrology.leakage_factor','>',0,'numel',1)
-            
-        md = checkfield(md,'fieldname','hydrology.spcsediment_head','forcing',1)
-        md = checkfield(md,'fieldname','hydrology.sediment_compressibility','>',0,'numel',1)
-        md = checkfield(md,'fieldname','hydrology.sediment_porosity','>',0,'numel',1)
-        md = checkfield(md,'fieldname','hydrology.sediment_thickness','>',0,'numel',1)
-        md = checkfield(md,'fieldname','hydrology.sediment_transmitivity','>=',0,'size',[md.mesh.numberofvertices 1])
-        if self.isefficientlayer==1:
-            md = checkfield(md,'fieldname','hydrology.spcepl_head','forcing',1)
-            md = checkfield(md,'fieldname','hydrology.mask_eplactive_node','size',[md.mesh.numberofvertices 1],'values',[0 1])
-            md = checkfield(md,'fieldname','hydrology.epl_compressibility','>',0,'numel',1)
-            md = checkfield(md,'fieldname','hydrology.epl_porosity','>',0,'numel',1)
-            md = checkfield(md,'fieldname','hydrology.epl_initial_thickness','>',0,'numel',1)
-            md = checkfield(md,'fieldname','hydrology.epl_conductivity','>',0,'numel',1)
-
-        # }}}
-    def marshall(self,md,fid): #{{{ 
-        WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologydcEnum(),'format','Integer')
-        WriteData(fid,'object',self,'fieldname','water_compressibility','format','Double')
-        WriteData(fid,'object',self,'fieldname','isefficientlayer','format','Boolean')
-        WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
-        WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer')
-        WriteData(fid,'object',self,'fieldname','rel_tol','format','Double')
-        WriteData(fid,'object',self,'fieldname','max_iter','format','Integer')
-        WriteData(fid,'object',self,'fieldname','sedimentlimit_flag','format','Integer')
-        WriteData(fid,'object',self,'fieldname','transfer_flag','format','Integer')
-
-        if self.sedimentlimit_flag==1:
-            WriteData(fid,'object',self,'fieldname','sedimentlimit','format','Double')
-
-        if self.transfer_flag==1:
-            WriteData(fid,'object',self,'fieldname','leakage_factor','format','Double')
-
-        WriteData(fid,'object',self,'fieldname','spcsediment_head','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
-        WriteData(fid,'object',self,'fieldname','sediment_compressibility','format','Double')
-        WriteData(fid,'object',self,'fieldname','sediment_porosity','format','Double')			
-        WriteData(fid,'object',self,'fieldname','sediment_thickness','format','Double')
-        WriteData(fid,'object',self,'fieldname','sediment_transmitivity','format','DoubleMat','mattype',1)		
-
-        if self.isefficientlayer==1:	
-            WriteData(fid,'object',self,'fieldname','spcepl_head','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)	
-            WriteData(fid,'object',self,'fieldname','mask_eplactive_node','format','DoubleMat','mattype',1)
-            WriteData(fid,'object',self,'fieldname','epl_compressibility','format','Double')			
-            WriteData(fid,'object',self,'fieldname','epl_porosity','format','Double')			
-            WriteData(fid,'object',self,'fieldname','epl_initial_thickness','format','Double')
-            WriteData(fid,'object',self,'fieldname','epl_conductivity','format','Double')
-# }}}
-
+		string='   hydrology Dual Porous Continuum Equivalent parameters:'
+		string='   - general parameters'
+		string="%s\n%s"%(string,fielddisplay(self,'water_compressibility','compressibility of water [Pa^-1]'))
+		string="%s\n%s"%(string,fielddisplay(self,'isefficientlayer','do we use an efficient drainage system [1: true 0: false]'))
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_factor','exponent of the value used in the penalisation method [dimensionless]'))
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_lock','stabilize unstable constraints that keep zigzagging after n iteration (default is 0, no stabilization)'))
+		string="%s\n%s"%(string,fielddisplay(self,'rel_tol','tolerance of the nonlinear iteration for the transfer between layers [dimensionless]'))
+		string="%s\n%s"%(string,fielddisplay(self,'max_iter','maximum number of nonlinear iteration'))
+		string="%s\n%s"%(string,fielddisplay(self,'basal_moulin_input','water flux at a given point [m3 s-1]'))
+		string="%s\n%s"%(string,fielddisplay(self,'sedimentlimit_flag','what kind of upper limit is applied for the inefficient layer'))
+		string="%s\n\t\t%s"%(string,'0: no limit')
+		string="%s\n\t\t%s"%(string,'1: user defined sedimentlimit')
+		string="%s\n\t\t%s"%(string,'2: hydrostatic pressure')
+		string="%s\n\t\t%s"%(string,'3: normal stress')
+	
+		if self.sedimentlimit_flag==1:
+			string="%s\n%s"%(string,fielddisplay(self,'sedimentlimit','user defined upper limit for the inefficient layer [m]'))
+
+		string="%s\n%s"%(string,fielddisplay(self,'transfer_flag','what kind of transfer method is applied between the layers'))
+		string="%s\n\t\t%s"%(string,'0: no transfer')
+		string="%s\n\t\t%s"%(string,'1: constant leakage factor: leakage_factor')
+			 
+		if self.transfer_flag is 1:
+			string="%s\n%s"%(string,fielddisplay(self,'leakage_factor','user defined leakage factor [m]'))
+
+		string="%s\n%s"%(string,'   - for the sediment layer')
+		string="%s\n%s"%(string,fielddisplay(self,'spcsediment_head','sediment water head constraints (NaN means no constraint) [m above MSL]'))
+		string="%s\n%s"%(string,fielddisplay(self,'sediment_compressibility','sediment compressibility [Pa^-1]'))
+		string="%s\n%s"%(string,fielddisplay(self,'sediment_porosity','sediment [dimensionless]'))
+		string="%s\n%s"%(string,fielddisplay(self,'sediment_thickness','sediment thickness [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'sediment_transmitivity','sediment transmitivity [m^2/s]'))
+
+		if self.isefficientlayer==1:
+			string="%s\n%s"%(string,'   - for the epl layer')
+			string="%s\n%s"%(string,fielddisplay(self,'spcepl_head','epl water head constraints (NaN means no constraint) [m above MSL]'))
+			string="%s\n%s"%(string,fielddisplay(self,'mask_eplactive_node','active (1) or not (0) EPL'))
+			string="%s\n%s"%(string,fielddisplay(self,'epl_compressibility','epl compressibility [Pa^-1]'))
+			string="%s\n%s"%(string,fielddisplay(self,'epl_porosity','epl [dimensionless]'))
+			string="%s\n%s"%(string,fielddisplay(self,'epl_max_thickness','epl initial thickness [m]'))
+			string="%s\n%s"%(string,fielddisplay(self,'epl_initial_thickness','epl initial thickness [m]'))			
+			string="%s\n%s"%(string,fielddisplay(self,'epl_colapse_thickness','epl colapsing thickness [m]'))
+			string="%s\n%s"%(string,fielddisplay(self,'epl_thick_comp','epl thickness computation flag'))
+			string="%s\n%s"%(string,fielddisplay(self,'epl_conductivity','epl conductivity [m^2/s]'))
+			string="%s\n%s"%(string,fielddisplay(self,'eplflip_lock','lock epl activity to avoid flip-floping (default is 0, no stabilization)'))
+		return string
+#}}}
+	def extrude(self,md): # {{{
+		self.spcsediment_head=project3d(md,'vector',self.spcsediment_head,'type','node','layer',1)
+		self.spcepl_head=project3d(md,'vector',self.spcepl_head,'type','node','layer',1)
+		self.mask_eplactive_node=project3d(md,'vector',self.mask_eplactive_node,'type','node','layer',1)
+		self.sediment_transmitivity=project3d(md,'vector',self.sediment_transmitivity,'type','node','layer',1)
+		self.basal_moulin_input=project3d(md,'vector',self.basal_moulin_input,'type','node','layer',1)
+		if self.isefficientlayer==1 :
+			self.spcepl_head=project3d(md,'vector',self.spcepl_head,'type','node','layer',1)
+		return self
+	#}}}
+	def setdefaultparameters(self): #{{{ 
+
+		#Parameters from de Fleurian 2014
+		self.water_compressibility    = 5.04e-10
+		self.isefficientlayer         = 1
+		self.penalty_factor           = 3
+		self.penalty_lock             = 0
+		self.rel_tol                  = 1.0e-06
+		self.max_iter                 = 100
+		self.sedimentlimit_flag       = 0
+		self.sedimentlimit            = 0
+		self.transfer_flag            = 0
+		self.leakage_factor           = 10.0
+
+		self.sediment_compressibility = 1.0e-08
+		self.sediment_porosity        = 0.4
+		self.sediment_thickness       = 20.0
+		self.sediment_transmitivity   = 8.0e-04
+
+		self.epl_compressibility      = 1.0e-08
+		self.epl_porosity             = 0.4
+		self.epl_initial_thickness    = 1.0
+		self.epl_colapse_thickness    = 1.0e-3
+		self.epl_thick_comp           = 1
+		self.epl_max_thickness        = 5.0
+		self.epl_conductivity         = 8.0e-02
+		self.eplflip_lock             = 0
+		
+		return self
+	# }}}
+	def initialize(self,md): # {{{
+		if numpy.all(numpy.isnan(self.basal_moulin_input)):
+			self.basal_moulin_input=numpy.zeros((md.mesh.numberofvertices,1))
+			print"      no hydrology.basal_moulin_input specified: values set as zero"
+
+		return self
+	# }}}
+	def checkconsistency(self,md,solution,analyses): #{{{ 
+
+		#Early return
+		if HydrologyDCInefficientAnalysisEnum() not in analyses and HydrologyDCEfficientAnalysisEnum() not in analyses:
+			return md
+
+		md = checkfield(md,'fieldname','hydrology.water_compressibility','numel',[1],'>',0.)
+		md = checkfield(md,'fieldname','hydrology.isefficientlayer','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','hydrology.penalty_factor','>',0.,'numel',[1])
+		md = checkfield(md,'fieldname','hydrology.penalty_lock','>=',0.,'numel',[1])
+		md = checkfield(md,'fieldname','hydrology.rel_tol','>',0.,'numel',[1])
+		md = checkfield(md,'fieldname','hydrology.max_iter','>',0.,'numel',[1])
+		md = checkfield(md,'fieldname','hydrology.sedimentlimit_flag','numel',[1],'values',[0,1,2,3])
+		md = checkfield(md,'fieldname','hydrology.transfer_flag','numel',[1],'values',[0,1])
+
+		if self.sedimentlimit_flag==1:
+			md = checkfield(md,'fieldname','hydrology.sedimentlimit','>',0.,'numel',[1])
+
+		if self.transfer_flag==1:
+			md = checkfield(md,'fieldname','hydrology.leakage_factor','>',0.,'numel',[1])
+
+		md = checkfield(md,'fieldname','hydrology.basal_moulin_input','NaN',1,'timeseries',1)
+		md = checkfield(md,'fieldname','hydrology.spcsediment_head','timeseries',1)
+		md = checkfield(md,'fieldname','hydrology.sediment_compressibility','>',0.,'numel',[1])
+		md = checkfield(md,'fieldname','hydrology.sediment_porosity','>',0.,'numel',[1])
+		md = checkfield(md,'fieldname','hydrology.sediment_thickness','>',0.,'numel',[1])
+		md = checkfield(md,'fieldname','hydrology.sediment_transmitivity','>=',0,'size',[md.mesh.numberofvertices,1])
+		if self.isefficientlayer==1:
+			md = checkfield(md,'fieldname','hydrology.spcepl_head','timeseries',1)
+			md = checkfield(md,'fieldname','hydrology.mask_eplactive_node','size',[md.mesh.numberofvertices,1],'values',[0,1])
+			md = checkfield(md,'fieldname','hydrology.epl_compressibility','>',0.,'numel',[1])
+			md = checkfield(md,'fieldname','hydrology.epl_porosity','>',0.,'numel',[1])
+			md = checkfield(md,'fieldname','hydrology.epl_max_thickness','numel',[1],'>',0.)
+			md = checkfield(md,'fieldname','hydrology.epl_initial_thickness','numel',[1],'>',0.)
+			md = checkfield(md,'fieldname','hydrology.epl_colapse_thickness','numel',[1],'>',0.)
+			md = checkfield(md,'fieldname','hydrology.epl_thick_comp','numel',[1],'values',[0,1])
+			md = checkfield(md,'fieldname','hydrology.eplflip_lock','>=',0.,'numel',[1])
+			if self.epl_colapse_thickness > self.epl_initial_thickness:
+				md.checkmessage('Colapsing thickness for EPL larger than initial thickness')
+			md = checkfield(md,'fieldname','hydrology.epl_conductivity','numel',[1],'>',0.)
+	# }}}
+	def marshall(self,md,fid): #{{{ 
+		WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologydcEnum(),'format','Integer')
+		WriteData(fid,'object',self,'fieldname','water_compressibility','format','Double')
+		WriteData(fid,'object',self,'fieldname','isefficientlayer','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+		WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer')
+		WriteData(fid,'object',self,'fieldname','rel_tol','format','Double')
+		WriteData(fid,'object',self,'fieldname','max_iter','format','Integer')
+		WriteData(fid,'object',self,'fieldname','sedimentlimit_flag','format','Integer')
+		WriteData(fid,'object',self,'fieldname','transfer_flag','format','Integer')
+		if self.sedimentlimit_flag==1:
+			WriteData(fid,'object',self,'fieldname','sedimentlimit','format','Double')
+
+		if self.transfer_flag==1:
+			WriteData(fid,'object',self,'fieldname','leakage_factor','format','Double')
+
+		WriteData(fid,'object',self,'fieldname','basal_moulin_input','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','spcsediment_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','sediment_compressibility','format','Double')
+		WriteData(fid,'object',self,'fieldname','sediment_porosity','format','Double')			
+		WriteData(fid,'object',self,'fieldname','sediment_thickness','format','Double')
+		WriteData(fid,'object',self,'fieldname','sediment_transmitivity','format','DoubleMat','mattype',1)		
+
+		if self.isefficientlayer==1:	
+			WriteData(fid,'object',self,'fieldname','spcepl_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)	
+			WriteData(fid,'object',self,'fieldname','mask_eplactive_node','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','epl_compressibility','format','Double')			
+			WriteData(fid,'object',self,'fieldname','epl_porosity','format','Double')			
+			WriteData(fid,'object',self,'fieldname','epl_max_thickness','format','Double')
+			WriteData(fid,'object',self,'fieldname','epl_initial_thickness','format','Double')			
+			WriteData(fid,'object',self,'fieldname','epl_colapse_thickness','format','Double')
+			WriteData(fid,'object',self,'fieldname','epl_thick_comp','format','Integer')			
+			WriteData(fid,'object',self,'fieldname','epl_conductivity','format','Double')
+			WriteData(fid,'object',self,'fieldname','eplflip_lock','format','Integer')
+	# }}}
Index: /issm/trunk/src/m/classes/hydrologyshreve.m
===================================================================
--- /issm/trunk/src/m/classes/hydrologyshreve.m	(revision 19104)
+++ /issm/trunk/src/m/classes/hydrologyshreve.m	(revision 19105)
@@ -10,31 +10,33 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- Hydrology -->');
-            
-            % Convergence criteria            
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Hydrologyshreve solution parameters">','<section name="hydrologyshreve" />');                    
-            
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcwatercolumn" type="',      class(obj.spcwatercolumn),'" default="',        convert2str(obj.spcwatercolumn),'">',	'     <section name="hydrologyshreve" />','     <help> water thickness constraints (NaN means no constraint) [m] </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="stabilization" type="',         class(obj.stabilization),'" default="',           convert2str(obj.stabilization),'">',	'     <section name="hydrologyshreve" />','     <help> artificial diffusivity (default is 1). can be more than 1 to increase diffusivity. </help>','</parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-        end % }}}
-		function obj = hydrologyshreve(varargin) % {{{
+		function createxml(self,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- Hydrology -->');
+
+			% Convergence criteria            
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Hydrologyshreve solution parameters">','<section name="hydrologyshreve" />');                    
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcwatercolumn" type="',      class(self.spcwatercolumn),'" default="',        convert2str(self.spcwatercolumn),'">',	'     <section name="hydrologyshreve" />','     <help> water thickness constraints (NaN means no constraint) [m] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="stabilization" type="',         class(self.stabilization),'" default="',           convert2str(self.stabilization),'">',	'     <section name="hydrologyshreve" />','     <help> artificial diffusivity (default is 1). can be more than 1 to increase diffusivity. </help>','</parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+		end % }}}
+		function self = extrude(self,md) % {{{
+		end % }}}
+		function self = hydrologyshreve(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
-					obj=structtoobj(obj,varargin{1});
+					self=structtoobj(self,varargin{1});
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%Type of stabilization to use 0:nothing 1:artificial_diffusivity
-			obj.stabilization=1;
+			self.stabilization=1;
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
@@ -43,17 +45,17 @@
 			end
 
-			md = checkfield(md,'fieldname','hydrology.spcwatercolumn','forcing',1);
+			md = checkfield(md,'fieldname','hydrology.spcwatercolumn','timeseries',1);
 			md = checkfield(md,'fieldname','hydrology.stabilization','>=',0);
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   hydrologyshreve solution parameters:'));
-			fielddisplay(obj,'spcwatercolumn','water thickness constraints (NaN means no constraint) [m]');
-			fielddisplay(obj,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.');
+			fielddisplay(self,'spcwatercolumn','water thickness constraints (NaN means no constraint) [m]');
+			fielddisplay(self,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 			WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologyshreveEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'fieldname','stabilization','format','Double');
+			WriteData(fid,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'fieldname','stabilization','format','Double');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/hydrologyshreve.py
===================================================================
--- /issm/trunk/src/m/classes/hydrologyshreve.py	(revision 19104)
+++ /issm/trunk/src/m/classes/hydrologyshreve.py	(revision 19105)
@@ -27,4 +27,7 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		
@@ -40,5 +43,5 @@
 			return md
 
-		md = checkfield(md,'fieldname','hydrology.spcwatercolumn','forcing',1)
+		md = checkfield(md,'fieldname','hydrology.spcwatercolumn','timeseries',1)
 		md = checkfield(md,'fieldname','hydrology.stabilization','>=',0)
 
@@ -47,5 +50,5 @@
 	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologyshreveEnum(),'format','Integer');
-		WriteData(fid,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
 		WriteData(fid,'object',self,'fieldname','stabilization','format','Double')
 	# }}}
Index: /issm/trunk/src/m/classes/independent.m
===================================================================
--- /issm/trunk/src/m/classes/independent.m	(revision 19104)
+++ /issm/trunk/src/m/classes/independent.m	(revision 19105)
@@ -13,5 +13,5 @@
 	end
 	methods
-		function obj = independent(varargin) % {{{
+		function self = independent(varargin) % {{{
 
 			%use provided options to change fields
@@ -19,53 +19,54 @@
 
 			%OK get other fields
-			obj=AssignObjectFields(pairoptions(varargin{:}),obj);
+			self=AssignObjectFields(pairoptions(varargin{:}),self);
 
 		end
 		%}}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 			%do nothing
 
 		end % }}}
-		function md = checkconsistency(obj,md,i,solution,analyses,driver) % {{{
-			if ~isnan(obj.fos_forward_index),
+		function md = checkconsistency(self,md,i,solution,analyses,driver) % {{{
+			if ~isnan(self.fos_forward_index),
 				if ~strcmpi(driver,'fos_forward'),
 					error('cannot declare an independent with a fos_forward_index when the driver is not fos_forward!');
 				end
-				if obj.nods==0,
+				if self.nods==0,
 					error('independent checkconsistency error: nods should be set to the size of the independent variable');
 				end
 			end
 
-			if ~isempty(obj.fov_forward_indices),
+			if ~isempty(self.fov_forward_indices),
 				if ~strcmpi(driver,'fov_forward'),
 					error('cannot declare an independent with fov_forward_indices when the driver is not fov_forward!');
 				end
-				if obj.nods==0,
+				if self.nods==0,
 					error('independent checkconsistency error: nods should be set to the size of the independent variable');
 				end
-				md = checkfield(md,'fieldname',['autodiff.independents{' num2str(i) '}.fov_forward_indices'],'>=',1,'<=',obj.nods,'size',[NaN 1]);
+				md = checkfield(md,'fieldname',['autodiff.independents{' num2str(i) '}.fov_forward_indices'],'>=',1,'<=',self.nods,'size',[NaN 1]);
 			end
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   independent variable:'));
 
-			fielddisplay(obj,'name','variable name (must match corresponding Enum)');
-			fielddisplay(obj,'type','type of variable (''vertex'' or ''scalar'')');
-			if ~isnan(obj.fos_forward_index),
-				fielddisplay(obj,'fos_forward_index','index for fos_foward driver of ADOLC');
+			fielddisplay(self,'name','variable name (must match corresponding Enum)');
+			fielddisplay(self,'type','type of variable (''vertex'' or ''scalar'')');
+			fielddisplay(self,'nods','size of dependent variables');
+			if ~isnan(self.fos_forward_index),
+				fielddisplay(self,'fos_forward_index','index for fos_foward driver of ADOLC');
 			end
-			if ~isnan(obj.fov_forward_indices),
-				fielddisplay(obj,'fov_forward_indices','indices for fov_foward driver of ADOLC');
+			if ~isnan(self.fov_forward_indices),
+				fielddisplay(self,'fov_forward_indices','indices for fov_foward driver of ADOLC');
 			end
 		end % }}}
-		function scalartype=typetoscalar(obj) % {{{
-			if strcmpi(obj.type,'scalar'),
+		function scalartype=typetoscalar(self) % {{{
+			if strcmpi(self.type,'scalar'),
 				scalartype=0;
-			elseif strcmpi(obj.type,'vertex'),
+			elseif strcmpi(self.type,'vertex'),
 				scalartype=1;
-			elseif strcmpi(obj.type,'matrix'),
+			elseif strcmpi(self.type,'matrix'),
 				scalartype=1;
-			else error([obj.type ' not supported yet!']);
+			else error([self.type ' not supported yet!']);
 			end
 		end % }}}
Index: /issm/trunk/src/m/classes/initialization.m
===================================================================
--- /issm/trunk/src/m/classes/initialization.m	(revision 19104)
+++ /issm/trunk/src/m/classes/initialization.m	(revision 19105)
@@ -19,33 +19,48 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- initialization -->');
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Initial field values">','<section name="initialization" />');                    
-            
-			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vx" type="',class(obj.vx),'" default="',obj.vx,'">','     <section name="initialization" />','     <help> x component of velocity [m/yr] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vy" type="',class(obj.vy),'" default="',obj.vy,'">','     <section name="initialization" />','     <help> y component of velocity [m/yr] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vz" type="',class(obj.vz),'" default="',obj.vz,'">','     <section name="initialization" />','     <help> z component of velocity [m/yr] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vel" type="',class(obj.vel),'" default="',obj.vel,'">','     <section name="initialization" />','     <help> velocity norm [m/yr] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="pressure" type="',class(obj.pressure),'" default="',obj.pressure,'">','     <section name="initialization" />','     <help> pressure field [Pa] </help>','</parameter>');
-        	 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="temperature" type="',class(obj.temperature),'" default="',obj.temperature,'">','     <section name="initialization" />','     <help> fraction of water in the ice </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="waterfraction" type="',class(obj.waterfraction),'" default="',obj.waterfraction,'">','     <section name="initialization" />','     <help> ice thickness [m] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="sediment_head" type="',class(obj.sediment_head),'" default="',obj.sediment_head,'">','     <section name="initialization" />','     <help> sediment water head of subglacial system [m] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="epl_head" type="',class(obj.epl_head),'" default="',obj.epl_head,'">','     <section name="initialization" />','     <help> epl water head of subglacial system [m] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="watercolumn" type="',class(obj.watercolumn),'" default="',obj.watercolumn,'">','     <section name="initialization" />','     <help> thickness of subglacial water [m] </help>','</parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-        end % }}}
-		function obj = initialization(varargin) % {{{
+		function createxml(self,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- initialization -->');
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Initial field values">','<section name="initialization" />');                    
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vx" type="',class(self.vx),'" default="',self.vx,'">','     <section name="initialization" />','     <help> x component of velocity [m/yr] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vy" type="',class(self.vy),'" default="',self.vy,'">','     <section name="initialization" />','     <help> y component of velocity [m/yr] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vz" type="',class(self.vz),'" default="',self.vz,'">','     <section name="initialization" />','     <help> z component of velocity [m/yr] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="vel" type="',class(self.vel),'" default="',self.vel,'">','     <section name="initialization" />','     <help> velocity norm [m/yr] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="pressure" type="',class(self.pressure),'" default="',self.pressure,'">','     <section name="initialization" />','     <help> pressure field [Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="temperature" type="',class(self.temperature),'" default="',self.temperature,'">','     <section name="initialization" />','     <help> fraction of water in the ice </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="waterfraction" type="',class(self.waterfraction),'" default="',self.waterfraction,'">','     <section name="initialization" />','     <help> ice thickness [m] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="sediment_head" type="',class(self.sediment_head),'" default="',self.sediment_head,'">','     <section name="initialization" />','     <help> sediment water head of subglacial system [m] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="epl_head" type="',class(self.epl_head),'" default="',self.epl_head,'">','     <section name="initialization" />','     <help> epl water head of subglacial system [m] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="watercolumn" type="',class(self.watercolumn),'" default="',self.watercolumn,'">','     <section name="initialization" />','     <help> thickness of subglacial water [m] </help>','</parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.vx=project3d(md,'vector',self.vx,'type','node');
+			self.vy=project3d(md,'vector',self.vy,'type','node');
+			self.vz=project3d(md,'vector',self.vz,'type','node');
+			self.vel=project3d(md,'vector',self.vel,'type','node');
+			self.temperature=project3d(md,'vector',self.temperature,'type','node');
+			self.waterfraction=project3d(md,'vector',self.waterfraction,'type','node');
+			self.watercolumn=project3d(md,'vector',self.watercolumn,'type','node','layer',1);
+			self.sediment_head=project3d(md,'vector',self.sediment_head,'type','node','layer',1);
+			self.epl_head=project3d(md,'vector',self.epl_head,'type','node','layer',1);
+			self.epl_thickness=project3d(md,'vector',self.epl_thickness,'type','node','layer',1);
+
+			%Lithostatic pressure by default
+			self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z);
+		end % }}}
+		function self = initialization(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 			if ismember(StressbalanceAnalysisEnum(),analyses)
 				if ~(isnan(md.initialization.vx) | isnan(md.initialization.vy)),
@@ -73,4 +88,5 @@
 				end
 				md = checkfield(md,'fieldname','initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'fieldname','initialization.temperature','NaN',1,'size',[md.mesh.numberofvertices 1]);
 			end
 			if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy)
@@ -91,6 +107,5 @@
 				if isa(md.hydrology,'hydrologydc'),
 					if md.hydrology.isefficientlayer==1,
-						md = checkfield(md,'fieldname', ...
-														'initialization.epl_head','NaN',1,'size',[md.mesh.numberofvertices 1]);
+						md = checkfield(md,'fieldname','initialization.epl_head','NaN',1,'size',[md.mesh.numberofvertices 1]);
 						md = checkfield(md,'fieldname','initialization.epl_thickness','NaN',1,'size',[md.mesh.numberofvertices 1]);
 					end
@@ -98,40 +113,40 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   initial field values:'));
 
-			fielddisplay(obj,'vx','x component of velocity [m/yr]');
-			fielddisplay(obj,'vy','y component of velocity [m/yr]');
-			fielddisplay(obj,'vz','z component of velocity [m/yr]');
-			fielddisplay(obj,'vel','velocity norm [m/yr]');
-			fielddisplay(obj,'pressure','pressure field [Pa]');
-			fielddisplay(obj,'temperature','temperature [K]');
-			fielddisplay(obj,'waterfraction','fraction of water in the ice');
-			fielddisplay(obj,'sediment_head','sediment water head of subglacial system [m]');
-			fielddisplay(obj,'epl_head','epl water head of subglacial system [m]');
-			fielddisplay(obj,'epl_thickness','epl layer thickness [m]');
-			fielddisplay(obj,'watercolumn','thickness of subglacial water [m]');
+			fielddisplay(self,'vx','x component of velocity [m/yr]');
+			fielddisplay(self,'vy','y component of velocity [m/yr]');
+			fielddisplay(self,'vz','z component of velocity [m/yr]');
+			fielddisplay(self,'vel','velocity norm [m/yr]');
+			fielddisplay(self,'pressure','pressure field [Pa]');
+			fielddisplay(self,'temperature','temperature [K]');
+			fielddisplay(self,'waterfraction','fraction of water in the ice');
+			fielddisplay(self,'sediment_head','sediment water head of subglacial system [m]');
+			fielddisplay(self,'epl_head','epl water head of subglacial system [m]');
+			fielddisplay(self,'epl_thickness','epl layer thickness [m]');
+			fielddisplay(self,'watercolumn','thickness of subglacial water [m]');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
-			WriteData(fid,'data',obj.vx,'format','DoubleMat','mattype',1,'enum',VxEnum,'scale',1./yts);
-			WriteData(fid,'data',obj.vy,'format','DoubleMat','mattype',1,'enum',VyEnum,'scale',1./yts);
-			WriteData(fid,'data',obj.vz,'format','DoubleMat','mattype',1,'enum',VzEnum,'scale',1./yts);
-			WriteData(fid,'data',obj.pressure,'format','DoubleMat','mattype',1,'enum',PressureEnum);
-			WriteData(fid,'data',obj.temperature,'format','DoubleMat','mattype',1,'enum',TemperatureEnum);
-			WriteData(fid,'data',obj.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum);
-			WriteData(fid,'data',obj.sediment_head,'format','DoubleMat','mattype',1,'enum',SedimentHeadEnum);
-			WriteData(fid,'data',obj.epl_head,'format','DoubleMat','mattype',1,'enum',EplHeadEnum);
-			WriteData(fid,'data',obj.epl_thickness,'format','DoubleMat','mattype',1,'enum',HydrologydcEplThicknessEnum);
-			WriteData(fid,'data',obj.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum);
+			WriteData(fid,'data',self.vx,'format','DoubleMat','mattype',1,'enum',VxEnum,'scale',1./yts);
+			WriteData(fid,'data',self.vy,'format','DoubleMat','mattype',1,'enum',VyEnum,'scale',1./yts);
+			WriteData(fid,'data',self.vz,'format','DoubleMat','mattype',1,'enum',VzEnum,'scale',1./yts);
+			WriteData(fid,'data',self.pressure,'format','DoubleMat','mattype',1,'enum',PressureEnum);
+			WriteData(fid,'data',self.temperature,'format','DoubleMat','mattype',1,'enum',TemperatureEnum);
+			WriteData(fid,'data',self.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum);
+			WriteData(fid,'data',self.sediment_head,'format','DoubleMat','mattype',1,'enum',SedimentHeadEnum);
+			WriteData(fid,'data',self.epl_head,'format','DoubleMat','mattype',1,'enum',EplHeadEnum);
+			WriteData(fid,'data',self.epl_thickness,'format','DoubleMat','mattype',1,'enum',HydrologydcEplThicknessEnum);
+			WriteData(fid,'data',self.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum);
 
 			if md.thermal.isenthalpy,
 				tpmp = md.materials.meltingpoint - md.materials.beta*md.initialization.pressure;
-				pos  = find(md.initialization.temperature>tpmp);
+				pos  = find(md.initialization.temperature>=tpmp);
 				enthalpy      = md.materials.heatcapacity*(md.initialization.temperature-md.constants.referencetemperature);
-				enthalpy(pos) = md.materials.heatcapacity*tpmp(pos) - md.constants.referencetemperature + md.materials.latentheat*md.initialization.waterfraction(pos);
+				enthalpy(pos) = md.materials.heatcapacity*(tpmp(pos) - md.constants.referencetemperature) + md.materials.latentheat*md.initialization.waterfraction(pos);
 				WriteData(fid,'data',enthalpy,'format','DoubleMat','mattype',1,'enum',EnthalpyEnum());
 			end
Index: /issm/trunk/src/m/classes/initialization.py
===================================================================
--- /issm/trunk/src/m/classes/initialization.py	(revision 19104)
+++ /issm/trunk/src/m/classes/initialization.py	(revision 19105)
@@ -1,3 +1,4 @@
 import numpy
+from project3d import project3d
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -9,11 +10,11 @@
 	"""
 	INITIALIZATION class definition
-
-	   Usage:
-	      initialization=initialization();
+	
+	Usage:
+	initialization=initialization();
 	"""
 
 	def __init__(self): # {{{
-		
+					
 		self.vx            = float('NaN')
 		self.vy            = float('NaN')
@@ -24,5 +25,7 @@
 		self.waterfraction = float('NaN')
 		self.watercolumn   = float('NaN')
-		self.sediment_head  = float('NaN')
+		self.sediment_head = float('NaN')
+		self.epl_head      = float('NaN')
+		self.epl_thickness = float('NaN')
 
 		#set defaults
@@ -32,5 +35,4 @@
 	def __repr__(self): # {{{
 		string='   initial field values:'
-
 		string="%s\n%s"%(string,fielddisplay(self,'vx','x component of velocity [m/yr]'))
 		string="%s\n%s"%(string,fielddisplay(self,'vy','y component of velocity [m/yr]'))
@@ -42,7 +44,25 @@
 		string="%s\n%s"%(string,fielddisplay(self,'watercolumn','thickness of subglacial water [m]'))
 		string="%s\n%s"%(string,fielddisplay(self,'sediment_head','sediment water head of subglacial system [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'epl_head','epl water head of subglacial system [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'epl_thickness','thickness of the epl [m]'))
 
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.vx=project3d(md,'vector',self.vx,'type','node')
+		self.vy=project3d(md,'vector',self.vy,'type','node')
+		self.vz=project3d(md,'vector',self.vz,'type','node')
+		self.vel=project3d(md,'vector',self.vel,'type','node')
+		self.temperature=project3d(md,'vector',self.temperature,'type','node')
+		self.waterfraction=project3d(md,'vector',self.waterfraction,'type','node')
+		self.watercolumn=project3d(md,'vector',self.watercolumn,'type','node')
+		self.sediment_head=project3d(md,'vector',self.sediment_head,'type','node','layer',1)
+		self.epl_head=project3d(md,'vector',self.epl_head,'type','node','layer',1)
+		self.epl_thickness=project3d(md,'vector',self.epl_thickness,'type','node','layer',1)
+
+		#Lithostatic pressure by default
+		self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z.reshape(-1,1))
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		return self
@@ -66,12 +86,23 @@
 			md = checkfield(md,'fieldname','initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
 			md = checkfield(md,'fieldname','initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'fieldname','initialization.temperature','NaN',1,'size',[md.mesh.numberofvertices])
 			if md.mesh.dimension()==3:
 				md = checkfield(md,'fieldname','initialization.vz','NaN',1,'size',[md.mesh.numberofvertices])
 			md = checkfield(md,'fieldname','initialization.pressure','NaN',1,'size',[md.mesh.numberofvertices])
-		if (EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy):
-			md = checkfield(md,'fieldname','initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices])
-			md = checkfield(md,'fieldname','initialization.watercolumn'  ,'>=',0,'size',[md.mesh.numberofvertices])
+			if (EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy):
+				md = checkfield(md,'fieldname','initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices])
+				md = checkfield(md,'fieldname','initialization.watercolumn'  ,'>=',0,'size',[md.mesh.numberofvertices])
 		if HydrologyShreveAnalysisEnum() in analyses:
-			md = checkfield(md,'fieldname','initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices])
+			if hasattr(md.hydrology,'hydrologyshreve'):
+				md = checkfield(md,'fieldname','initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices])
+		if HydrologyDCInefficientAnalysisEnum() in analyses:
+			if hasattr(md.hydrology,'hydrologydc'):
+				md = checkfield(md,'fieldname','initialization.sediment_head','NaN',1,'size',[md.mesh.numberofvertices,1])
+		if HydrologyDCEfficientAnalysisEnum() in analyses:
+			if hasattr(md.hydrology,'hydrologydc'):
+				if md.hydrology.isefficientlayer==1:
+					md = checkfield(md,'fieldname','initialization.epl_head','NaN',1,'size',[md.mesh.numberofvertices,1])
+					md = checkfield(md,'fieldname','initialization.epl_thickness','NaN',1,'size',[md.mesh.numberofvertices,1])
+
 		return md
 	# }}}
@@ -88,5 +119,8 @@
 		WriteData(fid,'data',self.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum())
 		WriteData(fid,'data',self.sediment_head,'format','DoubleMat','mattype',1,'enum',SedimentHeadEnum())
+		WriteData(fid,'data',self.epl_head,'format','DoubleMat','mattype',1,'enum',EplHeadEnum())
+		WriteData(fid,'data',self.epl_thickness,'format','DoubleMat','mattype',1,'enum',HydrologydcEplThicknessEnum())
 
+		
 		if md.thermal.isenthalpy:
 			tpmp = md.materials.meltingpoint - md.materials.beta*md.initialization.pressure;
Index: /issm/trunk/src/m/classes/inversion.m
===================================================================
--- /issm/trunk/src/m/classes/inversion.m	(revision 19104)
+++ /issm/trunk/src/m/classes/inversion.m	(revision 19105)
@@ -23,12 +23,13 @@
 		vel_obs                     = NaN
 		thickness_obs               = NaN
+		surface_obs                 = NaN
 	end
 	methods
-		function createxml(obj,fid) % {{{
+		function createxml(self,fid) % {{{
 			fprintf(fid, '<!-- inversion -->\n');            
 
 			% inversion parameters
 			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="inversion parameters">','<section name="inversion" />');                    
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="iscontrol" type="',class(obj.iscontrol),'" default="',convert2str(obj.iscontrol),'">','     <section name="inversion" />','     <help> is inversion activated? </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="iscontrol" type="',class(self.iscontrol),'" default="',convert2str(self.iscontrol),'">','     <section name="inversion" />','     <help> is inversion activated? </help>','  </parameter>');
 
 			% incompleteadjoing drop-down (0 or 1)
@@ -37,22 +38,22 @@
 			fprintf(fid,'%s\n%s\n','       <option value="1" type="string" default="false"> </option>','</parameter>');
 
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="control_parameters" type="',class(obj.control_parameters),'" default="',convert2str(obj.control_parameters),'">','     <section name="inversion" />','     <help> ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''} </help>','  </parameter>');
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="nsteps" type="',class(obj.nsteps),'" default="',convert2str(obj.nsteps),'">','     <section name="inversion" />','     <help> number of optimization searches </help>','  </parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_functions" type="',class(obj.cost_functions),'" default="',convert2str(obj.cost_functions),'">','     <section name="inversion" />','     <help> indicate the type of response for each optimization step  </help>','  </parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_functions_coefficients" type="',class(obj.cost_functions_coefficients),'" default="',convert2str(obj.cost_functions_coefficients),'">','     <section name="inversion" />','     <help> cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter </help>','  </parameter>');
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_function_threshold" type="',class(obj.cost_function_threshold),'" default="',convert2str(obj.cost_function_threshold),'">','     <section name="inversion" />','     <help> misfit convergence criterion. Default is 1%, NaN if not applied </help>','  </parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="maxiter_per_step" type="',class(obj.maxiter_per_step),'" default="',convert2str(obj.maxiter_per_step),'">','     <section name="inversion" />','     <help> maximum iterations during each optimization step  </help>','  </parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gradient_scaling" type="',class(obj.gradient_scaling),'" default="',convert2str(obj.gradient_scaling),'">','     <section name="inversion" />','     <help> scaling factor on gradient direction during optimization, for each optimization step </help>','  </parameter>');
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="step_threshold" type="',class(obj.step_threshold),'" default="',convert2str(obj.step_threshold),'">','     <section name="inversion" />','     <help> decrease threshold for misfit, default is 30% </help>','  </parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="min_parameters" type="',class(obj.min_parameters),'" default="',convert2str(obj.min_parameters),'">','     <section name="inversion" />','     <help> absolute minimum acceptable value of the inversed parameter on each vertex </help>','  </parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="max_parameters" type="',class(obj.max_parameters),'" default="',convert2str(obj.max_parameters),'">','     <section name="inversion" />','     <help> absolute maximum acceptable value of the inversed parameter on each vertex </help>','  </parameter>');
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vx_obs" type="',class(obj.vx_obs),'" default="',convert2str(obj.vx_obs),'">','     <section name="inversion" />','     <help> observed velocity x component [m/yr] </help>','  </parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vy_obs" type="',class(obj.vy_obs),'" default="',convert2str(obj.vy_obs),'">','     <section name="inversion" />','     <help> observed velocity y component [m/yr]  </help>','  </parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vel_obs" type="',class(obj.vel_obs),'" default="',convert2str(obj.vel_obs),'">','     <section name="inversion" />','     <help> observed velocity magnitude [m/yr] </help>','  </parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="thickness_obs" type="',class(obj.thickness_obs),'" default="',convert2str(obj.thickness_obs),'">','     <section name="inversion" />','     <help> observed thickness [m]) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="control_parameters" type="',class(self.control_parameters),'" default="',convert2str(self.control_parameters),'">','     <section name="inversion" />','     <help> ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''} </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="nsteps" type="',class(self.nsteps),'" default="',convert2str(self.nsteps),'">','     <section name="inversion" />','     <help> number of optimization searches </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_functions" type="',class(self.cost_functions),'" default="',convert2str(self.cost_functions),'">','     <section name="inversion" />','     <help> indicate the type of response for each optimization step  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_functions_coefficients" type="',class(self.cost_functions_coefficients),'" default="',convert2str(self.cost_functions_coefficients),'">','     <section name="inversion" />','     <help> cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="cost_function_threshold" type="',class(self.cost_function_threshold),'" default="',convert2str(self.cost_function_threshold),'">','     <section name="inversion" />','     <help> misfit convergence criterion. Default is 1%, NaN if not applied </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="maxiter_per_step" type="',class(self.maxiter_per_step),'" default="',convert2str(self.maxiter_per_step),'">','     <section name="inversion" />','     <help> maximum iterations during each optimization step  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="gradient_scaling" type="',class(self.gradient_scaling),'" default="',convert2str(self.gradient_scaling),'">','     <section name="inversion" />','     <help> scaling factor on gradient direction during optimization, for each optimization step </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="step_threshold" type="',class(self.step_threshold),'" default="',convert2str(self.step_threshold),'">','     <section name="inversion" />','     <help> decrease threshold for misfit, default is 30% </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="min_parameters" type="',class(self.min_parameters),'" default="',convert2str(self.min_parameters),'">','     <section name="inversion" />','     <help> absolute minimum acceptable value of the inversed parameter on each vertex </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="max_parameters" type="',class(self.max_parameters),'" default="',convert2str(self.max_parameters),'">','     <section name="inversion" />','     <help> absolute maximum acceptable value of the inversed parameter on each vertex </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vx_obs" type="',class(self.vx_obs),'" default="',convert2str(self.vx_obs),'">','     <section name="inversion" />','     <help> observed velocity x component [m/yr] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vy_obs" type="',class(self.vy_obs),'" default="',convert2str(self.vy_obs),'">','     <section name="inversion" />','     <help> observed velocity y component [m/yr]  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vel_obs" type="',class(self.vel_obs),'" default="',convert2str(self.vel_obs),'">','     <section name="inversion" />','     <help> observed velocity magnitude [m/yr] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="thickness_obs" type="',class(self.thickness_obs),'" default="',convert2str(self.thickness_obs),'">','     <section name="inversion" />','     <help> observed thickness [m]) </help>','  </parameter>');
 
 			fprintf(fid,'%s\n%s\n','</frame>');    
@@ -74,29 +75,38 @@
 
 		end % }}}       
-		function obj = inversion(varargin) % {{{
+		function self = inversion(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
-					obj=structtoobj(inversion(),varargin{1});
+					self =structtoobj(inversion(),varargin{1});
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = extrude(self,md) % {{{
+			self.vx_obs=project3d(md,'vector',self.vx_obs,'type','node');
+			self.vy_obs=project3d(md,'vector',self.vy_obs,'type','node');
+			self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node');
+			self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node');
+			if numel(self.cost_functions_coefficients)>1,self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node');end;
+			if numel(self.min_parameters)>1,self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node');end;
+			if numel(self.max_parameters)>1,self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node');end;
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
 
 			%default is incomplete adjoint for now
-			obj.incomplete_adjoint=1;
+			self.incomplete_adjoint=1;
 
 			%parameter to be inferred by control methods (only
 			%drag and B are supported yet)
-			obj.control_parameters={'FrictionCoefficient'};
+			self.control_parameters={'FrictionCoefficient'};
 
 			%number of steps in the control methods
-			obj.nsteps=20;
+			self.nsteps=20;
 
 			%maximum number of iteration in the optimization algorithm for
 			%each step
-			obj.maxiter_per_step=20*ones(obj.nsteps,1);
+			self.maxiter_per_step=20*ones(self.nsteps,1);
 
 			%the inversed parameter is updated as follows:
@@ -105,24 +115,24 @@
 			%inversed parameter (10^8 for B, 50 for drag) and can be decreased
 			%after the first iterations
-			obj.gradient_scaling=50*ones(obj.nsteps,1);
+			self.gradient_scaling=50*ones(self.nsteps,1);
 
 			%several responses can be used:
-			obj.cost_functions=101;
+			self.cost_functions=101;
 
 			%step_threshold is used to speed up control method. When
-			%misfit(1)/misfit(0) < obj.step_threshold, we go directly to
+			%misfit(1)/misfit(0) < self.step_threshold, we go directly to
 			%the next step
-			obj.step_threshold=.7*ones(obj.nsteps,1); %30 per cent decrement.
+			self.step_threshold=.7*ones(self.nsteps,1); %30 per cent decrement.
 
 			%cost_function_threshold is a criteria to stop the control methods.
 			%if J[n]-J[n-1]/J[n] < criteria, the control run stops
 			%NaN if not applied
-			obj.cost_function_threshold=NaN; %not activated
-
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			self.cost_function_threshold=NaN; %not activated
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
-			if ~obj.iscontrol, return; end
+			if ~self.iscontrol, return; end
 
 			num_controls=numel(md.inversion.control_parameters);
@@ -131,10 +141,9 @@
 			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
 			md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0 1]);
-			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
-				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'DamageDbar' 'Vx' 'Vy' 'Thickness' 'BalancethicknessNux' 'BalancethicknessNuy' 'BalancethicknessApparentMassbalance'});
+			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',supportedcontrols());
 			md = checkfield(md,'fieldname','inversion.nsteps','numel',1,'>=',0);
 			md = checkfield(md,'fieldname','inversion.maxiter_per_step','size',[md.inversion.nsteps 1],'>=',0);
 			md = checkfield(md,'fieldname','inversion.step_threshold','size',[md.inversion.nsteps 1]);
-			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:507]);
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',supportedcostfunctions());
 			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
 			md = checkfield(md,'fieldname','inversion.gradient_scaling','size',[md.inversion.nsteps num_controls]);
@@ -144,5 +153,5 @@
 			%Only SSA, HO and FS are supported right now
 			if solution==StressbalanceSolutionEnum()
-				if ~(md.flowequation.isSSA || md.flowequation.isHO || md.flowequation.isFS),
+				if ~(md.flowequation.isSSA || md.flowequation.isHO || md.flowequation.isFS || md.flowequation.isL1L2),
 					md = checkmessage(md,['inversion can only be performed for SSA, HO or FS ice flow models']);
 				end
@@ -158,22 +167,23 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   inversion parameters:'));
-			fielddisplay(obj,'iscontrol','is inversion activated?');
-			fielddisplay(obj,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
-			fielddisplay(obj,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
-			fielddisplay(obj,'nsteps','number of optimization searches');
-			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step');
-			fielddisplay(obj,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
-			fielddisplay(obj,'cost_function_threshold','misfit convergence criterion. Default is 1%, NaN if not applied');
-			fielddisplay(obj,'maxiter_per_step','maximum iterations during each optimization step');
-			fielddisplay(obj,'gradient_scaling','scaling factor on gradient direction during optimization, for each optimization step');
-			fielddisplay(obj,'step_threshold','decrease threshold for misfit, default is 30%');
-			fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
-			fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
-			fielddisplay(obj,'vx_obs','observed velocity x component [m/yr]');
-			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
-			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/yr]');
-			fielddisplay(obj,'thickness_obs','observed thickness [m]');
+			fielddisplay(self,'iscontrol','is inversion activated?');
+			fielddisplay(self,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
+			fielddisplay(self,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(self,'nsteps','number of optimization searches');
+			fielddisplay(self,'cost_functions','indicate the type of response for each optimization step');
+			fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
+			fielddisplay(self,'cost_function_threshold','misfit convergence criterion. Default is 1%, NaN if not applied');
+			fielddisplay(self,'maxiter_per_step','maximum iterations during each optimization step');
+			fielddisplay(self,'gradient_scaling','scaling factor on gradient direction during optimization, for each optimization step');
+			fielddisplay(self,'step_threshold','decrease threshold for misfit, default is 30%');
+			fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(self,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]');
+			fielddisplay(self,'thickness_obs','observed thickness [m]');
+			fielddisplay(self,'surface_obs','observed surface elevation [m]');
 			disp('Available cost functions:');
 			disp('   101: SurfaceAbsVelMisfit');
@@ -187,36 +197,37 @@
 			disp('   503: ThicknessAbsGradient');
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
 			WriteData(fid,'enum',InversionTypeEnum(),'data',0,'format','Integer');
-			WriteData(fid,'object',obj,'fieldname','iscontrol','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','incomplete_adjoint','format','Boolean');
-			if ~obj.iscontrol, return; end
-			WriteData(fid,'object',obj,'fieldname','nsteps','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','maxiter_per_step','format','IntMat','mattype',3);
-			WriteData(fid,'object',obj,'fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','gradient_scaling','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'fieldname','cost_function_threshold','format','Double');
-			WriteData(fid,'object',obj,'fieldname','min_parameters','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'fieldname','max_parameters','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'fieldname','step_threshold','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			if(numel(obj.thickness_obs)==md.mesh.numberofelements),
+			WriteData(fid,'object',self,'fieldname','iscontrol','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','incomplete_adjoint','format','Boolean');
+			if ~self.iscontrol, return; end
+			WriteData(fid,'object',self,'fieldname','nsteps','format','Integer');
+			WriteData(fid,'object',self,'fieldname','maxiter_per_step','format','IntMat','mattype',3);
+			WriteData(fid,'object',self,'fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','gradient_scaling','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'fieldname','cost_function_threshold','format','Double');
+			WriteData(fid,'object',self,'fieldname','min_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'fieldname','max_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'fieldname','step_threshold','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			if(numel(self.thickness_obs)==md.mesh.numberofelements),
 				mattype=2;
 			else
 				mattype=1;
 			end
-			WriteData(fid,'object',obj,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
+			WriteData(fid,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
+			WriteData(fid,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',mattype);
 
 
 			%process control parameters
-			num_control_parameters=numel(obj.control_parameters);
+			num_control_parameters=numel(self.control_parameters);
 			data=zeros(1,num_control_parameters);
 			for i=1:num_control_parameters,
-				data(i)=StringToEnum(obj.control_parameters{i});
+				data(i)=StringToEnum(self.control_parameters{i});
 			end
 			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
@@ -224,19 +235,6 @@
 
 			%process cost functions
-			num_cost_functions=size(obj.cost_functions,2);
-			data=obj.cost_functions;
-			pos=find(obj.cost_functions==101); data(pos)=SurfaceAbsVelMisfitEnum();
-			pos=find(obj.cost_functions==102); data(pos)=SurfaceRelVelMisfitEnum();
-			pos=find(obj.cost_functions==103); data(pos)=SurfaceLogVelMisfitEnum();
-			pos=find(obj.cost_functions==104); data(pos)=SurfaceLogVxVyMisfitEnum();
-			pos=find(obj.cost_functions==105); data(pos)=SurfaceAverageVelMisfitEnum();
-			pos=find(obj.cost_functions==201); data(pos)=ThicknessAbsMisfitEnum();
-			pos=find(obj.cost_functions==501); data(pos)=DragCoefficientAbsGradientEnum();
-			pos=find(obj.cost_functions==502); data(pos)=RheologyBbarAbsGradientEnum();
-			pos=find(obj.cost_functions==503); data(pos)=ThicknessAbsGradientEnum();
-			pos=find(obj.cost_functions==504); data(pos)=ThicknessAlongGradientEnum();
-			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
-			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
-			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
+			num_cost_functions=size(self.cost_functions,2);
+			data=marshallcostfunctions(self.cost_functions);
 			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
 			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
Index: /issm/trunk/src/m/classes/inversion.py
===================================================================
--- /issm/trunk/src/m/classes/inversion.py	(revision 19104)
+++ /issm/trunk/src/m/classes/inversion.py	(revision 19105)
@@ -1,4 +1,4 @@
 import numpy
-import copy
+from project3d import project3d
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -6,4 +6,7 @@
 from checkfield import checkfield
 from WriteData import WriteData
+from supportedcontrols import supportedcontrols
+from supportedcostfunctions import supportedcostfunctions
+from marshallcostfunctions import marshallcostfunctions
 
 class inversion(object):
@@ -33,4 +36,5 @@
 		self.vel_obs                     = float('NaN')
 		self.thickness_obs               = float('NaN')
+		self.surface_obs                 = float('NaN')
 
 		#set defaults
@@ -56,4 +60,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]'))
 		string="%s\n%s"%(string,fielddisplay(self,'thickness_obs','observed thickness [m]'))
+		string="%s\n%s"%(string,fielddisplay(self,'surface_obs','observed surface elevation [m]'))
 		string="%s\n%s"%(string,'Available cost functions:')
 		string="%s\n%s"%(string,'   101: SurfaceAbsVelMisfit')
@@ -68,4 +73,17 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.vx_obs=project3d(md,'vector',self.vx_obs,'type','node')
+		self.vy_obs=project3d(md,'vector',self.vy_obs,'type','node')
+		self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node')
+		self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node')
+		if not numpy.any(numpy.isnan(self.cost_functions_coefficients)):
+			self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node')
+		if not numpy.any(numpy.isnan(self.min_parameters)):
+			self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node')
+		if not numpy.any(numpy.isnan(self.max_parameters)):
+			self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node')
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		
@@ -117,9 +135,9 @@
 		md = checkfield(md,'fieldname','inversion.iscontrol','values',[0,1])
 		md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0,1])
-		md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',['BalancethicknessThickeningRate','FrictionCoefficient','MaterialsRheologyBbar','DamageDbar','Vx','Vy'])
+		md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',supportedcontrols())
 		md = checkfield(md,'fieldname','inversion.nsteps','numel',[1],'>=',0)
 		md = checkfield(md,'fieldname','inversion.maxiter_per_step','size',[md.inversion.nsteps],'>=',0)
 		md = checkfield(md,'fieldname','inversion.step_threshold','size',[md.inversion.nsteps])
-		md = checkfield(md,'fieldname','inversion.cost_functions','size',[num_costfunc],'values',[101,102,103,104,105,201,501,502,503,504,505])
+		md = checkfield(md,'fieldname','inversion.cost_functions','size',[num_costfunc],'values',supportedcostfunctions())
 		md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices,num_costfunc],'>=',0)
 		md = checkfield(md,'fieldname','inversion.gradient_scaling','size',[md.inversion.nsteps,num_controls])
@@ -129,5 +147,5 @@
 		#Only SSA, HO and FS are supported right now
 		if solution==StressbalanceSolutionEnum():
-			if not (md.flowequation.isSSA or md.flowequation.isHO or md.flowequation.isFS):
+			if not (md.flowequation.isSSA or md.flowequation.isHO or md.flowequation.isFS or md.flowequation.isL1L2):
 				md.checkmessage("'inversion can only be performed for SSA, HO or FS ice flow models");
 
@@ -161,4 +179,5 @@
 		WriteData(fid,'object',self,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
 		WriteData(fid,'object',self,'fieldname','thickness_obs','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','surface_obs','format','DoubleMat','mattype',1)
 
 		#process control parameters
@@ -170,27 +189,5 @@
 		#process cost functions
 		num_cost_functions=numpy.size(self.cost_functions)
-		data=copy.deepcopy(self.cost_functions)
-		pos=[i for i,x in enumerate(self.cost_functions) if x==101];
-		for i in pos: data[i]=SurfaceAbsVelMisfitEnum()        
-		pos=[i for i,x in enumerate(self.cost_functions) if x==102];
-		for i in pos: data[i]=SurfaceRelVelMisfitEnum()        
-		pos=[i for i,x in enumerate(self.cost_functions) if x==103];
-		for i in pos: data[i]=SurfaceLogVelMisfitEnum()        
-		pos=[i for i,x in enumerate(self.cost_functions) if x==104];
-		for i in pos: data[i]=SurfaceLogVxVyMisfitEnum()       
-		pos=[i for i,x in enumerate(self.cost_functions) if x==105];
-		for i in pos: data[i]=SurfaceAverageVelMisfitEnum()    
-		pos=[i for i,x in enumerate(self.cost_functions) if x==201];
-		for i in pos: data[i]=ThicknessAbsMisfitEnum()         
-		pos=[i for i,x in enumerate(self.cost_functions) if x==501];
-		for i in pos: data[i]=DragCoefficientAbsGradientEnum() 
-		pos=[i for i,x in enumerate(self.cost_functions) if x==502];
-		for i in pos: data[i]=RheologyBbarAbsGradientEnum()    
-		pos=[i for i,x in enumerate(self.cost_functions) if x==503];
-		for i in pos: data[i]=ThicknessAbsGradientEnum()       
-		pos=[i for i,x in enumerate(self.cost_functions) if x==504];
-		for i in pos: data[i]=ThicknessAlongGradientEnum()     
-		pos=[i for i,x in enumerate(self.cost_functions) if x==505];
-		for i in pos: data[i]=ThicknessAcrossGradientEnum()    
+		data=marshallcostfunctions(self.cost_functions)
 		WriteData(fid,'data',numpy.array(data).reshape(1,-1),'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)
 		WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')
Index: /issm/trunk/src/m/classes/inversionvalidation.m
===================================================================
--- /issm/trunk/src/m/classes/inversionvalidation.m	(revision 19104)
+++ /issm/trunk/src/m/classes/inversionvalidation.m	(revision 19105)
@@ -9,4 +9,5 @@
 		incomplete_adjoint          = 0
 		control_parameters          = NaN
+		control_scaling_factors     = NaN
 		cost_functions              = NaN
 		cost_functions_coefficients = NaN
@@ -18,12 +19,22 @@
 		vel_obs                     = NaN
 		thickness_obs               = NaN
+		surface_obs                 = NaN
 	end
 	methods
-		function obj = inversionvalidation(varargin) % {{{
+		function self = extrude(self,md) % {{{
+			self.vx_obs=project3d(md,'vector',self.vx_obs,'type','node');
+			self.vy_obs=project3d(md,'vector',self.vy_obs,'type','node');
+			self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node');
+			self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node');
+			if numel(self.cost_functions_coefficients)>1,self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node');end;
+			if numel(self.min_parameters)>1,self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node');end;
+			if numel(self.max_parameters)>1,self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node');end;
+		end % }}}
+		function self = inversionvalidation(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
-					obj=structtoobj(inversionvalidation(),varargin{1});
+					self=structtoobj(inversionvalidation(),varargin{1});
 				otherwise
 					error('constructor not supported');
@@ -39,11 +50,14 @@
 			self.control_parameters={'FrictionCoefficient'};
 
+			%Scaling factor for each control
+			self.control_scaling_factors=1;
+
 			%several responses can be used:
 			self.cost_functions=101;
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
-			if ~obj.iscontrol, return; end
+			if ~self.iscontrol, return; end
 
 			num_controls=numel(md.inversion.control_parameters);
@@ -52,7 +66,7 @@
 			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
 			md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0 1]);
-			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
-				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy' 'Thickness' 'BalancethicknessApparentMassbalance'});
-			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:507]);
+			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',supportedcontrols());
+			md = checkfield(md,'fieldname','inversion.control_scaling_factors','size',[1 num_controls],'>',0,'NaN',1);
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',supportedcostfunctions());
 			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
 			md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
@@ -70,17 +84,19 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   inversionvalidation parameters:'));
-			fielddisplay(obj,'iscontrol','is inversion activated?');
-			fielddisplay(obj,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
-			fielddisplay(obj,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
-			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step');
-			fielddisplay(obj,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
-			fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
-			fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
-			fielddisplay(obj,'vx_obs','observed velocity x component [m/yr]');
-			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
-			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/yr]');
-			fielddisplay(obj,'thickness_obs','observed thickness [m]');
+			fielddisplay(self,'iscontrol','is inversion activated?');
+			fielddisplay(self,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
+			fielddisplay(self,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(self,'control_scaling_factors','order of magnitude of each control (useful for multi-parameter optimization)');
+			fielddisplay(self,'cost_functions','indicate the type of response for each optimization step');
+			fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
+			fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(self,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]');
+			fielddisplay(self,'thickness_obs','observed thickness [m]');
+			fielddisplay(self,'surface_obs','observed surface elevation [m]');
 			disp('Available cost functions:');
 			disp('   101: SurfaceAbsVelMisfit');
@@ -94,30 +110,32 @@
 			disp('   503: ThicknessAbsGradient');
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
-			WriteData(fid,'object',obj,'class','inversion','fieldname','iscontrol','format','Boolean');
+			WriteData(fid,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean');
 			WriteData(fid,'enum',InversionTypeEnum(),'data',3,'format','Integer');
-			if ~obj.iscontrol, return; end
-			WriteData(fid,'object',obj,'class','inversion','fieldname','incomplete_adjoint','format','Boolean');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			if(numel(obj.thickness_obs)==md.mesh.numberofelements),
+			if ~self.iscontrol, return; end
+			WriteData(fid,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean');
+			WriteData(fid,'object',self,'class','inversion','fieldname','control_scaling_factors','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			if(numel(self.thickness_obs)==md.mesh.numberofelements),
 				mattype=2; 
 			else
 				mattype=1;
 			end
-			WriteData(fid,'object',obj,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
+			WriteData(fid,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
+			WriteData(fid,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',mattype);
 
 			%process control parameters
-			num_control_parameters=numel(obj.control_parameters);
+			num_control_parameters=numel(self.control_parameters);
 			data=zeros(1,num_control_parameters);
 			for i=1:num_control_parameters,
-				data(i)=StringToEnum(obj.control_parameters{i});
+				data(i)=StringToEnum(self.control_parameters{i});
 			end
 			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
@@ -125,19 +143,6 @@
 
 			%process cost functions
-			num_cost_functions=size(obj.cost_functions,2);
-			data=obj.cost_functions;
-			pos=find(obj.cost_functions==101); data(pos)=SurfaceAbsVelMisfitEnum();
-			pos=find(obj.cost_functions==102); data(pos)=SurfaceRelVelMisfitEnum();
-			pos=find(obj.cost_functions==103); data(pos)=SurfaceLogVelMisfitEnum();
-			pos=find(obj.cost_functions==104); data(pos)=SurfaceLogVxVyMisfitEnum();
-			pos=find(obj.cost_functions==105); data(pos)=SurfaceAverageVelMisfitEnum();
-			pos=find(obj.cost_functions==201); data(pos)=ThicknessAbsMisfitEnum();
-			pos=find(obj.cost_functions==501); data(pos)=DragCoefficientAbsGradientEnum();
-			pos=find(obj.cost_functions==502); data(pos)=RheologyBbarAbsGradientEnum();
-			pos=find(obj.cost_functions==503); data(pos)=ThicknessAbsGradientEnum();
-			pos=find(obj.cost_functions==504); data(pos)=ThicknessAlongGradientEnum();
-			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
-			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
-			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
+			num_cost_functions=size(self.cost_functions,2);
+			data=marshallcostfunctions(self.cost_functions);
 			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
 			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
Index: /issm/trunk/src/m/classes/linearbasalforcings.m
===================================================================
--- /issm/trunk/src/m/classes/linearbasalforcings.m	(revision 19104)
+++ /issm/trunk/src/m/classes/linearbasalforcings.m	(revision 19105)
@@ -13,17 +13,17 @@
 	end
 	methods
-     function createxml(obj,fid) % {{{
+     function createxml(self,fid) % {{{
             fprintf(fid, '\n\n');
             fprintf(fid, '%s\n', '<!-- basalforcings -->');
-			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="melting_rate" type="',            class(obj.melting_rate),'" default="',              num2str(obj.melting_rate),'">',              '     <section name="basalforcings" />','     <help> basal melting rate (positive if melting) [m/yr] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="geothermalflux" type="',          class(obj.geothermalflux),'" default="',            num2str(obj.geothermalflux),'">',            '     <section name="basalforcings" />','     <help> geothermal heat flux [W/m^2] </help>','</parameter>');
+			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="melting_rate" type="',            class(self.melting_rate),'" default="',              num2str(self.melting_rate),'">',              '     <section name="basalforcings" />','     <help> basal melting rate (positive if melting) [m/yr] </help>','</parameter>');
+             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',        '<parameter key ="geothermalflux" type="',          class(self.geothermalflux),'" default="',            num2str(self.geothermalflux),'">',            '     <section name="basalforcings" />','     <help> geothermal heat flux [W/m^2] </help>','</parameter>');
              
         end % }}}
-		function obj = linearbasalforcings(varargin) % {{{
+		function self = linearbasalforcings(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
-					obj=structtoobj(linearbasalforcings(),varargin{1});
+					self=structtoobj(linearbasalforcings(),varargin{1});
 				otherwise
 					error('constructor not supported');
@@ -38,16 +38,16 @@
 
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%default values for melting parameterization
-			obj.deepwater_melting_rate = 50;
-			obj.deepwater_elevation    = -800;
-			obj.upperwater_elevation   = -400;
+			self.deepwater_melting_rate = 50;
+			self.deepwater_elevation    = -800;
+			self.upperwater_elevation   = -400;
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			if ismember(MasstransportAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.ismasstransport==0),
-				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'timeseries',1);
 				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
 				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
@@ -61,22 +61,22 @@
 			end
 			if ismember(ThermalAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.isthermal==0),
-				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1);
+				md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'timeseries',1);
 				md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
 				md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
 				md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0,'numel',1);
-				md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0);
+				md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'timeseries',1,'>=',0);
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   basal forcings parameters:'));
 
-			fielddisplay(obj,'groundedice_melting_rate','basal melting rate (positive if melting) [m/yr]');
-			fielddisplay(obj,'deepwater_melting_rate','basal melting rate (positive if melting applied for floating ice whith base < deepwater_elevation) [m/yr]');
-			fielddisplay(obj,'deepwater_elevation','elevation of ocean deepwater [m]');
-			fielddisplay(obj,'upperwater_elevation','elevation of ocean upperwater [m]');
-			fielddisplay(obj,'geothermalflux','geothermal heat flux [W/m^2]');
+			fielddisplay(self,'groundedice_melting_rate','basal melting rate (positive if melting) [m/yr]');
+			fielddisplay(self,'deepwater_melting_rate','basal melting rate (positive if melting applied for floating ice whith base < deepwater_elevation) [m/yr]');
+			fielddisplay(self,'deepwater_elevation','elevation of ocean deepwater [m]');
+			fielddisplay(self,'upperwater_elevation','elevation of ocean upperwater [m]');
+			fielddisplay(self,'geothermalflux','geothermal heat flux [W/m^2]');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
@@ -87,10 +87,10 @@
 			floatingice_melting_rate(pos)=md.basalforcings.deepwater_melting_rate*(md.geometry.base(pos)-md.basalforcings.upperwater_elevation)/(md.basalforcings.deepwater_elevation-md.basalforcings.upperwater_elevation);
 			WriteData(fid,'enum',BasalforcingsEnum(),'data',LinearFloatingMeltRateEnum(),'format','Integer');
-			WriteData(fid,'data',floatingice_melting_rate,'format','DoubleMat','enum',BasalforcingsFloatingiceMeltingRateEnum(),'mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-			WriteData(fid,'object',obj,'fieldname','groundedice_melting_rate','format','DoubleMat','enum',BasalforcingsGroundediceMeltingRateEnum(),'mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-			WriteData(fid,'object',obj,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'fieldname','deepwater_melting_rate','format','Double','enum',BasalforcingsDeepwaterMeltingRateEnum(),'scale',1./yts)
-			WriteData(fid,'object',obj,'fieldname','deepwater_elevation','format','Double','enum',BasalforcingsDeepwaterElevationEnum())
-			WriteData(fid,'object',obj,'fieldname','upperwater_elevation','format','Double','enum',BasalforcingsUpperwaterElevationEnum())
+			WriteData(fid,'data',floatingice_melting_rate,'format','DoubleMat','enum',BasalforcingsFloatingiceMeltingRateEnum(),'mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','enum',BasalforcingsGroundediceMeltingRateEnum(),'mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+			WriteData(fid,'object',self,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'fieldname','deepwater_melting_rate','format','Double','enum',BasalforcingsDeepwaterMeltingRateEnum(),'scale',1./yts)
+			WriteData(fid,'object',self,'fieldname','deepwater_elevation','format','Double','enum',BasalforcingsDeepwaterElevationEnum())
+			WriteData(fid,'object',self,'fieldname','upperwater_elevation','format','Double','enum',BasalforcingsUpperwaterElevationEnum())
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/linearbasalforcings.py
===================================================================
--- /issm/trunk/src/m/classes/linearbasalforcings.py	(revision 19104)
+++ /issm/trunk/src/m/classes/linearbasalforcings.py	(revision 19105)
@@ -69,5 +69,5 @@
 
 		if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
-			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'timeseries',1)
 			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
 			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
@@ -81,9 +81,9 @@
 
 		if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isthermal):
-			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'forcing',1)
+			md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'timeseries',1)
 			md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
 			md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
 			md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
-			md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'forcing',1,'>=',0)
+			md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'timeseries',1,'>=',0)
 
 		return md
@@ -100,7 +100,7 @@
 
 		WriteData(fid,'enum',BasalforcingsEnum(),'data',LinearFloatingMeltRateEnum(),'format','Integer');
-		WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','enum',BasalforcingsGroundediceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'data',floatingice_melting_rate,'enum',BasalforcingsFloatingiceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','enum',BasalforcingsGroundediceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'data',floatingice_melting_rate,'enum',BasalforcingsFloatingiceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
 		WriteData(fid,'object',self,'fieldname','deepwater_melting_rate','enum',BasalforcingsDeepwaterMeltingRateEnum(),'format','Double','scale',1./yts)
 		WriteData(fid,'object',self,'fieldname','deepwater_elevation','enum',BasalforcingsDeepwaterElevationEnum(),'format','Double')
Index: /issm/trunk/src/m/classes/m1qn3inversion.m
===================================================================
--- /issm/trunk/src/m/classes/m1qn3inversion.m	(revision 19104)
+++ /issm/trunk/src/m/classes/m1qn3inversion.m	(revision 19105)
@@ -9,8 +9,9 @@
 		incomplete_adjoint          = 0
 		control_parameters          = NaN
+		control_scaling_factors     = NaN
 		maxsteps                    = 0
 		maxiter                     = 0
-		dxmin                       = 0;
-		gttol                       = 0;
+		dxmin                       = 0
+		gttol                       = 0
 		cost_functions              = NaN
 		cost_functions_coefficients = NaN
@@ -22,16 +23,26 @@
 		vel_obs                     = NaN
 		thickness_obs               = NaN
+		surface_obs                 = NaN
 
 	end
 	methods
-		function obj = m1qn3inversion(varargin) % {{{
+		function self = m1qn3inversion(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
-					obj=structtoobj(m1qn3inversion(),varargin{1});
+					self=structtoobj(m1qn3inversion(),varargin{1});
 				otherwise
 					error('constructor not supported');
 			end
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.vx_obs=project3d(md,'vector',self.vx_obs,'type','node');
+			self.vy_obs=project3d(md,'vector',self.vy_obs,'type','node');
+			self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node');
+			self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node');
+			if numel(self.cost_functions_coefficients)>1,self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node');end;
+			if numel(self.min_parameters)>1,self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node');end;
+			if numel(self.max_parameters)>1,self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node');end;
 		end % }}}
 		function self = setdefaultparameters(self) % {{{
@@ -43,4 +54,7 @@
 			%drag and B are supported yet)
 			self.control_parameters={'FrictionCoefficient'};
+
+			%Scaling factor for each control
+			self.control_scaling_factors=1;
 
 			%number of iterations
@@ -56,13 +70,12 @@
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
-			if ~obj.iscontrol, return; end
+			if ~self.iscontrol, return; end
 
 			if ~IssmConfig('_HAVE_M1QN3_'),
 				md = checkmessage(md,['M1QN3 has not been installed, ISSM needs to be reconfigured and recompiled with M1QN3']);
 			end
-
 			num_controls=numel(md.inversion.control_parameters);
 			num_costfunc=size(md.inversion.cost_functions,2);
@@ -70,11 +83,11 @@
 			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
 			md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0 1]);
-			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
-				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy' 'Thickness' 'BalancethicknessApparentMassbalance'});
+			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',supportedcontrols());
+			md = checkfield(md,'fieldname','inversion.control_scaling_factors','size',[1 num_controls],'>',0,'NaN',1);
 			md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0);
 			md = checkfield(md,'fieldname','inversion.maxiter','numel',1,'>=',0);
 			md = checkfield(md,'fieldname','inversion.dxmin','numel',1,'>',0);
 			md = checkfield(md,'fieldname','inversion.gttol','numel',1,'>',0);
-			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:507]);
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',supportedcostfunctions());
 			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
 			md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
@@ -83,4 +96,5 @@
 			if solution==BalancethicknessSolutionEnum()
 				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
+				md = checkfield(md,'fieldname','inversion.surface_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
 			elseif solution==BalancethicknessSoftSolutionEnum()
 				md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices 1],'NaN',1);
@@ -92,21 +106,23 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   m1qn3inversion parameters:'));
-			fielddisplay(obj,'iscontrol','is inversion activated?');
-			fielddisplay(obj,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
-			fielddisplay(obj,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
-			fielddisplay(obj,'maxsteps','maximum number of iterations (gradient computation)');
-			fielddisplay(obj,'maxiter','maximum number of Function evaluation (forward run)');
-			fielddisplay(obj,'dxmin','convergence criterion: two points less than dxmin from eachother (sup-norm) are considered identical');
-			fielddisplay(obj,'gttol','convergence criterion: ||g(X)||/||g(X0)|| (g(X0): gradient at initial guess X0)');
-			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step');
-			fielddisplay(obj,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
-			fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
-			fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
-			fielddisplay(obj,'vx_obs','observed velocity x component [m/yr]');
-			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
-			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/yr]');
-			fielddisplay(obj,'thickness_obs','observed thickness [m]');
+			fielddisplay(self,'iscontrol','is inversion activated?');
+			fielddisplay(self,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
+			fielddisplay(self,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(self,'control_scaling_factors','order of magnitude of each control (useful for multi-parameter optimization)');
+			fielddisplay(self,'maxsteps','maximum number of iterations (gradient computation)');
+			fielddisplay(self,'maxiter','maximum number of Function evaluation (forward run)');
+			fielddisplay(self,'dxmin','convergence criterion: two points less than dxmin from eachother (sup-norm) are considered identical');
+			fielddisplay(self,'gttol','convergence criterion: ||g(X)||/||g(X0)|| (g(X0): gradient at initial guess X0)');
+			fielddisplay(self,'cost_functions','indicate the type of response for each optimization step');
+			fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
+			fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(self,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]');
+			fielddisplay(self,'thickness_obs','observed thickness [m]');
+			fielddisplay(self,'surface_obs','observed surface elevation [m]');
 			disp('Available cost functions:');
 			disp('   101: SurfaceAbsVelMisfit');
@@ -120,34 +136,36 @@
 			disp('   503: ThicknessAbsGradient');
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
-			WriteData(fid,'object',obj,'class','inversion','fieldname','iscontrol','format','Boolean');
+			WriteData(fid,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean');
 			WriteData(fid,'enum',InversionTypeEnum(),'data',2,'format','Integer');
-			if ~obj.iscontrol, return; end
-			WriteData(fid,'object',obj,'class','inversion','fieldname','incomplete_adjoint','format','Boolean');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','maxsteps','format','Integer');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','maxiter','format','Integer');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','dxmin','format','Double');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','gttol','format','Double');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			if(numel(obj.thickness_obs)==md.mesh.numberofelements),
+			if ~self.iscontrol, return; end
+			WriteData(fid,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean');
+			WriteData(fid,'object',self,'class','inversion','fieldname','control_scaling_factors','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','inversion','fieldname','maxsteps','format','Integer');
+			WriteData(fid,'object',self,'class','inversion','fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',self,'class','inversion','fieldname','dxmin','format','Double');
+			WriteData(fid,'object',self,'class','inversion','fieldname','gttol','format','Double');
+			WriteData(fid,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			if(numel(self.thickness_obs)==md.mesh.numberofelements),
 				mattype=2;
 			else
 				mattype=1;
 			end
-			WriteData(fid,'object',obj,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
+			WriteData(fid,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',mattype);
+			WriteData(fid,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',mattype);
 
 			%process control parameters
-			num_control_parameters=numel(obj.control_parameters);
+			num_control_parameters=numel(self.control_parameters);
 			data=zeros(1,num_control_parameters);
 			for i=1:num_control_parameters,
-				data(i)=StringToEnum(obj.control_parameters{i});
+				data(i)=StringToEnum(self.control_parameters{i});
 			end
 			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
@@ -155,19 +173,6 @@
 
 			%process cost functions
-			num_cost_functions=size(obj.cost_functions,2);
-			data=obj.cost_functions;
-			pos=find(obj.cost_functions==101); data(pos)=SurfaceAbsVelMisfitEnum();
-			pos=find(obj.cost_functions==102); data(pos)=SurfaceRelVelMisfitEnum();
-			pos=find(obj.cost_functions==103); data(pos)=SurfaceLogVelMisfitEnum();
-			pos=find(obj.cost_functions==104); data(pos)=SurfaceLogVxVyMisfitEnum();
-			pos=find(obj.cost_functions==105); data(pos)=SurfaceAverageVelMisfitEnum();
-			pos=find(obj.cost_functions==201); data(pos)=ThicknessAbsMisfitEnum();
-			pos=find(obj.cost_functions==501); data(pos)=DragCoefficientAbsGradientEnum();
-			pos=find(obj.cost_functions==502); data(pos)=RheologyBbarAbsGradientEnum();
-			pos=find(obj.cost_functions==503); data(pos)=ThicknessAbsGradientEnum();
-			pos=find(obj.cost_functions==504); data(pos)=ThicknessAlongGradientEnum();
-			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
-			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
-			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
+			num_cost_functions=size(self.cost_functions,2);
+			data=marshallcostfunctions(self.cost_functions);
 			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
 			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
Index: /issm/trunk/src/m/classes/m1qn3inversion.py
===================================================================
--- /issm/trunk/src/m/classes/m1qn3inversion.py	(revision 19104)
+++ /issm/trunk/src/m/classes/m1qn3inversion.py	(revision 19105)
@@ -1,4 +1,4 @@
 import numpy
-import copy
+from project3d import project3d
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -6,4 +6,7 @@
 from checkfield import checkfield
 from WriteData import WriteData
+from supportedcontrols import supportedcontrols
+from supportedcostfunctions import supportedcostfunctions
+from marshallcostfunctions import marshallcostfunctions
 
 class m1qn3inversion(object):
@@ -22,4 +25,5 @@
 			self.incomplete_adjoint          = 0
 			self.control_parameters          = float('NaN')
+			self.control_scaling_factors     = float('NaN')
 			self.maxsteps                    = 0
 			self.maxiter                     = 0
@@ -41,4 +45,8 @@
 			print 'converting inversion to m1qn3inversion'
 			inv=args[0]
+			#first call setdefaultparameters: 
+			self.setdefaultparameters()
+
+			#then go fish whatever is available in the inversion object provided to the constructor
 			self.iscontrol                   = inv.iscontrol
 			self.incomplete_adjoint          = inv.incomplete_adjoint
@@ -62,4 +70,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity'))
 		string="%s\n%s"%(string,fielddisplay(self,'control_parameters','ex: [''FrictionCoefficient''], or [''MaterialsRheologyBbar'']'))
+		string="%s\n%s"%(string,fielddisplay(self,'control_scaling_factors','order of magnitude of each control (useful for multi-parameter optimization)'))
 		string="%s\n%s"%(string,fielddisplay(self,'maxsteps','maximum number of iterations (gradient computation)'))
 		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of Function evaluation (forward run)'))
@@ -86,4 +95,17 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.vx_obs=project3d(md,'vector',self.vx_obs,'type','node')
+		self.vy_obs=project3d(md,'vector',self.vy_obs,'type','node')
+		self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node')
+		self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node')
+		if not numpy.any(numpy.isnan(self.cost_functions_coefficients)):
+			self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node')
+		if not numpy.any(numpy.isnan(self.min_parameters)):
+			self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node')
+		if not numpy.any(numpy.isnan(self.max_parameters)):
+			self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node')
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		
@@ -94,4 +116,7 @@
 		#drag and B are supported yet)
 		self.control_parameters='FrictionCoefficient'
+		
+		#Scaling factor for each control
+		self.control_scaling_factors=1
 
 		#number of iterations
@@ -119,10 +144,11 @@
 		md = checkfield(md,'fieldname','inversion.iscontrol','values',[0,1])
 		md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0,1])
-		md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',['BalancethicknessThickeningRate','FrictionCoefficient','MaterialsRheologyBbar','DamageDbar','Vx','Vy','Thickness'])
+		md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',supportedcontrols())
+		md = checkfield(md,'fieldname','inversion.control_scaling_factors','size',[num_controls],'>',0,'NaN',1)
 		md = checkfield(md,'fieldname','inversion.maxsteps','numel',[1],'>=',0)
 		md = checkfield(md,'fieldname','inversion.maxiter','numel',[1],'>=',0)
 		md = checkfield(md,'fieldname','inversion.dxmin','numel',[1],'>',0.)
 		md = checkfield(md,'fieldname','inversion.gttol','numel',[1],'>',0.)
-		md = checkfield(md,'fieldname','inversion.cost_functions','size',[num_costfunc],'values',[101,102,103,104,105,201,501,502,503,504,505])
+		md = checkfield(md,'fieldname','inversion.cost_functions','size',[num_costfunc],'values',supportedcostfunctions())
 		md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices,num_costfunc],'>=',0)
 		md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices,num_controls])
@@ -146,4 +172,5 @@
 			return
 		WriteData(fid,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean')
+		WriteData(fid,'object',self,'class','inversion','fieldname','control_scaling_factors','format','DoubleMat','mattype',3)
 		WriteData(fid,'object',self,'class','inversion','fieldname','maxsteps','format','Integer')
 		WriteData(fid,'object',self,'class','inversion','fieldname','maxiter','format','Integer')
@@ -166,27 +193,5 @@
 		#process cost functions
 		num_cost_functions=numpy.size(self.cost_functions)
-		data=copy.deepcopy(self.cost_functions)
-		pos=[i for i,x in enumerate(self.cost_functions) if x==101];
-		for i in pos: data[i]=SurfaceAbsVelMisfitEnum()        
-		pos=[i for i,x in enumerate(self.cost_functions) if x==102];
-		for i in pos: data[i]=SurfaceRelVelMisfitEnum()        
-		pos=[i for i,x in enumerate(self.cost_functions) if x==103];
-		for i in pos: data[i]=SurfaceLogVelMisfitEnum()        
-		pos=[i for i,x in enumerate(self.cost_functions) if x==104];
-		for i in pos: data[i]=SurfaceLogVxVyMisfitEnum()       
-		pos=[i for i,x in enumerate(self.cost_functions) if x==105];
-		for i in pos: data[i]=SurfaceAverageVelMisfitEnum()    
-		pos=[i for i,x in enumerate(self.cost_functions) if x==201];
-		for i in pos: data[i]=ThicknessAbsMisfitEnum()         
-		pos=[i for i,x in enumerate(self.cost_functions) if x==501];
-		for i in pos: data[i]=DragCoefficientAbsGradientEnum() 
-		pos=[i for i,x in enumerate(self.cost_functions) if x==502];
-		for i in pos: data[i]=RheologyBbarAbsGradientEnum()    
-		pos=[i for i,x in enumerate(self.cost_functions) if x==503];
-		for i in pos: data[i]=ThicknessAbsGradientEnum()       
-		pos=[i for i,x in enumerate(self.cost_functions) if x==504];
-		for i in pos: data[i]=ThicknessAlongGradientEnum()     
-		pos=[i for i,x in enumerate(self.cost_functions) if x==505];
-		for i in pos: data[i]=ThicknessAcrossGradientEnum()    
+		data=marshallcostfunctions(self.cost_functions)
 		WriteData(fid,'data',numpy.array(data).reshape(1,-1),'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)
 		WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')
Index: /issm/trunk/src/m/classes/mask.m
===================================================================
--- /issm/trunk/src/m/classes/mask.m	(revision 19104)
+++ /issm/trunk/src/m/classes/mask.m	(revision 19105)
@@ -10,10 +10,10 @@
 	end
 	methods (Static)
-		function obj = loadobj(obj) % {{{
+		function self = loadobj(self) % {{{
 			% This function is directly called by matlab when a model object is
 			% loaded. Update old properties here
 
 			%2014 February 5th
-			if numel(obj.ice_levelset)>1 & all(obj.ice_levelset>=0),
+			if numel(self.ice_levelset)>1 & all(self.ice_levelset>=0),
 				disp('WARNING: md.mask.ice_levelset>=0, you probably need to change the sign of this levelset');
 			end
@@ -22,22 +22,26 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- mask -->');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="groundedice_levelset" type="',class(obj.groundedice_levelset),'" default="',obj.groundedice_levelset,'">','     <section name="mask" />','     <help> is ice grounded ? grounded ice if > 0, grounding line position if = 0, floating ice if &amp;lt; 0 </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="ice_levelset" type="',class(obj.ice_levelset),'" default="',obj.ice_levelset,'">','     <section name="mask" />','     <help> presence of ice if > 0, icefront position if = 0, no ice if &amp;lt; 0 </help>','</parameter>');
+		function createxml(self,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- mask -->');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="groundedice_levelset" type="',class(self.groundedice_levelset),'" default="',self.groundedice_levelset,'">','     <section name="mask" />','     <help> is ice grounded ? grounded ice if > 0, grounding line position if = 0, floating ice if &amp;lt; 0 </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','<parameter key ="ice_levelset" type="',class(self.ice_levelset),'" default="',self.ice_levelset,'">','     <section name="mask" />','     <help> presence of ice if > 0, icefront position if = 0, no ice if &amp;lt; 0 </help>','</parameter>');
 		end % }}}
-		function obj = mask(varargin) % {{{
+		function self = extrude(self,md) % {{{
+			self.groundedice_levelset=project3d(md,'vector',self.groundedice_levelset,'type','node');
+			self.ice_levelset=project3d(md,'vector',self.ice_levelset,'type','node');
+		end % }}}
+		function self = mask(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			md = checkfield(md,'fieldname','mask.groundedice_levelset','size',[md.mesh.numberofvertices 1]);
@@ -50,14 +54,18 @@
 				warning('no ice front provided');
 			end
+			icefront=sum(md.mask.ice_levelset(md.mesh.elements)==0,2);
+			if (max(icefront)==3 & strcmp(elementtype(md.mesh),'Tria')) | (max(icefront==6) & strcmp(elementtype(md.mesh),'Penta')),
+				error('At least one element has all nodes on ice front, change md.mask.ice_levelset to fix it')
+			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   masks:'));
 
-			fielddisplay(obj,'groundedice_levelset','is ice grounded ? grounded ice if > 0, grounding line position if = 0, floating ice if < 0');
-			fielddisplay(obj,'ice_levelset','presence of ice if < 0, icefront position if = 0, no ice if > 0');
+			fielddisplay(self,'groundedice_levelset','is ice grounded ? grounded ice if > 0, grounding line position if = 0, floating ice if < 0');
+			fielddisplay(self,'ice_levelset','presence of ice if < 0, icefront position if = 0, no ice if > 0');
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','groundedice_levelset','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','ice_levelset','format','DoubleMat','mattype',1);
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','groundedice_levelset','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','ice_levelset','format','DoubleMat','mattype',1);
 
 			% get mask of vertices of elements with ice
Index: /issm/trunk/src/m/classes/mask.py
===================================================================
--- /issm/trunk/src/m/classes/mask.py	(revision 19104)
+++ /issm/trunk/src/m/classes/mask.py	(revision 19105)
@@ -1,4 +1,5 @@
 import numpy
 from fielddisplay import fielddisplay
+from project3d import project3d
 from EnumDefinitions import *
 from checkfield import checkfield
@@ -28,4 +29,9 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.ice_levelset=project3d(md,'vector',self.ice_levelset,'type','node')
+		self.groundedice_levelset=project3d(md,'vector',self.groundedice_levelset,'type','node')
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		return self
@@ -37,4 +43,8 @@
 		if numpy.sum(isice)==0:
 			raise TypeError("no ice present in the domain")
+
+		icefront=numpy.sum(md.mask.ice_levelset[md.mesh.elements-1]==0,axis=1)
+		if (max(icefront)==3 and m.strcmp(md.mesh.elementtype(),'Tria')) or (max(icefront==6) and m.strcmp(md.mesh.elementtype(),'Penta')):
+			raise TypeError("At least one element has all nodes on ice front, change md.mask.ice_levelset to fix it")
 
 		return md
Index: /issm/trunk/src/m/classes/masscon.m
===================================================================
--- /issm/trunk/src/m/classes/masscon.m	(revision 19105)
+++ /issm/trunk/src/m/classes/masscon.m	(revision 19105)
@@ -0,0 +1,65 @@
+%MASSCON class definition
+%
+%   Usage:
+%      masscon=masscon();
+%      masscon=masscon('name','MassCon58',... %name of a North-East Greenland JPL MassCon
+%                    'levelset',level);
+% 
+%   where level is a levelset vectorial field.
+%
+%   See also: MISFIT
+
+classdef masscon
+	properties (SetAccess=public)
+		%masscon
+		name              = '';
+		definitionenum   = NaN; %enum that identifies this output definition uniquely, from Outputdefinition[1-10]Enum
+		levelset          = NaN; %levelset vectorial field which identifies the boundaries of the masscon
+	end
+	
+	methods
+		function self = masscon(varargin) % {{{
+			if nargin==0,
+				self=setdefaultparameters(self);
+			else
+				%use provided options to change fields
+				options=pairoptions(varargin{:});
+
+				%get name
+				self.name=getfieldvalue(options,'name','');
+				self.levelset=getfieldvalue(options,'levelset');
+				self.definitionenum=getfieldvalue(options,'definitionenum');
+
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			if ~ischar(self.name),
+				error('masscon error message: ''name'' field should be a string!');
+			end
+			
+			md = checkfield(md,'fieldname','self.definitionenum','field',self.definitionenum,'values',[Outputdefinition1Enum:Outputdefinition100Enum]);
+
+			md = checkfield(md,'fieldname','self.levelset','field',self.levelset,'timeseries',1,'NaN',1);
+
+		end % }}}
+		function md = disp(self) % {{{
+		
+			disp(sprintf('   Misfit:\n'));
+
+			fielddisplay(self,'name','identifier for this masscon response');
+			fielddisplay(self,'definitionenum','enum that identifies this output definition uniquely, from Outputdefinition[1-10]Enum');
+			fielddisplay(self,'levelset','levelset vectorial field which identifies the boundaries of the masscon');
+
+		end % }}}
+		function md = marshall(self,md,fid) % {{{
+
+		WriteData(fid,'object',self,'fieldname','name','format','String');
+		WriteData(fid,'object',self,'fieldname','definitionenum','format','Integer');
+		WriteData(fid,'object',self,'fieldname','levelset','format','DoubleMat','mattype',1);
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/massconaxpby.m
===================================================================
--- /issm/trunk/src/m/classes/massconaxpby.m	(revision 19105)
+++ /issm/trunk/src/m/classes/massconaxpby.m	(revision 19105)
@@ -0,0 +1,82 @@
+%MASSCONAXPBY class definition
+%
+%   Usage:
+%      massconaxpby=massconaxpby();
+%      massconsumaxpby=massconaxpby('name','MassCon58+35','namex','MassCon58','alpha',.5,'namey','MassCon35','beta',.5); 
+% 
+%   where name is the name of the massconaxpby object, namex is the name of the first masscon, namey the name of the second masscon and alpha,beta the 
+%         multiplicators. The meaning of axpby here is: resulting masscon is the linear combination (alpha *x + beta * y) 
+%         of two masscons.
+%
+%   See also: MASSCON
+
+classdef massconaxpby
+	properties (SetAccess=public)
+		%masscon axpby
+		name              = '';
+		definitionenum   = NaN; %enum that identifies this output definition uniquely, from Outputdefinition[1-10]Enum
+		namex              = '';
+		namey              = '';
+		alpha              = NaN;
+		beta              = NaN;
+	end
+	
+	methods
+		function self = massconaxpby(varargin) % {{{
+			if nargin==0,
+				self=setdefaultparameters(self);
+			else
+				%use provided options to change fields
+				options=pairoptions(varargin{:});
+
+				%get names
+				self.name=getfieldvalue(options,'name','');
+				self.definitionenum=getfieldvalue(options,'definitionenum');
+				self.namex=getfieldvalue(options,'namex');
+				self.namey=getfieldvalue(options,'namey');
+
+				%get multiplicators: 
+				self.alpha=getfieldvalue(options,'alpha');
+				self.beta=getfieldvalue(options,'beta');
+
+
+			end
+		end % }}}
+		function self = setdefaultparameters(self) % {{{
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+
+			if ~ischar(self.name), error('masscon error message: ''name'' field should be a string!'); end
+			if ~ischar(self.namex), error('masscon error message: ''namex'' field should be a string!'); end
+			if ~ischar(self.namey), error('masscon error message: ''namey'' field should be a string!'); end
+			
+			md = checkfield(md,'fieldname','self.definitionenum','field',self.definitionenum,'values',[Outputdefinition1Enum:Outputdefinition100Enum]);
+
+			md = checkfield(md,'fieldname','self.alpha','field',self.alpha,'NaN',1,'size',[1 1]);
+			md = checkfield(md,'fieldname','self.betaa','field',self.beta,'NaN',1,'size',[1 1]);
+
+		end % }}}
+		function md = disp(self) % {{{
+		
+			disp(sprintf('   Misfit:\n'));
+
+			fielddisplay(self,'name','name');
+			fielddisplay(self,'definitionenum','enum that identifies this output definition uniquely, from Outputdefinition[1-10]Enum');
+			fielddisplay(self,'namex','identifier for the first masscon');
+			fielddisplay(self,'alpha','first masscon multiplicator');
+			fielddisplay(self,'namey','identifier for the second masscon');
+			fielddisplay(self,'beta','second masscon multiplicator');
+
+		end % }}}
+		function md = marshall(self,md,fid) % {{{
+
+		WriteData(fid,'object',self,'fieldname','name','format','String');
+		WriteData(fid,'object',self,'fieldname','definitionenum','format','Integer');
+		WriteData(fid,'object',self,'fieldname','namex','format','String');
+		WriteData(fid,'object',self,'fieldname','namey','format','String');
+		WriteData(fid,'object',self,'fieldname','alpha','format','Double');
+		WriteData(fid,'object',self,'fieldname','beta','format','Double');
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/massfluxatgate.m
===================================================================
--- /issm/trunk/src/m/classes/massfluxatgate.m	(revision 19104)
+++ /issm/trunk/src/m/classes/massfluxatgate.m	(revision 19105)
@@ -3,60 +3,65 @@
 %   Usage:
 %      massfluxatgate=massfluxatgate();
-%      massfluxatgate=massfluxatgate('GateName','PathToExpFile');
+%      massfluxatgate=massfluxatgate('name','GateName','definitionname',Outputdefinition1Enum,'profilename','PathToExpFile');
 
 classdef massfluxatgate
 	properties (SetAccess=public)  
 		%massfluxatgate 
-		name                = '';
-		profilename            = ''; 
+		name            = '';
+		definitionenum  = 0;
+		profilename     = ''; 
 	end
 	properties (SetAccess=private)  
-		segments            = NaN;
+		segments        = NaN;
 	end
 	methods
-		function obj = massfluxatgate(varargin) % {{{
-			switch nargin
-				case 0
-					obj=setdefaultparameters(obj);
-				case 1
-					obj.name=varargin{1};
-				case 2
-					obj.name=varargin{1};
-					obj.profilename=varargin{2};
-				otherwise
-					error('constructor not supported');
+		function self = massfluxatgate(varargin) % {{{
+			if nargin==0,
+				self=setdefaultparameters(self);
+			else
+				%use provided options to change fields
+				options=pairoptions(varargin{:});
+
+				%get name
+				self.name=getfieldvalue(options,'name','');
+				self.definitionenum=getfieldvalue(options,'definitionenum');
+				self.profilename=getfieldvalue(options,'profilename');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 			
-			if ~ischar(obj.name),
+			if ~ischar(self.name),
 				error('massfluxatgate error message: ''name'' field should be a string!');
 			end
-			if ~ischar(obj.profilename),
+			if ~ischar(self.profilename),
 				error('massfluxatgate error message: ''profilename'' field should be a string!');
 			end
+			
+			md = checkfield(md,'field',self.definitionenum,'values',[Outputdefinition1Enum():Outputdefinition100Enum()]);
 
 			%check the profilename points to a file!: 
-			if exist(obj.profilename,'file')~=2,
+			if exist(self.profilename,'file')~=2,
 				error('massfluxatgate error message: file name for profile corresponding to gate does not point to a legitimate file on disk!');
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   Massfluxatgate:\n'));
 
-			fielddisplay(obj,'name','identifier for this massfluxatgate response');
-			fielddisplay(obj,'profilename','name of file (shapefile or argus file) defining a profile (or gate)');
+			fielddisplay(self,'name','identifier for this massfluxatgate response');
+			fielddisplay(self,'profilename','name of file (shapefile or argus file) defining a profile (or gate)');
+			fielddisplay(self,'definitionenum','enum that identifies this output definition uniquely, from Outputdefinition[1-10]Enum');
 			
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 		%before marshalling, we need to create the segments out of the profilename: 
-		obj.segments=MeshProfileIntersection(md.mesh.elements,md.mesh.x,md.mesh.y,obj.profilename);
+		self.segments=MeshProfileIntersection(md.mesh.elements,md.mesh.x,md.mesh.y,self.profilename);
 
 		%ok, marshall name and segments: 
-		WriteData(fid,'object',obj,'fieldname','name','format','String');
-		WriteData(fid,'object',obj,'fieldname','segments','format','DoubleMat','mattype',1);
+		WriteData(fid,'object',self,'fieldname','name','format','String');
+		WriteData(fid,'object',self,'fieldname','definitionenum','format','Integer');
+		WriteData(fid,'object',self,'fieldname','segments','format','DoubleMat','mattype',1);
 
 		end % }}}
Index: /issm/trunk/src/m/classes/massfluxatgate.py
===================================================================
--- /issm/trunk/src/m/classes/massfluxatgate.py	(revision 19104)
+++ /issm/trunk/src/m/classes/massfluxatgate.py	(revision 19105)
@@ -1,4 +1,5 @@
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
+from pairoptions import pairoptions
 from checkfield import checkfield
 from WriteData import WriteData
@@ -14,8 +15,19 @@
 	"""
 
-	def __init__(self,name,profilename): # {{{
-		self.name           = name
-		self.profilename    = profilename
-		self.segments       = float('NaN')
+	def __init__(self,*args): # {{{
+
+		self.name            = ''
+		self.definitionenum  = 0
+		self.profilename     = ''
+		self.segments        = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#use provided options to change fields
+		options=pairoptions(*args)
+
+		#OK get other fields
+		self=options.AssignObjectFields(self)
 
 		#}}}
@@ -24,4 +36,5 @@
 		string="   Massfluxatgate:"
 		string="%s\n%s"%(string,fielddisplay(self,'name','identifier for this massfluxatgate response'))
+		string="%s\n%s"%(string,fielddisplay(self,'definitionenum','enum that identifies this output definition uniquely, from Outputdefinition[1-10]Enum'))
 		string="%s\n%s"%(string,fielddisplay(self,'profilename','name of file (shapefile or argus file) defining a profile (or gate)'))
 		return string
@@ -37,4 +50,6 @@
 		if  not isinstance(self.profilename, basestring):
 			raise RuntimeError("massfluxatgate error message: 'profilename' field should be a string!") 
+
+			md = checkfield(md,'field',self.definitionenum,'values',[Outputdefinition1Enum(),Outputdefinition2Enum(),Outputdefinition3Enum(),Outputdefinition4Enum(),Outputdefinition5Enum(),Outputdefinition6Enum(),Outputdefinition7Enum(),Outputdefinition8Enum(),Outputdefinition9Enum(),Outputdefinition10Enum()])
 		
 		#check the profilename points to a file!: 
@@ -51,4 +66,5 @@
 		#ok, marshall name and segments: 
 		WriteData(fid,'object',self,'fieldname','name','format','String')
+		WriteData(fid,'object',self,'fieldname','definitionenum','format','Integer')
 		WriteData(fid,'object',self,'fieldname','segments','format','DoubleMat','mattype',1)
 
Index: /issm/trunk/src/m/classes/masstransport.m
===================================================================
--- /issm/trunk/src/m/classes/masstransport.m	(revision 19104)
+++ /issm/trunk/src/m/classes/masstransport.m	(revision 19105)
@@ -7,5 +7,4 @@
 	properties (SetAccess=public) 
 		 spcthickness           = NaN;
-		 calvingrate            = NaN;
 		 isfreesurface          = 0;
 		 min_thickness          = 0;
@@ -17,5 +16,5 @@
 	end
 	methods (Static)
-		function obj = loadobj(obj) % {{{
+		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
@@ -35,48 +34,15 @@
 			end
 
-			if isstruct(obj)
+			if isstruct(self)
 				disp('Recovering masstransport from older version');
-				objstruct = obj;
-				obj = structtoobj(masstransport(),objstruct);
+				self = structtoobj(masstransport(),self);
 			end
 		end% }}}
 	end
 	methods
-         function createxml(obj,fid) % {{{
-            fprintf(fid, '<!-- masstransport -->\n');            
-                    
-            % Masstransport solution parameters
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Masstransport solution parameters">','<section name="masstransport" />');                    
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="spcthickness" type="',class(obj.spcthickness),'" default="',convert2str(obj.spcthickness),'">','     <section name="masstransport" />','     <help> thickness constraints (NaN means no constraint) [m] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="calvingrate" type="',class(obj.calvingrate),'" default="',convert2str(obj.calvingrate),'">','     <section name="masstransport" />','     <help> calving rate at given location [m/a] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isfreesurface" type="',class(obj.isfreesurface),'" default="',convert2str(obj.isfreesurface),'">','     <section name="masstransport" />','     <help> do we use free surfaces (FS only) are mass conservation </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="min_thickness" type="',class(obj.min_thickness),'" default="',convert2str(obj.min_thickness),'">','     <section name="masstransport" />','     <help> minimum ice thickness allowed [m] </help>','  </parameter>');
-            
-            % hydrostatic_adjustment drop-down (incremental or absolute )
-            fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="hydrostatic_adjustment" type="alternative" optional ="false">','     <section name="masstransport" />','     <help> adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute''  </help>');
-            fprintf(fid,'%s\n','       <option value="Incremental" type="string" default="true"> </option>');
-            fprintf(fid,'%s\n%s\n','       <option value="Absolute" type="string" default="false"> </option>','</parameter>');
-            
-            %stabilization drop-down (0, 1, 2, or 3)
-            fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="stabilization" type="alternative" optional="false">','     <section name="masstransport" />','     <help> 0: no, 1:  artificial_diffusivity, 2: streamline upwinding, 3: discontinuous Galerkin </help>');
-            fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
-            fprintf(fid,'%s\n','       <option value="1" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n','       <option value="2" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n%s\n','       <option value="3" type="string" default="false"> </option>','</parameter>');
-
-            fprintf(fid,'%s\n%s\n','</frame>');    
-            
-            %Penalty options
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Penalty options">','<section name="masstransport" />'); 
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertex_pairing" type="',class(obj.vertex_pairing),'" default="',convert2str(obj.vertex_pairing),'">','     <section name="masstransport" />','     <help> offset used by penalties: penalty = Kmax*10^offset </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="penalty_factor" type="',class(obj.penalty_factor),'" default="',convert2str(obj.penalty_factor),'">','     <section name="masstransport" />','     <help> pairs of vertices that are penalized </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="requested_outputs" type="',class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','     <section name="masstransport" />','     <help> additional outputs requested </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-        
-        end % }}}
-		function obj = masstransport(varargin) % {{{
+		function self = masstransport(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
 					inputstruct=varargin{1};
@@ -86,5 +52,5 @@
 						fieldname = list1{i};
 						if ismember(fieldname,list2),
-							obj.(fieldname) = inputstruct.(fieldname);
+							self.(fieldname) = inputstruct.(fieldname);
 						end
 					end
@@ -93,4 +59,7 @@
 			end
 		end % }}}
+		function self = extrude(self,md) % {{{
+			self.spcthickness=project3d(md,'vector',self.spcthickness,'type','node');
+		end % }}}
 		function list = defaultoutputs(self,md) % {{{
 
@@ -98,72 +67,66 @@
 
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
-			obj.stabilization=1;
+			self.stabilization=1;
 
 			%Factor applied to compute the penalties kappa=max(stiffness matrix)*10^penalty_factor
-			obj.penalty_factor=3;
+			self.penalty_factor=3;
 
 			%Minimum ice thickness that can be used
-			obj.min_thickness=1;
+			self.min_thickness=1;
 
 			%Hydrostatic adjustment
-			obj.hydrostatic_adjustment='Absolute';
+			self.hydrostatic_adjustment='Absolute';
 
 			%default output
-			obj.requested_outputs={'default'};
+			self.requested_outputs={'default'};
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
 			if ~ismember(MasstransportAnalysisEnum(),analyses) |  (solution==TransientSolutionEnum() & md.transient.ismasstransport==0), return; end
 
-			md = checkfield(md,'fieldname','masstransport.spcthickness','forcing',1);
-			if(ismember(LevelsetAnalysisEnum(), analyses) & md.transient.islevelset)
-				md = checkfield(md,'fieldname','masstransport.calvingrate','NaN',1,'size',[md.mesh.numberofvertices 1],'>=',0);
-			end
-
+			md = checkfield(md,'fieldname','masstransport.spcthickness','timeseries',1);
 			md = checkfield(md,'fieldname','masstransport.isfreesurface','values',[0 1]);
 			md = checkfield(md,'fieldname','masstransport.hydrostatic_adjustment','values',{'Absolute' 'Incremental'});
-			md = checkfield(md,'fieldname','masstransport.stabilization','values',[0 1 2 3]);
+			md = checkfield(md,'fieldname','masstransport.stabilization','values',[0 1 2 3 4]);
 			md = checkfield(md,'fieldname','masstransport.min_thickness','>',0);
 			md = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1);
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   Masstransport solution parameters:'));
-			fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint) [m]');
-			fielddisplay(obj,'calvingrate','calving rate at given location [m/a]');
-			fielddisplay(obj,'isfreesurface','do we use free surfaces (FS only) are mass conservation');
-			fielddisplay(obj,'min_thickness','minimum ice thickness allowed [m]');
-			fielddisplay(obj,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' ');
-			fielddisplay(obj,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding, 3: discontinuous Galerkin');
+			fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint) [m]');
+			fielddisplay(self,'isfreesurface','do we use free surfaces (FS only) are mass conservation');
+			fielddisplay(self,'min_thickness','minimum ice thickness allowed [m]');
+			fielddisplay(self,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' ');
+			fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding, 3: discontinuous Galerkin, 4: Flux Correction Transport');
 
 			disp(sprintf('\n      %s','Penalty options:'));
-			fielddisplay(obj,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset');
-			fielddisplay(obj,'vertex_pairing','pairs of vertices that are penalized');
-			fielddisplay(obj,'requested_outputs','additional outputs requested');
+			fielddisplay(self,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset');
+			fielddisplay(self,'vertex_pairing','pairs of vertices that are penalized');
+			fielddisplay(self,'requested_outputs','additional outputs requested');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.*24.*3600.;
 
-			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'fieldname','calvingrate','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1,'scale',1./yts);
-			WriteData(fid,'object',obj,'fieldname','isfreesurface','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','min_thickness','format','Double');
-			WriteData(fid,'data',StringToEnum(obj.hydrostatic_adjustment),'format','Integer','enum',MasstransportHydrostaticAdjustmentEnum());
-			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','vertex_pairing','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'fieldname','isfreesurface','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','min_thickness','format','Double');
+			WriteData(fid,'data',StringToEnum(self.hydrostatic_adjustment),'format','Integer','enum',MasstransportHydrostaticAdjustmentEnum());
+			WriteData(fid,'object',self,'fieldname','stabilization','format','Integer');
+			WriteData(fid,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double');
 			
 			%process requested outputs
-			outputs = obj.requested_outputs;
+			outputs = self.requested_outputs;
 			pos  = find(ismember(outputs,'default'));
 			if ~isempty(pos),
 				outputs(pos) = [];                         %remove 'default' from outputs
-				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+				outputs      = [outputs defaultoutputs(self,md)]; %add defaults
 			end
 			WriteData(fid,'data',outputs,'enum',MasstransportRequestedOutputsEnum,'format','StringArray');
Index: /issm/trunk/src/m/classes/masstransport.py
===================================================================
--- /issm/trunk/src/m/classes/masstransport.py	(revision 19104)
+++ /issm/trunk/src/m/classes/masstransport.py	(revision 19105)
@@ -1,3 +1,4 @@
 from fielddisplay import fielddisplay
+from project3d import project3d
 from EnumDefinitions import *
 from StringToEnum import StringToEnum
@@ -15,7 +16,6 @@
 	def __init__(self): # {{{
 		self.spcthickness           = float('NaN')
-		self.calvingrate            = float('NaN')
 		self.isfreesurface          = 0
-		self.min_thickness          = 0
+		self.min_thickness          = 0.
 		self.hydrostatic_adjustment = 0
 		self.stabilization          = 0
@@ -31,13 +31,16 @@
 		string='   Masstransport solution parameters:'
 		string="%s\n%s"%(string,fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint) [m]'))
-		string="%s\n%s"%(string,fielddisplay(self,'calvingrate','calving rate at given location [m/a]'))
 		string="%s\n%s"%(string,fielddisplay(self,'isfreesurface','do we use free surfaces (FS only) are mass conservation'))
 		string="%s\n%s"%(string,fielddisplay(self,'min_thickness','minimum ice thickness allowed [m]'))
 		string="%s\n%s"%(string,fielddisplay(self,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' '))
-		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding, 3: discontinuous Galerkin'))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding, 3: discontinuous Galerkin, 4: Flux Correction Transport'))
 		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
 
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.spcthickness=project3d(md,'vector',self.spcthickness,'type','node')
+		return self
+	#}}}
 	def defaultoutputs(self,md): # {{{
 
@@ -46,5 +49,5 @@
 	#}}}
 	def setdefaultparameters(self): # {{{
-		
+
 		#Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
 		self.stabilization=1
@@ -69,10 +72,8 @@
 			return md
 
-		md = checkfield(md,'fieldname','masstransport.spcthickness','forcing',1)
-		if LevelsetAnalysisEnum() in analyses and md.transient.islevelset:
-			md = checkfield(md,'fieldname','masstransport.calvingrate','NaN',1,'size',[md.mesh.numberofvertices],'>=',0)
+		md = checkfield(md,'fieldname','masstransport.spcthickness','timeseries',1)
 		md = checkfield(md,'fieldname','masstransport.isfreesurface','values',[0,1])
 		md = checkfield(md,'fieldname','masstransport.hydrostatic_adjustment','values',['Absolute','Incremental'])
-		md = checkfield(md,'fieldname','masstransport.stabilization','values',[0,1,2,3])
+		md = checkfield(md,'fieldname','masstransport.stabilization','values',[0,1,2,3,4])
 		md = checkfield(md,'fieldname','masstransport.min_thickness','>',0)
 		md = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1)
@@ -84,6 +85,5 @@
 		yts=365.*24.*3600.
 
-		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'fieldname','calvingrate','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1,'scale',1./yts)
+		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
 		WriteData(fid,'object',self,'fieldname','isfreesurface','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','min_thickness','format','Double')
Index: /issm/trunk/src/m/classes/matdamageice.m
===================================================================
--- /issm/trunk/src/m/classes/matdamageice.m	(revision 19104)
+++ /issm/trunk/src/m/classes/matdamageice.m	(revision 19105)
@@ -30,42 +30,46 @@
 	end
 	methods
-		function createxml(obj,fid) % {{{
+		function createxml(self,fid) % {{{
 			fprintf(fid, '\n\n');
 			fprintf(fid, '<!-- materials -->\n');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_ice" type="',class(obj.rho_ice),'" default="',convert2str(obj.rho_ice),'">','     <section name="materials" />','     <help> ice density [kg/m^3] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_water" type="',class(obj.rho_water),'" default="',convert2str(obj.rho_water),'">','     <section name="materials" />','     <help> ocean water density [kg/m^3] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_freshwater" type="',class(obj.rho_freshwater),'" default="',convert2str(obj.rho_freshwater),'">','     <section name="materials" />','     <help> fresh water density [kg/m^3] </help>','</parameter>');
-
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mu_water" type="',class(obj.mu_water),'" default="',convert2str(obj.mu_water),'">','     <section name="materials" />','     <help> water viscosity [N s/m^2] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="heatcapacity" type="',class(obj.heatcapacity),'" default="',convert2str(obj.heatcapacity),'">','     <section name="materials" />','     <help> heat capacity [J/kg/K] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="latentheat" type="',class(obj.latentheat),'" default="',convert2str(obj.latentheat),'">','     <section name="materials" />','     <help> latent heat of fusion [J/kg] </help>','</parameter>');
-
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermalconductivity" type="',class(obj.thermalconductivity),'" default="',convert2str(obj.thermalconductivity),'">','     <section name="materials" />','     <help> ice thermal conductivity [W/m/K] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="temperateiceconductivity" type="',class(obj.temperateiceconductivity),'" default="',convert2str(obj.temperateiceconductivity),'">','     <section name="materials" />','     <help> temperate ice thermal conductivity [W/m/K] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="meltingpoint" type="',class(obj.meltingpoint),'" default="',convert2str(obj.meltingpoint),'">','     <section name="materials" />','     <help> melting point of ice at 1atm in K </help>','</parameter>');
-
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="beta" type="',class(obj.beta),'" default="',convert2str(obj.beta),'">','     <section name="materials" />','     <help> rate of change of melting point with pressure [K/Pa] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mixed_layer_capacity" type="',class(obj.mixed_layer_capacity),'" default="',convert2str(obj.mixed_layer_capacity),'">','     <section name="materials" />','     <help> mixed layer capacity [W/kg/K] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermal_exchange_velocity" type="',class(obj.thermal_exchange_velocity),'" default="',convert2str(obj.thermal_exchange_velocity),'">','     <section name="materials" />','     <help> thermal exchange velocity [m/s] </help>','</parameter>');
-
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_B" type="',class(obj.rheology_B),'" default="',convert2str(obj.rheology_B),'">','     <section name="materials" />','     <help> flow law parameter [Pa/s^(1/n)] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_n" type="',class(obj.rheology_n),'" default="',convert2str(obj.rheology_n),'">','     <section name="materials" />','     <help> Glens flow law exponent </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_law" type="',class(obj.rheology_law),'" default="',convert2str(obj.rheology_law),'">','     <section name="materials" />','     <help> law for the temperature dependance of the rheology: "None", "Paterson",  "Arrhenius" or "LliboutryDuval" </help>','</parameter>');
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_shear_modulus" type="',class(obj.lithosphere_shear_modulus),'" default="',convert2str(obj.lithosphere_shear_modulus),'">','     <section name="materials" />','     <help> Lithosphere shear modulus [Pa] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_density" type="',class(obj.lithosphere_density),'" default="',convert2str(obj.lithosphere_density),'">','     <section name="materials" />','     <help> Lithosphere density [g/cm^-3] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_shear_modulus" type="',class(obj.mantle_shear_modulus),'" default="',convert2str(obj.mantle_shear_modulus),'">','     <section name="materials" />','     <help> Mantle shear modulus [Pa] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_density" type="',class(obj.mantle_density),'" default="',convert2str(obj.mantle_density),'">','     <section name="materials" />','     <help> Mantle density [g/cm^-3] </help>','</parameter>');
-
-
-		end % }}}
-		function obj = matdamageice(varargin) % {{{
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_ice" type="',class(self.rho_ice),'" default="',convert2str(self.rho_ice),'">','     <section name="materials" />','     <help> ice density [kg/m^3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_water" type="',class(self.rho_water),'" default="',convert2str(self.rho_water),'">','     <section name="materials" />','     <help> ocean water density [kg/m^3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_freshwater" type="',class(self.rho_freshwater),'" default="',convert2str(self.rho_freshwater),'">','     <section name="materials" />','     <help> fresh water density [kg/m^3] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mu_water" type="',class(self.mu_water),'" default="',convert2str(self.mu_water),'">','     <section name="materials" />','     <help> water viscosity [N s/m^2] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="heatcapacity" type="',class(self.heatcapacity),'" default="',convert2str(self.heatcapacity),'">','     <section name="materials" />','     <help> heat capacity [J/kg/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="latentheat" type="',class(self.latentheat),'" default="',convert2str(self.latentheat),'">','     <section name="materials" />','     <help> latent heat of fusion [J/kg] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermalconductivity" type="',class(self.thermalconductivity),'" default="',convert2str(self.thermalconductivity),'">','     <section name="materials" />','     <help> ice thermal conductivity [W/m/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="temperateiceconductivity" type="',class(self.temperateiceconductivity),'" default="',convert2str(self.temperateiceconductivity),'">','     <section name="materials" />','     <help> temperate ice thermal conductivity [W/m/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="meltingpoint" type="',class(self.meltingpoint),'" default="',convert2str(self.meltingpoint),'">','     <section name="materials" />','     <help> melting point of ice at 1atm in K </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="beta" type="',class(self.beta),'" default="',convert2str(self.beta),'">','     <section name="materials" />','     <help> rate of change of melting point with pressure [K/Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mixed_layer_capacity" type="',class(self.mixed_layer_capacity),'" default="',convert2str(self.mixed_layer_capacity),'">','     <section name="materials" />','     <help> mixed layer capacity [W/kg/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermal_exchange_velocity" type="',class(self.thermal_exchange_velocity),'" default="',convert2str(self.thermal_exchange_velocity),'">','     <section name="materials" />','     <help> thermal exchange velocity [m/s] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_B" type="',class(self.rheology_B),'" default="',convert2str(self.rheology_B),'">','     <section name="materials" />','     <help> flow law parameter [Pa/s^(1/n)] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_n" type="',class(self.rheology_n),'" default="',convert2str(self.rheology_n),'">','     <section name="materials" />','     <help> Glens flow law exponent </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_law" type="',class(self.rheology_law),'" default="',convert2str(self.rheology_law),'">','     <section name="materials" />','     <help> law for the temperature dependance of the rheology: "None", "Paterson",  "Arrhenius" or "LliboutryDuval" </help>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_shear_modulus" type="',class(self.lithosphere_shear_modulus),'" default="',convert2str(self.lithosphere_shear_modulus),'">','     <section name="materials" />','     <help> Lithosphere shear modulus [Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_density" type="',class(self.lithosphere_density),'" default="',convert2str(self.lithosphere_density),'">','     <section name="materials" />','     <help> Lithosphere density [g/cm^-3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_shear_modulus" type="',class(self.mantle_shear_modulus),'" default="',convert2str(self.mantle_shear_modulus),'">','     <section name="materials" />','     <help> Mantle shear modulus [Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_density" type="',class(self.mantle_density),'" default="',convert2str(self.mantle_density),'">','     <section name="materials" />','     <help> Mantle density [g/cm^-3] </help>','</parameter>');
+
+
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.rheology_B=project3d(md,'vector',self.rheology_B,'type','node');
+			self.rheology_n=project3d(md,'vector',self.rheology_n,'type','element');
+		end % }}}
+		function self = matdamageice(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
 					inputstruct=varargin{1};
@@ -75,5 +79,5 @@
 						fieldname = list1{i};
 						if ismember(fieldname,list2),
-							obj.(fieldname) = inputstruct.(fieldname);
+							self.(fieldname) = inputstruct.(fieldname);
 						end
 					end
@@ -82,54 +86,54 @@
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%ice density (kg/m^3)
-			obj.rho_ice=917.;
+			self.rho_ice=917.;
 
 			%ocean water density (kg/m^3)
-			obj.rho_water=1023.;
+			self.rho_water=1023.;
 
 			%fresh water density (kg/m^3)
-			obj.rho_freshwater=1000.;
+			self.rho_freshwater=1000.;
 
 			%water viscosity (N.s/m^2)
-			obj.mu_water=0.001787;  
+			self.mu_water=0.001787;  
 
 			%ice heat capacity cp (J/kg/K)
-			obj.heatcapacity=2093.;
+			self.heatcapacity=2093.;
 
 			%ice latent heat of fusion L (J/kg)
-			obj.latentheat=3.34*10^5;
+			self.latentheat=3.34*10^5;
 
 			%ice thermal conductivity (W/m/K)
-			obj.thermalconductivity=2.4;
+			self.thermalconductivity=2.4;
 			
 			%wet ice thermal conductivity (W/m/K)
-			obj.temperateiceconductivity=.24;
+			self.temperateiceconductivity=.24;
 
 			%the melting point of ice at 1 atmosphere of pressure in K
-			obj.meltingpoint=273.15;
+			self.meltingpoint=273.15;
 
 			%rate of change of melting point with pressure (K/Pa)
-			obj.beta=9.8*10^-8;
+			self.beta=9.8*10^-8;
 
 			%mixed layer (ice-water interface) heat capacity (J/kg/K)
-			obj.mixed_layer_capacity=3974.;
+			self.mixed_layer_capacity=3974.;
 
 			%thermal exchange velocity (ice-water interface) (m/s)
-			obj.thermal_exchange_velocity=1.00*10^-4;
+			self.thermal_exchange_velocity=1.00*10^-4;
 
 			%Rheology law: what is the temperature dependence of B with T
 			%available: none, paterson and arrhenius
-			obj.rheology_law='Paterson';
+			self.rheology_law='Paterson';
 
 			% GIA:
-			obj.lithosphere_shear_modulus  = 6.7*10^10;  % (Pa)
-			obj.lithosphere_density        = 3.32;       % (g/cm^-3)
-			obj.mantle_shear_modulus       = 1.45*10^11; % (Pa)
-			obj.mantle_density             = 3.34;       % (g/cm^-3)
-
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			self.lithosphere_shear_modulus  = 6.7*10^10;  % (Pa)
+			self.lithosphere_density        = 3.32;       % (g/cm^-3)
+			self.mantle_shear_modulus       = 1.45*10^11; % (Pa)
+			self.mantle_density             = 3.34;       % (g/cm^-3)
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 			md = checkfield(md,'fieldname','materials.rho_ice','>',0);
 			md = checkfield(md,'fieldname','materials.rho_water','>',0);
@@ -148,49 +152,49 @@
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   Materials:'));
 
-			fielddisplay(obj,'rho_ice','ice density [kg/m^3]');
-			fielddisplay(obj,'rho_water','ocean water density [kg/m^3]');
-			fielddisplay(obj,'rho_freshwater','fresh water density [kg/m^3]');
-			fielddisplay(obj,'mu_water','water viscosity [N s/m^2]');
-			fielddisplay(obj,'heatcapacity','heat capacity [J/kg/K]');
-			fielddisplay(obj,'thermalconductivity',['ice thermal conductivity [W/m/K]']);
-			fielddisplay(obj,'temperateiceconductivity','temperate ice thermal conductivity [W/m/K]');
-			fielddisplay(obj,'meltingpoint','melting point of ice at 1atm in K');
-			fielddisplay(obj,'latentheat','latent heat of fusion [J/kg]');
-			fielddisplay(obj,'beta','rate of change of melting point with pressure [K/Pa]');
-			fielddisplay(obj,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
-			fielddisplay(obj,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
-			fielddisplay(obj,'rheology_B','flow law parameter [Pa/s^(1/n)]');
-			fielddisplay(obj,'rheology_n','Glen''s flow law exponent');
-			fielddisplay(obj,'rheology_law',['law for the temperature dependance of the rheology: ''None'', ''Cuffey'', ''Paterson'', ''Arrhenius'' or ''LliboutryDuval''']);
-			fielddisplay(obj,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
-			fielddisplay(obj,'lithosphere_density','Lithosphere density [g/cm^-3]');
-			fielddisplay(obj,'mantle_shear_modulus','Mantle shear modulus [Pa]');
-			fielddisplay(obj,'mantle_density','Mantle density [g/cm^-3]');
-		end % }}}
-		function marshall(obj,md,fid) % {{{
+			fielddisplay(self,'rho_ice','ice density [kg/m^3]');
+			fielddisplay(self,'rho_water','ocean water density [kg/m^3]');
+			fielddisplay(self,'rho_freshwater','fresh water density [kg/m^3]');
+			fielddisplay(self,'mu_water','water viscosity [N s/m^2]');
+			fielddisplay(self,'heatcapacity','heat capacity [J/kg/K]');
+			fielddisplay(self,'thermalconductivity',['ice thermal conductivity [W/m/K]']);
+			fielddisplay(self,'temperateiceconductivity','temperate ice thermal conductivity [W/m/K]');
+			fielddisplay(self,'meltingpoint','melting point of ice at 1atm in K');
+			fielddisplay(self,'latentheat','latent heat of fusion [J/kg]');
+			fielddisplay(self,'beta','rate of change of melting point with pressure [K/Pa]');
+			fielddisplay(self,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
+			fielddisplay(self,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
+			fielddisplay(self,'rheology_B','flow law parameter [Pa/s^(1/n)]');
+			fielddisplay(self,'rheology_n','Glen''s flow law exponent');
+			fielddisplay(self,'rheology_law',['law for the temperature dependance of the rheology: ''None'', ''Cuffey'', ''Paterson'', ''Arrhenius'' or ''LliboutryDuval''']);
+			fielddisplay(self,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
+			fielddisplay(self,'lithosphere_density','Lithosphere density [g/cm^-3]');
+			fielddisplay(self,'mantle_shear_modulus','Mantle shear modulus [Pa]');
+			fielddisplay(self,'mantle_density','Mantle density [g/cm^-3]');
+		end % }}}
+		function marshall(self,md,fid) % {{{
 			WriteData(fid,'enum',MaterialsEnum(),'data',MatdamageiceEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rho_ice','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rho_water','enum',MaterialsRhoSeawaterEnum(),'format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rho_freshwater','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','mu_water','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','heatcapacity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','latentheat','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','thermalconductivity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','temperateiceconductivity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','meltingpoint','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','beta','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','mixed_layer_capacity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','thermal_exchange_velocity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
-			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
-
-			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_density','format','Double','scale',10^3);
-			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_shear_modulus','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_density','format','Double','scale',10^3);
+			WriteData(fid,'object',self,'class','materials','fieldname','rho_ice','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','rho_water','enum',MaterialsRhoSeawaterEnum(),'format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','rho_freshwater','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','mu_water','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','heatcapacity','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','latentheat','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','thermalconductivity','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','meltingpoint','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','beta','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
+			WriteData(fid,'data',StringToEnum(self.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
+
+			WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10^3);
+			WriteData(fid,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10^3);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/matdamageice.py
===================================================================
--- /issm/trunk/src/m/classes/matdamageice.py	(revision 19104)
+++ /issm/trunk/src/m/classes/matdamageice.py	(revision 19105)
@@ -1,3 +1,4 @@
 from fielddisplay import fielddisplay
+from project3d import project3d
 from EnumDefinitions import MaterialsEnum, MatdamageiceEnum, MaterialsRheologyLawEnum, MaterialsRhoSeawaterEnum
 from StringToEnum import StringToEnum
@@ -63,4 +64,9 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.rheology_B=project3d(md,'vector',self.rheology_B,'type','node')
+		self.rheology_n=project3d(md,'vector',self.rheology_n,'type','element')
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		#ice density (kg/m^3)
Index: /issm/trunk/src/m/classes/matice.m
===================================================================
--- /issm/trunk/src/m/classes/matice.m	(revision 19104)
+++ /issm/trunk/src/m/classes/matice.m	(revision 19105)
@@ -30,29 +30,29 @@
 	end
 	methods
-		function createxml(obj,fid) % {{{
+		function createxml(self,fid) % {{{
 			fprintf(fid, '\n\n');
 			fprintf(fid, '<!-- materials -->\n');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_ice" type="',class(obj.rho_ice),'" default="',convert2str(obj.rho_ice),'">','     <section name="materials" />','     <help> ice density [kg/m^3] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_water" type="',class(obj.rho_water),'" default="',convert2str(obj.rho_water),'">','     <section name="materials" />','     <help> ocean water density [kg/m^3] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_freshwater" type="',class(obj.rho_freshwater),'" default="',convert2str(obj.rho_freshwater),'">','     <section name="materials" />','     <help> fresh water density [kg/m^3] </help>','</parameter>');
-
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mu_water" type="',class(obj.mu_water),'" default="',convert2str(obj.mu_water),'">','     <section name="materials" />','     <help> water viscosity [N s/m^2] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="heatcapacity" type="',class(obj.heatcapacity),'" default="',convert2str(obj.heatcapacity),'">','     <section name="materials" />','     <help> heat capacity [J/kg/K] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="latentheat" type="',class(obj.latentheat),'" default="',convert2str(obj.latentheat),'">','     <section name="materials" />','     <help> latent heat of fusion [J/kg] </help>','</parameter>');
-
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermalconductivity" type="',class(obj.thermalconductivity),'" default="',convert2str(obj.thermalconductivity),'">','     <section name="materials" />','     <help> ice thermal conductivity [W/m/K] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="temperateiceconductivity" type="',class(obj.temperateiceconductivity),'" default="',convert2str(obj.temperateiceconductivity),'">','     <section name="materials" />','     <help> temperate ice thermal conductivity [W/m/K] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="meltingpoint" type="',class(obj.meltingpoint),'" default="',convert2str(obj.meltingpoint),'">','     <section name="materials" />','     <help> melting point of ice at 1atm in K </help>','</parameter>');
-
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="beta" type="',class(obj.beta),'" default="',convert2str(obj.beta),'">','     <section name="materials" />','     <help> rate of change of melting point with pressure [K/Pa] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mixed_layer_capacity" type="',class(obj.mixed_layer_capacity),'" default="',convert2str(obj.mixed_layer_capacity),'">','     <section name="materials" />','     <help> mixed layer capacity [W/kg/K] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermal_exchange_velocity" type="',class(obj.thermal_exchange_velocity),'" default="',convert2str(obj.thermal_exchange_velocity),'">','     <section name="materials" />','     <help> thermal exchange velocity [m/s] </help>','</parameter>');
-
-
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_B" type="',class(obj.rheology_B),'" default="',convert2str(obj.rheology_B),'">','     <section name="materials" />','     <help> flow law parameter [Pa/s^(1/n)] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_n" type="',class(obj.rheology_n),'" default="',convert2str(obj.rheology_n),'">','     <section name="materials" />','     <help> Glens flow law exponent </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_ice" type="',class(self.rho_ice),'" default="',convert2str(self.rho_ice),'">','     <section name="materials" />','     <help> ice density [kg/m^3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_water" type="',class(self.rho_water),'" default="',convert2str(self.rho_water),'">','     <section name="materials" />','     <help> ocean water density [kg/m^3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rho_freshwater" type="',class(self.rho_freshwater),'" default="',convert2str(self.rho_freshwater),'">','     <section name="materials" />','     <help> fresh water density [kg/m^3] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mu_water" type="',class(self.mu_water),'" default="',convert2str(self.mu_water),'">','     <section name="materials" />','     <help> water viscosity [N s/m^2] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="heatcapacity" type="',class(self.heatcapacity),'" default="',convert2str(self.heatcapacity),'">','     <section name="materials" />','     <help> heat capacity [J/kg/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="latentheat" type="',class(self.latentheat),'" default="',convert2str(self.latentheat),'">','     <section name="materials" />','     <help> latent heat of fusion [J/kg] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermalconductivity" type="',class(self.thermalconductivity),'" default="',convert2str(self.thermalconductivity),'">','     <section name="materials" />','     <help> ice thermal conductivity [W/m/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="temperateiceconductivity" type="',class(self.temperateiceconductivity),'" default="',convert2str(self.temperateiceconductivity),'">','     <section name="materials" />','     <help> temperate ice thermal conductivity [W/m/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="meltingpoint" type="',class(self.meltingpoint),'" default="',convert2str(self.meltingpoint),'">','     <section name="materials" />','     <help> melting point of ice at 1atm in K </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="beta" type="',class(self.beta),'" default="',convert2str(self.beta),'">','     <section name="materials" />','     <help> rate of change of melting point with pressure [K/Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mixed_layer_capacity" type="',class(self.mixed_layer_capacity),'" default="',convert2str(self.mixed_layer_capacity),'">','     <section name="materials" />','     <help> mixed layer capacity [W/kg/K] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="thermal_exchange_velocity" type="',class(self.thermal_exchange_velocity),'" default="',convert2str(self.thermal_exchange_velocity),'">','     <section name="materials" />','     <help> thermal exchange velocity [m/s] </help>','</parameter>');
+
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_B" type="',class(self.rheology_B),'" default="',convert2str(self.rheology_B),'">','     <section name="materials" />','     <help> flow law parameter [Pa/s^(1/n)] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="rheology_n" type="',class(self.rheology_n),'" default="',convert2str(self.rheology_n),'">','     <section name="materials" />','     <help> Glens flow law exponent </help>','</parameter>');
 
 			% rheology_law drop-down
@@ -64,15 +64,19 @@
 
 
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_shear_modulus" type="',class(obj.lithosphere_shear_modulus),'" default="',convert2str(obj.lithosphere_shear_modulus),'">','     <section name="materials" />','     <help> Lithosphere shear modulus [Pa] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_density" type="',class(obj.lithosphere_density),'" default="',convert2str(obj.lithosphere_density),'">','     <section name="materials" />','     <help> Lithosphere density [g/cm^-3] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_shear_modulus" type="',class(obj.mantle_shear_modulus),'" default="',convert2str(obj.mantle_shear_modulus),'">','     <section name="materials" />','     <help> Mantle shear modulus [Pa] </help>','</parameter>');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_density" type="',class(obj.mantle_density),'" default="',convert2str(obj.mantle_density),'">','     <section name="materials" />','     <help> Mantle density [g/cm^-3] </help>','</parameter>');
-
-
-		end % }}}
-		function obj = matice(varargin) % {{{
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_shear_modulus" type="',class(self.lithosphere_shear_modulus),'" default="',convert2str(self.lithosphere_shear_modulus),'">','     <section name="materials" />','     <help> Lithosphere shear modulus [Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="lithosphere_density" type="',class(self.lithosphere_density),'" default="',convert2str(self.lithosphere_density),'">','     <section name="materials" />','     <help> Lithosphere density [g/cm^-3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_shear_modulus" type="',class(self.mantle_shear_modulus),'" default="',convert2str(self.mantle_shear_modulus),'">','     <section name="materials" />','     <help> Mantle shear modulus [Pa] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','<parameter key ="mantle_density" type="',class(self.mantle_density),'" default="',convert2str(self.mantle_density),'">','     <section name="materials" />','     <help> Mantle density [g/cm^-3] </help>','</parameter>');
+
+
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.rheology_B=project3d(md,'vector',self.rheology_B,'type','node');
+			self.rheology_n=project3d(md,'vector',self.rheology_n,'type','element');
+		end % }}}
+		function self = matice(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
 					inputstruct=varargin{1};
@@ -82,5 +86,5 @@
 						fieldname = list1{i};
 						if ismember(fieldname,list2),
-							obj.(fieldname) = inputstruct.(fieldname);
+							self.(fieldname) = inputstruct.(fieldname);
 						end
 					end
@@ -89,59 +93,59 @@
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%ice density (kg/m^3)
-			obj.rho_ice=917.;
+			self.rho_ice=917.;
 
 			%ocean water density (kg/m^3)
-			obj.rho_water=1023.;
+			self.rho_water=1023.;
 
 			%fresh water density (kg/m^3)
-			obj.rho_freshwater=1000.;
+			self.rho_freshwater=1000.;
 
 			%water viscosity (N.s/m^2)
-			obj.mu_water=0.001787;  
+			self.mu_water=0.001787;  
 
 			%ice heat capacity cp (J/kg/K)
-			obj.heatcapacity=2093.;
+			self.heatcapacity=2093.;
 
 			%ice latent heat of fusion L (J/kg)
-			obj.latentheat=3.34*10^5;
+			self.latentheat=3.34*10^5;
 
 			%ice thermal conductivity (W/m/K)
-			obj.thermalconductivity=2.4;
+			self.thermalconductivity=2.4;
 			
 			%wet ice thermal conductivity (W/m/K)
-			obj.temperateiceconductivity=.24;
+			self.temperateiceconductivity=.24;
 
 			%the melting point of ice at 1 atmosphere of pressure in K
-			obj.meltingpoint=273.15;
+			self.meltingpoint=273.15;
 
 			%rate of change of melting point with pressure (K/Pa)
-			obj.beta=9.8*10^-8;
+			self.beta=9.8*10^-8;
 
 			%mixed layer (ice-water interface) heat capacity (J/kg/K)
-			obj.mixed_layer_capacity=3974.;
+			self.mixed_layer_capacity=3974.;
 
 			%thermal exchange velocity (ice-water interface) (m/s)
-			obj.thermal_exchange_velocity=1.00*10^-4;
+			self.thermal_exchange_velocity=1.00*10^-4;
 
 			%Rheology law: what is the temperature dependence of B with T
 			%available: none, paterson and arrhenius
-			obj.rheology_law='Paterson';
+			self.rheology_law='Paterson';
 
 			% GIA:
-			obj.lithosphere_shear_modulus  = 6.7*10^10;  % (Pa)
-			obj.lithosphere_density        = 3.32;       % (g/cm^-3)
-			obj.mantle_shear_modulus       = 1.45*10^11; % (Pa)
-			obj.mantle_density             = 3.34;       % (g/cm^-3)
-
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			self.lithosphere_shear_modulus  = 6.7*10^10;  % (Pa)
+			self.lithosphere_density        = 3.32;       % (g/cm^-3)
+			self.mantle_shear_modulus       = 1.45*10^11; % (Pa)
+			self.mantle_density             = 3.34;       % (g/cm^-3)
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 			md = checkfield(md,'fieldname','materials.rho_ice','>',0);
 			md = checkfield(md,'fieldname','materials.rho_water','>',0);
 			md = checkfield(md,'fieldname','materials.rho_freshwater','>',0);
 			md = checkfield(md,'fieldname','materials.mu_water','>',0);
-			md = checkfield(md,'fieldname','materials.rheology_B','>',0,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','materials.rheology_B','>',0,'timeseries',1,'NaN',1);
 			md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements 1]);
 			md = checkfield(md,'fieldname','materials.rheology_law','values',{'None' 'Cuffey' 'Paterson' 'Arrhenius' 'LliboutryDuval'});
@@ -155,49 +159,49 @@
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   Materials:'));
 
-			fielddisplay(obj,'rho_ice','ice density [kg/m^3]');
-			fielddisplay(obj,'rho_water','ocean water density [kg/m^3]');
-			fielddisplay(obj,'rho_freshwater','fresh water density [kg/m^3]');
-			fielddisplay(obj,'mu_water','water viscosity [N s/m^2]');
-			fielddisplay(obj,'heatcapacity','heat capacity [J/kg/K]');
-			fielddisplay(obj,'thermalconductivity',['ice thermal conductivity [W/m/K]']);
-			fielddisplay(obj,'temperateiceconductivity','temperate ice thermal conductivity [W/m/K]');
-			fielddisplay(obj,'meltingpoint','melting point of ice at 1atm in K');
-			fielddisplay(obj,'latentheat','latent heat of fusion [J/kg]');
-			fielddisplay(obj,'beta','rate of change of melting point with pressure [K/Pa]');
-			fielddisplay(obj,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
-			fielddisplay(obj,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
-			fielddisplay(obj,'rheology_B','flow law parameter [Pa/s^(1/n)]');
-			fielddisplay(obj,'rheology_n','Glen''s flow law exponent');
-			fielddisplay(obj,'rheology_law',['law for the temperature dependance of the rheology: ''None'', ''Cuffey'', ''Paterson'', ''Arrhenius'' or ''LliboutryDuval''']);
-			fielddisplay(obj,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
-			fielddisplay(obj,'lithosphere_density','Lithosphere density [g/cm^-3]');
-			fielddisplay(obj,'mantle_shear_modulus','Mantle shear modulus [Pa]');
-			fielddisplay(obj,'mantle_density','Mantle density [g/cm^-3]');
-		end % }}}
-		function marshall(obj,md,fid) % {{{
+			fielddisplay(self,'rho_ice','ice density [kg/m^3]');
+			fielddisplay(self,'rho_water','ocean water density [kg/m^3]');
+			fielddisplay(self,'rho_freshwater','fresh water density [kg/m^3]');
+			fielddisplay(self,'mu_water','water viscosity [N s/m^2]');
+			fielddisplay(self,'heatcapacity','heat capacity [J/kg/K]');
+			fielddisplay(self,'thermalconductivity',['ice thermal conductivity [W/m/K]']);
+			fielddisplay(self,'temperateiceconductivity','temperate ice thermal conductivity [W/m/K]');
+			fielddisplay(self,'meltingpoint','melting point of ice at 1atm in K');
+			fielddisplay(self,'latentheat','latent heat of fusion [J/kg]');
+			fielddisplay(self,'beta','rate of change of melting point with pressure [K/Pa]');
+			fielddisplay(self,'mixed_layer_capacity','mixed layer capacity [W/kg/K]');
+			fielddisplay(self,'thermal_exchange_velocity','thermal exchange velocity [m/s]');
+			fielddisplay(self,'rheology_B','flow law parameter [Pa/s^(1/n)]');
+			fielddisplay(self,'rheology_n','Glen''s flow law exponent');
+			fielddisplay(self,'rheology_law',['law for the temperature dependance of the rheology: ''None'', ''Cuffey'', ''Paterson'', ''Arrhenius'' or ''LliboutryDuval''']);
+			fielddisplay(self,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
+			fielddisplay(self,'lithosphere_density','Lithosphere density [g/cm^-3]');
+			fielddisplay(self,'mantle_shear_modulus','Mantle shear modulus [Pa]');
+			fielddisplay(self,'mantle_density','Mantle density [g/cm^-3]');
+		end % }}}
+		function marshall(self,md,fid) % {{{
 			WriteData(fid,'enum',MaterialsEnum(),'data',MaticeEnum(),'format','Integer');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rho_ice','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rho_water','enum',MaterialsRhoSeawaterEnum(),'format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rho_freshwater','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','mu_water','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','heatcapacity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','latentheat','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','thermalconductivity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','temperateiceconductivity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','meltingpoint','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','beta','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','mixed_layer_capacity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','thermal_exchange_velocity','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
-			WriteData(fid,'data',StringToEnum(obj.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
-
-			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','lithosphere_density','format','Double','scale',10^3);
-			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_shear_modulus','format','Double');
-			WriteData(fid,'object',obj,'class','materials','fieldname','mantle_density','format','Double','scale',10^3);
+			WriteData(fid,'object',self,'class','materials','fieldname','rho_ice','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','rho_water','enum',MaterialsRhoSeawaterEnum(),'format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','rho_freshwater','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','mu_water','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','heatcapacity','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','latentheat','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','thermalconductivity','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','meltingpoint','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','beta','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2);
+			WriteData(fid,'data',StringToEnum(self.rheology_law),'enum',MaterialsRheologyLawEnum(),'format','Integer');
+
+			WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10^3);
+			WriteData(fid,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double');
+			WriteData(fid,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10^3);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/matice.py
===================================================================
--- /issm/trunk/src/m/classes/matice.py	(revision 19104)
+++ /issm/trunk/src/m/classes/matice.py	(revision 19105)
@@ -1,3 +1,4 @@
 from fielddisplay import fielddisplay
+from project3d import project3d
 from EnumDefinitions import *
 from StringToEnum import StringToEnum
@@ -63,4 +64,9 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.rheology_B=project3d(md,'vector',self.rheology_B,'type','node')
+		self.rheology_n=project3d(md,'vector',self.rheology_n,'type','element')
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		#ice density (kg/m^3)
@@ -117,5 +123,5 @@
 		md = checkfield(md,'fieldname','materials.rho_freshwater','>',0)
 		md = checkfield(md,'fieldname','materials.mu_water','>',0)
-		md = checkfield(md,'fieldname','materials.rheology_B','>',0,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'fieldname','materials.rheology_B','>',0,'timeseries',1,'NaN',1)
 		md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
 		md = checkfield(md,'fieldname','materials.rheology_law','values',['None','Cuffey','Paterson','Arrhenius','LliboutryDuval'])
@@ -140,4 +146,5 @@
 		WriteData(fid,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
 		WriteData(fid,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
+		WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
 		WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1)
 		WriteData(fid,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
Index: /issm/trunk/src/m/classes/mesh2d.m
===================================================================
--- /issm/trunk/src/m/classes/mesh2d.m	(revision 19104)
+++ /issm/trunk/src/m/classes/mesh2d.m	(revision 19105)
@@ -8,24 +8,46 @@
 		x                           = NaN;
 		y                           = NaN;
-		elements                    = NaN
+		elements                    = NaN;
 		numberofelements            = 0;
 		numberofvertices            = 0;
 		numberofedges               = 0;
 
-		lat                         = NaN
-		long                        = NaN
-		hemisphere                  = NaN
+		lat                         = NaN;
+		long                        = NaN;
+		epsg                        = 0;
 
-		vertexonboundary            = NaN
+		vertexonboundary            = NaN;
 
-		edges                       = NaN
-		segments                    = NaN
-		segmentmarkers              = NaN
-		vertexconnectivity          = NaN
-		elementconnectivity         = NaN
+		edges                       = NaN;
+		segments                    = NaN;
+		segmentmarkers              = NaN;
+		vertexconnectivity          = NaN;
+		elementconnectivity         = NaN;
 		average_vertex_connectivity = 0;
 
-		extractedvertices           = NaN
-		extractedelements           = NaN
+		extractedvertices           = NaN;
+		extractedelements           = NaN;
+	end
+	methods (Static)
+		function self = loadobj(self) % {{{
+			% This function is directly called by matlab when a model selfect is
+			% loaded. Update old properties here
+
+			%2014 Oct. 1st
+			if isstruct(self),
+				oldself=self;
+				%Assign property values from struct
+				self=structtoobj(mesh2d(),oldself);
+				if isfield(oldself,'hemisphere'),
+					disp('md.mesh.hemisphere has been automatically converted to EPSG code');
+					if strcmpi(oldself.hemisphere,'n'),
+						self.epsg=3413;
+					else
+						self.epsg=3031;
+					end
+				end
+			end
+
+		end% }}}
 	end
 	methods
@@ -48,5 +70,5 @@
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%the connectivity is the averaged number of nodes linked to a
@@ -55,7 +77,7 @@
 			%give a good memory/time ration. This value can be checked in
 			%trunk/test/Miscellaneous/runme.m
-			obj.average_vertex_connectivity=25;
+			self.average_vertex_connectivity=25;
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			md = checkfield(md,'fieldname','mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
@@ -75,95 +97,95 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   2D tria Mesh (horizontal):')); 
 
 			disp(sprintf('\n      Elements and vertices:'));
-			fielddisplay(obj,'numberofelements','number of elements');
-			fielddisplay(obj,'numberofvertices','number of vertices');
-			fielddisplay(obj,'elements','vertex indices of the mesh elements');
-			fielddisplay(obj,'x','vertices x coordinate [m]');
-			fielddisplay(obj,'y','vertices y coordinate [m]');
-			fielddisplay(obj,'edges','edges of the 2d mesh (vertex1 vertex2 element1 element2)');
-			fielddisplay(obj,'numberofedges','number of edges of the 2d mesh');
+			fielddisplay(self,'numberofelements','number of elements');
+			fielddisplay(self,'numberofvertices','number of vertices');
+			fielddisplay(self,'elements','vertex indices of the mesh elements');
+			fielddisplay(self,'x','vertices x coordinate [m]');
+			fielddisplay(self,'y','vertices y coordinate [m]');
+			fielddisplay(self,'edges','edges of the 2d mesh (vertex1 vertex2 element1 element2)');
+			fielddisplay(self,'numberofedges','number of edges of the 2d mesh');
 
 			disp(sprintf('\n      Properties:'));
-			fielddisplay(obj,'vertexonboundary','vertices on the boundary of the domain flag list');
-			fielddisplay(obj,'segments','edges on domain boundary (vertex1 vertex2 element)');
-			fielddisplay(obj,'segmentmarkers','number associated to each segment');
-			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
-			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
-			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+			fielddisplay(self,'vertexonboundary','vertices on the boundary of the domain flag list');
+			fielddisplay(self,'segments','edges on domain boundary (vertex1 vertex2 element)');
+			fielddisplay(self,'segmentmarkers','number associated to each segment');
+			fielddisplay(self,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(self,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(self,'average_vertex_connectivity','average number of vertices connected to one vertex');
 
 			disp(sprintf('\n      Extracted model:'));
-			fielddisplay(obj,'extractedvertices','vertices extracted from the model');
-			fielddisplay(obj,'extractedelements','elements extracted from the model');
+			fielddisplay(self,'extractedvertices','vertices extracted from the model');
+			fielddisplay(self,'extractedelements','elements extracted from the model');
 
 			disp(sprintf('\n      Projection:'));
-			fielddisplay(obj,'lat','vertices latitude [degrees]');
-			fielddisplay(obj,'long','vertices longitude [degrees]');
-			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
+			fielddisplay(self,'lat','vertices latitude [degrees]');
+			fielddisplay(self,'long','vertices longitude [degrees]');
+			fielddisplay(self,'epsg','EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)');
 		end % }}}
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '<!-- 2D tria Mesh (horizontal) -->\n');
-            
-            %elements and vertices
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Elements and vertices">','<section name="mesh" />');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="numberofelements" type="',class(obj.numberofelements),'" default="',convert2str(obj.numberofelements),'">','     <section name="mesh" />','     <help> number of elements </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="numberofvertices" type="',class(obj.numberofvertices),'" default="',convert2str(obj.numberofvertices),'">','     <section name="mesh" />','     <help> number of vertices </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="elements" type="',class(obj.elements),'" default="',convert2str(obj.elements),'">','     <section name="mesh" />','     <help> vertex indices of the mesh elements </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(obj.x),'" default="',convert2str(obj.x),'">','     <section name="mesh" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="edges" type="',class(obj.edges),'" default="',convert2str(obj.edges),'">','     <section name="mesh" />','     <help> edges of the 2d mesh (vertex1 vertex2 element1 element2) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofedges" type="',class(obj.numberofedges),'" default="',convert2str(obj.numberofedges),'">','     <section name="mesh" />','     <help> number of edges of the 2d mesh </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-     
-            % properties
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Properties">','<section name="mesh" />');             
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(obj.vertexonboundary),'" default="',convert2str(obj.vertexonboundary),'">','     <section name="mesh" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segments" type="',class(obj.segments),'" default="',convert2str(obj.segments),'">','     <section name="mesh" />','     <help> edges on domain boundary (vertex1 vertex2 element) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segmentmarkers" type="',class(obj.segmentmarkers),'" default="',convert2str(obj.segmentmarkers),'">','     <section name="mesh" />','     <help> number associated to each segment </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(obj.vertexconnectivity),'" default="',convert2str(obj.vertexconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(obj.elementconnectivity),'" default="',convert2str(obj.elementconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to element_i </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(obj.average_vertex_connectivity),'" default="',convert2str(obj.average_vertex_connectivity),'">','     <section name="mesh" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-            
-            %extracted model
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Extracted Model">','<section name="mesh" />'); 
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedvertices" type="',class(obj.extractedvertices),'" default="',convert2str(obj.extractedvertices),'">','     <section name="mesh" />','     <help> vertices extracted from the model </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedelements" type="',class(obj.extractedelements),'" default="',convert2str(obj.extractedelements),'">','     <section name="mesh" />','     <help> elements extracted from the model </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-            
-            %projection
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Projection">','<section name="mesh" />'); 
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(obj.lat),'" default="',convert2str(obj.lat),'">','     <section name="mesh" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(obj.long),'" default="',convert2str(obj.long),'">','     <section name="mesh" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
-            % choice (hemisphere) 'n' or 's'
-            fprintf(fid,'%s\n%s\n%s\n','  <parameter key ="hemisphere" type="alternative" optional="false">','     <section name="mesh" />','     <help> Indicate hemisphere ''n'' or ''s'' </help>');
-            fprintf(fid,'%s\n','       <option value="n" type="string" default="true"> </option>');
-            fprintf(fid,'%s\n','       <option value="s" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-        
-        end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(obj)]),'format','Integer');
-			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(obj),'format','Integer');
-			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(obj)),'format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
-			WriteData(fid,'enum',MeshZEnum(),'data',zeros(obj.numberofvertices,1),'format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonboundary','format','DoubleMat','mattype',1);
+		function createxml(self,fid) % {{{
+			fprintf(fid, '<!-- 2D tria Mesh (horizontal) -->\n');
+
+			%elements and vertices
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Elements and vertices">','<section name="mesh" />');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="numberofelements" type="',class(self.numberofelements),'" default="',convert2str(self.numberofelements),'">','     <section name="mesh" />','     <help> number of elements </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="numberofvertices" type="',class(self.numberofvertices),'" default="',convert2str(self.numberofvertices),'">','     <section name="mesh" />','     <help> number of vertices </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="elements" type="',class(self.elements),'" default="',convert2str(self.elements),'">','     <section name="mesh" />','     <help> vertex indices of the mesh elements </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(self.x),'" default="',convert2str(self.x),'">','     <section name="mesh" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(self.y),'" default="',convert2str(self.y),'">','     <section name="mesh" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="edges" type="',class(self.edges),'" default="',convert2str(self.edges),'">','     <section name="mesh" />','     <help> edges of the 2d mesh (vertex1 vertex2 element1 element2) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofedges" type="',class(self.numberofedges),'" default="',convert2str(self.numberofedges),'">','     <section name="mesh" />','     <help> number of edges of the 2d mesh </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			% properties
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Properties">','<section name="mesh" />');             
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(self.vertexonboundary),'" default="',convert2str(self.vertexonboundary),'">','     <section name="mesh" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segments" type="',class(self.segments),'" default="',convert2str(self.segments),'">','     <section name="mesh" />','     <help> edges on domain boundary (vertex1 vertex2 element) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segmentmarkers" type="',class(self.segmentmarkers),'" default="',convert2str(self.segmentmarkers),'">','     <section name="mesh" />','     <help> number associated to each segment </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(self.vertexconnectivity),'" default="',convert2str(self.vertexconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(self.elementconnectivity),'" default="',convert2str(self.elementconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to element_i </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(self.average_vertex_connectivity),'" default="',convert2str(self.average_vertex_connectivity),'">','     <section name="mesh" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			%extracted model
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Extracted Model">','<section name="mesh" />'); 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedvertices" type="',class(self.extractedvertices),'" default="',convert2str(self.extractedvertices),'">','     <section name="mesh" />','     <help> vertices extracted from the model </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedelements" type="',class(self.extractedelements),'" default="',convert2str(self.extractedelements),'">','     <section name="mesh" />','     <help> elements extracted from the model </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			%projection
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Projection">','<section name="mesh" />'); 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(self.lat),'" default="',convert2str(self.lat),'">','     <section name="mesh" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(self.long),'" default="',convert2str(self.long),'">','     <section name="mesh" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
+			% choice (epsg) 'n' or 's'
+			fprintf(fid,'%s\n%s\n%s\n','  <parameter key ="epsg" type="alternative" optional="false">','     <section name="mesh" />','     <help> Indicate epsg ''n'' or ''s'' </help>');
+			fprintf(fid,'%s\n','       <option value="n" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="s" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
 		end % }}}
-		function t = domaintype(obj) % {{{
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(self)]),'format','Integer');
+			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(self),'format','Integer');
+			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(self)),'format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'enum',MeshZEnum(),'data',zeros(self.numberofvertices,1),'format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','vertexonboundary','format','DoubleMat','mattype',1);
+		end % }}}
+		function t = domaintype(self) % {{{
 			t = '2Dhorizontal';
 		end % }}}
-		function d = dimension(obj) % {{{
+		function d = dimension(self) % {{{
 			d = 2;
 		end % }}}
-		function s = elementtype(obj) % {{{
+		function s = elementtype(self) % {{{
 			s = 'Tria';
 		end % }}}
Index: /issm/trunk/src/m/classes/mesh2d.py
===================================================================
--- /issm/trunk/src/m/classes/mesh2d.py	(revision 19104)
+++ /issm/trunk/src/m/classes/mesh2d.py	(revision 19105)
@@ -24,5 +24,5 @@
 		self.lat                         = float('NaN');
 		self.long                        = float('NaN');
-		self.hemisphere                  = float('NaN');
+		self.epsg                        = 0;
 
 		self.vertexonboundary            = float('NaN');
@@ -68,5 +68,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,"lat","vertices latitude [degrees]"))
 		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]"))
-		string="%s\n%s"%(string,fielddisplay(self,"hemisphere","Indicate hemisphere 'n' or 's'"))
+		string="%s\n%s"%(string,fielddisplay(self,"epsg","EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)"))
 		return string
 		#}}}
Index: /issm/trunk/src/m/classes/mesh2dvertical.m
===================================================================
--- /issm/trunk/src/m/classes/mesh2dvertical.m	(revision 19104)
+++ /issm/trunk/src/m/classes/mesh2dvertical.m	(revision 19105)
@@ -8,62 +8,84 @@
 		x                           = NaN;
 		y                           = NaN;
-		elements                    = NaN
+		elements                    = NaN;
 		numberofelements            = 0;
 		numberofvertices            = 0;
 		numberofedges               = 0;
 
-		lat                         = NaN
-		long                        = NaN
-		hemisphere                  = NaN
-
-		vertexonboundary            = NaN
-		vertexonbase                 = NaN
-		vertexonsurface             = NaN
-
-		edges                       = NaN
-		segments                    = NaN
-		segmentmarkers              = NaN
-		vertexconnectivity          = NaN
-		elementconnectivity         = NaN
+		lat                         = NaN;
+		long                        = NaN;
+		epsg                        = NaN;
+
+		vertexonboundary            = NaN;
+		vertexonbase                = NaN;
+		vertexonsurface             = NaN;
+
+		edges                       = NaN;
+		segments                    = NaN;
+		segmentmarkers              = NaN;
+		vertexconnectivity          = NaN;
+		elementconnectivity         = NaN;
 		average_vertex_connectivity = 0;
 	end
+	methods (Static)
+		function self = loadobj(self) % {{{
+			% This function is directly called by matlab when a model selfect is
+			% loaded. Update old properties here
+
+			%2014 Oct. 1st
+			if isstruct(self),
+				oldself=self;
+				%Assign property values from struct
+				self=structtoobj(mesh2dvertical(),oldself);
+				if isfield(oldself,'hemisphere'),
+					disp('md.mesh.hemisphere has been automatically converted to EPSG code');
+					if strcmpi(oldself.hemisphere,'n'),
+						self.epsg=3413;
+					else
+						self.epsg=3031;
+					end
+				end
+			end
+
+		end% }}}
+	end
 	methods
-                function createxml(obj,fid) % {{{
-            fprintf(fid, '<!-- 2d Mesh (Vertical) -->\n');
-            
-            %elements and vertices
-            fprintf(fid,'%s\n%s\n%s\n','       <frame key="1" label="Elements and vertices">','       <section name="mesh" />');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements" type="',class(obj.numberofelements),'" default="',convert2str(obj.numberofelements),'">','              <help> number of elements </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices" type="',class(obj.numberofvertices),'" default="',convert2str(obj.numberofvertices),'">','              <help> number of vertices </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements" type="',class(obj.elements),'" default="',convert2str(obj.elements),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(obj.x),'" default="',convert2str(obj.x),'">','     <section name="mesh" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="edges" type="',class(obj.edges),'" default="',convert2str(obj.edges),'">','     <section name="mesh" />','     <help> edges of the 2d mesh (vertex1 vertex2 element1 element2) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofedges" type="',class(obj.numberofedges),'" default="',convert2str(obj.numberofedges),'">','     <section name="mesh" />','     <help> number of edges of the 2d mesh </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','       </frame>');
-     
-            % properties
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Properties">','<section name="mesh" />');             
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(obj.vertexonboundary),'" default="',convert2str(obj.vertexonboundary),'">','     <section name="mesh" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonbase" type="',class(obj.vertexonbase),'" default="',convert2str(obj.vertexonbase),'">','     <section name="mesh" />','     <help> vertices on the bed of the domain flag list </help>','  </parameter>');            
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segments" type="',class(obj.segments),'" default="',convert2str(obj.segments),'">','     <section name="mesh" />','     <help> edges on domain boundary (vertex1 vertex2 element) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segmentmarkers" type="',class(obj.segmentmarkers),'" default="',convert2str(obj.segmentmarkers),'">','     <section name="mesh" />','     <help> number associated to each segment </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(obj.vertexconnectivity),'" default="',convert2str(obj.vertexconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(obj.elementconnectivity),'" default="',convert2str(obj.elementconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to element_i </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(obj.average_vertex_connectivity),'" default="',convert2str(obj.average_vertex_connectivity),'">','     <section name="mesh" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-
-            %projection
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Projection">','<section name="mesh" />'); 
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(obj.lat),'" default="',convert2str(obj.lat),'">','     <section name="mesh" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(obj.long),'" default="',convert2str(obj.long),'">','     <section name="mesh" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="hemisphere" type="',class(obj.hemisphere),'" default="',convert2str(obj.hemisphere),'">','     <section name="mesh" />','     <help> Indicate hemisphere ''n'' or ''s'' </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-        
-        end % }}}
-		function obj = mesh2dvertical(varargin) % {{{
+		function createxml(self,fid) % {{{
+			fprintf(fid, '<!-- 2d Mesh (Vertical) -->\n');
+
+			%elements and vertices
+			fprintf(fid,'%s\n%s\n%s\n','       <frame key="1" label="Elements and vertices">','       <section name="mesh" />');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements" type="',class(self.numberofelements),'" default="',convert2str(self.numberofelements),'">','              <help> number of elements </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices" type="',class(self.numberofvertices),'" default="',convert2str(self.numberofvertices),'">','              <help> number of vertices </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements" type="',class(self.elements),'" default="',convert2str(self.elements),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(self.x),'" default="',convert2str(self.x),'">','     <section name="mesh" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(self.y),'" default="',convert2str(self.y),'">','     <section name="mesh" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="edges" type="',class(self.edges),'" default="',convert2str(self.edges),'">','     <section name="mesh" />','     <help> edges of the 2d mesh (vertex1 vertex2 element1 element2) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofedges" type="',class(self.numberofedges),'" default="',convert2str(self.numberofedges),'">','     <section name="mesh" />','     <help> number of edges of the 2d mesh </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','       </frame>');
+
+			% properties
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Properties">','<section name="mesh" />');             
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(self.vertexonboundary),'" default="',convert2str(self.vertexonboundary),'">','     <section name="mesh" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonbase" type="',class(self.vertexonbase),'" default="',convert2str(self.vertexonbase),'">','     <section name="mesh" />','     <help> vertices on the bed of the domain flag list </help>','  </parameter>');            
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segments" type="',class(self.segments),'" default="',convert2str(self.segments),'">','     <section name="mesh" />','     <help> edges on domain boundary (vertex1 vertex2 element) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segmentmarkers" type="',class(self.segmentmarkers),'" default="',convert2str(self.segmentmarkers),'">','     <section name="mesh" />','     <help> number associated to each segment </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(self.vertexconnectivity),'" default="',convert2str(self.vertexconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(self.elementconnectivity),'" default="',convert2str(self.elementconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to element_i </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(self.average_vertex_connectivity),'" default="',convert2str(self.average_vertex_connectivity),'">','     <section name="mesh" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			%projection
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Projection">','<section name="mesh" />'); 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(self.lat),'" default="',convert2str(self.lat),'">','     <section name="mesh" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(self.long),'" default="',convert2str(self.long),'">','     <section name="mesh" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="epsg" type="',class(self.epsg),'" default="',convert2str(self.epsg),'">','     <section name="mesh" />','     <help> Indicate epsg ''n'' or ''s'' </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+		end % }}}
+		function self = mesh2dvertical(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
 					inputstruct=varargin{1};
@@ -73,5 +95,5 @@
 						fieldname = list1{i};
 						if ismember(fieldname,list2),
-							obj.(fieldname) = inputstruct.(fieldname);
+							self.(fieldname) = inputstruct.(fieldname);
 						end
 					end
@@ -80,5 +102,5 @@
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%the connectivity is the averaged number of nodes linked to a
@@ -87,7 +109,7 @@
 			%give a good memory/time ration. This value can be checked in
 			%trunk/test/Miscellaneous/runme.m
-			obj.average_vertex_connectivity=25;
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			self.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			md = checkfield(md,'fieldname','mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
@@ -109,52 +131,52 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   2D tria Mesh (vertical):')); 
 
 			disp(sprintf('\n      Elements and vertices:'));
-			fielddisplay(obj,'numberofelements','number of elements');
-			fielddisplay(obj,'numberofvertices','number of vertices');
-			fielddisplay(obj,'elements','vertex indices of the mesh elements');
-			fielddisplay(obj,'x','vertices x coordinate [m]');
-			fielddisplay(obj,'y','vertices y coordinate [m]');
-			fielddisplay(obj,'edges','edges of the 2d mesh (vertex1 vertex2 element1 element2)');
-			fielddisplay(obj,'numberofedges','number of edges of the 2d mesh');
+			fielddisplay(self,'numberofelements','number of elements');
+			fielddisplay(self,'numberofvertices','number of vertices');
+			fielddisplay(self,'elements','vertex indices of the mesh elements');
+			fielddisplay(self,'x','vertices x coordinate [m]');
+			fielddisplay(self,'y','vertices y coordinate [m]');
+			fielddisplay(self,'edges','edges of the 2d mesh (vertex1 vertex2 element1 element2)');
+			fielddisplay(self,'numberofedges','number of edges of the 2d mesh');
 
 			disp(sprintf('\n      Properties:'));
-			fielddisplay(obj,'vertexonboundary','vertices on the boundary of the domain flag list');
-			fielddisplay(obj,'vertexonbase','vertices on the bed of the domain flag list');
-			fielddisplay(obj,'vertexonsurface','vertices on the surface of the domain flag list');
-			fielddisplay(obj,'segments','edges on domain boundary (vertex1 vertex2 element)');
-			fielddisplay(obj,'segmentmarkers','number associated to each segment');
-			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
-			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
-			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+			fielddisplay(self,'vertexonboundary','vertices on the boundary of the domain flag list');
+			fielddisplay(self,'vertexonbase','vertices on the bed of the domain flag list');
+			fielddisplay(self,'vertexonsurface','vertices on the surface of the domain flag list');
+			fielddisplay(self,'segments','edges on domain boundary (vertex1 vertex2 element)');
+			fielddisplay(self,'segmentmarkers','number associated to each segment');
+			fielddisplay(self,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(self,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(self,'average_vertex_connectivity','average number of vertices connected to one vertex');
 
 			disp(sprintf('\n      Projection:'));
-			fielddisplay(obj,'lat','vertices latitude [degrees]');
-			fielddisplay(obj,'long','vertices longitude [degrees]');
-			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
-		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(obj)]),'format','Integer');
-			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(obj),'format','Integer');
-			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(obj)),'format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
-			WriteData(fid,'enum',MeshZEnum(),'data',zeros(obj.numberofvertices,1),'format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
-		end % }}}
-		function t = domaintype(obj) % {{{
+			fielddisplay(self,'lat','vertices latitude [degrees]');
+			fielddisplay(self,'long','vertices longitude [degrees]');
+			fielddisplay(self,'epsg','EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)');
+		end % }}}
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(self)]),'format','Integer');
+			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(self),'format','Integer');
+			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(self)),'format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'enum',MeshZEnum(),'data',zeros(self.numberofvertices,1),'format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+		end % }}}
+		function t = domaintype(self) % {{{
 			t = '2Dvertical';
 		end % }}}
-		function d = dimension(obj) % {{{
+		function d = dimension(self) % {{{
 			d = 2;
 		end % }}}
-		function s = elementtype(obj) % {{{
+		function s = elementtype(self) % {{{
 			s = 'Tria';
 		end % }}}
Index: /issm/trunk/src/m/classes/mesh3dprisms.m
===================================================================
--- /issm/trunk/src/m/classes/mesh3dprisms.m	(revision 19104)
+++ /issm/trunk/src/m/classes/mesh3dprisms.m	(revision 19105)
@@ -8,89 +8,111 @@
 		x                           = NaN;
 		y                           = NaN;
-		z                           = NaN
-		elements                    = NaN
+		z                           = NaN;
+		elements                    = NaN;
 		numberoflayers              = 0;
 		numberofelements            = 0;
 		numberofvertices            = 0;
 
-		lat                         = NaN
-		long                        = NaN
-		hemisphere                  = NaN
-
-		vertexonbase                 = NaN
-		vertexonsurface             = NaN
-		lowerelements               = NaN
-		lowervertex                 = NaN
-		upperelements               = NaN
-		uppervertex                 = NaN
-		vertexonboundary            = NaN
-
-		vertexconnectivity          = NaN
-		elementconnectivity         = NaN
+		lat                         = NaN;
+		long                        = NaN;
+		epsg                        = 0;
+
+		vertexonbase                = NaN;
+		vertexonsurface             = NaN;
+		lowerelements               = NaN;
+		lowervertex                 = NaN;
+		upperelements               = NaN;
+		uppervertex                 = NaN;
+		vertexonboundary            = NaN;
+
+		vertexconnectivity          = NaN;
+		elementconnectivity         = NaN;
 		average_vertex_connectivity = 0;
 
-		x2d                         = NaN
-		y2d                         = NaN
-		elements2d                  = NaN
+		x2d                         = NaN;
+		y2d                         = NaN;
+		elements2d                  = NaN;
 		numberofvertices2d          = 0;
 		numberofelements2d          = 0;
 
-		extractedvertices           = NaN
-		extractedelements           = NaN
+		extractedvertices           = NaN;
+		extractedelements           = NaN;
+	end
+	methods (Static)
+		function self = loadobj(self) % {{{
+			% This function is directly called by matlab when a model selfect is
+			% loaded. Update old properties here
+
+			%2014 Oct. 1st
+			if isstruct(self),
+				oldself=self;
+				%Assign property values from struct
+				self=structtoobj(mesh3dprisms(),oldself);
+				if isfield(oldself,'hemisphere'),
+					disp('md.mesh.hemisphere has been automatically converted to EPSG code');
+					if strcmpi(oldself.hemisphere,'n'),
+						self.epsg=3413;
+					else
+						self.epsg=3031;
+					end
+				end
+			end
+
+		end% }}}
 	end
 	methods
-           function createxml(obj,fid) % {{{
-            fprintf(fid, '<!-- 3D prism Mesh -->\n');
-            
-            % Elements and verticies of the original 2d mesh
-            fprintf(fid,'%s\n%s\n%s\n','       <frame key="1" label="Elements and vertices of the orginal 2d mesh">','       <section name="mesh3dprisms" />');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements2d" type="',class(obj.numberofelements2d),'" default="',convert2str(obj.numberofelements2d),'">','              <help> number of elements </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices2d" type="',class(obj.numberofvertices2d),'" default="',convert2str(obj.numberofvertices2d),'">','              <help> number of vertices </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements2d" type="',class(obj.elements2d),'" default="',convert2str(obj.elements2d),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x2d" type="',class(obj.x2d),'" default="',convert2str(obj.x2d),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y2d" type="',class(obj.y2d),'" default="',convert2str(obj.y2d),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','       </frame>');
-            
-            % Elements and vertices of the extruded 3d mesh
-            fprintf(fid,'%s\n%s\n%s\n','       <frame key="2" label="Elements and vertices of the orginal 3d mesh">','       <section name="mesh3dprisms" />');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements" type="',class(obj.numberofelements),'" default="',convert2str(obj.numberofelements),'">','              <help> number of elements </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices" type="',class(obj.numberofvertices),'" default="',convert2str(obj.numberofvertices),'">','              <help> number of vertices </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements" type="',class(obj.elements),'" default="',convert2str(obj.elements),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(obj.x),'" default="',convert2str(obj.x),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="z" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh3dprisms" />','     <help> vertices z coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','       </frame>');
-     
-            % properties
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Properties">','<section name="mesh3dprisms" />');             
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberoflayers" type="',class(obj.numberoflayers),'" default="',convert2str(obj.numberoflayers),'">','     <section name="mesh3dprisms" />','     <help> number of extrusion layers </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonbase" type="',class(obj.vertexonbase),'" default="',convert2str(obj.vertexonbase),'">','     <section name="mesh3dprisms" />','     <help> lower vertices flags list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontbase" type="',class(obj.elementontbase),'" default="',convert2str(obj.elementontbase),'">','     <section name="mesh3dprisms" />','     <help> lower elements flags list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonsurface" type="',class(obj.vertexonsurface),'" default="',convert2str(obj.vertexonsurface),'">','     <section name="mesh3dprisms" />','     <help> upper vertices flags list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontsurface" type="',class(obj.elementontsurface),'" default="',convert2str(obj.elementontsurface),'">','     <section name="mesh3dprisms" />','     <help> upper elements flags list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="uppervertex" type="',class(obj.uppervertex),'" default="',convert2str(obj.uppervertex),'">','     <section name="mesh3dprisms" />','     <help> upper vertex list (NaN for vertex on the upper surface) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="upperelements" type="',class(obj.upperelements),'" default="',convert2str(obj.upperelements),'">','     <section name="mesh3dprisms" />','     <help> upper element list (NaN for element on the upper layer) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowervertex" type="',class(obj.lowervertex),'" default="',convert2str(obj.lowervertex),'">','     <section name="mesh3dprisms" />','     <help> lower vertex list (NaN for vertex on the lower surface) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowerelements" type="',class(obj.lowerelements),'" default="',convert2str(obj.lowerelements),'">','     <section name="mesh3dprisms" />','     <help> element list (NaN for element on the lower layer) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(obj.vertexonboundary),'" default="',convert2str(obj.vertexonboundary),'">','     <section name="mesh3dprisms" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(obj.vertexconnectivity),'" default="',convert2str(obj.vertexconnectivity),'">','     <section name="mesh3dprisms" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(obj.elementconnectivity),'" default="',convert2str(obj.elementconnectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(obj.average_vertex_connectivity),'" default="',convert2str(obj.average_vertex_connectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-            
-            % Extracted model
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Extracted Model">','<section name="mesh3dprisms" />'); 
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedvertices" type="',class(obj.extractedvertices),'" default="',convert2str(obj.extractedvertices),'">','     <section name="mesh3dprisms" />','     <help> vertices extracted from the model </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedelements" type="',class(obj.extractedelements),'" default="',convert2str(obj.extractedelements),'">','     <section name="mesh3dprisms" />','     <help> elements extracted from the model </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-            
-            % Projection
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="5" label="Projection">','<section name="mesh3dprisms" />'); 
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(obj.lat),'" default="',convert2str(obj.lat),'">','     <section name="mesh3dprisms" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(obj.long),'" default="',convert2str(obj.long),'">','     <section name="mesh3dprisms" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="hemisphere" type="',class(obj.hemisphere),'" default="',convert2str(obj.hemisphere),'">','     <section name="mesh3dprisms" />','     <help> Indicate hemisphere ''n'' or ''s'' </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-        
-        end % }}}cd
+		function createxml(self,fid) % {{{
+			fprintf(fid, '<!-- 3D prism Mesh -->\n');
+
+			% Elements and verticies of the original 2d mesh
+			fprintf(fid,'%s\n%s\n%s\n','       <frame key="1" label="Elements and vertices of the orginal 2d mesh">','       <section name="mesh3dprisms" />');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements2d" type="',class(self.numberofelements2d),'" default="',convert2str(self.numberofelements2d),'">','              <help> number of elements </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices2d" type="',class(self.numberofvertices2d),'" default="',convert2str(self.numberofvertices2d),'">','              <help> number of vertices </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements2d" type="',class(self.elements2d),'" default="',convert2str(self.elements2d),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x2d" type="',class(self.x2d),'" default="',convert2str(self.x2d),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y2d" type="',class(self.y2d),'" default="',convert2str(self.y2d),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','       </frame>');
+
+			% Elements and vertices of the extruded 3d mesh
+			fprintf(fid,'%s\n%s\n%s\n','       <frame key="2" label="Elements and vertices of the orginal 3d mesh">','       <section name="mesh3dprisms" />');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements" type="',class(self.numberofelements),'" default="',convert2str(self.numberofelements),'">','              <help> number of elements </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices" type="',class(self.numberofvertices),'" default="',convert2str(self.numberofvertices),'">','              <help> number of vertices </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements" type="',class(self.elements),'" default="',convert2str(self.elements),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(self.x),'" default="',convert2str(self.x),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(self.y),'" default="',convert2str(self.y),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="z" type="',class(self.y),'" default="',convert2str(self.y),'">','     <section name="mesh3dprisms" />','     <help> vertices z coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','       </frame>');
+
+			% properties
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Properties">','<section name="mesh3dprisms" />');             
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberoflayers" type="',class(self.numberoflayers),'" default="',convert2str(self.numberoflayers),'">','     <section name="mesh3dprisms" />','     <help> number of extrusion layers </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonbase" type="',class(self.vertexonbase),'" default="',convert2str(self.vertexonbase),'">','     <section name="mesh3dprisms" />','     <help> lower vertices flags list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontbase" type="',class(self.elementontbase),'" default="',convert2str(self.elementontbase),'">','     <section name="mesh3dprisms" />','     <help> lower elements flags list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonsurface" type="',class(self.vertexonsurface),'" default="',convert2str(self.vertexonsurface),'">','     <section name="mesh3dprisms" />','     <help> upper vertices flags list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontsurface" type="',class(self.elementontsurface),'" default="',convert2str(self.elementontsurface),'">','     <section name="mesh3dprisms" />','     <help> upper elements flags list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="uppervertex" type="',class(self.uppervertex),'" default="',convert2str(self.uppervertex),'">','     <section name="mesh3dprisms" />','     <help> upper vertex list (NaN for vertex on the upper surface) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="upperelements" type="',class(self.upperelements),'" default="',convert2str(self.upperelements),'">','     <section name="mesh3dprisms" />','     <help> upper element list (NaN for element on the upper layer) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowervertex" type="',class(self.lowervertex),'" default="',convert2str(self.lowervertex),'">','     <section name="mesh3dprisms" />','     <help> lower vertex list (NaN for vertex on the lower surface) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowerelements" type="',class(self.lowerelements),'" default="',convert2str(self.lowerelements),'">','     <section name="mesh3dprisms" />','     <help> element list (NaN for element on the lower layer) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(self.vertexonboundary),'" default="',convert2str(self.vertexonboundary),'">','     <section name="mesh3dprisms" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(self.vertexconnectivity),'" default="',convert2str(self.vertexconnectivity),'">','     <section name="mesh3dprisms" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(self.elementconnectivity),'" default="',convert2str(self.elementconnectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(self.average_vertex_connectivity),'" default="',convert2str(self.average_vertex_connectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			% Extracted model
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Extracted Model">','<section name="mesh3dprisms" />'); 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedvertices" type="',class(self.extractedvertices),'" default="',convert2str(self.extractedvertices),'">','     <section name="mesh3dprisms" />','     <help> vertices extracted from the model </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedelements" type="',class(self.extractedelements),'" default="',convert2str(self.extractedelements),'">','     <section name="mesh3dprisms" />','     <help> elements extracted from the model </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			% Projection
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="5" label="Projection">','<section name="mesh3dprisms" />'); 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(self.lat),'" default="',convert2str(self.lat),'">','     <section name="mesh3dprisms" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(self.long),'" default="',convert2str(self.long),'">','     <section name="mesh3dprisms" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="epsg" type="',class(self.epsg),'" default="',convert2str(self.epsg),'">','     <section name="mesh3dprisms" />','     <help> Indicate epsg ''n'' or ''s'' </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+		end % }}}cd
 		function self = mesh3dprisms(varargin) % {{{
 			switch nargin
@@ -111,5 +133,5 @@
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%the connectivity is the averaged number of nodes linked to a
@@ -118,7 +140,7 @@
 			%give a good memory/time ration. This value can be checked in
 			%trunk/test/Miscellaneous/runme.m
-			obj.average_vertex_connectivity=25;
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			self.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			md = checkfield(md,'fieldname','mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
@@ -133,5 +155,4 @@
 			md = checkfield(md,'fieldname','mesh.numberofelements','>',0);
 			md = checkfield(md,'fieldname','mesh.numberofvertices','>',0);
-			%no checks for numberofedges lat long and hemisphere
 			md = checkfield(md,'fieldname','mesh.vertexonbase','size',[md.mesh.numberofvertices 1],'values',[0 1]);
 			md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices 1],'values',[0 1]);
@@ -140,72 +161,72 @@
 			md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',24,'message','''mesh.average_vertex_connectivity'' should be at least 24 in 3d');
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   3D prism Mesh:')); 
 
 			disp(sprintf('\n      Elements and vertices of the original 2d mesh:'));
-			fielddisplay(obj,'numberofelements2d','number of elements');
-			fielddisplay(obj,'numberofvertices2d','number of vertices');
-			fielddisplay(obj,'elements2d','vertex indices of the mesh elements');
-			fielddisplay(obj,'x2d','vertices x coordinate [m]');
-			fielddisplay(obj,'y2d','vertices y coordinate [m]');
+			fielddisplay(self,'numberofelements2d','number of elements');
+			fielddisplay(self,'numberofvertices2d','number of vertices');
+			fielddisplay(self,'elements2d','vertex indices of the mesh elements');
+			fielddisplay(self,'x2d','vertices x coordinate [m]');
+			fielddisplay(self,'y2d','vertices y coordinate [m]');
 
 			disp(sprintf('\n      Elements and vertices of the extruded 3d mesh:'));
-			fielddisplay(obj,'numberofelements','number of elements');
-			fielddisplay(obj,'numberofvertices','number of vertices');
-			fielddisplay(obj,'elements','vertex indices of the mesh elements');
-			fielddisplay(obj,'x','vertices x coordinate [m]');
-			fielddisplay(obj,'y','vertices y coordinate [m]');
-			fielddisplay(obj,'z','vertices z coordinate [m]');
+			fielddisplay(self,'numberofelements','number of elements');
+			fielddisplay(self,'numberofvertices','number of vertices');
+			fielddisplay(self,'elements','vertex indices of the mesh elements');
+			fielddisplay(self,'x','vertices x coordinate [m]');
+			fielddisplay(self,'y','vertices y coordinate [m]');
+			fielddisplay(self,'z','vertices z coordinate [m]');
 
 			disp(sprintf('\n      Properties:'));
-			fielddisplay(obj,'numberoflayers','number of extrusion layers');
-			fielddisplay(obj,'vertexonbase','lower vertices flags list');
-			fielddisplay(obj,'vertexonsurface','upper vertices flags list');
-			fielddisplay(obj,'uppervertex','upper vertex list (NaN for vertex on the upper surface)');
-			fielddisplay(obj,'upperelements','upper element list (NaN for element on the upper layer)');
-			fielddisplay(obj,'lowervertex','lower vertex list (NaN for vertex on the lower surface)');
-			fielddisplay(obj,'lowerelements','lower element list (NaN for element on the lower layer');
-			fielddisplay(obj,'vertexonboundary','vertices on the boundary of the domain flag list');
-
-			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
-			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
-			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+			fielddisplay(self,'numberoflayers','number of extrusion layers');
+			fielddisplay(self,'vertexonbase','lower vertices flags list');
+			fielddisplay(self,'vertexonsurface','upper vertices flags list');
+			fielddisplay(self,'uppervertex','upper vertex list (NaN for vertex on the upper surface)');
+			fielddisplay(self,'upperelements','upper element list (NaN for element on the upper layer)');
+			fielddisplay(self,'lowervertex','lower vertex list (NaN for vertex on the lower surface)');
+			fielddisplay(self,'lowerelements','lower element list (NaN for element on the lower layer');
+			fielddisplay(self,'vertexonboundary','vertices on the boundary of the domain flag list');
+
+			fielddisplay(self,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(self,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(self,'average_vertex_connectivity','average number of vertices connected to one vertex');
 
 			disp(sprintf('\n      Extracted model:'));
-			fielddisplay(obj,'extractedvertices','vertices extracted from the model');
-			fielddisplay(obj,'extractedelements','elements extracted from the model');
+			fielddisplay(self,'extractedvertices','vertices extracted from the model');
+			fielddisplay(self,'extractedelements','elements extracted from the model');
 
 			disp(sprintf('\n      Projection:'));
-			fielddisplay(obj,'lat','vertices latitude [degrees]');
-			fielddisplay(obj,'long','vertices longitude [degrees]');
-			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
-		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(obj)]),'format','Integer');
-			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(obj),'format','Integer');
-			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(obj)),'format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','z','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberoflayers','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices2d','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements2d','format','Integer');
-		end % }}}
-		function type = domaintype(obj) % {{{
+			fielddisplay(self,'lat','vertices latitude [degrees]');
+			fielddisplay(self,'long','vertices longitude [degrees]');
+			fielddisplay(self,'epsg','EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)');
+		end % }}}
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(self)]),'format','Integer');
+			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(self),'format','Integer');
+			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(self)),'format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','z','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberoflayers','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices2d','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements2d','format','Integer');
+		end % }}}
+		function type = domaintype(self) % {{{
 			type = '3D';
 		end % }}}
-		function d = dimension(obj) % {{{
+		function d = dimension(self) % {{{
 			d = 3;
 		end % }}}
-		function s = elementtype(obj) % {{{
+		function s = elementtype(self) % {{{
 			s = 'Penta';
 		end % }}}
Index: /issm/trunk/src/m/classes/mesh3dprisms.py
===================================================================
--- /issm/trunk/src/m/classes/mesh3dprisms.py	(revision 19104)
+++ /issm/trunk/src/m/classes/mesh3dprisms.py	(revision 19105)
@@ -25,7 +25,7 @@
 		self.lat                         = float('NaN');
 		self.long                        = float('NaN');
-		self.hemisphere                  = float('NaN');
+		self.epsg                        = 0;
 
-		self.vertexonbase                 = float('NaN');
+		self.vertexonbase                = float('NaN');
 		self.vertexonsurface             = float('NaN');
 		self.lowerelements               = float('NaN');
@@ -90,5 +90,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,"lat","vertices latitude [degrees]"))
 		string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]"))
-		string="%s\n%s"%(string,fielddisplay(self,"hemisphere","Indicate hemisphere 'n' or 's'"))
+		string="%s\n%s"%(string,fielddisplay(self,"epsg","EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)"))
 		return string
 		#}}}
@@ -116,5 +116,4 @@
 		md = checkfield(md,'fieldname','mesh.numberofelements','>',0)
 		md = checkfield(md,'fieldname','mesh.numberofvertices','>',0)
-		#no checks for numberofedges lat long and hemisphere
 		md = checkfield(md,'fieldname','mesh.vertexonbase','size',[md.mesh.numberofvertices],'values',[0,1])
 		md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices],'values',[0,1])
Index: /issm/trunk/src/m/classes/mesh3dsurface.m
===================================================================
--- /issm/trunk/src/m/classes/mesh3dsurface.m	(revision 19105)
+++ /issm/trunk/src/m/classes/mesh3dsurface.m	(revision 19105)
@@ -0,0 +1,211 @@
+%MESH3DSURFACE class definition
+%
+%   Usage:
+%      mesh3dsurface=mesh3dsurface();
+
+classdef mesh3dsurface
+	properties (SetAccess=public) 
+		x                           = NaN;
+		y                           = NaN;
+		z                           = NaN;
+		elements                    = NaN;
+		numberofelements            = 0;
+		numberofvertices            = 0;
+		numberofedges               = 0;
+
+		lat                         = NaN;
+		long                        = NaN;
+		r                           = NaN;
+
+		vertexonboundary            = NaN;
+		edges                       = NaN;
+		segments                    = NaN;
+		segmentmarkers              = NaN;
+		vertexconnectivity          = NaN;
+		elementconnectivity         = NaN;
+		average_vertex_connectivity = 0;
+
+		extractedvertices           = NaN;
+		extractedelements           = NaN;
+	end
+	methods (Static)
+		function self = loadobj(self) % {{{
+			% This function is directly called by matlab when a model selfect is
+			% loaded. Update old properties here
+
+			%2014 Oct. 1st
+			if isstruct(self),
+				oldself=self;
+				%Assign property values from struct
+				self=structtoobj(mesh3dsurface(),oldself);
+				if isfield(oldself,'hemisphere'),
+					disp('md.mesh.hemisphere has been automatically converted to EPSG code');
+					if strcmpi(oldself.hemisphere,'n'),
+						self.epsg=3413;
+					else
+						self.epsg=3031;
+					end
+				end
+			end
+
+		end% }}}
+	end
+	methods
+		function self = mesh3dsurface(varargin) % {{{
+			switch nargin
+				case 0
+					self=setdefaultparameters(self);
+				case 1
+					self=mesh3dsurface();
+					object=varargin{1};
+					fields=fieldnames(object);
+					for i=1:length(fields)
+						field=fields{i};
+						if ismember(field,properties('mesh3dsurface')),
+							self.(field)=object.(field);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%the connectivity is the averaged number of nodes linked to a
+			%given node through an edge. This connectivity is used to initially
+			%allocate memory to the stiffness matrix. A value of 16 seems to
+			%give a good memory/time ration. This value can be checked in
+			%trunk/test/Miscellaneous/runme.m
+			obj.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			md = checkfield(md,'fieldname','mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.y','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.z','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.lat','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.long','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.r','NaN',1,'size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'fieldname','mesh.elements','NaN',1,'>',0,'values',1:md.mesh.numberofvertices);
+			md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements 3]);
+			if any(~ismember(1:md.mesh.numberofvertices,sort(unique(md.mesh.elements(:)))));
+				md = checkmessage(md,'orphan nodes have been found. Check the mesh outline');
+			end
+			md = checkfield(md,'fieldname','mesh.numberofelements','>',0);
+			md = checkfield(md,'fieldname','mesh.numberofvertices','>',0);
+			md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',9,'message','''mesh.average_vertex_connectivity'' should be at least 9 in 2d');
+
+			switch(solution),
+				case ThermalSolutionEnum(),
+					md = checkmessage(md,'thermal not supported for 2d mesh');
+			end
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   2D tria Mesh (horizontal):')); 
+
+			disp(sprintf('\n      Elements and vertices:'));
+			fielddisplay(obj,'numberofelements','number of elements');
+			fielddisplay(obj,'numberofvertices','number of vertices');
+			fielddisplay(obj,'elements','vertex indices of the mesh elements');
+			fielddisplay(obj,'x','vertices x coordinate [m]');
+			fielddisplay(obj,'y','vertices y coordinate [m]');
+			fielddisplay(obj,'z','vertices z coordinate [m]');
+			fielddisplay(obj,'lat','vertices latitude [degrees]');
+			fielddisplay(obj,'long','vertices longitude [degrees]');
+			fielddisplay(obj,'r','vertices radius [m]');
+			
+			fielddisplay(obj,'edges','edges of the 2d mesh (vertex1 vertex2 element1 element2)');
+			fielddisplay(obj,'numberofedges','number of edges of the 2d mesh');
+
+			disp(sprintf('\n      Properties:'));
+			fielddisplay(obj,'vertexonboundary','vertices on the boundary of the domain flag list');
+			fielddisplay(obj,'segments','edges on domain boundary (vertex1 vertex2 element)');
+			fielddisplay(obj,'segmentmarkers','number associated to each segment');
+			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+
+			disp(sprintf('\n      Extracted model:'));
+			fielddisplay(obj,'extractedvertices','vertices extracted from the model');
+			fielddisplay(obj,'extractedelements','elements extracted from the model'); 
+		end % }}}
+		function createxml(obj,fid) % {{{
+			fprintf(fid, '<!-- #D surface Mesh -->\n');
+
+			%elements and vertices
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Elements and vertices">','<section name="mesh" />');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="numberofelements" type="',class(obj.numberofelements),'" default="',convert2str(obj.numberofelements),'">','     <section name="mesh" />','     <help> number of elements </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="numberofvertices" type="',class(obj.numberofvertices),'" default="',convert2str(obj.numberofvertices),'">','     <section name="mesh" />','     <help> number of vertices </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="elements" type="',class(obj.elements),'" default="',convert2str(obj.elements),'">','     <section name="mesh" />','     <help> vertex indices of the mesh elements </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(obj.x),'" default="',convert2str(obj.x),'">','     <section name="mesh" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="edges" type="',class(obj.edges),'" default="',convert2str(obj.edges),'">','     <section name="mesh" />','     <help> edges of the 2d mesh (vertex1 vertex2 element1 element2) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofedges" type="',class(obj.numberofedges),'" default="',convert2str(obj.numberofedges),'">','     <section name="mesh" />','     <help> number of edges of the 2d mesh </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			% properties
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Properties">','<section name="mesh" />');             
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(obj.vertexonboundary),'" default="',convert2str(obj.vertexonboundary),'">','     <section name="mesh" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segments" type="',class(obj.segments),'" default="',convert2str(obj.segments),'">','     <section name="mesh" />','     <help> edges on domain boundary (vertex1 vertex2 element) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="segmentmarkers" type="',class(obj.segmentmarkers),'" default="',convert2str(obj.segmentmarkers),'">','     <section name="mesh" />','     <help> number associated to each segment </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(obj.vertexconnectivity),'" default="',convert2str(obj.vertexconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(obj.elementconnectivity),'" default="',convert2str(obj.elementconnectivity),'">','     <section name="mesh" />','     <help> list of vertices connected to element_i </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(obj.average_vertex_connectivity),'" default="',convert2str(obj.average_vertex_connectivity),'">','     <section name="mesh" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			%extracted model
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Extracted Model">','<section name="mesh" />'); 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedvertices" type="',class(obj.extractedvertices),'" default="',convert2str(obj.extractedvertices),'">','     <section name="mesh" />','     <help> vertices extracted from the model </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedelements" type="',class(obj.extractedelements),'" default="',convert2str(obj.extractedelements),'">','     <section name="mesh" />','     <help> elements extracted from the model </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			%projection
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Projection">','<section name="mesh" />'); 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(obj.lat),'" default="',convert2str(obj.lat),'">','     <section name="mesh" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(obj.long),'" default="',convert2str(obj.long),'">','     <section name="mesh" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
+			% choice (epsg) 'n' or 's'
+			fprintf(fid,'%s\n%s\n%s\n','  <parameter key ="epsg" type="alternative" optional="false">','     <section name="mesh" />','     <help> Indicate epsg ''n'' or ''s'' </help>');
+			fprintf(fid,'%s\n','       <option value="n" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="s" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(obj)]),'format','Integer');
+			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(obj),'format','Integer');
+			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(obj)),'format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','z','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','lat','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','long','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','r','format','DoubleMat','mattype',1);
+			WriteData(fid,'enum',MeshZEnum(),'data',zeros(obj.numberofvertices,1),'format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonboundary','format','DoubleMat','mattype',1);
+		end % }}}
+		function t = domaintype(obj) % {{{
+			t = '3Dsurface';
+		end % }}}
+		function d = dimension(obj) % {{{
+			d = 2;
+		end % }}}
+		function s = elementtype(obj) % {{{
+			s = 'Tria';
+		end % }}}
+		function [x y z elements is2d isplanet] = processmesh(self,options) % {{{
+
+			isplanet = 1;
+			is2d     = 0;
+
+			elements = self.elements;
+			x        = self.x;
+			y        = self.y;
+			z        = self.z;
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/mesh3dtetras.m
===================================================================
--- /issm/trunk/src/m/classes/mesh3dtetras.m	(revision 19104)
+++ /issm/trunk/src/m/classes/mesh3dtetras.m	(revision 19105)
@@ -8,89 +8,111 @@
 		x                           = NaN;
 		y                           = NaN;
-		z                           = NaN
-		elements                    = NaN
+		z                           = NaN;
+		elements                    = NaN;
 		numberoflayers              = 0;
 		numberofelements            = 0;
 		numberofvertices            = 0;
 
-		lat                         = NaN
-		long                        = NaN
-		hemisphere                  = NaN
-
-		vertexonbase                 = NaN
-		vertexonsurface             = NaN
-		lowerelements               = NaN
-		lowervertex                 = NaN
-		upperelements               = NaN
-		uppervertex                 = NaN
-		vertexonboundary            = NaN
-
-		vertexconnectivity          = NaN
-		elementconnectivity         = NaN
+		lat                         = NaN;
+		long                        = NaN;
+		epsg                        = 0;
+
+		vertexonbase                = NaN;
+		vertexonsurface             = NaN;
+		lowerelements               = NaN;
+		lowervertex                 = NaN;
+		upperelements               = NaN;
+		uppervertex                 = NaN;
+		vertexonboundary            = NaN;
+
+		vertexconnectivity          = NaN;
+		elementconnectivity         = NaN;
 		average_vertex_connectivity = 0;
 
-		x2d                         = NaN
-		y2d                         = NaN
-		elements2d                  = NaN
+		x2d                         = NaN;
+		y2d                         = NaN;
+		elements2d                  = NaN;
 		numberofvertices2d          = 0;
 		numberofelements2d          = 0;
 
-		extractedvertices           = NaN
-		extractedelements           = NaN
+		extractedvertices           = NaN;
+		extractedelements           = NaN;
+	end
+	methods (Static)
+		function self = loadobj(self) % {{{
+			% This function is directly called by matlab when a model selfect is
+			% loaded. Update old properties here
+
+			%2014 Oct. 1st
+			if isstruct(self),
+				oldself=self;
+				%Assign property values from struct
+				self=structtoobj(mesh3dtetras(),oldself);
+				if isfield(oldself,'hemisphere'),
+					disp('md.mesh.hemisphere has been automatically converted to EPSG code');
+					if strcmpi(oldself.hemisphere,'n'),
+						self.epsg=3413;
+					else
+						self.epsg=3031;
+					end
+				end
+			end
+
+		end% }}}
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '<!-- 3D Tetra Mesh -->\n');
-            
-            % Elements and verticies of the original 2d mesh
-            fprintf(fid,'%s\n%s\n%s\n','       <frame key="1" label="Elements and vertices of the orginal 2d mesh">','       <section name="mesh3dprisms" />');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements2d" type="',class(obj.numberofelements2d),'" default="',convert2str(obj.numberofelements2d),'">','              <help> number of elements </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices2d" type="',class(obj.numberofvertices2d),'" default="',convert2str(obj.numberofvertices2d),'">','              <help> number of vertices </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements2d" type="',class(obj.elements2d),'" default="',convert2str(obj.elements2d),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x2d" type="',class(obj.x2d),'" default="',convert2str(obj.x2d),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y2d" type="',class(obj.y2d),'" default="',convert2str(obj.y2d),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','       </frame>');
-            
-            % Elements and vertices of the extruded 3d mesh
-            fprintf(fid,'%s\n%s\n%s\n','       <frame key="2" label="Elements and vertices of the orginal 3d mesh">','       <section name="mesh3dprisms" />');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements" type="',class(obj.numberofelements),'" default="',convert2str(obj.numberofelements),'">','              <help> number of elements </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices" type="',class(obj.numberofvertices),'" default="',convert2str(obj.numberofvertices),'">','              <help> number of vertices </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements" type="',class(obj.elements),'" default="',convert2str(obj.elements),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(obj.x),'" default="',convert2str(obj.x),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="z" type="',class(obj.y),'" default="',convert2str(obj.y),'">','     <section name="mesh3dprisms" />','     <help> vertices z coordinate [m] </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','       </frame>');
-     
-            % properties
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Properties">','<section name="mesh3dprisms" />');             
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberoflayers" type="',class(obj.numberoflayers),'" default="',convert2str(obj.numberoflayers),'">','     <section name="mesh3dprisms" />','     <help> number of extrusion layers </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonbase" type="',class(obj.vertexonbase),'" default="',convert2str(obj.vertexonbase),'">','     <section name="mesh3dprisms" />','     <help> lower vertices flags list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontbase" type="',class(obj.elementontbase),'" default="',convert2str(obj.elementontbase),'">','     <section name="mesh3dprisms" />','     <help> lower elements flags list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonsurface" type="',class(obj.vertexonsurface),'" default="',convert2str(obj.vertexonsurface),'">','     <section name="mesh3dprisms" />','     <help> upper vertices flags list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontsurface" type="',class(obj.elementontsurface),'" default="',convert2str(obj.elementontsurface),'">','     <section name="mesh3dprisms" />','     <help> upper elements flags list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="uppervertex" type="',class(obj.uppervertex),'" default="',convert2str(obj.uppervertex),'">','     <section name="mesh3dprisms" />','     <help> upper vertex list (NaN for vertex on the upper surface) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="upperelements" type="',class(obj.upperelements),'" default="',convert2str(obj.upperelements),'">','     <section name="mesh3dprisms" />','     <help> upper element list (NaN for element on the upper layer) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowervertex" type="',class(obj.lowervertex),'" default="',convert2str(obj.lowervertex),'">','     <section name="mesh3dprisms" />','     <help> lower vertex list (NaN for vertex on the lower surface) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowerelements" type="',class(obj.lowerelements),'" default="',convert2str(obj.lowerelements),'">','     <section name="mesh3dprisms" />','     <help> element list (NaN for element on the lower layer) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(obj.vertexonboundary),'" default="',convert2str(obj.vertexonboundary),'">','     <section name="mesh3dprisms" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(obj.vertexconnectivity),'" default="',convert2str(obj.vertexconnectivity),'">','     <section name="mesh3dprisms" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(obj.elementconnectivity),'" default="',convert2str(obj.elementconnectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(obj.average_vertex_connectivity),'" default="',convert2str(obj.average_vertex_connectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-            
-            % Extracted model
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Extracted Model">','<section name="mesh3dprisms" />'); 
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedvertices" type="',class(obj.extractedvertices),'" default="',convert2str(obj.extractedvertices),'">','     <section name="mesh3dprisms" />','     <help> vertices extracted from the model </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedelements" type="',class(obj.extractedelements),'" default="',convert2str(obj.extractedelements),'">','     <section name="mesh3dprisms" />','     <help> elements extracted from the model </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-            
-            % Projection
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="5" label="Projection">','<section name="mesh3dprisms" />'); 
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(obj.lat),'" default="',convert2str(obj.lat),'">','     <section name="mesh3dprisms" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(obj.long),'" default="',convert2str(obj.long),'">','     <section name="mesh3dprisms" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="hemisphere" type="',class(obj.hemisphere),'" default="',convert2str(obj.hemisphere),'">','     <section name="mesh3dprisms" />','     <help> Indicate hemisphere ''n'' or ''s'' </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-        
-        end % }}}cd
+		function createxml(self,fid) % {{{
+			fprintf(fid, '<!-- 3D Tetra Mesh -->\n');
+
+			% Elements and verticies of the original 2d mesh
+			fprintf(fid,'%s\n%s\n%s\n','       <frame key="1" label="Elements and vertices of the orginal 2d mesh">','       <section name="mesh3dprisms" />');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements2d" type="',class(self.numberofelements2d),'" default="',convert2str(self.numberofelements2d),'">','              <help> number of elements </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices2d" type="',class(self.numberofvertices2d),'" default="',convert2str(self.numberofvertices2d),'">','              <help> number of vertices </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements2d" type="',class(self.elements2d),'" default="',convert2str(self.elements2d),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x2d" type="',class(self.x2d),'" default="',convert2str(self.x2d),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y2d" type="',class(self.y2d),'" default="',convert2str(self.y2d),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','       </frame>');
+
+			% Elements and vertices of the extruded 3d mesh
+			fprintf(fid,'%s\n%s\n%s\n','       <frame key="2" label="Elements and vertices of the orginal 3d mesh">','       <section name="mesh3dprisms" />');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofelements" type="',class(self.numberofelements),'" default="',convert2str(self.numberofelements),'">','              <help> number of elements </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="numberofvertices" type="',class(self.numberofvertices),'" default="',convert2str(self.numberofvertices),'">','              <help> number of vertices </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','          <parameter key ="elements" type="',class(self.elements),'" default="',convert2str(self.elements),'">','              <help> vertex indices of the mesh elements </help>','          </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="x" type="',class(self.x),'" default="',convert2str(self.x),'">','     <section name="mesh3dprisms" />','     <help> vertices x coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="y" type="',class(self.y),'" default="',convert2str(self.y),'">','     <section name="mesh3dprisms" />','     <help> vertices y coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="z" type="',class(self.y),'" default="',convert2str(self.y),'">','     <section name="mesh3dprisms" />','     <help> vertices z coordinate [m] </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','       </frame>');
+
+			% properties
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Properties">','<section name="mesh3dprisms" />');             
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberoflayers" type="',class(self.numberoflayers),'" default="',convert2str(self.numberoflayers),'">','     <section name="mesh3dprisms" />','     <help> number of extrusion layers </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonbase" type="',class(self.vertexonbase),'" default="',convert2str(self.vertexonbase),'">','     <section name="mesh3dprisms" />','     <help> lower vertices flags list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontbase" type="',class(self.elementontbase),'" default="',convert2str(self.elementontbase),'">','     <section name="mesh3dprisms" />','     <help> lower elements flags list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonsurface" type="',class(self.vertexonsurface),'" default="',convert2str(self.vertexonsurface),'">','     <section name="mesh3dprisms" />','     <help> upper vertices flags list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementontsurface" type="',class(self.elementontsurface),'" default="',convert2str(self.elementontsurface),'">','     <section name="mesh3dprisms" />','     <help> upper elements flags list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="uppervertex" type="',class(self.uppervertex),'" default="',convert2str(self.uppervertex),'">','     <section name="mesh3dprisms" />','     <help> upper vertex list (NaN for vertex on the upper surface) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="upperelements" type="',class(self.upperelements),'" default="',convert2str(self.upperelements),'">','     <section name="mesh3dprisms" />','     <help> upper element list (NaN for element on the upper layer) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowervertex" type="',class(self.lowervertex),'" default="',convert2str(self.lowervertex),'">','     <section name="mesh3dprisms" />','     <help> lower vertex list (NaN for vertex on the lower surface) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lowerelements" type="',class(self.lowerelements),'" default="',convert2str(self.lowerelements),'">','     <section name="mesh3dprisms" />','     <help> element list (NaN for element on the lower layer) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexonboundary" type="',class(self.vertexonboundary),'" default="',convert2str(self.vertexonboundary),'">','     <section name="mesh3dprisms" />','     <help> vertices on the boundary of the domain flag list </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertexconnectivity" type="',class(self.vertexconnectivity),'" default="',convert2str(self.vertexconnectivity),'">','     <section name="mesh3dprisms" />','     <help> list of vertices connected to vertex_i </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="elementconnectivity" type="',class(self.elementconnectivity),'" default="',convert2str(self.elementconnectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="average_vertex_connectivity" type="',class(self.average_vertex_connectivity),'" default="',convert2str(self.average_vertex_connectivity),'">','     <section name="mesh3dprisms" />','     <help> average number of vertices connected to one vertex </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			% Extracted model
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Extracted Model">','<section name="mesh3dprisms" />'); 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedvertices" type="',class(self.extractedvertices),'" default="',convert2str(self.extractedvertices),'">','     <section name="mesh3dprisms" />','     <help> vertices extracted from the model </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="extractedelements" type="',class(self.extractedelements),'" default="',convert2str(self.extractedelements),'">','     <section name="mesh3dprisms" />','     <help> elements extracted from the model </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			% Projection
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="5" label="Projection">','<section name="mesh3dprisms" />'); 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="lat" type="',class(self.lat),'" default="',convert2str(self.lat),'">','     <section name="mesh3dprisms" />','     <help> vertices latitude [degrees] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="long" type="',class(self.long),'" default="',convert2str(self.long),'">','     <section name="mesh3dprisms" />','     <help> verticies longitude [degrees] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n','  <parameter key ="epsg" type="',class(self.epsg),'" default="',convert2str(self.epsg),'">','     <section name="mesh3dprisms" />','     <help> Indicate epsg ''n'' or ''s'' </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+		end % }}}cd
 		function self = mesh3dtetras(varargin) % {{{
 			switch nargin
@@ -111,5 +133,5 @@
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%the connectivity is the averaged number of nodes linked to a
@@ -118,7 +140,7 @@
 			%give a good memory/time ration. This value can be checked in
 			%trunk/test/Miscellaneous/runme.m
-			obj.average_vertex_connectivity=25;
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			self.average_vertex_connectivity=25;
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			md = checkfield(md,'fieldname','mesh.x','NaN',1,'size',[md.mesh.numberofvertices 1]);
@@ -133,5 +155,4 @@
 			md = checkfield(md,'fieldname','mesh.numberofelements','>',0);
 			md = checkfield(md,'fieldname','mesh.numberofvertices','>',0);
-			%no checks for numberofedges lat long and hemisphere
 			md = checkfield(md,'fieldname','mesh.vertexonbase','size',[md.mesh.numberofvertices 1],'values',[0 1]);
 			md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices 1],'values',[0 1]);
@@ -140,72 +161,72 @@
 			md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',24,'message','''mesh.average_vertex_connectivity'' should be at least 24 in 3d');
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   3D tetra Mesh:')); 
 
 			disp(sprintf('\n      Elements and vertices of the original 2d mesh:'));
-			fielddisplay(obj,'numberofelements2d','number of elements');
-			fielddisplay(obj,'numberofvertices2d','number of vertices');
-			fielddisplay(obj,'elements2d','vertex indices of the mesh elements');
-			fielddisplay(obj,'x2d','vertices x coordinate [m]');
-			fielddisplay(obj,'y2d','vertices y coordinate [m]');
+			fielddisplay(self,'numberofelements2d','number of elements');
+			fielddisplay(self,'numberofvertices2d','number of vertices');
+			fielddisplay(self,'elements2d','vertex indices of the mesh elements');
+			fielddisplay(self,'x2d','vertices x coordinate [m]');
+			fielddisplay(self,'y2d','vertices y coordinate [m]');
 
 			disp(sprintf('\n      Elements and vertices of the extruded 3d mesh:'));
-			fielddisplay(obj,'numberofelements','number of elements');
-			fielddisplay(obj,'numberofvertices','number of vertices');
-			fielddisplay(obj,'elements','vertex indices of the mesh elements');
-			fielddisplay(obj,'x','vertices x coordinate [m]');
-			fielddisplay(obj,'y','vertices y coordinate [m]');
-			fielddisplay(obj,'z','vertices z coordinate [m]');
+			fielddisplay(self,'numberofelements','number of elements');
+			fielddisplay(self,'numberofvertices','number of vertices');
+			fielddisplay(self,'elements','vertex indices of the mesh elements');
+			fielddisplay(self,'x','vertices x coordinate [m]');
+			fielddisplay(self,'y','vertices y coordinate [m]');
+			fielddisplay(self,'z','vertices z coordinate [m]');
 
 			disp(sprintf('\n      Properties:'));
-			fielddisplay(obj,'numberoflayers','number of extrusion layers');
-			fielddisplay(obj,'vertexonbase','lower vertices flags list');
-			fielddisplay(obj,'vertexonsurface','upper vertices flags list');
-			fielddisplay(obj,'uppervertex','upper vertex list (NaN for vertex on the upper surface)');
-			fielddisplay(obj,'upperelements','upper element list (NaN for element on the upper layer)');
-			fielddisplay(obj,'lowervertex','lower vertex list (NaN for vertex on the lower surface)');
-			fielddisplay(obj,'lowerelements','lower element list (NaN for element on the lower layer');
-			fielddisplay(obj,'vertexonboundary','vertices on the boundary of the domain flag list');
-
-			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
-			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
-			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+			fielddisplay(self,'numberoflayers','number of extrusion layers');
+			fielddisplay(self,'vertexonbase','lower vertices flags list');
+			fielddisplay(self,'vertexonsurface','upper vertices flags list');
+			fielddisplay(self,'uppervertex','upper vertex list (NaN for vertex on the upper surface)');
+			fielddisplay(self,'upperelements','upper element list (NaN for element on the upper layer)');
+			fielddisplay(self,'lowervertex','lower vertex list (NaN for vertex on the lower surface)');
+			fielddisplay(self,'lowerelements','lower element list (NaN for element on the lower layer');
+			fielddisplay(self,'vertexonboundary','vertices on the boundary of the domain flag list');
+
+			fielddisplay(self,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(self,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(self,'average_vertex_connectivity','average number of vertices connected to one vertex');
 
 			disp(sprintf('\n      Extracted model:'));
-			fielddisplay(obj,'extractedvertices','vertices extracted from the model');
-			fielddisplay(obj,'extractedelements','elements extracted from the model');
+			fielddisplay(self,'extractedvertices','vertices extracted from the model');
+			fielddisplay(self,'extractedelements','elements extracted from the model');
 
 			disp(sprintf('\n      Projection:'));
-			fielddisplay(obj,'lat','vertices latitude [degrees]');
-			fielddisplay(obj,'long','vertices longitude [degrees]');
-			fielddisplay(obj,'hemisphere','Indicate hemisphere ''n'' or ''s'' ');
-		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(obj)]),'format','Integer');
-			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(obj),'format','Integer');
-			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(obj)),'format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','z','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberoflayers','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofvertices2d','format','Integer');
-			WriteData(fid,'object',obj,'class','mesh','fieldname','numberofelements2d','format','Integer');
-		end % }}}
-		function t = domaintype(obj) % {{{
+			fielddisplay(self,'lat','vertices latitude [degrees]');
+			fielddisplay(self,'long','vertices longitude [degrees]');
+			fielddisplay(self,'epsg','EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)');
+		end % }}}
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum(['Domain' domaintype(self)]),'format','Integer');
+			WriteData(fid,'enum',DomainDimensionEnum(),'data',dimension(self),'format','Integer');
+			WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(elementtype(self)),'format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','z','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberoflayers','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1);
+			WriteData(fid,'object',self,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices2d','format','Integer');
+			WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements2d','format','Integer');
+		end % }}}
+		function t = domaintype(self) % {{{
 			t = '3D';
 		end % }}}
-		function d = dimension(obj) % {{{
+		function d = dimension(self) % {{{
 			d = 3;
 		end % }}}
-		function s = elementtype(obj) % {{{
+		function s = elementtype(self) % {{{
 			s = 'Tetra';
 		end % }}}
Index: /issm/trunk/src/m/classes/miscellaneous.m
===================================================================
--- /issm/trunk/src/m/classes/miscellaneous.m	(revision 19104)
+++ /issm/trunk/src/m/classes/miscellaneous.m	(revision 19105)
@@ -11,41 +11,41 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
+        function createxml(self,fid) % {{{
             fprintf(fid, '<!-- miscellaneous -->\n');            
                     
             % miscellaneous solution parameters
             fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="miscellaneous parameters">','<section name="miscellaneous" />');                    
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="notes" type="',class(obj.notes),'" default="',convert2str(obj.notes),'">','     <section name="miscellaneous" />','     <help> notes in a cell of strings </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="name" type="',class(obj.name),'" default="',convert2str(obj.name),'">','     <section name="miscellaneous" />','     <help> model name </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="dummy" type="',class(obj.dummy),'" default="',convert2str(obj.dummy),'">','     <section name="miscellaneous" />','     <help> empty field to store some data </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="notes" type="',class(self.notes),'" default="',convert2str(self.notes),'">','     <section name="miscellaneous" />','     <help> notes in a cell of strings </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="name" type="',class(self.name),'" default="',convert2str(self.name),'">','     <section name="miscellaneous" />','     <help> model name </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="dummy" type="',class(self.dummy),'" default="',convert2str(self.dummy),'">','     <section name="miscellaneous" />','     <help> empty field to store some data </help>','  </parameter>');
             fprintf(fid,'%s\n%s\n','</frame>');    
         
         end % }}}        
-		function obj = miscellaneous(varargin) % {{{
+		function self = miscellaneous(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			md = checkfield(md,'fieldname','miscellaneous.name','empty',1);
 
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   miscellaneous parameters:'));
 
-			fielddisplay(obj,'notes','notes in a cell of strings');
-			fielddisplay(obj,'name','model name');
-			fielddisplay(obj,'dummy','empty field to store some data');
+			fielddisplay(self,'notes','notes in a cell of strings');
+			fielddisplay(self,'name','model name');
+			fielddisplay(self,'dummy','empty field to store some data');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','name','format','String');
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','name','format','String');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/misfit.m
===================================================================
--- /issm/trunk/src/m/classes/misfit.m	(revision 19104)
+++ /issm/trunk/src/m/classes/misfit.m	(revision 19105)
@@ -4,8 +4,9 @@
 %      misfit=misfit();
 %      misfit=misfit('name','SurfaceAltimetry',...
-%                    'model_enum',SurfaceEnum,...
+%                    'definitionenum',Outputdefinition1Enum, 'model_enum',SurfaceEnum,...
 %                    'observation_enum',SurfaceObservationsEnum,...
 %                    'observation',md.geometry.surface,...
 %                    'timeinterpolation','nearestneighbor',...
+%                    'local',1,...
 %                    'weights',ones(md.mesh.numberofvertices,1),...
 %                    'weights_enum',WeightsSurfaceObservationsEnum);
@@ -17,8 +18,10 @@
 		%misfit
 		name              = '';
+		definitionenum   = NaN; %enum that identifies this output definition uniquely, from Outputdefinition[1-10]Enum
 		model_enum        = NaN; %enum for field that is modeled
 		observation       = NaN; %observed field that we compare the model against
 		observation_enum  = NaN; %enum for observed field.
 		timeinterpolation = '';
+		local             = 1;
 		weights           = NaN; %weight coefficients for every vertex
 		weights_enum      = NaN; %enum to identify this particular set of weights
@@ -27,7 +30,7 @@
 	
 	methods
-		function obj = misfit(varargin) % {{{
+		function self = misfit(varargin) % {{{
 			if nargin==0,
-				obj=setdefaultparameters(obj);
+				self=setdefaultparameters(self);
 			else
 				%use provided options to change fields
@@ -35,53 +38,61 @@
 
 				%get name
-				obj.name=getfieldvalue(options,'name','');
-				obj.model_enum=getfieldvalue(options,'model_enum');
-				obj.observation=getfieldvalue(options,'observation',NaN);
-				obj.observation_enum=getfieldvalue(options,'observation_enum');
-				obj.timeinterpolation=getfieldvalue(options,'timeinterpolation','nearestneighbor');
-				obj.weights=getfieldvalue(options,'weights',NaN);
-				obj.weights_enum=getfieldvalue(options,'weights_enum',NaN);
+				self.name=getfieldvalue(options,'name','');
+				self.definitionenum=getfieldvalue(options,'definitionenum');
+				self.model_enum=getfieldvalue(options,'model_enum');
+				self.observation=getfieldvalue(options,'observation',NaN);
+				self.observation_enum=getfieldvalue(options,'observation_enum');
+				self.local=getfieldvalue(options,'local',1);
+				self.timeinterpolation=getfieldvalue(options,'timeinterpolation','nearestneighbor');
+				self.weights=getfieldvalue(options,'weights',NaN);
+				self.weights_enum=getfieldvalue(options,'weights_enum',NaN);
 
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
-			obj.timeinterpolation='nearestneighbor';
+		function self = setdefaultparameters(self) % {{{
+			self.local=1;
+			self.timeinterpolation='nearestneighbor';
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
-			if ~ischar(obj.name),
+			if ~ischar(self.name),
 				error('misfit error message: ''name'' field should be a string!');
 			end
+			md = checkfield(md,'fieldname','self.definitionenum','field',self.definitionenum,'values',[Outputdefinition1Enum:Outputdefinition100Enum]);
 
-			if ~ischar(obj.timeinterpolation),
+			if ~ischar(self.timeinterpolation),
 				error('misfit error message: ''timeinterpolation'' field should be a string!');
 			end
-			md = checkfield(md,'fieldname','obj.observation','field',obj.observation,'forcing',1,'NaN',1);
-			md = checkfield(md,'fieldname','obj.timeinterpolation','field',obj.timeinterpolation,'values',{'nearestneighbor'});
-			md = checkfield(md,'fieldname','obj.weights','field',obj.weights,'forcing',1,'NaN',1);
+			md = checkfield(md,'fieldname','self.observation','field',self.observation,'timeseries',1,'NaN',1);
+			md = checkfield(md,'fieldname','self.timeinterpolation','field',self.timeinterpolation,'values',{'nearestneighbor'});
+			md = checkfield(md,'fieldname','self.weights','field',self.weights,'timeseries',1,'NaN',1);
 
 		end % }}}
-		function md = disp(obj) % {{{
+		function md = disp(self) % {{{
 		
 			disp(sprintf('   Misfit:\n'));
 
-			fielddisplay(obj,'name','identifier for this misfit response');
-			fielddisplay(obj,'model_enum','enum for field that is modeled');
-			fielddisplay(obj,'observation','observed field that we compare the model against');
-			fielddisplay(obj,'observation_enum','observation enum');
-			fielddisplay(obj,'timeinterpolation','interpolation routine used to interpolate misfit between two time steps (default is ''nearestneighbor''');
-			fielddisplay(obj,'weights','weights (at vertices) to apply to the misfit');
-			fielddisplay(obj,'weights_enum','enum for weights for identification purposes');
+			fielddisplay(self,'name','identifier for this misfit response');
+			fielddisplay(self,'definitionenum','enum that identifies this output definition uniquely, from Outputdefinition[1-10]Enum');
+			fielddisplay(self,'model_enum','enum for field that is modeled');
+			fielddisplay(self,'observation','observed field that we compare the model against');
+			fielddisplay(self,'observation_enum','observation enum');
+			fielddisplay(self,'local','is the response local to the elements, or global? (default is 1)''');
+			fielddisplay(self,'timeinterpolation','interpolation routine used to interpolate misfit between two time steps (default is ''nearestneighbor''');
+			fielddisplay(self,'weights','weights (at vertices) to apply to the misfit');
+			fielddisplay(self,'weights_enum','enum for weights for identification purposes');
 
 		end % }}}
-		function md = marshall(obj,md,fid) % {{{
+		function md = marshall(self,md,fid) % {{{
 
-		WriteData(fid,'object',obj,'fieldname','name','format','String');
-		WriteData(fid,'object',obj,'fieldname','model_enum','format','Integer');
-		WriteData(fid,'object',obj,'fieldname','observation','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-		WriteData(fid,'object',obj,'fieldname','observation_enum','format','Integer');
-		WriteData(fid,'object',obj,'fieldname','timeinterpolation','format','String');
-		WriteData(fid,'object',obj,'fieldname','weights','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-		WriteData(fid,'object',obj,'fieldname','weights_enum','format','Integer');
+		WriteData(fid,'object',self,'fieldname','name','format','String');
+		WriteData(fid,'object',self,'fieldname','definitionenum','format','Integer');
+		WriteData(fid,'object',self,'fieldname','model_enum','format','Integer');
+		WriteData(fid,'object',self,'fieldname','observation','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+		WriteData(fid,'object',self,'fieldname','observation_enum','format','Integer');
+		WriteData(fid,'object',self,'fieldname','local','format','Integer');
+		WriteData(fid,'object',self,'fieldname','timeinterpolation','format','String');
+		WriteData(fid,'object',self,'fieldname','weights','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+		WriteData(fid,'object',self,'fieldname','weights_enum','format','Integer');
 
 		end % }}}
Index: /issm/trunk/src/m/classes/model.m
===================================================================
--- /issm/trunk/src/m/classes/model.m	(revision 19104)
+++ /issm/trunk/src/m/classes/model.m	(revision 19105)
@@ -37,4 +37,5 @@
 		steadystate      = 0;
 		transient        = 0;
+		calving          = 0;
 		gia              = 0;
 
@@ -124,4 +125,8 @@
 				end
 			end
+			%2014 November 12
+			if isa(md.calving,'double');
+				md.calving=calving();
+			end
 		end% }}}
 	end
@@ -132,4 +137,7 @@
 				case 0
 					md=setdefaultparameters(md);
+				case 1
+					error('model constructor not supported yet');
+
 				otherwise
 					error('model constructor error message: 0 of 1 argument only in input.');
@@ -162,10 +170,24 @@
 			%Start with changing all the fields from the 3d mesh 
 
+			%dealing with the friciton law
 			%drag is limited to nodes that are on the bedrock.
-			md.friction.coefficient=project2d(md,md.friction.coefficient,1);
-
-			%p and q (same deal, except for element that are on the bedrock: )
-			md.friction.p=project2d(md,md.friction.p,1);
-			md.friction.q=project2d(md,md.friction.q,1);
+			if isa(md.friction,'friction'),
+				md.friction.coefficient=project2d(md,md.friction.coefficient,1);
+				md.friction.p=project2d(md,md.friction.p,1);
+				md.friction.q=project2d(md,md.friction.q,1);
+			elseif isa(md.friction,'frictionhydro'),
+				md.friction.q=project2d(md,md.friction.q,1);
+				md.friction.C=project2d(md,md.friction.C,1);
+				md.friction.As=project2d(md,md.friction.As,1);
+				md.friction.effective_pressure=project2d(md,md.friction.effective_pressure,1);
+			elseif isa(md.friction,'frictionwaterlayer'),
+				md.friction.coefficient=project2d(md,md.friction.coefficient,1);
+				md.friction.p=project2d(md,md.friction.p,1);
+				md.friction.q=project2d(md,md.friction.q,1);
+				md.friction.water_layer=project2d(md,md.friction.water_layer,1);
+			elseif isa(md.friction,'frictionweertman'),
+				md.friction.C=project2d(md,md.friction.C,1);
+				md.friction.m=project2d(md,md.friction.m,1);
+	    end
 
 			%observations
@@ -187,5 +209,8 @@
 			if ~isnan(md.initialization.vel),md.initialization.vel=DepthAverage(md,md.initialization.vel);end;
 			if ~isnan(md.initialization.temperature),md.initialization.temperature=DepthAverage(md,md.initialization.temperature);end;
-
+			if ~isnan(md.initialization.pressure),md.initialization.pressure=project2d(md,md.initialization.pressure,1);end;
+			if ~isnan(md.initialization.sediment_head),md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1);end;
+			if ~isnan(md.initialization.epl_head),md.initialization.epl_head=project2d(md,md.initialization.epl_head,1);end;
+			if ~isnan(md.initialization.epl_thickness),md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1);end;
 			%gia
 			if ~isnan(md.gia.mantle_viscosity), md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1); end
@@ -211,4 +236,15 @@
 			md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
 
+			% Hydrologydc variables
+			if isa(md.hydrology,'hydrologydc');
+				md.hydrology.spcsediment_head=project2d(md,md.hydrology.spcsediment_head,1);
+				md.hydrology.mask_eplactive_node=project2d(md,md.hydrology.mask_eplactive_node,1);
+				md.hydrology.sediment_transmitivity=project2d(md,md.hydrology.sediment_transmitivity,1);
+				md.hydrology.basal_moulin_input=project2d(md,md.hydrology.basal_moulin_input,1);
+				if(md.hydrology.isefficientlayer==1)
+					md.hydrology.spcepl_head=project2d(md,md.hydrology.spcepl_head,1);
+		    end
+	    end
+			
 			%materials
 			md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B);
@@ -221,6 +257,10 @@
 
 			%special for thermal modeling:
-			md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1); 
-			md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_melting_rate,1); 
+			if ~isnan(md.basalforcings.groundedice_melting_rate),
+				md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1); 
+			end
+			if ~isnan(md.basalforcings.floatingice_melting_rate),
+				md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_melting_rate,1); 
+			end
 			md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1); %bedrock only gets geothermal flux
 
@@ -236,8 +276,14 @@
 			md.geometry.thickness=project2d(md,md.geometry.thickness,1);
 			md.geometry.base=project2d(md,md.geometry.base,1);
-			md.geometry.bed=project2d(md,md.geometry.bed,1);
-
-			md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1);
-			md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1);
+			if ~isnan(md.geometry.bed),
+				md.geometry.bed=project2d(md,md.geometry.bed,1);
+			end
+
+			if ~isnan(md.mask.groundedice_levelset),
+				md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1);
+			end
+			if ~isnan(md.mask.ice_levelset),
+				md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1);
+			end
 
 			%lat long
@@ -255,4 +301,7 @@
 			if ~isnan(md.mesh.elementconnectivity), mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1); end
 			md.mesh=mesh;
+			md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices);
+			md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity);
+			md.mesh.segments=contourenvelope(md);
 
 		end % }}}
@@ -613,5 +662,5 @@
 			md.mesh.lat                         = mesh2d.lat;
 			md.mesh.long                        = mesh2d.long;
-			md.mesh.hemisphere                  = mesh2d.hemisphere;
+			md.mesh.epsg                        = mesh2d.epsg;
 
 			md.mesh.vertexonboundary            = mesh2d.vertexonboundary;
@@ -679,83 +728,25 @@
 			%Ok, now deal with the other fields from the 2d mesh:
 
+			%bedinfo and surface info
+			md.mesh.vertexonbase=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',1);
+			md.mesh.vertexonsurface=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',md.mesh.numberoflayers);
+			md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node');
+
 			%lat long
 			md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node');
 			md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node');
 
-			%drag coefficient is limited to nodes that are on the bedrock.
-			md.friction.coefficient=project3d(md,'vector',md.friction.coefficient,'type','node','layer',1);
-
-			%p and q (same deal, except for element that are on the bedrock: )
-			md.friction.p=project3d(md,'vector',md.friction.p,'type','element');
-			md.friction.q=project3d(md,'vector',md.friction.q,'type','element');
-
-			%observations
-			md.inversion.vx_obs=project3d(md,'vector',md.inversion.vx_obs,'type','node');
-			md.inversion.vy_obs=project3d(md,'vector',md.inversion.vy_obs,'type','node');
-			md.inversion.vel_obs=project3d(md,'vector',md.inversion.vel_obs,'type','node');
-			md.inversion.thickness_obs=project3d(md,'vector',md.inversion.thickness_obs,'type','node');
+			md.geometry=extrude(md.geometry,md);
+			md.friction  = extrude(md.friction,md);
+			md.inversion = extrude(md.inversion,md);
 			md.surfaceforcings = extrude(md.surfaceforcings,md);
-			md.balancethickness.thickening_rate=project3d(md,'vector',md.balancethickness.thickening_rate,'type','node');
-
-			%results
-			if ~isnan(md.initialization.vx),md.initialization.vx=project3d(md,'vector',md.initialization.vx,'type','node');end;
-			if ~isnan(md.initialization.vy),md.initialization.vy=project3d(md,'vector',md.initialization.vy,'type','node');end;
-			if ~isnan(md.initialization.vz),md.initialization.vz=project3d(md,'vector',md.initialization.vz,'type','node');end;
-			if ~isnan(md.initialization.vel),md.initialization.vel=project3d(md,'vector',md.initialization.vel,'type','node');end;
-			if ~isnan(md.initialization.temperature),md.initialization.temperature=project3d(md,'vector',md.initialization.temperature,'type','node');end;
-			if ~isnan(md.initialization.waterfraction),md.initialization.waterfraction=project3d(md,'vector',md.initialization.waterfraction,'type','node');end;
-      if ~isnan(md.initialization.watercolumn),md.initialization.watercolumn=project3d(md,'vector',md.initialization.watercolumn,'type','node','layer',1);end;
-      if ~isnan(md.initialization.sediment_head),md.initialization.sediment_head=project3d(md,'vector',md.initialization.sediment_head,'type','node','layer',1);end;
-      if ~isnan(md.initialization.epl_head),md.initialization.epl_head=project3d(md,'vector',md.initialization.epl_head,'type','node','layer',1);end;
-      if ~isnan(md.initialization.epl_thickness),md.initialization.epl_thickness=project3d(md,'vector',md.initialization.epl_thickness,'type','node','layer',1);end;
-
-			%bedinfo and surface info
-			md.mesh.vertexonbase=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',1);
-			md.mesh.vertexonsurface=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',md.mesh.numberoflayers);
-
-			%elementstype
-			if ~isnan(md.flowequation.element_equation)
-				oldelements_type=md.flowequation.element_equation;
-				md.flowequation.element_equation=zeros(number_el3d,1);
-				md.flowequation.element_equation=project3d(md,'vector',oldelements_type,'type','element');
-			end
-
-			%verticestype
-			if ~isnan(md.flowequation.vertex_equation)
-				oldvertices_type=md.flowequation.vertex_equation;
-				md.flowequation.vertex_equation=zeros(number_nodes3d,1);
-				md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node');
-			end
-			md.flowequation.borderSSA=project3d(md,'vector',md.flowequation.borderSSA,'type','node');
-			md.flowequation.borderHO=project3d(md,'vector',md.flowequation.borderHO,'type','node');
-			md.flowequation.borderFS=project3d(md,'vector',md.flowequation.borderFS,'type','node');
-
-			%boundary conditions
-			md.stressbalance.spcvx=project3d(md,'vector',md.stressbalance.spcvx,'type','node');
-			md.stressbalance.spcvy=project3d(md,'vector',md.stressbalance.spcvy,'type','node');
-			md.stressbalance.spcvz=project3d(md,'vector',md.stressbalance.spcvz,'type','node');
-			md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',NaN);
-			if (length(md.initialization.temperature)==md.mesh.numberofvertices),
-				md.thermal.spctemperature=NaN*ones(md.mesh.numberofvertices,1);
-				if isprop(md.mesh,'vertexonsurface'),
-					pos=find(md.mesh.vertexonsurface);
-					md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
-				end
-			end
-			md.masstransport.spcthickness=project3d(md,'vector',md.masstransport.spcthickness,'type','node');
-			md.masstransport.calvingrate=project3d(md,'vector',md.masstransport.calvingrate,'type','node');
-			md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node');
-			md.damage.spcdamage=project3d(md,'vector',md.damage.spcdamage,'type','node');
-			md.stressbalance.referential=project3d(md,'vector',md.stressbalance.referential,'type','node');
-			md.stressbalance.loadingforce=project3d(md,'vector',md.stressbalance.loadingforce,'type','node');
-
-			% Hydrologydc variables
-			if isa(md.hydrology,'hydrologydc');
-				md.hydrology.spcsediment_head=project3d(md,'vector',md.hydrology.spcsediment_head,'type','node','layer',1);
-				md.hydrology.spcepl_head=project3d(md,'vector',md.hydrology.spcepl_head,'type','node','layer',1);
-				md.hydrology.mask_eplactive_node=project3d(md,'vector',md.hydrology.mask_eplactive_node,'type','node','layer',1);
-				md.hydrology.sediment_transmitivity=project3d(md,'vector',md.hydrology.sediment_transmitivity,'type','node','layer',1);
-				md.hydrology.basal_moulin_input=project3d(md,'vector',md.hydrology.basal_moulin_input,'type','node','layer',1);
-	    end
+			md.initialization = extrude(md.initialization,md);
+
+			md.flowequation=md.flowequation.extrude(md);
+			md.stressbalance=extrude(md.stressbalance,md);
+			md.thermal=md.thermal.extrude(md);
+			md.masstransport=md.masstransport.extrude(md);
+			md.calving=extrude(md.calving,md);
+			md.hydrology = extrude(md.hydrology,md);
 
 			%connectivity
@@ -770,38 +761,9 @@
 			end
 
-			%materials
-			md.materials.rheology_B=project3d(md,'vector',md.materials.rheology_B,'type','node');
-			md.materials.rheology_n=project3d(md,'vector',md.materials.rheology_n,'type','element');
-				
-			%damage
-			md.damage.D=project3d(md,'vector',md.damage.D,'type','node');
-
-			%parameters
-			md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node');
-			md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node');
-			md.gia.mantle_viscosity=project3d(md,'vector',md.gia.mantle_viscosity,'type','node');
-			md.gia.lithosphere_thickness=project3d(md,'vector',md.gia.lithosphere_thickness,'type','node');
-			md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node');
-			md.geometry.base=project3d(md,'vector',md.geometry.base,'type','node');
-			md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node');
-			md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node');
-			md.mask.groundedice_levelset=project3d(md,'vector',md.mask.groundedice_levelset,'type','node');
-			md.mask.ice_levelset=project3d(md,'vector',md.mask.ice_levelset,'type','node');
-			if ~isnan(md.inversion.cost_functions_coefficients),md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node');end;
-			if ~isnan(md.inversion.min_parameters),md.inversion.min_parameters=project3d(md,'vector',md.inversion.min_parameters,'type','node');end;
-			if ~isnan(md.inversion.max_parameters),md.inversion.max_parameters=project3d(md,'vector',md.inversion.max_parameters,'type','node');end;
-			if ~isnan(md.qmu.partition),md.qmu.partition=project3d(md,'vector',md.qmu.partition','type','node');end
-
-			%Put lithostatic pressure if there is an existing pressure
-			if ~isnan(md.initialization.pressure),
-				md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z);
-			end
-
-			%special for thermal modeling:
-			md.basalforcings.groundedice_melting_rate=project3d(md,'vector',md.basalforcings.groundedice_melting_rate,'type','node','layer',1); 
-			md.basalforcings.floatingice_melting_rate=project3d(md,'vector',md.basalforcings.floatingice_melting_rate,'type','node','layer',1); 
-			if ~isnan(md.basalforcings.geothermalflux)
-				md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1); %bedrock only gets geothermal flux
-			end
+			md.materials=extrude(md.materials,md);
+			md.damage=extrude(md.damage,md);
+			md.mask=extrude(md.mask,md);
+			md.qmu=extrude(md.qmu,md);
+			md.basalforcings=extrude(md.basalforcings,md);
 
 			%increase connectivity if less than 25:
@@ -825,6 +787,7 @@
 			if isfield(structmd,'p'), md.friction.p=structmd.p; end
 			if isfield(structmd,'q'), md.friction.q=structmd.p; end
-			if isfield(structmd,'melting'), md.basalforcings.melting_rate=structmd.melting; end
+			if isfield(structmd,'melting'), md.basalforcings.floatingice_melting_rate=structmd.melting; end
 			if isfield(structmd,'melting_rate'), md.basalforcings.floatingice_melting_rate=structmd.melting_rate; end
+			if isfield(structmd,'melting_rate'), md.basalforcings.groundedice_melting_rate=structmd.melting_rate; end
 			if isfield(structmd,'accumulation'), md.surfaceforcings.mass_balance=structmd.accumulation; end
 			if isfield(structmd,'numberofgrids'), md.mesh.numberofvertices=structmd.numberofgrids; end
@@ -923,5 +886,4 @@
 			if isfield(structmd,'extractedelements'), md.mesh.extractedelements=structmd.extractedelements; end
 			if isfield(structmd,'nodeonboundary'), md.mesh.vertexonboundary=structmd.nodeonboundary; end
-			if isfield(structmd,'hemisphere'), md.mesh.hemisphere=structmd.hemisphere; end
 			if isfield(structmd,'lat'), md.mesh.lat=structmd.lat; end
 			if isfield(structmd,'long'), md.mesh.long=structmd.long; end
@@ -1106,4 +1068,5 @@
 			md.steadystate      = steadystate();
 			md.transient        = transient();
+			md.calving          = calving();
 			md.gia              = gia();
 			md.autodiff         = autodiff();
@@ -1248,42 +1211,43 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
-			disp(sprintf('%19s: %-22s -- %s','mesh'            ,['[1x1 ' class(obj.mesh) ']'],'mesh properties'));
-			disp(sprintf('%19s: %-22s -- %s','mask'            ,['[1x1 ' class(obj.mask) ']'],'defines grounded and floating elements'));
-			disp(sprintf('%19s: %-22s -- %s','geometry'        ,['[1x1 ' class(obj.geometry) ']'],'surface elevation, bedrock topography, ice thickness,...'));
-			disp(sprintf('%19s: %-22s -- %s','constants'       ,['[1x1 ' class(obj.constants) ']'],'physical constants'));
-			disp(sprintf('%19s: %-22s -- %s','surfaceforcings' ,['[1x1 ' class(obj.surfaceforcings) ']'],'surface forcings'));
-			disp(sprintf('%19s: %-22s -- %s','basalforcings'   ,['[1x1 ' class(obj.basalforcings) ']'],'bed forcings'));
-			disp(sprintf('%19s: %-22s -- %s','materials'       ,['[1x1 ' class(obj.materials) ']'],'material properties'));
-			disp(sprintf('%19s: %-22s -- %s','damage'          ,['[1x1 ' class(obj.damage) ']'],'parameters for damage evolution solution'));
-			disp(sprintf('%19s: %-22s -- %s','friction'        ,['[1x1 ' class(obj.friction) ']'],'basal friction/drag properties'));
-			disp(sprintf('%19s: %-22s -- %s','flowequation'    ,['[1x1 ' class(obj.flowequation) ']'],'flow equations'));
-			disp(sprintf('%19s: %-22s -- %s','timestepping'    ,['[1x1 ' class(obj.timestepping) ']'],'time stepping for transient models'));
-			disp(sprintf('%19s: %-22s -- %s','initialization'  ,['[1x1 ' class(obj.initialization) ']'],'initial guess/state'));
-			disp(sprintf('%19s: %-22s -- %s','rifts'           ,['[1x1 ' class(obj.rifts) ']'],'rifts properties'));
-			disp(sprintf('%19s: %-22s -- %s','debug'           ,['[1x1 ' class(obj.debug) ']'],'debugging tools (valgrind, gprof)'));
-			disp(sprintf('%19s: %-22s -- %s','verbose'         ,['[1x1 ' class(obj.verbose) ']'],'verbosity level in solve'));
-			disp(sprintf('%19s: %-22s -- %s','settings'        ,['[1x1 ' class(obj.settings) ']'],'settings properties'));
-			disp(sprintf('%19s: %-22s -- %s','toolkits'          ,['[1x1 ' class(obj.toolkits) ']'],'PETSc options for each solution'));
-			disp(sprintf('%19s: %-22s -- %s','cluster'         ,['[1x1 ' class(obj.cluster) ']'],'cluster parameters (number of cpus...)'));
-			disp(sprintf('%19s: %-22s -- %s','balancethickness',['[1x1 ' class(obj.balancethickness) ']'],'parameters for balancethickness solution'));
-			disp(sprintf('%19s: %-22s -- %s','stressbalance'      ,['[1x1 ' class(obj.stressbalance) ']'],'parameters for stressbalance solution'));
-			disp(sprintf('%19s: %-22s -- %s','groundingline'   ,['[1x1 ' class(obj.groundingline) ']'],'parameters for groundingline solution'));
-			disp(sprintf('%19s: %-22s -- %s','hydrology'       ,['[1x1 ' class(obj.hydrology) ']'],'parameters for hydrology solution'));
-			disp(sprintf('%19s: %-22s -- %s','masstransport'      ,['[1x1 ' class(obj.masstransport) ']'],'parameters for masstransport solution'));
-			disp(sprintf('%19s: %-22s -- %s','thermal'         ,['[1x1 ' class(obj.thermal) ']'],'parameters for thermal solution'));
-			disp(sprintf('%19s: %-22s -- %s','steadystate'     ,['[1x1 ' class(obj.steadystate) ']'],'parameters for steadystate solution'));
-			disp(sprintf('%19s: %-22s -- %s','transient'       ,['[1x1 ' class(obj.transient) ']'],'parameters for transient solution'));
-			disp(sprintf('%19s: %-22s -- %s','gia'       ,['[1x1 ' class(obj.gia) ']'],'parameters for gia solution'));
-			disp(sprintf('%19s: %-22s -- %s','autodiff'        ,['[1x1 ' class(obj.autodiff) ']'],'automatic differentiation parameters'));
-			disp(sprintf('%19s: %-22s -- %s','flaim'           ,['[1x1 ' class(obj.flaim) ']'],'flaim parameters'));
-			disp(sprintf('%19s: %-22s -- %s','inversion'       ,['[1x1 ' class(obj.inversion) ']'],'parameters for inverse methods'));
-			disp(sprintf('%19s: %-22s -- %s','qmu'             ,['[1x1 ' class(obj.qmu) ']'],'dakota properties'));
-			disp(sprintf('%19s: %-22s -- %s','outputdefinition',['[1x1 ' class(obj.outputdefinition) ']'],'output definition'));
-			disp(sprintf('%19s: %-22s -- %s','results'         ,['[1x1 ' class(obj.results) ']'],'model results'));
-			disp(sprintf('%19s: %-22s -- %s','radaroverlay'    ,['[1x1 ' class(obj.radaroverlay) ']'],'radar image for plot overlay'));
-			disp(sprintf('%19s: %-22s -- %s','miscellaneous'   ,['[1x1 ' class(obj.miscellaneous) ']'],'miscellaneous fields'));
+		function disp(self) % {{{
+			disp(sprintf('%19s: %-22s -- %s','mesh'            ,['[1x1 ' class(self.mesh) ']'],'mesh properties'));
+			disp(sprintf('%19s: %-22s -- %s','mask'            ,['[1x1 ' class(self.mask) ']'],'defines grounded and floating elements'));
+			disp(sprintf('%19s: %-22s -- %s','geometry'        ,['[1x1 ' class(self.geometry) ']'],'surface elevation, bedrock topography, ice thickness,...'));
+			disp(sprintf('%19s: %-22s -- %s','constants'       ,['[1x1 ' class(self.constants) ']'],'physical constants'));
+			disp(sprintf('%19s: %-22s -- %s','surfaceforcings' ,['[1x1 ' class(self.surfaceforcings) ']'],'surface forcings'));
+			disp(sprintf('%19s: %-22s -- %s','basalforcings'   ,['[1x1 ' class(self.basalforcings) ']'],'bed forcings'));
+			disp(sprintf('%19s: %-22s -- %s','materials'       ,['[1x1 ' class(self.materials) ']'],'material properties'));
+			disp(sprintf('%19s: %-22s -- %s','damage'          ,['[1x1 ' class(self.damage) ']'],'parameters for damage evolution solution'));
+			disp(sprintf('%19s: %-22s -- %s','friction'        ,['[1x1 ' class(self.friction) ']'],'basal friction/drag properties'));
+			disp(sprintf('%19s: %-22s -- %s','flowequation'    ,['[1x1 ' class(self.flowequation) ']'],'flow equations'));
+			disp(sprintf('%19s: %-22s -- %s','timestepping'    ,['[1x1 ' class(self.timestepping) ']'],'time stepping for transient models'));
+			disp(sprintf('%19s: %-22s -- %s','initialization'  ,['[1x1 ' class(self.initialization) ']'],'initial guess/state'));
+			disp(sprintf('%19s: %-22s -- %s','rifts'           ,['[1x1 ' class(self.rifts) ']'],'rifts properties'));
+			disp(sprintf('%19s: %-22s -- %s','debug'           ,['[1x1 ' class(self.debug) ']'],'debugging tools (valgrind, gprof)'));
+			disp(sprintf('%19s: %-22s -- %s','verbose'         ,['[1x1 ' class(self.verbose) ']'],'verbosity level in solve'));
+			disp(sprintf('%19s: %-22s -- %s','settings'        ,['[1x1 ' class(self.settings) ']'],'settings properties'));
+			disp(sprintf('%19s: %-22s -- %s','toolkits'        ,['[1x1 ' class(self.toolkits) ']'],'PETSc options for each solution'));
+			disp(sprintf('%19s: %-22s -- %s','cluster'         ,['[1x1 ' class(self.cluster) ']'],'cluster parameters (number of cpus...)'));
+			disp(sprintf('%19s: %-22s -- %s','balancethickness',['[1x1 ' class(self.balancethickness) ']'],'parameters for balancethickness solution'));
+			disp(sprintf('%19s: %-22s -- %s','stressbalance'   ,['[1x1 ' class(self.stressbalance) ']'],'parameters for stressbalance solution'));
+			disp(sprintf('%19s: %-22s -- %s','groundingline'   ,['[1x1 ' class(self.groundingline) ']'],'parameters for groundingline solution'));
+			disp(sprintf('%19s: %-22s -- %s','hydrology'       ,['[1x1 ' class(self.hydrology) ']'],'parameters for hydrology solution'));
+			disp(sprintf('%19s: %-22s -- %s','masstransport'   ,['[1x1 ' class(self.masstransport) ']'],'parameters for masstransport solution'));
+			disp(sprintf('%19s: %-22s -- %s','thermal'         ,['[1x1 ' class(self.thermal) ']'],'parameters for thermal solution'));
+			disp(sprintf('%19s: %-22s -- %s','steadystate'     ,['[1x1 ' class(self.steadystate) ']'],'parameters for steadystate solution'));
+			disp(sprintf('%19s: %-22s -- %s','transient'       ,['[1x1 ' class(self.transient) ']'],'parameters for transient solution'));
+			disp(sprintf('%19s: %-22s -- %s','calving'         ,['[1x1 ' class(self.calving) ']'],'parameters for calving'));
+			disp(sprintf('%19s: %-22s -- %s','gia'             ,['[1x1 ' class(self.gia) ']'],'parameters for gia solution'));
+			disp(sprintf('%19s: %-22s -- %s','autodiff'        ,['[1x1 ' class(self.autodiff) ']'],'automatic differentiation parameters'));
+			disp(sprintf('%19s: %-22s -- %s','flaim'           ,['[1x1 ' class(self.flaim) ']'],'flaim parameters'));
+			disp(sprintf('%19s: %-22s -- %s','inversion'       ,['[1x1 ' class(self.inversion) ']'],'parameters for inverse methods'));
+			disp(sprintf('%19s: %-22s -- %s','qmu'             ,['[1x1 ' class(self.qmu) ']'],'dakota properties'));
+			disp(sprintf('%19s: %-22s -- %s','outputdefinition',['[1x1 ' class(self.outputdefinition) ']'],'output definition'));
+			disp(sprintf('%19s: %-22s -- %s','results'         ,['[1x1 ' class(self.results) ']'],'model results'));
+			disp(sprintf('%19s: %-22s -- %s','radaroverlay'    ,['[1x1 ' class(self.radaroverlay) ']'],'radar image for plot overlay'));
+			disp(sprintf('%19s: %-22s -- %s','miscellaneous'   ,['[1x1 ' class(self.miscellaneous) ']'],'miscellaneous fields'));
 		end % }}}
-		function memory(obj) % {{{
+		function memory(self) % {{{
 
 		disp(sprintf('\nMemory imprint:\n'));
@@ -1293,5 +1257,5 @@
 
 		for i=1:length(fields),
-			field=obj.(fields{i});
+			field=self.(fields{i});
 			s=whos('field'); 
 			mem=mem+s.bytes/1e6;
@@ -1301,5 +1265,5 @@
 		disp(sprintf('%19s: %g Mb','Total',mem));
 		end % }}}
-		function netcdf(obj,filename) % {{{
+		function netcdf(self,filename) % {{{
 		%NETCDF - save model as netcdf
 		%
@@ -1314,5 +1278,5 @@
 		ncid=netcdf.create(filename,'CLOBBER');
 		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Conventions','CF-1.4');
-		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Title',['ISSM model (' obj.miscellaneous.name ')']);
+		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Title',['ISSM model (' self.miscellaneous.name ')']);
 		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Author',getenv('USER'));
 		netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Date',datestr(now));
@@ -1323,5 +1287,5 @@
 		for step=1:2,
 			counter=0;
-			[var_id,counter]=structtonc(ncid,'md',obj,0,var_id,counter,step);
+			[var_id,counter]=structtonc(ncid,'md',self,0,var_id,counter,step);
 			if step==1, netcdf.endDef(ncid); end
 		end
@@ -1333,8 +1297,8 @@
 		netcdf.close(ncid)
 		end % }}}
-		function xylim(obj) % {{{
-
-			xlim([min(obj.mesh.x) max(obj.mesh.x)]);
-			ylim([min(obj.mesh.y) max(obj.mesh.y)])
+		function xylim(self) % {{{
+
+			xlim([min(self.mesh.x) max(self.mesh.x)]);
+			ylim([min(self.mesh.y) max(self.mesh.y)])
 		end % }}}
 		function md=upload(md) % {{{
Index: /issm/trunk/src/m/classes/model.py
===================================================================
--- /issm/trunk/src/m/classes/model.py	(revision 19104)
+++ /issm/trunk/src/m/classes/model.py	(revision 19105)
@@ -15,4 +15,7 @@
 from basalforcings import basalforcings
 from matice import matice
+from calving import calving
+from calvinglevermann import calvinglevermann
+#from calvingpi import calvingpi
 from damage import damage
 from friction import friction
@@ -30,4 +33,5 @@
 from groundingline import groundingline
 from hydrologyshreve import hydrologyshreve
+from hydrologydc import hydrologydc
 from masstransport import masstransport
 from thermal import thermal
@@ -59,4 +63,11 @@
 	#properties
 	def __init__(self):#{{{
+
+		# classtype=model.properties
+				
+		# for classe in dict.keys(classtype):
+		# 	print classe
+		# 	self.__dict__[classe] = classtype[str(classe)]
+
 		self.mesh             = mesh2d()
 		self.mask             = mask()
@@ -80,11 +91,12 @@
 
 		self.balancethickness = balancethickness()
-		self.stressbalance       = stressbalance()
+		self.stressbalance    = stressbalance()
 		self.groundingline    = groundingline()
 		self.hydrology        = hydrologyshreve()
-		self.masstransport       = masstransport()
+		self.masstransport    = masstransport()
 		self.thermal          = thermal()
 		self.steadystate      = steadystate()
 		self.transient        = transient()
+		self.calving          = calving()
 		self.gia              = gia()
 
@@ -128,5 +140,6 @@
 		        'steadystate',\
 		        'transient',\
-				  'gia',\
+		        'calving',\
+						'gia',\
 		        'autodiff',\
 		        'flaim',\
@@ -167,4 +180,5 @@
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("steadystate","[%s,%s]" % ("1x1",obj.steadystate.__class__.__name__),"parameters for steadystate solution"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("transient","[%s,%s]" % ("1x1",obj.transient.__class__.__name__),"parameters for transient solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("calving","[%s,%s]" % ("1x1",obj.calving.__class__.__name__),"parameters for calving"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("autodiff","[%s,%s]" % ("1x1",obj.autodiff.__class__.__name__),"automatic differentiation parameters"))
 		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flaim","[%s,%s]" % ("1x1",obj.flaim.__class__.__name__),"flaim parameters"))
@@ -517,5 +531,5 @@
 		md.mesh.lat                         = mesh2d.lat
 		md.mesh.long                        = mesh2d.long
-		md.mesh.hemisphere                  = mesh2d.hemisphere
+		md.mesh.epsg                        = mesh2d.epsg
 
 		md.mesh.vertexonboundary            = mesh2d.vertexonboundary
@@ -581,76 +595,27 @@
 		#Ok, now deal with the other fields from the 2d mesh:
 
+		#bedinfo and surface info
+		md.mesh.vertexonbase=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',1)
+		md.mesh.vertexonsurface=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',md.mesh.numberoflayers)
+		md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node')
+
 		#lat long
 		md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node')
 		md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node')
 
-		#drag coefficient is limited to nodes that are on the bedrock.
-		md.friction.coefficient=project3d(md,'vector',md.friction.coefficient,'type','node','layer',1)
-
-		#p and q (same deal, except for element that are on the bedrock: )
-		md.friction.p=project3d(md,'vector',md.friction.p,'type','element')
-		md.friction.q=project3d(md,'vector',md.friction.q,'type','element')
-
-		#observations
-		md.inversion.vx_obs=project3d(md,'vector',md.inversion.vx_obs,'type','node')
-		md.inversion.vy_obs=project3d(md,'vector',md.inversion.vy_obs,'type','node')
-		md.inversion.vel_obs=project3d(md,'vector',md.inversion.vel_obs,'type','node')
-		md.inversion.thickness_obs=project3d(md,'vector',md.inversion.thickness_obs,'type','node')
+		md.geometry.extrude(md)
+		md.friction.extrude(md)
+		md.inversion.extrude(md)
 		md.surfaceforcings.extrude(md)
-		md.balancethickness.thickening_rate=project3d(md,'vector',md.balancethickness.thickening_rate,'type','node')
-
-		#results
-		if not numpy.any(numpy.isnan(md.initialization.vx)):
-			md.initialization.vx=project3d(md,'vector',md.initialization.vx,'type','node')
-		if not numpy.any(numpy.isnan(md.initialization.vy)):
-			md.initialization.vy=project3d(md,'vector',md.initialization.vy,'type','node')
-		if not numpy.any(numpy.isnan(md.initialization.vz)):
-			md.initialization.vz=project3d(md,'vector',md.initialization.vz,'type','node')
-		if not numpy.any(numpy.isnan(md.initialization.vel)):
-			md.initialization.vel=project3d(md,'vector',md.initialization.vel,'type','node')
-		if not numpy.any(numpy.isnan(md.initialization.temperature)):
-			md.initialization.temperature=project3d(md,'vector',md.initialization.temperature,'type','node')
-		if not numpy.any(numpy.isnan(md.initialization.waterfraction)):
-			md.initialization.waterfraction=project3d(md,'vector',md.initialization.waterfraction,'type','node')
-		if not numpy.any(numpy.isnan(md.initialization.watercolumn)):
-			md.initialization.watercolumn=project3d(md,'vector',md.initialization.watercolumn,'type','node')
-
-
-		#bedinfo and surface info
-		md.mesh.vertexonbase=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',1)
-		md.mesh.vertexonsurface=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',md.mesh.numberoflayers)
-
-		#elementstype
-		if not numpy.any(numpy.isnan(md.flowequation.element_equation)):
-			oldelements_type=md.flowequation.element_equation
-			md.flowequation.element_equation=numpy.zeros(number_el3d,int)
-			md.flowequation.element_equation=project3d(md,'vector',oldelements_type,'type','element')
-
-		#verticestype
-		if not numpy.any(numpy.isnan(md.flowequation.vertex_equation)):
-			oldvertices_type=md.flowequation.vertex_equation
-			md.flowequation.vertex_equation=numpy.zeros(number_nodes3d,int)
-			md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node')
-
-		md.flowequation.borderSSA=project3d(md,'vector',md.flowequation.borderSSA,'type','node')
-		md.flowequation.borderHO=project3d(md,'vector',md.flowequation.borderHO,'type','node')
-		md.flowequation.borderFS=project3d(md,'vector',md.flowequation.borderFS,'type','node')
-
-		#boundary conditions
-		md.stressbalance.spcvx=project3d(md,'vector',md.stressbalance.spcvx,'type','node')
-		md.stressbalance.spcvy=project3d(md,'vector',md.stressbalance.spcvy,'type','node')
-		md.stressbalance.spcvz=project3d(md,'vector',md.stressbalance.spcvz,'type','node')
-		md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',numpy.nan)
-		if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
-			md.thermal.spctemperature=numpy.nan*numpy.ones((md.mesh.numberofvertices,1))
-			if hasattr(md.mesh,'vertexonsurface'):
-				pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
-				md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
-		md.masstransport.spcthickness=project3d(md,'vector',md.masstransport.spcthickness,'type','node')
-		md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node')
-		md.damage.spcdamage=project3d(md,'vector',md.damage.spcdamage,'type','node')
-		md.stressbalance.referential=project3d(md,'vector',md.stressbalance.referential,'type','node')
-		md.stressbalance.loadingforce=project3d(md,'vector',md.stressbalance.loadingforce,'type','node')
-		md.masstransport.calvingrate=project3d(md,'vector',md.masstransport.calvingrate,'type','node')
+		md.initialization.extrude(md)
+		md.flowequation.extrude(md)
+
+		md.stressbalance.extrude(md)
+		md.thermal.extrude(md)
+		md.masstransport.extrude(md)
+
+		# Calving variables
+		md.hydrology.extrude(md)
+		md.calving.extrude(md)
 
 		#connectivity
@@ -663,40 +628,10 @@
 				md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity<0)]=0
 
-		#materials
-		md.materials.rheology_B=project3d(md,'vector',md.materials.rheology_B,'type','node')
-		md.materials.rheology_n=project3d(md,'vector',md.materials.rheology_n,'type','element')
-
-		#damage
-		md.damage.D=project3d(md,'vector',md.damage.D,'type','node')
-
-		#parameters
-		md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node')
-		md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node')
-		md.gia.mantle_viscosity=project3d(md,'vector',md.gia.mantle_viscosity,'type','node')
-		md.gia.lithosphere_thickness=project3d(md,'vector',md.gia.lithosphere_thickness,'type','node')
-		md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node')
-		md.geometry.base=project3d(md,'vector',md.geometry.base,'type','node')
-		md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node')
-		md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node')
-		md.mask.ice_levelset=project3d(md,'vector',md.mask.ice_levelset,'type','node')
-		md.mask.groundedice_levelset=project3d(md,'vector',md.mask.groundedice_levelset,'type','node')
-		if not numpy.any(numpy.isnan(md.inversion.cost_functions_coefficients)):
-			md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node')
-		if not numpy.any(numpy.isnan(md.inversion.min_parameters)):
-			md.inversion.min_parameters=project3d(md,'vector',md.inversion.min_parameters,'type','node')
-		if not numpy.any(numpy.isnan(md.inversion.max_parameters)):
-			md.inversion.max_parameters=project3d(md,'vector',md.inversion.max_parameters,'type','node')
-		if not numpy.any(numpy.isnan(md.qmu.partition)):
-			md.qmu.partition=project3d(md,'vector',numpy.transpose(md.qmu.partition),'type','node')
-
-		#Put lithostatic pressure if there is an existing pressure
-		if not numpy.any(numpy.isnan(md.initialization.pressure)):
-			md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z.reshape(-1,1))
-
-		#special for thermal modeling:
-		md.basalforcings.groundedice_melting_rate=project3d(md,'vector',md.basalforcings.groundedice_melting_rate,'type','node','layer',1)
-		md.basalforcings.floatingice_melting_rate=project3d(md,'vector',md.basalforcings.floatingice_melting_rate,'type','node','layer',1)
-		if not numpy.any(numpy.isnan(md.basalforcings.geothermalflux)):
-			md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1)    #bedrock only gets geothermal flux
+		md.materials.extrude(md)
+		md.damage.extrude(md)
+		md.gia.extrude(md)
+		md.mask.extrude(md)
+		md.qmu.extrude(md)
+		md.basalforcings.extrude(md)
 
 		#increase connectivity if less than 25:
@@ -746,4 +681,8 @@
 		if not numpy.isnan(md.initialization.vel).all(): md.initialization.vel=DepthAverage(md,md.initialization.vel)
 		if not numpy.isnan(md.initialization.temperature).all(): md.initialization.temperature=DepthAverage(md,md.initialization.temperature)
+                if not numpy.isnan(md.initialization.pressure).all(): md.initialization.pressure=project2d(md,md.initialization.pressure,1)
+                if not numpy.isnan(md.initialization.sediment_head).all(): md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1)
+                if not numpy.isnan(md.initialization.epl_head).all(): md.initialization.epl_head=project2d(md,md.initialization.epl_head,1)
+                if not numpy.isnan(md.initialization.epl_thickness).all(): md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1)
 
 		#gia
@@ -758,4 +697,14 @@
 			md.flowequation.borderHO=project2d(md,md.flowequation.borderHO,1)
 			md.flowequation.borderFS=project2d(md,md.flowequation.borderFS,1)
+
+
+                # Hydrologydc variables
+                if hasattr(md.hydrology,'hydrologydc'):
+                        md.hydrology.spcsediment_head=project2d(md,md.hydrology.spcsediment_head,1)
+                        md.hydrology.mask_eplactive_node=project2d(md,md.hydrology.mask_eplactive_node,1)
+                        md.hydrology.sediment_transmitivity=project2d(md,md.hydrology.sediment_transmitivity,1)
+                        md.hydrology.basal_moulin_input=project2d(md,md.hydrology.basal_moulin_input,1)
+                if md.hydrology.isefficientlayer == 1:
+                        md.hydrology.spcepl_head=project2d(md,md.hydrology.spcepl_head,1)
 
 		#boundary conditions
Index: /issm/trunk/src/m/classes/modellist.m
===================================================================
--- /issm/trunk/src/m/classes/modellist.m	(revision 19104)
+++ /issm/trunk/src/m/classes/modellist.m	(revision 19105)
@@ -122,5 +122,5 @@
 
 		end % }}}
-		function obj = modellist(varargin) % {{{
+		function self = modellist(varargin) % {{{
 
 			%initialize list
@@ -146,9 +146,9 @@
 				end
 
-				obj.models  = celllist;
-				obj.cluster = obj.models{1}.cluster;
-			end
-		end % }}}
-		function val = get(obj, propName)% {{{
+				self.models  = celllist;
+				self.cluster = self.models{1}.cluster;
+			end
+		end % }}}
+		function val = get(self, propName)% {{{
 		%GET - gets model propertie from a specified object ans returns the value
 		% 
@@ -158,30 +158,30 @@
 			switch propName
 				case 'numberofelements'
-					val = obj.numberofelements;
+					val = self.numberofelements;
 				case 'numberofnodes'
-					val = obj.numberofnodes;
+					val = self.numberofnodes;
 				case 'elements' 
-					val = obj.elements;
+					val = self.elements;
 				case 'x' 
-					val = obj.x;
+					val = self.x;
 				case 'y' 
-					val = obj.y;
+					val = self.y;
 				case 'z' 
-					val = obj.z;
+					val = self.z;
 				otherwise
 					error(['get error message: ' propName,' is not a valid model property'])
 			end
 		end % }}}
-		function obj = loadmultipleresultsfromcluster(obj) % {{{
+		function self = loadmultipleresultsfromcluster(self) % {{{
 			%LOADMULTIPLERESULTSFROMCLUSTER - load multiple results of solution sequences from cluster
 			%
 			%   Usage:
-			%      obj=loadresultsfromcluster(obj);
-
-			nummodels=length(obj.models);
+			%      self=loadresultsfromcluster(self);
+
+			nummodels=length(self.models);
 
 			%Get cluster settings
-			cluster=obj.cluster;
-			name=obj.name;
+			cluster=self.cluster;
+			name=self.name;
 			cluster_rc_location=which('cluster.rc');
 			[codepath,executionpath]=ClusterParameters(cluster,cluster_rc_location);
@@ -200,5 +200,5 @@
 			for i=1:nummodels,
 				%load  results for this model
-				obj.models{i}=loadresultsfromdisk(obj.models{i},[name '-' num2str(i) 'vs' num2str(nummodels) '.outbin']);
+				self.models{i}=loadresultsfromdisk(self.models{i},[name '-' num2str(i) 'vs' num2str(nummodels) '.outbin']);
 
 				delete([name '-' num2str(i) 'vs' num2str(nummodels) '.outbin']);
@@ -208,14 +208,14 @@
 			delete('ModelResults.tar.gz');
 		end % }}}
-		function obj = solve(obj,varargin)% {{{
+		function self = solve(self,varargin)% {{{
 			%SOLVE - apply solution sequence for  a list of models. Used in batch mode.
 			%
 			%   Usage:
-			%      obj=solve(obj,varargin)
+			%      self=solve(self,varargin)
 			%      where varargin is a lit of paired arguments. 
 			%      arguments can be: 'analysis_type': 'stressbalance','thermal','masstransport','transient'
 			%
 			%   Examples:
-			%      obj=solve(obj,'analysis_type','stressbalance');
+			%      self=solve(self,'analysis_type','stressbalance');
 
 			%recover options
@@ -226,11 +226,11 @@
 
 			%length of list
-			nummodels=length(obj.models);
+			nummodels=length(self.models);
 
 			%name of queue: to make it unique, add a time stamp
-			name=[obj.name '-' datestr(now,1) '-' datestr(now,'HH-MM-SS') ];
+			name=[self.name '-' datestr(now,1) '-' datestr(now,'HH-MM-SS') ];
 
 			%name of cluster will be first name of list
-			cluster=obj.cluster;
+			cluster=self.cluster;
 
 			%Figure out parameters for this particular cluster
@@ -242,5 +242,5 @@
 
 				%model
-				mdex=obj.models{i};
+				mdex=self.models{i};
 
 				%recover some fields
@@ -248,9 +248,9 @@
 
 				mdex.name=[name '-' num2str(i) 'vs' num2str(nummodels)];
-				mdex.time=obj.time;
-				mdex.queue=obj.queue;
-				mdex.cluster=obj.cluster;
-				if ~isnan(obj.np),
-					mdex.np=obj.np;
+				mdex.time=self.time;
+				mdex.queue=self.queue;
+				mdex.cluster=self.cluster;
+				if ~isnan(self.np),
+					mdex.np=self.np;
 				end
 
@@ -263,5 +263,5 @@
 
 				%feed back
-				obj.models{i}=mdex;
+				self.models{i}=mdex;
 			end
 
@@ -287,5 +287,5 @@
 
 			%save name: 
-			obj.name=name;
+			self.name=name;
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/organizer.py
===================================================================
--- /issm/trunk/src/m/classes/organizer.py	(revision 19104)
+++ /issm/trunk/src/m/classes/organizer.py	(revision 19105)
@@ -151,5 +151,5 @@
 		return bool
 	#}}}
-	def savemodel(self,md):    # {{{
+	def savemodel(self,md, name='default'):    # {{{
 
 		#check
@@ -159,5 +159,6 @@
 			raise RuntimeError("Cannot save model because organizer (org) is not up to date!")
 
-		name=os.path.join(self.repository,self.prefix+'.step#'+self.steps[self._currentstep-1]['string']+'.python')
+		if (name=='default'):
+			name=os.path.join(self.repository,self.prefix+'.step#'+self.steps[self._currentstep-1]['string']+'.python')
 		print "saving model as: '%s'" % name
 
Index: /issm/trunk/src/m/classes/outputdefinition.m
===================================================================
--- /issm/trunk/src/m/classes/outputdefinition.m	(revision 19104)
+++ /issm/trunk/src/m/classes/outputdefinition.m	(revision 19105)
@@ -9,46 +9,46 @@
 	end
 	methods
-	   function createxml(obj,fid) % {{{
+	   function createxml(self,fid) % {{{
             fprintf(fid, '<!-- outputdefinition -->\n');            
                     
             % outputdefinition solution parameters
             fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="outputdefinition">','<section name="outputdefinition" />');                    
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="definitions" type="',class(obj.definitions),'" default="',convert2str(obj.definitions),'">','     <section name="outputdefinition" />','     <help> list of potential outputs that can be requested, but which need additional data to be defined </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="definitions" type="',class(self.definitions),'" default="',convert2str(self.definitions),'">','     <section name="outputdefinition" />','     <help> list of potential outputs that can be requested, but which need additional data to be defined </help>','  </parameter>');
             fprintf(fid,'%s\n%s\n','</frame>');    
         
         end % }}}
-		function obj = outputdefinition(varargin) % {{{
+		function self = outputdefinition(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
-			obj.definitions={};
+			self.definitions={};
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			md = checkfield(md,'fieldname','outputdefinition.definitions','cell',1);
 
-			for i=1:length(obj.definitions),
-				md=checkconsistency(obj.definitions{i},md,solution,analyses);
+			for i=1:length(self.definitions),
+				md=checkconsistency(self.definitions{i},md,solution,analyses);
 			end
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   outputdefinition:'));
-			fielddisplay(obj,'definitions','list of potential outputs that can be requested, but which need additional data to be defined');
+			fielddisplay(self,'definitions','list of potential outputs that can be requested, but which need additional data to be defined');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
-		enums=zeros(length(obj.definitions),1);
-		for i=1:length(obj.definitions),
-			obj.definitions{i}.marshall(md,fid);
-			classdefinition=class(obj.definitions{i});
+		enums=zeros(length(self.definitions),1);
+		for i=1:length(self.definitions),
+			self.definitions{i}.marshall(md,fid);
+			classdefinition=class(self.definitions{i});
 			classdefinition(1)=upper(classdefinition(1)); %so it matches our enums definitions.
 			enums(i)=StringToEnum(classdefinition);
Index: /issm/trunk/src/m/classes/pairoptions.m
===================================================================
--- /issm/trunk/src/m/classes/pairoptions.m	(revision 19104)
+++ /issm/trunk/src/m/classes/pairoptions.m	(revision 19105)
@@ -11,12 +11,12 @@
 	end
 	methods
-		function obj = pairoptions(varargin) % {{{
+		function self = pairoptions(varargin) % {{{
 
 			%get calling function name
 			a=dbstack;
 			if length(a)>1,
-				obj.functionname=a(2).file(1:end-2);
-			else
-				obj.functionname='';
+				self.functionname=a(2).file(1:end-2);
+			else
+				self.functionname='';
 			end
 
@@ -25,8 +25,8 @@
 				%Do nothing,
 			else
-				obj=buildlist(obj,varargin{:});
-			end
-		end % }}}
-		function obj = buildlist(obj,varargin) % {{{
+				self=buildlist(self,varargin{:});
+			end
+		end % }}}
+		function self = buildlist(self,varargin) % {{{
 		%BUILDLIST - build list of obj from input
 
@@ -38,34 +38,34 @@
 
 			%Allocate memory
-			obj.list=cell(numoptions,3);
+			self.list=cell(numoptions,3);
 
 			%go through varargin and build list of obj
 			for i=1:numoptions,
 				if ischar(varargin{2*i-1}),
-					obj.list{i,1}=varargin{2*i-1};
-					obj.list{i,2}=varargin{2*i};
-					obj.list{i,3}=false; %used?
+					self.list{i,1}=varargin{2*i-1};
+					self.list{i,2}=varargin{2*i};
+					self.list{i,3}=false; %used?
 				else
 					%option is not a string, ignore it
 					disp(['WARNING: option number ' num2str(i) ' is not a string, it will be ignored']);
-					obj.list(i,:)=[];
+					self.list(i,:)=[];
 					continue
 				end
 			end
 		end % }}}
-		function obj = addfield(obj,field,value) % {{{
+		function self = addfield(self,field,value) % {{{
 			if ischar(field),
-				obj.list{end+1,1} = field;
-				obj.list{end,2}   = value;
-				obj.list{end,3}   = false;
-			end
-		end % }}}
-		function obj = addfielddefault(obj,field,value) % {{{
+				self.list{end+1,1} = field;
+				self.list{end,2}   = value;
+				self.list{end,3}   = false;
+			end
+		end % }}}
+		function self = addfielddefault(self,field,value) % {{{
 		%ADDFIELDDEFAULT - add a field to an options list if it does not exist
 			if ischar(field),
-				if ~exist(obj,field),
-					obj.list{end+1,1} = field;
-					obj.list{end,2}   = value;
-					obj.list{end,3}   = true;  %It is a default so user will not be notified if not used
+				if ~exist(self,field),
+					self.list{end+1,1} = field;
+					self.list{end,2}   = value;
+					self.list{end,3}   = true;  %It is a default so user will not be notified if not used
 				end
 			end
@@ -84,34 +84,34 @@
 			end
 		end % }}}
-		function obj = changefieldvalue(obj,field,newvalue) % {{{
+		function self = changefieldvalue(self,field,newvalue) % {{{
 		%CHANGEOPTIONVALUE - change the value of an option in an option list
 
 			%track occurrence of field
-			lines=find(strcmpi(obj.list(:,1),field));
+			lines=find(strcmpi(self.list(:,1),field));
 
 			%replace value
 			if isempty(lines),
 				%add new field if not found
-				obj=addfield(obj,field,newvalue);
-				obj.list{end,3}=true; % do not notify user if unused
+				self=addfield(self,field,newvalue);
+				self.list{end,3}=true; % do not notify user if unused
 			else
 				for i=1:length(lines),
-					obj.list{lines(i),2}=newvalue;
-				end
-			end
-		end % }}}
-		function obj = deleteduplicates(obj,warn) % {{{
+					self.list{lines(i),2}=newvalue;
+				end
+			end
+		end % }}}
+		function self = deleteduplicates(self,warn) % {{{
 		%DELETEDUPLICATES - delete duplicates in an option list
 
 			%track the first occurrence of each option
-			[dummy lines]=unique(obj.list(:,1),'first');
+			[dummy lines]=unique(self.list(:,1),'first');
 			clear dummy
 
 			%warn user if requested
 			if warn,
-				numoptions=size(obj.list,1);
+				numoptions=size(self.list,1);
 				for i=1:numoptions,
 					if ~ismember(i,lines),
-						disp(['WARNING: option ' obj.list{i,1} ' appeared more than once. Only its first occurrence will be kept'])
+						disp(['WARNING: option ' self.list{i,1} ' appeared more than once. Only its first occurrence will be kept'])
 					end
 				end
@@ -119,29 +119,29 @@
 
 			%remove duplicates from the options list
-			obj.list=obj.list(lines,:);
-		end % }}}
-		function displayunused(obj) % {{{
+			self.list=self.list(lines,:);
+		end % }}}
+		function displayunused(self) % {{{
 			%DISPLAYUNUSED - display unused options
 
-			numoptions=size(obj.list,1);
+			numoptions=size(self.list,1);
 			for i=1:numoptions,
-				if ~obj.list{i,3},
-					disp(['WARNING: option ' obj.list{i,1} ' was not used'])
-				end
-			end
-		end % }}}
-		function disp(obj) % {{{
-			disp(sprintf('   functionname: %s',obj.functionname));
-			if ~isempty(obj.list),
-				disp(sprintf('   list: (%ix%i)\n',size(obj.list,1),size(obj.list,2)));
-				for i=1:size(obj.list,1),
-					if ischar(obj.list{i,2}),
-						disp(sprintf('     field: %-10s value: ''%s''',obj.list{i,1},obj.list{i,2}));
-					elseif isnumeric(obj.list{i,2}) & length(obj.list{i,2})==1,
-						disp(sprintf('     field: %-10s value: %g',obj.list{i,1},obj.list{i,2}));
-					elseif isnumeric(obj.list{i,2}) & length(obj.list{i,2})==2,
-						disp(sprintf('     field: %-10s value: [%g %g]',obj.list{i,1},obj.list{i,2}));
+				if ~self.list{i,3},
+					disp(['WARNING: option ' self.list{i,1} ' was not used'])
+				end
+			end
+		end % }}}
+		function disp(self) % {{{
+			disp(sprintf('   functionname: %s',self.functionname));
+			if ~isempty(self.list),
+				disp(sprintf('   list: (%ix%i)\n',size(self.list,1),size(self.list,2)));
+				for i=1:size(self.list,1),
+					if ischar(self.list{i,2}),
+						disp(sprintf('     field: %-10s value: ''%s''',self.list{i,1},self.list{i,2}));
+					elseif isnumeric(self.list{i,2}) & length(self.list{i,2})==1,
+						disp(sprintf('     field: %-10s value: %g',self.list{i,1},self.list{i,2}));
+					elseif isnumeric(self.list{i,2}) & length(self.list{i,2})==2,
+						disp(sprintf('     field: %-10s value: [%g %g]',self.list{i,1},self.list{i,2}));
 					else
-						disp(sprintf('     field: %-10s value: (%ix%i)',obj.list{i,1},size(obj.list{i,2},1),size(obj.list{i,2},2)));
+						disp(sprintf('     field: %-10s value: (%ix%i)',self.list{i,1},size(self.list{i,2},1),size(self.list{i,2},2)));
 					end
 				end
@@ -150,5 +150,5 @@
 			end
 		end % }}}
-		function bool = exist(obj,field) % {{{
+		function bool = exist(self,field) % {{{
 		%EXIST - check if the option exists
 
@@ -162,13 +162,13 @@
 
 			%Recover option
-			pos=find(strcmpi(field,obj.list(:,1)));
+			pos=find(strcmpi(field,self.list(:,1)));
 			if ~isempty(pos),
 				bool=true;
-				obj.list{pos,3}   = true;  %It is a default so user will not be notified if not used
+				self.list{pos,3}   = true;  %It is a default so user will not be notified if not used
 			else
 				bool=false;
 			end
 		end % }}}
-		function num = fieldoccurrences(obj,field), % {{{
+		function num = fieldoccurrences(self,field), % {{{
 		%FIELDOCCURRENCES - get number of occurrence of a field
 
@@ -179,11 +179,11 @@
 
 			%get number of occurrence
-			num=sum(strcmpi(field,obj.list(:,1)));
-		end % }}}
-		function value = getfieldvalue(obj,field,varargin), % {{{
+			num=sum(strcmpi(field,self.list(:,1)));
+		end % }}}
+		function value = getfieldvalue(self,field,varargin), % {{{
 		%GETOPTION - get the value of an option
 		%
 		%   Usage:
-		%      value=getfieldvalue(obj,field,varargin)
+		%      value=getfieldvalue(self,field,varargin)
 		%
 		%   Find an option value from a field. A default option
@@ -205,8 +205,8 @@
 
 			%Recover option
-			pos=find(strcmpi(obj.list(:,1),field));
+			pos=find(strcmpi(self.list(:,1),field));
 			if ~isempty(pos),
-				value=obj.list{pos(1),2}; % ignore extra entry
-				obj.list{pos(1),3}=true;  % option used
+				value=self.list{pos(1),2}; % ignore extra entry
+				self.list{pos(1),3}=true;  % option used
 				return;
 			end
@@ -219,9 +219,9 @@
 			end
 		end % }}}
-		function obj = removefield(obj,field,warn)% {{{
+		function self = removefield(self,field,warn)% {{{
 		%REMOVEFIELD - delete a field in an option list
 		%
 		%   Usage:
-		%      obj=removefield(obj,field,warn)
+		%      self=removefield(self,field,warn)
 		%
 		%   if warn==1 display an info message to warn user that
@@ -229,11 +229,11 @@
 
 			%check is field exist
-			if exist(obj,field),
+			if exist(self,field),
 
 				%find where the field is located
-				lines=find(~strcmpi(obj.list(:,1),field));
+				lines=find(~strcmpi(self.list(:,1),field));
 
 				%remove duplicates from the options list
-				obj.list=obj.list(lines,:);
+				self.list=self.list(lines,:);
 
 				%warn user if requested
@@ -243,9 +243,9 @@
 			end
 		end % }}}
-		function marshall(obj,fid,firstindex)% {{{
-
-			for i=1:size(obj.list,1),
-				name  = obj.list{i,1};
-				value = obj.list{i,2};
+		function marshall(self,fid,firstindex)% {{{
+
+			for i=1:size(self.list,1),
+				name  = self.list{i,1};
+				value = self.list{i,2};
 
 				%Write option name
Index: /issm/trunk/src/m/classes/private.m
===================================================================
--- /issm/trunk/src/m/classes/private.m	(revision 19104)
+++ /issm/trunk/src/m/classes/private.m	(revision 19105)
@@ -12,25 +12,25 @@
 	end
 	methods
-		function obj = private(varargin) % {{{
+		function self = private(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   private parameters: do not change'));
 
-			fielddisplay(obj,'isconsistent','is model self consistent');
-			fielddisplay(obj,'runtimename','name of the run launched');
-			fielddisplay(obj,'bamg','structure with mesh properties constructed if bamg is used to mesh the domain');
-			fielddisplay(obj,'solution','type of solution launched');
+			fielddisplay(self,'isconsistent','is model self consistent');
+			fielddisplay(self,'runtimename','name of the run launched');
+			fielddisplay(self,'bamg','structure with mesh properties constructed if bamg is used to mesh the domain');
+			fielddisplay(self,'solution','type of solution launched');
 
 		end % }}}
Index: /issm/trunk/src/m/classes/qmu.m
===================================================================
--- /issm/trunk/src/m/classes/qmu.m	(revision 19104)
+++ /issm/trunk/src/m/classes/qmu.m	(revision 19105)
@@ -24,45 +24,48 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '<!-- qmu -->\n');            
-                    
-            % qmu solution parameters
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="qmu parameters">','<section name="qmu" />');                    
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isdakota" type="',class(obj.isdakota),'" default="',convert2str(obj.isdakota),'">','     <section name="qmu" />','     <help> is qmu analysis activated? </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="variables" type="',class(obj.variables),'" default="',convert2str(obj.variables),'">','     <section name="qmu" />','     <help> (arrays of each variable class) </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="responses" type="',class(obj.responses),'" default="',convert2str(obj.responses),'">','     <section name="qmu" />','     <help> (arrays of each response class) </help>','  </parameter>');
-                
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofresponses" type="',class(obj.numberofresponses),'" default="',convert2str(obj.numberofresponses),'">','     <section name="qmu" />','     <help> number of responses </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="params" type="',class(obj.params),'" default="',convert2str(obj.params),'">','     <section name="qmu" />','     <help> (array of method-independent parameters)  </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="results" type="',class(obj.results),'" default="',convert2str(obj.results),'">','     <section name="qmu" />','     <help> (information from dakota files) </help>','  </parameter>');
-                
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="partition" type="',class(obj.partition),'" default="',convert2str(obj.partition),'">','     <section name="qmu" />','     <help> user provided mesh partitioning, defaults to metis if not specified </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofpartitions" type="',class(obj.numberofpartitions),'" default="',convert2str(obj.numberofpartitions),'">','     <section name="qmu" />','     <help> number of partitions for semi-discrete qmu  </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="variabledescriptors" type="',class(obj.variabledescriptors),'" default="',convert2str(obj.variabledescriptors),'">','     <section name="qmu" />','     <help>  </help>','  </parameter>');
-            
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="responsedescriptors" type="',class(obj.responsedescriptors),'" default="',convert2str(obj.responsedescriptors),'">','     <section name="qmu" />','     <help> use an enthalpy formulation to include temperate ice (default is 0) </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="method" type="',class(obj.method),'" default="',convert2str(obj.method),'">','     <section name="qmu" />','     <help> array of dakota_method class </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mass_flux_profile_directory" type="',class(obj.mass_flux_profile_directory),'" default="',convert2str(obj.mass_flux_profile_directory),'">','     <section name="qmu" />','     <help> directory for mass flux profiles </help>','  </parameter>');
-                
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mass_flux_profiles" type="',class(obj.mass_flux_profiles),'" default="',convert2str(obj.mass_flux_profiles),'">','     <section name="qmu" />','     <help>  </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mass_flux_segments" type="',class(obj.mass_flux_segments),'" default="',convert2str(obj.mass_flux_segments),'">','     <section name="qmu" />','     <help>  </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="adjacency" type="',class(obj.adjacency),'" default="',convert2str(obj.adjacency),'">','     <section name="qmu" />','     <help> additional outputs requested </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertex_weight" type="',class(obj.vertex_weight),'" default="',convert2str(obj.vertex_weight),'">','     <section name="qmu" />','     <help> weight applied to each mesh vertex </help>','  </parameter>');
-            
-            fprintf(fid,'%s\n%s\n','</frame>');    
-        
-        end % }}}        
-		function obj = qmu(varargin) % {{{
+		function createxml(self,fid) % {{{
+			fprintf(fid, '<!-- qmu -->\n');            
+
+			% qmu solution parameters
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="qmu parameters">','<section name="qmu" />');                    
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isdakota" type="',class(self.isdakota),'" default="',convert2str(self.isdakota),'">','     <section name="qmu" />','     <help> is qmu analysis activated? </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="variables" type="',class(self.variables),'" default="',convert2str(self.variables),'">','     <section name="qmu" />','     <help> (arrays of each variable class) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="responses" type="',class(self.responses),'" default="',convert2str(self.responses),'">','     <section name="qmu" />','     <help> (arrays of each response class) </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofresponses" type="',class(self.numberofresponses),'" default="',convert2str(self.numberofresponses),'">','     <section name="qmu" />','     <help> number of responses </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="params" type="',class(self.params),'" default="',convert2str(self.params),'">','     <section name="qmu" />','     <help> (array of method-independent parameters)  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="results" type="',class(self.results),'" default="',convert2str(self.results),'">','     <section name="qmu" />','     <help> (information from dakota files) </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="partition" type="',class(self.partition),'" default="',convert2str(self.partition),'">','     <section name="qmu" />','     <help> user provided mesh partitioning, defaults to metis if not specified </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="numberofpartitions" type="',class(self.numberofpartitions),'" default="',convert2str(self.numberofpartitions),'">','     <section name="qmu" />','     <help> number of partitions for semi-discrete qmu  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="variabledescriptors" type="',class(self.variabledescriptors),'" default="',convert2str(self.variabledescriptors),'">','     <section name="qmu" />','     <help>  </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="responsedescriptors" type="',class(self.responsedescriptors),'" default="',convert2str(self.responsedescriptors),'">','     <section name="qmu" />','     <help> use an enthalpy formulation to include temperate ice (default is 0) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="method" type="',class(self.method),'" default="',convert2str(self.method),'">','     <section name="qmu" />','     <help> array of dakota_method class </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mass_flux_profile_directory" type="',class(self.mass_flux_profile_directory),'" default="',convert2str(self.mass_flux_profile_directory),'">','     <section name="qmu" />','     <help> directory for mass flux profiles </help>','  </parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mass_flux_profiles" type="',class(self.mass_flux_profiles),'" default="',convert2str(self.mass_flux_profiles),'">','     <section name="qmu" />','     <help>  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="mass_flux_segments" type="',class(self.mass_flux_segments),'" default="',convert2str(self.mass_flux_segments),'">','     <section name="qmu" />','     <help>  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="adjacency" type="',class(self.adjacency),'" default="',convert2str(self.adjacency),'">','     <section name="qmu" />','     <help> additional outputs requested </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="vertex_weight" type="',class(self.vertex_weight),'" default="',convert2str(self.vertex_weight),'">','     <section name="qmu" />','     <help> weight applied to each mesh vertex </help>','  </parameter>');
+
+			fprintf(fid,'%s\n%s\n','</frame>');    
+
+		end % }}}        
+		function self = extrude(self,md) % {{{
+			self.partition=project3d(md,'vector',self.partition','type','node');
+		end % }}}
+		function self = qmu(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
@@ -90,12 +93,12 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   qmu parameters:'));
 
-			fielddisplay(obj,'isdakota','is qmu analysis activated?');
-			for i=1:numel(obj.variables)
+			fielddisplay(self,'isdakota','is qmu analysis activated?');
+			for i=1:numel(self.variables)
 				disp(sprintf('         variables%s:  (arrays of each variable class)',...
-					string_dim(obj.variables,i)));
-				fnames=fieldnames(obj.variables(i));
+					string_dim(self.variables,i)));
+				fnames=fieldnames(self.variables(i));
 				maxlen=0;
 				for j=1:numel(fnames)
@@ -105,11 +108,11 @@
 				for j=1:numel(fnames)
 					disp(sprintf(['            %-' num2str(maxlen+1) 's:    [%ix%i]    ''%s'''],...
-						fnames{j},size(obj.variables.(fnames{j})),class(obj.variables.(fnames{j}))));
+						fnames{j},size(self.variables.(fnames{j})),class(self.variables.(fnames{j}))));
 				end
 			end
-			for i=1:numel(obj.responses)
+			for i=1:numel(self.responses)
 				disp(sprintf('         responses%s:  (arrays of each response class)',...
-					string_dim(obj.responses,i)));
-				fnames=fieldnames(obj.responses(i));
+					string_dim(self.responses,i)));
+				fnames=fieldnames(self.responses(i));
 				maxlen=0;
 				for j=1:numel(fnames)
@@ -119,18 +122,18 @@
 				for j=1:numel(fnames)
 					disp(sprintf(['            %-' num2str(maxlen+1) 's:    [%ix%i]    ''%s'''],...
-						fnames{j},size(obj.responses.(fnames{j})),class(obj.responses.(fnames{j}))));
+						fnames{j},size(self.responses.(fnames{j})),class(self.responses.(fnames{j}))));
 				end
 			end
-			fielddisplay(obj,'numberofresponses','number of responses') 
-			for i=1:numel(obj.method);
-				if strcmp(class(obj.method(i)),'dakota_method')
+			fielddisplay(self,'numberofresponses','number of responses') 
+			for i=1:numel(self.method);
+				if strcmp(class(self.method(i)),'dakota_method')
 					disp(sprintf('            method%s :    ''%s''',...
-						string_dim(obj.method,i),obj.method(i).method));
+						string_dim(self.method,i),self.method(i).method));
 				end
 			end
-			for i=1:numel(obj.params)
+			for i=1:numel(self.params)
 				disp(sprintf('         params%s:  (array of method-independent parameters)',...
-					string_dim(obj.params,i)));
-				fnames=fieldnames(obj.params(i));
+					string_dim(self.params,i)));
+				fnames=fieldnames(self.params(i));
 				maxlen=0;
 				for j=1:numel(fnames)
@@ -140,11 +143,11 @@
 				for j=1:numel(fnames)
 					disp(sprintf(['            %-' num2str(maxlen+1) 's: %s'],...
-						fnames{j},any2str(obj.params(i).(fnames{j}))));
+						fnames{j},any2str(self.params(i).(fnames{j}))));
 				end
 			end
-			for i=1:numel(obj.results)
+			for i=1:numel(self.results)
 				disp(sprintf('         results%s:  (information from dakota files)',...
-					string_dim(obj.results,i)));
-				fnames=fieldnames(obj.results(i));
+					string_dim(self.results,i)));
+				fnames=fieldnames(self.results(i));
 				maxlen=0;
 				for j=1:numel(fnames)
@@ -154,32 +157,32 @@
 				for j=1:numel(fnames)
 					disp(sprintf(['            %-' num2str(maxlen+1) 's:    [%ix%i]    ''%s'''],...
-						fnames{j},size(obj.results.(fnames{j})),class(obj.results.(fnames{j}))));
+						fnames{j},size(self.results.(fnames{j})),class(self.results.(fnames{j}))));
 				end
 			end
-			fielddisplay(obj,'partition','user provided mesh partitioning, defaults to metis if not specified') 
-			fielddisplay(obj,'numberofpartitions','number of partitions for semi-discrete qmu') 
-			fielddisplay(obj,'variabledescriptors','');
-			fielddisplay(obj,'responsedescriptors','');
-			fielddisplay(obj,'method','array of dakota_method class');
-			fielddisplay(obj,'mass_flux_profile_directory','directory for mass flux profiles');
-			fielddisplay(obj,'mass_flux_profiles','list of mass_flux profiles');
-			fielddisplay(obj,'mass_flux_segments','');
-			fielddisplay(obj,'adjacency','');
-			fielddisplay(obj,'vertex_weight','weight applied to each mesh vertex');
+			fielddisplay(self,'partition','user provided mesh partitioning, defaults to metis if not specified') 
+			fielddisplay(self,'numberofpartitions','number of partitions for semi-discrete qmu') 
+			fielddisplay(self,'variabledescriptors','');
+			fielddisplay(self,'responsedescriptors','');
+			fielddisplay(self,'method','array of dakota_method class');
+			fielddisplay(self,'mass_flux_profile_directory','directory for mass flux profiles');
+			fielddisplay(self,'mass_flux_profiles','list of mass_flux profiles');
+			fielddisplay(self,'mass_flux_segments','');
+			fielddisplay(self,'adjacency','');
+			fielddisplay(self,'vertex_weight','weight applied to each mesh vertex');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','isdakota','format','Boolean');
-			if ~obj.isdakota, 
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','isdakota','format','Boolean');
+			if ~self.isdakota, 
 				WriteData(fid,'data',false,'enum',QmuMassFluxSegmentsPresentEnum,'format','Boolean');
 				return; 
 			end
-			WriteData(fid,'object',obj,'fieldname','partition','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'fieldname','numberofpartitions','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','numberofresponses','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','variabledescriptors','format','StringArray');
-			WriteData(fid,'object',obj,'fieldname','responsedescriptors','format','StringArray');
-			if ~isempty(obj.mass_flux_segments), 
-				WriteData(fid,'data',obj.mass_flux_segments,'enum',MassFluxSegmentsEnum,'format','MatArray');
+			WriteData(fid,'object',self,'fieldname','partition','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'fieldname','numberofpartitions','format','Integer');
+			WriteData(fid,'object',self,'fieldname','numberofresponses','format','Integer');
+			WriteData(fid,'object',self,'fieldname','variabledescriptors','format','StringArray');
+			WriteData(fid,'object',self,'fieldname','responsedescriptors','format','StringArray');
+			if ~isempty(self.mass_flux_segments), 
+				WriteData(fid,'data',self.mass_flux_segments,'enum',MassFluxSegmentsEnum,'format','MatArray');
 				flag=true; 
 			else 
Index: /issm/trunk/src/m/classes/qmu.py
===================================================================
--- /issm/trunk/src/m/classes/qmu.py	(revision 19104)
+++ /issm/trunk/src/m/classes/qmu.py	(revision 19105)
@@ -1,3 +1,4 @@
 import numpy
+from project3d import project3d
 from collections import OrderedDict
 from fielddisplay import fielddisplay
@@ -37,4 +38,80 @@
 
 		#}}}
+	def __repr__(self):    # {{{
+		s ='   qmu parameters:\n'
+
+		s+="%s\n" % fielddisplay(self,'isdakota','is qmu analysis activated?')
+		for i,variable in enumerate(self.variables.iteritems()):
+			s+="         variables%s:  (arrays of each variable class)\n" % \
+					string_dim(self.variables,i)
+			fnames=vars(variable)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="'            %-*s:    [%ix%i]    '%s'\n" % \
+						(maxlen+1,fname,size(getattr(variable,fname)),type(getattr(variable,fname)))
+
+		for i,response in enumerate(self.responses.iteritems()):
+			s+="         responses%s:  (arrays of each response class)\n" % \
+					string_dim(self.responses,i)
+			fnames=vars(response)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s:    [%ix%i]    '%s'\n" % \
+						(maxlen+1,fname,size(getattr(response,fname)),type(getattr(response,fname)))
+
+		s+="%s\n" % fielddisplay(self,'numberofresponses','number of responses') 
+
+		for i,method in enumerate(self.method.iteritems()):
+			if isinstance(method,'dakota_method'):
+				s+="            method%s :    '%s'\n" % \
+						(string_dim(method,i),method.method)
+
+		for i,param in enumerate(self.params.iteritems()):
+			s+="         params%s:  (array of method-independent parameters)\n" % \
+					string_dim(self.params,i)
+			fnames=vars(param)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s: %s\n" % \
+						(maxlen+1,fname,any2str(getattr(param,fname)))
+
+		for i,result in enumerate(self.results.iteritems()):
+			s+="         results%s:  (information from dakota files)\n" % \
+					string_dim(self.results,i)
+			fnames=vars(result)
+			maxlen=0
+			for fname in fnames:
+				maxlen=max(maxlen,len(fname))
+
+			for fname in fnames:
+				s+="            %-*s:    [%ix%i]    '%s'\n" % \
+						(maxlen+1,fname,size(getattr(result,fname)),type(getattr(result,fname)))
+
+		s+="%s\n" % fielddisplay(self,'partition','user provided mesh partitioning, defaults to metis if not specified') 
+		s+="%s\n" % fielddisplay(self,'numberofpartitions','number of partitions for semi-discrete qmu') 
+		s+="%s\n" % fielddisplay(self,'variabledescriptors','')
+		s+="%s\n" % fielddisplay(self,'responsedescriptors','')
+		s+="%s\n" % fielddisplay(self,'method','array of dakota_method class')
+		s+="%s\n" % fielddisplay(self,'mass_flux_profile_directory','directory for mass flux profiles')
+		s+="%s\n" % fielddisplay(self,'mass_flux_profiles','list of mass_flux profiles')
+		s+="%s\n" % fielddisplay(self,'mass_flux_segments','')
+		s+="%s\n" % fielddisplay(self,'adjacency','')
+		s+="%s\n" % fielddisplay(self,'vertex_weight','weight applied to each mesh vertex')
+
+		return s
+	# }}}
+	def extrude(self,md): # {{{
+		self.partition=project3d(md,'vector',numpy.transpose(self.partition),'type','node')
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		return self
@@ -62,76 +139,4 @@
 		return md
 	# }}}
-	def __repr__(self):    # {{{
-		s ='   qmu parameters:\n'
-
-		s+="%s\n" % fielddisplay(self,'isdakota','is qmu analysis activated?')
-		for i,variable in enumerate(self.variables.iteritems()):
-			s+="         variables%s:  (arrays of each variable class)\n" % \
-				string_dim(self.variables,i)
-			fnames=vars(variable)
-			maxlen=0
-			for fname in fnames:
-				maxlen=max(maxlen,len(fname))
-
-			for fname in fnames:
-				s+="'            %-*s:    [%ix%i]    '%s'\n" % \
-					(maxlen+1,fname,size(getattr(variable,fname)),type(getattr(variable,fname)))
-
-		for i,response in enumerate(self.responses.iteritems()):
-			s+="         responses%s:  (arrays of each response class)\n" % \
-				string_dim(self.responses,i)
-			fnames=vars(response)
-			maxlen=0
-			for fname in fnames:
-				maxlen=max(maxlen,len(fname))
-
-			for fname in fnames:
-				s+="            %-*s:    [%ix%i]    '%s'\n" % \
-					(maxlen+1,fname,size(getattr(response,fname)),type(getattr(response,fname)))
-
-		s+="%s\n" % fielddisplay(self,'numberofresponses','number of responses') 
-
-		for i,method in enumerate(self.method.iteritems()):
-			if isinstance(method,'dakota_method'):
-				s+="            method%s :    '%s'\n" % \
-					(string_dim(method,i),method.method)
-
-		for i,param in enumerate(self.params.iteritems()):
-			s+="         params%s:  (array of method-independent parameters)\n" % \
-				string_dim(self.params,i)
-			fnames=vars(param)
-			maxlen=0
-			for fname in fnames:
-				maxlen=max(maxlen,len(fname))
-
-			for fname in fnames:
-				s+="            %-*s: %s\n" % \
-					(maxlen+1,fname,any2str(getattr(param,fname)))
-
-		for i,result in enumerate(self.results.iteritems()):
-			s+="         results%s:  (information from dakota files)\n" % \
-				string_dim(self.results,i)
-			fnames=vars(result)
-			maxlen=0
-			for fname in fnames:
-				maxlen=max(maxlen,len(fname))
-
-			for fname in fnames:
-				s+="            %-*s:    [%ix%i]    '%s'\n" % \
-					(maxlen+1,fname,size(getattr(result,fname)),type(getattr(result,fname)))
-
-		s+="%s\n" % fielddisplay(self,'partition','user provided mesh partitioning, defaults to metis if not specified') 
-		s+="%s\n" % fielddisplay(self,'numberofpartitions','number of partitions for semi-discrete qmu') 
-		s+="%s\n" % fielddisplay(self,'variabledescriptors','')
-		s+="%s\n" % fielddisplay(self,'responsedescriptors','')
-		s+="%s\n" % fielddisplay(self,'method','array of dakota_method class')
-		s+="%s\n" % fielddisplay(self,'mass_flux_profile_directory','directory for mass flux profiles')
-		s+="%s\n" % fielddisplay(self,'mass_flux_profiles','list of mass_flux profiles')
-		s+="%s\n" % fielddisplay(self,'mass_flux_segments','')
-		s+="%s\n" % fielddisplay(self,'adjacency','')
-		s+="%s\n" % fielddisplay(self,'vertex_weight','weight applied to each mesh vertex')
-
-		return s
-	# }}}
 	def marshall(self,md,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','isdakota','format','Boolean')
Index: /issm/trunk/src/m/classes/radaroverlay.m
===================================================================
--- /issm/trunk/src/m/classes/radaroverlay.m	(revision 19104)
+++ /issm/trunk/src/m/classes/radaroverlay.m	(revision 19105)
@@ -11,21 +11,21 @@
 	end
 	methods
-		function obj = radaroverlay(varargin) % {{{
+		function self = radaroverlay(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   radaroverlay parameters:'));
 
-			fielddisplay(obj,'pwr','radar power image (matrix)');
-			fielddisplay(obj,'x','corresponding x coordinates [m]');
-			fielddisplay(obj,'y','corresponding y coordinates [m]');
+			fielddisplay(self,'pwr','radar power image (matrix)');
+			fielddisplay(self,'x','corresponding x coordinates [m]');
+			fielddisplay(self,'y','corresponding y coordinates [m]');
 
 		end % }}}
Index: /issm/trunk/src/m/classes/rifts.m
===================================================================
--- /issm/trunk/src/m/classes/rifts.m	(revision 19104)
+++ /issm/trunk/src/m/classes/rifts.m	(revision 19105)
@@ -10,27 +10,27 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
+        function createxml(self,fid) % {{{
             fprintf(fid, '\n\n');
             fprintf(fid, '%s\n', '<!-- rifts -->');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="riftstruct" type="',              class(obj.riftstruct),'" default="',                  obj.riftstruct,'">',              '     <section name="rifts" />','     <help> structure containing all rift information (vertices coordinates, segments, type of melange, ...) </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="riftproperties" type="',            class(obj.riftproperties),'" default="',                obj.riftproperties,'">',   '     <section name="rifts" />','     <help> N/A </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="riftstruct" type="',              class(self.riftstruct),'" default="',                  self.riftstruct,'">',              '     <section name="rifts" />','     <help> structure containing all rift information (vertices coordinates, segments, type of melange, ...) </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="riftproperties" type="',            class(self.riftproperties),'" default="',                self.riftproperties,'">',   '     <section name="rifts" />','     <help> N/A </help>','</parameter>');
     
         end % }}}
-		function obj = rifts(varargin) % {{{
+		function self = rifts(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
-			if isempty(obj.riftstruct) | isnans(obj.riftstruct),
+		function md = checkconsistency(self,md,solution,analyses) % {{{
+			if isempty(self.riftstruct) | isnans(self.riftstruct),
 				numrifts=0;
 			else
-				numrifts=numel(obj.riftstruct);
+				numrifts=numel(self.riftstruct);
 			end
 			if numrifts,
@@ -38,5 +38,5 @@
 					md = checkmessage(md,['models with rifts are only supported in 2d for now!']);
 				end
-				if ~isstruct(obj.riftstruct),
+				if ~isstruct(self.riftstruct),
 					md = checkmessage(md,['rifts.riftstruct should be a structure!']);
 				end
@@ -49,27 +49,27 @@
 				end
 			else
-				if ~isnans(obj.riftstruct),
+				if ~isnans(self.riftstruct),
 					md = checkmessage(md,['riftstruct should be NaN since numrifts is 0!']);
 				end
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   rifts parameters:'));
 
-			fielddisplay(obj,'riftstruct','structure containing all rift information (vertices coordinates, segments, type of melange, ...)');
-			fielddisplay(obj,'riftproperties','');
+			fielddisplay(self,'riftstruct','structure containing all rift information (vertices coordinates, segments, type of melange, ...)');
+			fielddisplay(self,'riftproperties','');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			%Process rift info
-			if isempty(obj.riftstruct) | isnans(obj.riftstruct),
+			if isempty(self.riftstruct) | isnans(self.riftstruct),
 				numrifts=0;
 			else
-				numrifts=numel(obj.riftstruct);
+				numrifts=numel(self.riftstruct);
 			end
 			numpairs=0;
 			for i=1:numrifts,
-				numpairs=numpairs+size(obj.riftstruct(i).penaltypairs,1);
+				numpairs=numpairs+size(self.riftstruct(i).penaltypairs,1);
 			end
 
@@ -78,11 +78,11 @@
 			count=1;
 			for i=1:numrifts,
-				numpairsforthisrift=size(obj.riftstruct(i).penaltypairs,1);
-				data(count:count+numpairsforthisrift-1,1:7)=obj.riftstruct(i).penaltypairs;
-				data(count:count+numpairsforthisrift-1,8)=obj.riftstruct(i).fill;
-				data(count:count+numpairsforthisrift-1,9)=obj.riftstruct(i).friction;
-				data(count:count+numpairsforthisrift-1,10)=obj.riftstruct(i).fraction;
-				data(count:count+numpairsforthisrift-1,11)=obj.riftstruct(i).fractionincrement;
-				data(count:count+numpairsforthisrift-1,12)=obj.riftstruct(i).state;
+				numpairsforthisrift=size(self.riftstruct(i).penaltypairs,1);
+				data(count:count+numpairsforthisrift-1,1:7)=self.riftstruct(i).penaltypairs;
+				data(count:count+numpairsforthisrift-1,8)=self.riftstruct(i).fill;
+				data(count:count+numpairsforthisrift-1,9)=self.riftstruct(i).friction;
+				data(count:count+numpairsforthisrift-1,10)=self.riftstruct(i).fraction;
+				data(count:count+numpairsforthisrift-1,11)=self.riftstruct(i).fractionincrement;
+				data(count:count+numpairsforthisrift-1,12)=self.riftstruct(i).state;
 				count=count+numpairsforthisrift;
 			end
Index: /issm/trunk/src/m/classes/settings.m
===================================================================
--- /issm/trunk/src/m/classes/settings.m	(revision 19104)
+++ /issm/trunk/src/m/classes/settings.m	(revision 19105)
@@ -19,9 +19,9 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
+        function createxml(self,fid) % {{{
             fprintf(fid, '\n\n');
             fprintf(fid, '%s\n', '<!-- settings -->');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="results_on_nodes" type="',      class(obj.results_on_nodes),'" default="',        convert2str(obj.results_on_nodes),'">',	'     <section name="settings" />','     <help> results are output for all the nodes of each element </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="io_gather" type="',          class(obj.io_gather),'" default="',           convert2str(obj.io_gather),'">',     '     <section name="settings" />','     <help> I/O gathering strategy for result outputs (default 1) </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="results_on_nodes" type="',      class(self.results_on_nodes),'" default="',        convert2str(self.results_on_nodes),'">',	'     <section name="settings" />','     <help> results are output for all the nodes of each element </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="io_gather" type="',          class(self.io_gather),'" default="',           convert2str(self.io_gather),'">',     '     <section name="settings" />','     <help> I/O gathering strategy for result outputs (default 1) </help>','</parameter>');
             
             % lowmen drop-down (0 or 1)
@@ -30,31 +30,31 @@
             fprintf(fid,'%s\n%s\n','       <option value="1" type="string" default="false"> </option>','</parameter>');
 
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="output_frequency" type="',          class(obj.output_frequency),'" default="',           convert2str(obj.output_frequency),'">',	'     <section name="settings" />','     <help> frequency at which results are saved in all solutions with multiple time_steps </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="waitonlock" type="',  	class(obj.waitonlock),'" default="',      convert2str(obj.waitonlock),'">',     '     <section name="settings" />','     <help> maximum number of minutes to wait for batch results (NaN to deactivate) </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_server" type="',         class(obj.upload_server),'" default="',          convert2str(obj.upload_server),'">',	'     <section name="settings" />','     <help> server hostname where model should be uploaded </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_path" type="',             class(obj.upload_path),'" default="',              convert2str(obj.upload_path),'">',     '     <section name="settings" />','     <help> path on server where model should be uploaded </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_login" type="',        class(obj.upload_login),'" default="',         convert2str(obj.upload_login),'">',	'     <section name="settings" />','     <help> server login </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_port" type="',    	class(obj.upload_port),'" default="',      convert2str(obj.upload_port),'">',     '     <section name="settings" />','     <help> port login (default is 0) </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',    	'<parameter key ="upload_filename" type="',         class(obj.upload_filename),'" default="',          convert2str(obj.upload_filename),'">',	'     <section name="settings" />','     <help> unique id generated when uploading the file to server </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="output_frequency" type="',          class(self.output_frequency),'" default="',           convert2str(self.output_frequency),'">',	'     <section name="settings" />','     <help> frequency at which results are saved in all solutions with multiple time_steps </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="waitonlock" type="',  	class(self.waitonlock),'" default="',      convert2str(self.waitonlock),'">',     '     <section name="settings" />','     <help> maximum number of minutes to wait for batch results (NaN to deactivate) </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_server" type="',         class(self.upload_server),'" default="',          convert2str(self.upload_server),'">',	'     <section name="settings" />','     <help> server hostname where model should be uploaded </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_path" type="',             class(self.upload_path),'" default="',              convert2str(self.upload_path),'">',     '     <section name="settings" />','     <help> path on server where model should be uploaded </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_login" type="',        class(self.upload_login),'" default="',         convert2str(self.upload_login),'">',	'     <section name="settings" />','     <help> server login </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="upload_port" type="',    	class(self.upload_port),'" default="',      convert2str(self.upload_port),'">',     '     <section name="settings" />','     <help> port login (default is 0) </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n',    	'<parameter key ="upload_filename" type="',         class(self.upload_filename),'" default="',          convert2str(self.upload_filename),'">',	'     <section name="settings" />','     <help> unique id generated when uploading the file to server </help>','</parameter>');
              
         end % }}}
-		function obj = settings(varargin) % {{{
+		function self = settings(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%are we short in memory ? (0 faster but requires more memory)
-			obj.lowmem=0;
+			self.lowmem=0;
 
 			%i/o:
-			obj.io_gather=1;
+			self.io_gather=1;
 
 			%results frequency by default every step
-			obj.output_frequency=1;
+			self.output_frequency=1;
 
 			%this option can be activated to load automatically the results
@@ -62,5 +62,5 @@
 			%N minutes that is generated once the solution has converged
 			%0 to deactivate
-			obj.waitonlock=Inf;
+			self.waitonlock=Inf;
 
 			%upload options: 
@@ -68,5 +68,5 @@
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			md = checkfield(md,'fieldname','settings.results_on_nodes','numel',[1],'values',[0 1]);
@@ -77,25 +77,25 @@
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   general settings parameters:'));
 
-			fielddisplay(obj,'results_on_nodes','results are output for all the nodes of each element');
-			fielddisplay(obj,'io_gather','I/O gathering strategy for result outputs (default 1)');
-			fielddisplay(obj,'lowmem','is the memory limited ? (0 or 1)');
-			fielddisplay(obj,'output_frequency','frequency at which results are saved in all solutions with multiple time_steps');
-			fielddisplay(obj,'waitonlock','maximum number of minutes to wait for batch results (NaN to deactivate)');
-			fielddisplay(obj,'upload_server','server hostname where model should be uploaded');
-			fielddisplay(obj,'upload_path','path on server where model should be uploaded');
-			fielddisplay(obj,'upload_login','server login');
-			fielddisplay(obj,'upload_port','port login (default is 0)');
-			fielddisplay(obj,'upload_filename','unique id generated when uploading the file to server');
+			fielddisplay(self,'results_on_nodes','results are output for all the nodes of each element');
+			fielddisplay(self,'io_gather','I/O gathering strategy for result outputs (default 1)');
+			fielddisplay(self,'lowmem','is the memory limited ? (0 or 1)');
+			fielddisplay(self,'output_frequency','frequency at which results are saved in all solutions with multiple time_steps');
+			fielddisplay(self,'waitonlock','maximum number of minutes to wait for batch results (NaN to deactivate)');
+			fielddisplay(self,'upload_server','server hostname where model should be uploaded');
+			fielddisplay(self,'upload_path','path on server where model should be uploaded');
+			fielddisplay(self,'upload_login','server login');
+			fielddisplay(self,'upload_port','port login (default is 0)');
+			fielddisplay(self,'upload_filename','unique id generated when uploading the file to server');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','results_on_nodes','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','io_gather','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','lowmem','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','output_frequency','format','Integer');
-			if obj.waitonlock>0,
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','results_on_nodes','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','io_gather','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','lowmem','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','output_frequency','format','Integer');
+			if self.waitonlock>0,
 				WriteData(fid,'enum',SettingsWaitonlockEnum(),'data',true,'format','Boolean');
 			else
Index: /issm/trunk/src/m/classes/snowpack.m
===================================================================
--- /issm/trunk/src/m/classes/snowpack.m	(revision 19104)
+++ /issm/trunk/src/m/classes/snowpack.m	(revision 19105)
@@ -105,8 +105,8 @@
 	end
 	methods
-		function obj = snowpack(varargin) % {{{
+		function self = snowpack(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
 					inputstruct=varargin{1};
@@ -116,5 +116,5 @@
 						fieldname = list1{i};
 						if ismember(fieldname,list2),
-							obj.(fieldname) = inputstruct.(fieldname);
+							self.(fieldname) = inputstruct.(fieldname);
 						end
 					end
@@ -123,99 +123,99 @@
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 		%snowpack:  %{{{
-		obj.snowpack_meas_tss = 1;
-		obj.snowpack_enforce_measured_snow_heights = 0;
-		obj.snowpack_sw_mode = 0;
-		obj.snowpack_incoming_longwave = 1;
-		obj.snowpack_height_of_wind_value = 12.;
-		obj.snowpack_height_of_meteo_values = 12.;
-		obj.snowpack_neutral = 0;
-		obj.snowpack_roughness_length = 0.002;
-		obj.snowpack_number_slopes = 1;
-		obj.snowpack_snow_redistribution = 1;
-		obj.snowpack_calculation_step_length = 15.0;
-		obj.snowpack_change_bc = 0;
-		obj.snowpack_thresh_change_bc = -1.0;
-		obj.snowpack_snp_soil = 0;
-		obj.snowpack_soil_flux = 0;
-		obj.snowpack_geo_heat = 0.06;
-		obj.snowpack_canopy = 0;
+		self.snowpack_meas_tss = 1;
+		self.snowpack_enforce_measured_snow_heights = 0;
+		self.snowpack_sw_mode = 0;
+		self.snowpack_incoming_longwave = 1;
+		self.snowpack_height_of_wind_value = 12.;
+		self.snowpack_height_of_meteo_values = 12.;
+		self.snowpack_neutral = 0;
+		self.snowpack_roughness_length = 0.002;
+		self.snowpack_number_slopes = 1;
+		self.snowpack_snow_redistribution = 1;
+		self.snowpack_calculation_step_length = 15.0;
+		self.snowpack_change_bc = 0;
+		self.snowpack_thresh_change_bc = -1.0;
+		self.snowpack_snp_soil = 0;
+		self.snowpack_soil_flux = 0;
+		self.snowpack_geo_heat = 0.06;
+		self.snowpack_canopy = 0;
 		%}}}
 		%snowpackadvanced:  %{{{
-		obj.snowpackadvanced_variant = 'ANTARCTICA'; % use 320 kg m-3 for fixed density
-		obj.snowpackadvanced_hn_density = 'EVENT';
+		self.snowpackadvanced_variant = 'ANTARCTICA'; % use 320 kg m-3 for fixed density
+		self.snowpackadvanced_hn_density = 'EVENT';
 		%}}}
 		%general:  %{{{
-		obj.general_pluginpath = '/usr/local/lib/meteoio/plugins/';
-		obj.general_buff_chunk_size = 90;
-		obj.general_buff_before = 1.5;
+		self.general_pluginpath = '/usr/local/lib/meteoio/plugins/';
+		self.general_buff_chunk_size = 90;
+		self.general_buff_before = 1.5;
 		%}}}
 		%input {{{
-		obj.input_coordsys = 'ch1903';
-		obj.input_coordparam = 'null';
-		obj.input_time_zone = 8;
-		obj.input_meteo = 'smet';
-		obj.input_meteopath = './input';
-		obj.input_station1 = 'domec.smet';
-		obj.input_snowfile1 = 'domec.sno';
+		self.input_coordsys = 'ch1903';
+		self.input_coordparam = 'null';
+		self.input_time_zone = 8;
+		self.input_meteo = 'smet';
+		self.input_meteopath = './input';
+		self.input_station1 = 'domec.smet';
+		self.input_snowfile1 = 'domec.sno';
 		%}}}
 		%output {{{
-		obj.output_coordsys = 'ch1903';
-		obj.output_coordparam = 'null';
-		obj.output_time_zone = 8;
-		obj.output_meteopath = './output';
-		obj.output_experiment = 'smet';
-		obj.output_ts_write = 1;
-		obj.output_ts_start = 0.0;
-		obj.output_ts_days_between = 0.04166667;
-		obj.output_profile = 'ascii';
-		obj.output_prof_write = 1;
-		obj.output_prof_start = 0.0;
-		obj.output_prof_days_between = 0.04166667;
+		self.output_coordsys = 'ch1903';
+		self.output_coordparam = 'null';
+		self.output_time_zone = 8;
+		self.output_meteopath = './output';
+		self.output_experiment = 'smet';
+		self.output_ts_write = 1;
+		self.output_ts_start = 0.0;
+		self.output_ts_days_between = 0.04166667;
+		self.output_profile = 'ascii';
+		self.output_prof_write = 1;
+		self.output_prof_start = 0.0;
+		self.output_prof_days_between = 0.04166667;
 		%}}}
 		%interpolations1d %{{{
-		obj.interpolations1d_window_size = 439200; %that is 5 d and 2 h; 1 d = 86400
-		obj.interpolations1d_hnw_resample = 'none';
-		obj.interpolations1d_hs_resample = 'linear';
-		obj.interpolations1d_tsg_resample = 'linear';
-		obj.interpolations1d_rho_hn_resample = 'none';
-		obj.interpolations1d_vw_resample = 'nearest_neighbour';
-		obj.interpolations1d_vw_args = 'extrapolate';
+		self.interpolations1d_window_size = 439200; %that is 5 d and 2 h; 1 d = 86400
+		self.interpolations1d_hnw_resample = 'none';
+		self.interpolations1d_hs_resample = 'linear';
+		self.interpolations1d_tsg_resample = 'linear';
+		self.interpolations1d_rho_hn_resample = 'none';
+		self.interpolations1d_vw_resample = 'nearest_neighbour';
+		self.interpolations1d_vw_args = 'extrapolate';
 		%}}}
 		%filters {{{
-		obj.filters_ta_filter1 = 'min_max';
-		obj.filters_ta_arg1 = [190 280];
-		obj.filters_rh_filter1 = 'min_max';
-		obj.filters_rh_arg1 = [0.01 1.2];
-		obj.filters_rh_filter2 = 'min_max';
-		obj.filters_rh_arg2 = {'soft' 0.01 1.0};
-		obj.filters_iswr_filter1 = 'min_max';
-		obj.filters_iswr_arg1 = [-10 1500];
-		obj.filters_iswr_filter2 = 'min_max';
-		obj.filters_iswr_arg2 = {'soft' 0 1500};
-		obj.filters_rswr_filter1 = 'min_max';
-		obj.filters_rswr_arg1 = [-10 1500];
-		obj.filters_rswr_filter2 = 'min_max';
-		obj.filters_rswr_arg2 = {'soft' 0 1500};
+		self.filters_ta_filter1 = 'min_max';
+		self.filters_ta_arg1 = [190 280];
+		self.filters_rh_filter1 = 'min_max';
+		self.filters_rh_arg1 = [0.01 1.2];
+		self.filters_rh_filter2 = 'min_max';
+		self.filters_rh_arg2 = {'soft' 0.01 1.0};
+		self.filters_iswr_filter1 = 'min_max';
+		self.filters_iswr_arg1 = [-10 1500];
+		self.filters_iswr_filter2 = 'min_max';
+		self.filters_iswr_arg2 = {'soft' 0 1500};
+		self.filters_rswr_filter1 = 'min_max';
+		self.filters_rswr_arg1 = [-10 1500];
+		self.filters_rswr_filter2 = 'min_max';
+		self.filters_rswr_arg2 = {'soft' 0 1500};
 
 		%for ta between 190 and 280 k;
-		obj.filters_ilwr_filter1 = 'min_max';
-		obj.filters_ilwr_arg1 = [30 355];
-		obj.filters_ilwr_filter2 = 'min_max';
-		obj.filters_ilwr_arg2 = {'soft' 35 350};
-		obj.filters_tss_filter1 = 'min_max';
-		obj.filters_tss_arg1 = [180 275];
-		obj.filters_tsg_filter1 = 'min_max';
-		obj.filters_tsg_arg1 = [200 275];
-		obj.filters_vw_filter1 = 'min_max';
-		obj.filters_vw_arg1 = [-2 70];
-		obj.filters_vw_filter2 = 'min_max';
-		obj.filters_vw_arg2 = {'soft' 0 50};
+		self.filters_ilwr_filter1 = 'min_max';
+		self.filters_ilwr_arg1 = [30 355];
+		self.filters_ilwr_filter2 = 'min_max';
+		self.filters_ilwr_arg2 = {'soft' 35 350};
+		self.filters_tss_filter1 = 'min_max';
+		self.filters_tss_arg1 = [180 275];
+		self.filters_tsg_filter1 = 'min_max';
+		self.filters_tsg_arg1 = [200 275];
+		self.filters_vw_filter1 = 'min_max';
+		self.filters_vw_arg1 = [-2 70];
+		self.filters_vw_filter2 = 'min_max';
+		self.filters_vw_arg2 = {'soft' 0 50};
 		%}}}
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 			%snowpack:  %{{{
 			md=checkfield(md,'fieldname','snowpack.snowpack_meas_tss','values',[0 1]);
@@ -337,142 +337,142 @@
 			%}}}
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 
 			disp(sprintf('   Snowpack solution parameters:'));
 			disp(sprintf('\n	%s','Snowpack parameters:')); % {{{
-			fielddisplay(obj,'snowpack_meas_tss',{'A measured surface temperature is available and can be reliably ','used for various consistency tests (it needs to be set to true if enabling CHANGE_BC) (0 or 1)'});
-			fielddisplay(obj,'snowpack_enforce_measured_snow_heights','Input mode by which a measurement of snow depth is used to drive the snow cover mass balance (0 or 1)');
-			fielddisplay(obj,'snowpack_sw_mode',{'Define the shortwave radiation input:',...
+			fielddisplay(self,'snowpack_meas_tss',{'A measured surface temperature is available and can be reliably ','used for various consistency tests (it needs to be set to true if enabling CHANGE_BC) (0 or 1)'});
+			fielddisplay(self,'snowpack_enforce_measured_snow_heights','Input mode by which a measurement of snow depth is used to drive the snow cover mass balance (0 or 1)');
+			fielddisplay(self,'snowpack_sw_mode',{'Define the shortwave radiation input:',...
 				'0 Incoming shortwave radiation is measured and albedo estimated by the model',...
 				'1 Reflected shortwave radiation is available as input and albedo is estimated by the model (IMIS standard)',...
 				'2 Incoming and reflected shortwave radiation are both measured and the albedo is estimated from both measurements subject to plausibility checks.'});
-			fielddisplay(obj,'snowpack_incoming_longwave','Use the provided incoming long wave on the virtual slopes? (0 or 1)');
-			fielddisplay(obj,'snowpack_height_of_wind_value',{'The instrument height (or model layer height) for wind input data; note that height ',...
+			fielddisplay(self,'snowpack_incoming_longwave','Use the provided incoming long wave on the virtual slopes? (0 or 1)');
+			fielddisplay(self,'snowpack_height_of_wind_value',{'The instrument height (or model layer height) for wind input data; note that height ',...
 				'is above ground for a standard SNOWPACK application but above surface (snow or ground) for Alpine3D applications '});
-			fielddisplay(obj,'snowpack_height_of_meteo_values',{'The instrument height (or model layer height) for meteorological input data except for wind,',...
+			fielddisplay(self,'snowpack_height_of_meteo_values',{'The instrument height (or model layer height) for meteorological input data except for wind,',...
 				'which may be at a different height; note that height is above ground for a standard SNOWPACK ',...
 				'application but above surface (snow or ground) for Alpine3D applications. '});
-			fielddisplay(obj,'snowpack_neutral',{'Select the atmospheric stability correction model:',...
+			fielddisplay(self,'snowpack_neutral',{'Select the atmospheric stability correction model:',...
 				'-1 use a simplified Richardson number stability correction',...
 				'0 assume standard Monin-Obukhov bulk formulation for surface exchange iteration with Paulson, Stearns and Weidner (can be used with BC_CHANGE=0)',...
 				'1 force Monin-Obukhov formulation to assume neutral conditions regardless of the actual stratification; it has been shown to work well in ',...
 				'complex terrain settings. It should be used with BC_CHANGE=1, i.e., Dirichlet /* but also is recommended with Neumann b.c., i.e., BC_CHANGE=0.'});
-			fielddisplay(obj,'snowpack_roughness_length',{'Aerodynamic roughness length as a parameter for the Monin-Obukhov bulk formulation;',...
+			fielddisplay(self,'snowpack_roughness_length',{'Aerodynamic roughness length as a parameter for the Monin-Obukhov bulk formulation;',...
 				'A typical value for complex terrain is 0.01 m and for snow covered flat sites 0.001 m. '});
-			fielddisplay(obj,'snowpack_number_slopes',{'Based on meteorological input from a (flat field) automatic station or numerical weather model,',...
+			fielddisplay(self,'snowpack_number_slopes',{'Based on meteorological input from a (flat field) automatic station or numerical weather model,',...
 				'up to 8 expositions can be calculated in addition to the flat field if the corresponding *.sno files are provided. For example,',...
 				'if you provide a flat field *.snow file (mandatory), which is named KLO3.sno and you want 4 slopes to be calculated the corresponding',...
 				'slope files should be named KLO21.sno, ...,KLO24.sno '});
-			fielddisplay(obj,'snowpack_snow_redistribution',{'Specifies if redistribution of snow is allowed from (upwind) expositions to lee slopes.',...
+			fielddisplay(self,'snowpack_snow_redistribution',{'Specifies if redistribution of snow is allowed from (upwind) expositions to lee slopes.',...
 				'In case just the flat field is calculated, snow erosion is enabled but only for "ENFORCE_MEASURED_SNOW_HEIGHTS".'});
-				fielddisplay(obj,'snowpack_calculation_step_length',{'Internal time step (in minutes) used for model simulation. Please note that this MUST ',...
+				fielddisplay(self,'snowpack_calculation_step_length',{'Internal time step (in minutes) used for model simulation. Please note that this MUST ',...
 				'be the same as HNW::accumulate (the latter being in seconds) if re-acumulating precipitation, otherwise it would lead to wrong results.'});
-			fielddisplay(obj,'snowpack_change_bc',{'Use measured surface temperature as Dirichlet temperature BC for sub-freezing snowpacks and switch to ',...
+			fielddisplay(self,'snowpack_change_bc',{'Use measured surface temperature as Dirichlet temperature BC for sub-freezing snowpacks and switch to ',...
 			'Neumann only for melting snowpacks. If set to false, assumes Neumann boundary conditions.'});
-			fielddisplay(obj,'snowpack_thresh_change_bc','Threshold value (small number below freezing), which switches from Dirichlet to Neumann BCs if CHANGE_BC is selected');
-			fielddisplay(obj,'snowpack_snp_soil','Soil layers as defined by the *.sno files are included in the simulation');
-			fielddisplay(obj,'snowpack_soil_flux','Assume that the lower temperature boundary condition is given by GEO_HEAT (Neumann) and not by a measured temperature');
-			fielddisplay(obj,'snowpack_geo_heat','Constant geothermal heat flux at great) depth W m-2): Lower flux boundary condition for temperature equation if BC is Neumann');
-			fielddisplay(obj,'snowpack_canopy','Switch to tell the model that canopy is present (note that Canopy parameters should then be provided in the *.sno file)');
+			fielddisplay(self,'snowpack_thresh_change_bc','Threshold value (small number below freezing), which switches from Dirichlet to Neumann BCs if CHANGE_BC is selected');
+			fielddisplay(self,'snowpack_snp_soil','Soil layers as defined by the *.sno files are included in the simulation');
+			fielddisplay(self,'snowpack_soil_flux','Assume that the lower temperature boundary condition is given by GEO_HEAT (Neumann) and not by a measured temperature');
+			fielddisplay(self,'snowpack_geo_heat','Constant geothermal heat flux at great) depth W m-2): Lower flux boundary condition for temperature equation if BC is Neumann');
+			fielddisplay(self,'snowpack_canopy','Switch to tell the model that canopy is present (note that Canopy parameters should then be provided in the *.sno file)');
 			% }}}
 			disp(sprintf('\n	%s','Snowpackadvanced parameters:')); % {{{
-			fielddisplay(obj,'snowpackadvanced_variant','variant selection (includes a choice of specific models, DEFAULT, ANTARCTICA and JAPAN )'); % use 320 kg m-3 for fixed density
-			fielddisplay(obj,'snowpackadvanced_hn_density',{'Fixed value to be used as new snow density if a constant density model is chosen, otherwise the choices are "PARAMETERIZED" "EVENT" "MEASURED"'});
+			fielddisplay(self,'snowpackadvanced_variant','variant selection (includes a choice of specific models, DEFAULT, ANTARCTICA and JAPAN )'); % use 320 kg m-3 for fixed density
+			fielddisplay(self,'snowpackadvanced_hn_density',{'Fixed value to be used as new snow density if a constant density model is chosen, otherwise the choices are "PARAMETERIZED" "EVENT" "MEASURED"'});
 			% }}}
 			disp(sprintf('\n	%s','General parameters:')); % {{{
-			fielddisplay(obj,'general_pluginpath','');
-			fielddisplay(obj,'general_buff_chunk_size','Size in days of a chunk of data to read at once.');
-			fielddisplay(obj,'general_buff_before','Alternate way of buffer centering: When rebuffering, the new date will be located BUFF_BEFORE days from the beginning of the buffer (therefore, it takes a value in days). ');
+			fielddisplay(self,'general_pluginpath','');
+			fielddisplay(self,'general_buff_chunk_size','Size in days of a chunk of data to read at once.');
+			fielddisplay(self,'general_buff_before','Alternate way of buffer centering: When rebuffering, the new date will be located BUFF_BEFORE days from the beginning of the buffer (therefore, it takes a value in days). ');
 			% }}}
 			disp(sprintf('\n	%s','Input  parameter:')); % {{{
-			fielddisplay(obj,'input_coordsys','coordinates in the Swiss Grid (http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf). One of CH1903,UTM,UPS,PROJ4 or LOCAL');
-			fielddisplay(obj,'input_coordparam',' ');
-			fielddisplay(obj,'input_time_zone',' ');
-			fielddisplay(obj,'input_meteo','plugin for METEO data (one of BORMA,COSMO,GEOTOP,GRIB,GS,IMIS,SMET,SNOWPACK');
-			fielddisplay(obj,'input_meteopath','string containing the path to the xml files.');
-			fielddisplay(obj,'input_station1','Meteorology file for station number #');
-			fielddisplay(obj,'input_snowfile1','File name for the initial snow profile for station number #');
+			fielddisplay(self,'input_coordsys','coordinates in the Swiss Grid (http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf). One of CH1903,UTM,UPS,PROJ4 or LOCAL');
+			fielddisplay(self,'input_coordparam',' ');
+			fielddisplay(self,'input_time_zone',' ');
+			fielddisplay(self,'input_meteo','plugin for METEO data (one of BORMA,COSMO,GEOTOP,GRIB,GS,IMIS,SMET,SNOWPACK');
+			fielddisplay(self,'input_meteopath','string containing the path to the xml files.');
+			fielddisplay(self,'input_station1','Meteorology file for station number #');
+			fielddisplay(self,'input_snowfile1','File name for the initial snow profile for station number #');
 			% }}}
 			disp(sprintf('\n	%s','Output parameters:')); % {{{
-			fielddisplay(obj,'output_coordsys','Coordinates in the Swiss Grid http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf. One of CH1903,UTM,UPS,PROJ4 or LOCAL ');
-			fielddisplay(obj,'output_coordparam','');
-			fielddisplay(obj,'output_time_zone','');
-			fielddisplay(obj,'output_meteopath','Path to the outputs (this path MUST exist, it won''t be created)');
-			fielddisplay(obj,'output_experiment','Option to give an additional simulation specific output name to the run in addition to "STATION_NAME"');
-			fielddisplay(obj,'output_ts_write','Write meteo data out? (0 or 1)');
-			fielddisplay(obj,'output_ts_start','When to start writing meteo data out (offset, in days)');
-			fielddisplay(obj,'output_ts_days_between','How often to write meteo data out (in days: 3 hours=.125, 1 hour=4.1666e-2)');
-			fielddisplay(obj,'output_profile','How to write the profiles (default: ASCII, choice is ASCII,IMIS or ASCII IMIS)');
+			fielddisplay(self,'output_coordsys','Coordinates in the Swiss Grid http://geomatics.ladetto.ch/ch1903_wgs84_de.pdf. One of CH1903,UTM,UPS,PROJ4 or LOCAL ');
+			fielddisplay(self,'output_coordparam','');
+			fielddisplay(self,'output_time_zone','');
+			fielddisplay(self,'output_meteopath','Path to the outputs (this path MUST exist, it won''t be created)');
+			fielddisplay(self,'output_experiment','Option to give an additional simulation specific output name to the run in addition to "STATION_NAME"');
+			fielddisplay(self,'output_ts_write','Write meteo data out? (0 or 1)');
+			fielddisplay(self,'output_ts_start','When to start writing meteo data out (offset, in days)');
+			fielddisplay(self,'output_ts_days_between','How often to write meteo data out (in days: 3 hours=.125, 1 hour=4.1666e-2)');
+			fielddisplay(self,'output_profile','How to write the profiles (default: ASCII, choice is ASCII,IMIS or ASCII IMIS)');
 )');
-			fielddisplay(obj,'output_prof_write','Write profile data out? (0 or 1) ');
-			fielddisplay(obj,'output_prof_start','When to start writing profile data out (offset, in days)');
-			fielddisplay(obj,'output_prof_days_between','How often to write profile data out (in days: 3 hours=.125, 1 hour=4.1666e-2)');
+			fielddisplay(self,'output_prof_write','Write profile data out? (0 or 1) ');
+			fielddisplay(self,'output_prof_start','When to start writing profile data out (offset, in days)');
+			fielddisplay(self,'output_prof_days_between','How often to write profile data out (in days: 3 hours=.125, 1 hour=4.1666e-2)');
 			% }}}
 			disp(sprintf('\n	%s','Interpolations1d parameters:')); % {{{
-			fielddisplay(obj,'interpolations1d_window_size','Affects resampling: expresses (in seconds) how far a valid point can be searched for when re-interpolating a missing value'); 
-			fielddisplay(obj,'interpolations1d_hnw_resample','NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR');
+			fielddisplay(self,'interpolations1d_window_size','Affects resampling: expresses (in seconds) how far a valid point can be searched for when re-interpolating a missing value'); 
+			fielddisplay(self,'interpolations1d_hnw_resample','NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR');
  ');
-			fielddisplay(obj,'interpolations1d_hs_resample','Mean average processing. The mean average filter returns the mean value of all values within a user given time window. (NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
-			fielddisplay(obj,'interpolations1d_tsg_resample','Mean average processing. The mean average filter returns the mean value of all values within a user given time window.(NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
-			fielddisplay(obj,'interpolations1d_rho_hn_resample','(NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
-			fielddisplay(obj,'interpolations1d_vw_resample','(NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
-			fielddisplay(obj,'interpolations1d_vw_args','default nothing, otherwise, ''extrapolcate''');
+			fielddisplay(self,'interpolations1d_hs_resample','Mean average processing. The mean average filter returns the mean value of all values within a user given time window. (NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
+			fielddisplay(self,'interpolations1d_tsg_resample','Mean average processing. The mean average filter returns the mean value of all values within a user given time window.(NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
+			fielddisplay(self,'interpolations1d_rho_hn_resample','(NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
+			fielddisplay(self,'interpolations1d_vw_resample','(NONE, NEAREST_NEIGHBOUR, ACCUMULATE or LINEAR)');
+			fielddisplay(self,'interpolations1d_vw_args','default nothing, otherwise, ''extrapolcate''');
 			% }}}
 			disp(sprintf('\n	%s','Filters parameters:')); % {{{
-			fielddisplay(obj,'filters_ta_filter1',' ');
-			fielddisplay(obj,'filters_ta_arg1','');
-			fielddisplay(obj,'filters_rh_filter1',' ');
-			fielddisplay(obj,'filters_rh_arg1','');
-			fielddisplay(obj,'filters_rh_filter2',' ');
-			fielddisplay(obj,'filters_rh_arg2','');
-			fielddisplay(obj,'filters_iswr_filter1',' ');
-			fielddisplay(obj,'filters_iswr_arg1','');
-			fielddisplay(obj,'filters_iswr_filter2',' ');
-			fielddisplay(obj,'filters_iswr_arg2','');
-			fielddisplay(obj,'filters_rswr_filter1',' ');
-			fielddisplay(obj,'filters_rswr_arg1','');
-			fielddisplay(obj,'filters_rswr_filter2',' ');
-			fielddisplay(obj,'filters_rswr_arg2','');
+			fielddisplay(self,'filters_ta_filter1',' ');
+			fielddisplay(self,'filters_ta_arg1','');
+			fielddisplay(self,'filters_rh_filter1',' ');
+			fielddisplay(self,'filters_rh_arg1','');
+			fielddisplay(self,'filters_rh_filter2',' ');
+			fielddisplay(self,'filters_rh_arg2','');
+			fielddisplay(self,'filters_iswr_filter1',' ');
+			fielddisplay(self,'filters_iswr_arg1','');
+			fielddisplay(self,'filters_iswr_filter2',' ');
+			fielddisplay(self,'filters_iswr_arg2','');
+			fielddisplay(self,'filters_rswr_filter1',' ');
+			fielddisplay(self,'filters_rswr_arg1','');
+			fielddisplay(self,'filters_rswr_filter2',' ');
+			fielddisplay(self,'filters_rswr_arg2','');
 
 			%for ta between 190 and 280 k;
-			fielddisplay(obj,'filters_ilwr_filter1',' ');
-			fielddisplay(obj,'filters_ilwr_arg1','');
-			fielddisplay(obj,'filters_ilwr_filter2',' ');
-			fielddisplay(obj,'filters_ilwr_arg2','');
-			fielddisplay(obj,'filters_tss_filter1',' ');
-			fielddisplay(obj,'filters_tss_arg1','');
-			fielddisplay(obj,'filters_tsg_filter1',' ');
-			fielddisplay(obj,'filters_tsg_arg1','');
-			fielddisplay(obj,'filters_vw_filter1',' ');
-			fielddisplay(obj,'filters_vw_arg1','');
-			fielddisplay(obj,'filters_vw_filter2',' ');
-			fielddisplay(obj,'filters_vw_arg2','');
+			fielddisplay(self,'filters_ilwr_filter1',' ');
+			fielddisplay(self,'filters_ilwr_arg1','');
+			fielddisplay(self,'filters_ilwr_filter2',' ');
+			fielddisplay(self,'filters_ilwr_arg2','');
+			fielddisplay(self,'filters_tss_filter1',' ');
+			fielddisplay(self,'filters_tss_arg1','');
+			fielddisplay(self,'filters_tsg_filter1',' ');
+			fielddisplay(self,'filters_tsg_arg1','');
+			fielddisplay(self,'filters_vw_filter1',' ');
+			fielddisplay(self,'filters_vw_arg1','');
+			fielddisplay(self,'filters_vw_filter2',' ');
+			fielddisplay(self,'filters_vw_arg2','');
 			% }}}
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','restol','format','Double');
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','reltol','format','Double');
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','abstol','format','Double');
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','isnewton','format','Integer');
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','FSreconditioning','format','Double');
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','viscosity_overshoot','format','Double');
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','maxiter','format','Integer');
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','shelf_dampening','format','Integer');
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','vertex_pairing','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','penalty_factor','format','Double');
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','rift_penalty_lock','format','Integer');
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','rift_penalty_threshold','format','Integer');
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','referential','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','snowpack','fieldname','requested_outputs','format','StringArray');
-			WriteData(fid,'data',obj.loadingforce(:,1),'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum);
-			WriteData(fid,'data',obj.loadingforce(:,2),'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum);
-			WriteData(fid,'data',obj.loadingforce(:,3),'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum);
+			WriteData(fid,'object',self,'class','snowpack','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','snowpack','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','snowpack','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','snowpack','fieldname','restol','format','Double');
+			WriteData(fid,'object',self,'class','snowpack','fieldname','reltol','format','Double');
+			WriteData(fid,'object',self,'class','snowpack','fieldname','abstol','format','Double');
+			WriteData(fid,'object',self,'class','snowpack','fieldname','isnewton','format','Integer');
+			WriteData(fid,'object',self,'class','snowpack','fieldname','FSreconditioning','format','Double');
+			WriteData(fid,'object',self,'class','snowpack','fieldname','viscosity_overshoot','format','Double');
+			WriteData(fid,'object',self,'class','snowpack','fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',self,'class','snowpack','fieldname','shelf_dampening','format','Integer');
+			WriteData(fid,'object',self,'class','snowpack','fieldname','vertex_pairing','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','snowpack','fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',self,'class','snowpack','fieldname','rift_penalty_lock','format','Integer');
+			WriteData(fid,'object',self,'class','snowpack','fieldname','rift_penalty_threshold','format','Integer');
+			WriteData(fid,'object',self,'class','snowpack','fieldname','referential','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','snowpack','fieldname','requested_outputs','format','StringArray');
+			WriteData(fid,'data',self.loadingforce(:,1),'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum);
+			WriteData(fid,'data',self.loadingforce(:,2),'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum);
+			WriteData(fid,'data',self.loadingforce(:,3),'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/spheremesh.m
===================================================================
--- /issm/trunk/src/m/classes/spheremesh.m	(revision 19104)
+++ /issm/trunk/src/m/classes/spheremesh.m	(revision 19105)
@@ -22,13 +22,13 @@
 	end
 	methods
-		function obj = spheremesh(varargin) % {{{
+		function self = spheremesh(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%the connectivity is the avergaded number of nodes linked to a
@@ -37,7 +37,7 @@
 			%give a good memory/time ration. This value can be checked in
 			%trunk/test/Miscellaneous/runme.m
-			obj.average_vertex_connectivity=25;
+			self.average_vertex_connectivity=25;
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			md = checkfield(md,'fieldname','spheremesh.x','NaN',1,'size',[md.spheremesh.numberofvertices 1]);
@@ -57,39 +57,39 @@
 			md = checkfield(md,'fieldname','spheremesh.elementconnectivity','size',[md.spheremesh.numberofelements 3],'NaN',1);
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   Mesh:')); 
 
 			disp(sprintf('\n      Elements and vertices:'));
-			fielddisplay(obj,'numberofelements','number of elements');
-			fielddisplay(obj,'numberofvertices','number of vertices');
-			fielddisplay(obj,'elements','vertex indices of the mesh elements');
-			fielddisplay(obj,'x','vertices x coordinate [m]');
-			fielddisplay(obj,'y','vertices y coordinate [m]');
-			fielddisplay(obj,'z','vertices z coordinate [m]');
-			fielddisplay(obj,'r','vertices r coordinate [m]');
-			fielddisplay(obj,'theta','vertices theta coordinate [degrees]');
-			fielddisplay(obj,'phi','vertices phi coordinate [degrees]');
+			fielddisplay(self,'numberofelements','number of elements');
+			fielddisplay(self,'numberofvertices','number of vertices');
+			fielddisplay(self,'elements','vertex indices of the mesh elements');
+			fielddisplay(self,'x','vertices x coordinate [m]');
+			fielddisplay(self,'y','vertices y coordinate [m]');
+			fielddisplay(self,'z','vertices z coordinate [m]');
+			fielddisplay(self,'r','vertices r coordinate [m]');
+			fielddisplay(self,'theta','vertices theta coordinate [degrees]');
+			fielddisplay(self,'phi','vertices phi coordinate [degrees]');
 
 			disp(sprintf('\n      Properties:'));
-			fielddisplay(obj,'numberoflayers','number of extrusion layers');
+			fielddisplay(self,'numberoflayers','number of extrusion layers');
 
-			fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
-			fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
-			fielddisplay(obj,'average_vertex_connectivity','average number of vertices connected to one vertex');
+			fielddisplay(self,'vertexconnectivity','list of vertices connected to vertex_i');
+			fielddisplay(self,'elementconnectivity','list of vertices connected to element_i');
+			fielddisplay(self,'average_vertex_connectivity','average number of vertices connected to one vertex');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','x','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','y','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','z','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','r','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','theta','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','phi','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','elements','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'fieldname','numberoflayers','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','numberofelements','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','numberofvertices','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','elementconnectivity','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'fieldname','average_vertex_connectivity','format','Integer');
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','x','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','y','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','z','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','r','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','theta','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','phi','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'fieldname','elements','format','DoubleMat','mattype',2);
+			WriteData(fid,'object',self,'fieldname','numberoflayers','format','Integer');
+			WriteData(fid,'object',self,'fieldname','numberofelements','format','Integer');
+			WriteData(fid,'object',self,'fieldname','numberofvertices','format','Integer');
+			WriteData(fid,'object',self,'fieldname','elementconnectivity','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'fieldname','average_vertex_connectivity','format','Integer');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/steadystate.m
===================================================================
--- /issm/trunk/src/m/classes/steadystate.m	(revision 19104)
+++ /issm/trunk/src/m/classes/steadystate.m	(revision 19105)
@@ -11,32 +11,32 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
+        function createxml(self,fid) % {{{
             fprintf(fid, '<!-- steadystate -->\n');            
                     
             % steadystate solution parameters
             fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="steadystate solution parameters">','<section name="steadystate" />');                    
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="reltol" type="',class(obj.reltol),'" default="',convert2str(obj.reltol),'">','     <section name="steadystate" />','     <help> relative tolerance criterion [K] </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="maxiter" type="',class(obj.maxiter),'" default="',convert2str(obj.maxiter),'">','     <section name="steadystate" />','     <help> maximum number of iterations </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="requested_outputs" type="',class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','     <section name="steadystate" />','     <help> additional requested outputs </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="reltol" type="',class(self.reltol),'" default="',convert2str(self.reltol),'">','     <section name="steadystate" />','     <help> relative tolerance criterion [K] </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="maxiter" type="',class(self.maxiter),'" default="',convert2str(self.maxiter),'">','     <section name="steadystate" />','     <help> maximum number of iterations </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="requested_outputs" type="',class(self.requested_outputs),'" default="',convert2str(self.requested_outputs),'">','     <section name="steadystate" />','     <help> additional requested outputs </help>','  </parameter>');
             fprintf(fid,'%s\n%s\n','</frame>');    
         
         end % }}}
-		function obj = steadystate(varargin) % {{{
+		function self = steadystate(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 			%maximum of steady state iterations
-			obj.maxiter=100;
+			self.maxiter=100;
 
 			%Relative tolerance for the steadystate convertgence
-			obj.reltol=0.01;
+			self.reltol=0.01;
 
 			%default output
-			obj.requested_outputs={'default'};
+			self.requested_outputs={'default'};
 		end % }}}
 		function list=defaultoutputs(self,md) % {{{
@@ -45,5 +45,5 @@
 
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
@@ -59,22 +59,22 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   steadystate solution parameters:'));
 
-			fielddisplay(obj,'reltol','relative tolerance criterion');
-			fielddisplay(obj,'maxiter','maximum number of iterations');
-			fielddisplay(obj,'requested_outputs','additional requested outputs');
+			fielddisplay(self,'reltol','relative tolerance criterion');
+			fielddisplay(self,'maxiter','maximum number of iterations');
+			fielddisplay(self,'requested_outputs','additional requested outputs');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','reltol','format','Double');
-			WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','reltol','format','Double');
+			WriteData(fid,'object',self,'fieldname','maxiter','format','Integer');
 
 			%process requested outputs
-			outputs = obj.requested_outputs;
+			outputs = self.requested_outputs;
 			pos  = find(ismember(outputs,'default'));
 			if ~isempty(pos),
 				outputs(pos) = [];                         %remove 'default' from outputs
-				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+				outputs      = [outputs defaultoutputs(self,md)]; %add defaults
 			end
 			WriteData(fid,'data',outputs,'enum',SteadystateRequestedOutputsEnum,'format','StringArray');
Index: /issm/trunk/src/m/classes/stressbalance.m
===================================================================
--- /issm/trunk/src/m/classes/stressbalance.m	(revision 19104)
+++ /issm/trunk/src/m/classes/stressbalance.m	(revision 19105)
@@ -26,52 +26,60 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- StressBalance solution parameters: -->');
-            
-            % Convergence criteria            
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Convergence criteria">','<section name="stressbalance" />'); 
-			 fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="restol" type="',      class(obj.restol),'" default="',        convert2str(obj.restol),'">',	'     <section name="stressbalance" />','     <help> mechanical equilibrium residual convergence criterion </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="reltol" type="',          class(obj.reltol),'" default="',            convert2str(obj.reltol),'">',     '     <section name="stressbalance" />','     <help> velocity relative convergence criterion, NaN: not applied </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',	'<parameter key ="abstol" type="',        class(obj.abstol),'" default="',          convert2str(obj.abstol),'">',	'     <section name="stressbalance" />','     <help> velocity absolute convergence criterion, NaN: not applied </help>','</parameter>');
-             
-             %is newton drop-down (0,1,or 2)
-             fprintf(fid,'%s\n%s\n%s\n%s\n',    '<parameter key ="isnewton" type="alternative" optional="false">',	'     <section name="stressbalance" />','     <help> 0: Picards fixed point, 1: Newtons method, 2: hybrid </help>');
-             fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
-             fprintf(fid,'%s\n','       <option value="1" type="string" default="false"> </option>');
-             fprintf(fid,'%s\n%s\n','       <option value="2" type="string" default="false"> </option>','</parameter>');
-    
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="maxiter" type="',  	class(obj.maxiter),'" default="',       convert2str(obj.maxiter),'">',     '     <section name="stressbalance" />','     <help> maximum number of nonlinear iterations </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="viscosity_overshoot" type="',         class(obj.viscosity_overshoot),'" default="',           convert2str(obj.viscosity_overshoot),'">',	'     <section name="stressbalance" />','     <help> over-shooting constant new=new+C*(new-old) </help>','</parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-            
-            % boundary conditions    
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Boundary conditions">','<section name="stressbalance" />'); 			 
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcvx" type="',     	class(obj.spcvx),'" default="',    	convert2str(obj.spcvx),'">',     '     <section name="stressbalance" />','     <help> x-axis velocity constraint (NaN means no constraint) [m/yr] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcvy" type="',     	class(obj.spcvy),'" default="',    	convert2str(obj.spcvy),'">',	'     <section name="stressbalance" />','     <help> y-axis velocity constraint (NaN means no constraint) [m/yr] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcvz" type="',    	class(obj.spcvz),'" default="',    	convert2str(obj.spcvz),'">',     '     <section name="stressbalance" />','     <help> z-axis velocity constraint (NaN means no constraint) [m/yr] </help>','</parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');
-            
-            % Rift options   
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Rift options">','<section name="stressbalance" />'); 	
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="rift_penalty_threshold" type="',    	class(obj.rift_penalty_threshold),'" default="',       convert2str(obj.rift_penalty_threshold),'">',     '     <section name="stressbalance" />','     <help> threshold for instability of mechanical constraints </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    	'<parameter key ="rift_penalty_lock" type="',         class(obj.rift_penalty_lock),'" default="',           convert2str(obj.rift_penalty_lock),'">',	'     <section name="stressbalance" />','     <help> number of iterations before rift penalties are locked </help>','</parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>'); 
-            
-            %others
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Other">','<section name="stressbalance" />'); 	
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="shelf_dampening" type="',  	class(obj.shelf_dampening),'" default="',       convert2str(obj.shelf_dampening),'">',     '     <section name="stressbalance" />','     <help> use dampening for floating ice ? Only for FS model </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',  	'<parameter key ="FSreconditioning" type="', 	class(obj.FSreconditioning),'" default="',           convert2str(obj.FSreconditioning),'">',	'     <section name="stressbalance" />','     <help> multiplier for incompressibility equation. Only for FS model </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="referential" type="',  	class(obj.referential),'" default="',       convert2str(obj.referential),'">',     '     <section name="stressbalance" />','     <help> local referential </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',  	'<parameter key ="loadingforce" type="', 	class(obj.loadingforce),'" default="',           convert2str(obj.loadingforce),'">',	'     <section name="stressbalance" />','     <help> loading force applied on each point [N/m^3] </help>','</parameter>');
-             fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="requested_outputs" type="',  	class(obj.requested_outputs),'" default="',       convert2str(obj.requested_outputs),'">',     '     <section name="stressbalance" />','     <help> additional outputs requested </help>','</parameter>');
-             
-            
-            fprintf(fid,'%s\n%s\n','</frame>'); 
-        end % }}}
-		function obj = stressbalance(varargin) % {{{
+		function createxml(self,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- StressBalance solution parameters: -->');
+
+			% Convergence criteria            
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Convergence criteria">','<section name="stressbalance" />'); 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="restol" type="',      class(self.restol),'" default="',        convert2str(self.restol),'">',	'     <section name="stressbalance" />','     <help> mechanical equilibrium residual convergence criterion </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="reltol" type="',          class(self.reltol),'" default="',            convert2str(self.reltol),'">',     '     <section name="stressbalance" />','     <help> velocity relative convergence criterion, NaN: not applied </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',	'<parameter key ="abstol" type="',        class(self.abstol),'" default="',          convert2str(self.abstol),'">',	'     <section name="stressbalance" />','     <help> velocity absolute convergence criterion, NaN: not applied </help>','</parameter>');
+
+			%is newton drop-down (0,1,or 2)
+			fprintf(fid,'%s\n%s\n%s\n%s\n',    '<parameter key ="isnewton" type="alternative" optional="false">',	'     <section name="stressbalance" />','     <help> 0: Picards fixed point, 1: Newtons method, 2: hybrid </help>');
+			fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="1" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="2" type="string" default="false"> </option>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="maxiter" type="',  	class(self.maxiter),'" default="',       convert2str(self.maxiter),'">',     '     <section name="stressbalance" />','     <help> maximum number of nonlinear iterations </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="viscosity_overshoot" type="',         class(self.viscosity_overshoot),'" default="',           convert2str(self.viscosity_overshoot),'">',	'     <section name="stressbalance" />','     <help> over-shooting constant new=new+C*(new-old) </help>','</parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			% boundary conditions    
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="2" label="Boundary conditions">','<section name="stressbalance" />'); 			 
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcvx" type="',     	class(self.spcvx),'" default="',    	convert2str(self.spcvx),'">',     '     <section name="stressbalance" />','     <help> x-axis velocity constraint (NaN means no constraint) [m/yr] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcvy" type="',     	class(self.spcvy),'" default="',    	convert2str(self.spcvy),'">',	'     <section name="stressbalance" />','     <help> y-axis velocity constraint (NaN means no constraint) [m/yr] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="spcvz" type="',    	class(self.spcvz),'" default="',    	convert2str(self.spcvz),'">',     '     <section name="stressbalance" />','     <help> z-axis velocity constraint (NaN means no constraint) [m/yr] </help>','</parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');
+
+			% Rift options   
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="3" label="Rift options">','<section name="stressbalance" />'); 	
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="rift_penalty_threshold" type="',    	class(self.rift_penalty_threshold),'" default="',       convert2str(self.rift_penalty_threshold),'">',     '     <section name="stressbalance" />','     <help> threshold for instability of mechanical constraints </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    	'<parameter key ="rift_penalty_lock" type="',         class(self.rift_penalty_lock),'" default="',           convert2str(self.rift_penalty_lock),'">',	'     <section name="stressbalance" />','     <help> number of iterations before rift penalties are locked </help>','</parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>'); 
+
+			%others
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="4" label="Other">','<section name="stressbalance" />'); 	
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="shelf_dampening" type="',  	class(self.shelf_dampening),'" default="',       convert2str(self.shelf_dampening),'">',     '     <section name="stressbalance" />','     <help> use dampening for floating ice ? Only for FS model </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',  	'<parameter key ="FSreconditioning" type="', 	class(self.FSreconditioning),'" default="',           convert2str(self.FSreconditioning),'">',	'     <section name="stressbalance" />','     <help> multiplier for incompressibility equation. Only for FS model </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="referential" type="',  	class(self.referential),'" default="',       convert2str(self.referential),'">',     '     <section name="stressbalance" />','     <help> local referential </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',  	'<parameter key ="loadingforce" type="', 	class(self.loadingforce),'" default="',           convert2str(self.loadingforce),'">',	'     <section name="stressbalance" />','     <help> loading force applied on each point [N/m^3] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="requested_outputs" type="',  	class(self.requested_outputs),'" default="',       convert2str(self.requested_outputs),'">',     '     <section name="stressbalance" />','     <help> additional outputs requested </help>','</parameter>');
+
+
+			fprintf(fid,'%s\n%s\n','</frame>'); 
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.spcvx=project3d(md,'vector',self.spcvx,'type','node');
+			self.spcvy=project3d(md,'vector',self.spcvy,'type','node');
+			self.spcvz=project3d(md,'vector',self.spcvz,'type','node');
+			self.referential=project3d(md,'vector',self.referential,'type','node');
+			self.loadingforce=project3d(md,'vector',self.loadingforce,'type','node');
+
+		end % }}}
+		function self = stressbalance(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
 					inputstruct=varargin{1};
@@ -81,5 +89,5 @@
 						fieldname = list1{i};
 						if ismember(fieldname,list2),
-							obj.(fieldname) = inputstruct.(fieldname);
+							self.(fieldname) = inputstruct.(fieldname);
 						end
 					end
@@ -88,45 +96,45 @@
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			 %maximum of non-linear iterations.
-			 obj.maxiter=100;
+			 self.maxiter=100;
 
 			 %Convergence criterion: absolute, relative and residual
-			 obj.restol=10^-4; 
-			 obj.reltol=0.01;
-			 obj.abstol=10;
-
-			 obj.FSreconditioning=10^13;
-			 obj.shelf_dampening=0;
+			 self.restol=10^-4; 
+			 self.reltol=0.01;
+			 self.abstol=10;
+
+			 self.FSreconditioning=10^13;
+			 self.shelf_dampening=0;
 
 			 %Penalty factor applied kappa=max(stiffness matrix)*10^penalty_factor
-			 obj.penalty_factor=3;
+			 self.penalty_factor=3;
 
 			 %coefficient to update the viscosity between each iteration of
 			 %a stressbalance according to the following formula
 			 %viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
-			 obj.viscosity_overshoot=0;
+			 self.viscosity_overshoot=0;
 
 			 %Stop the iterations of rift if below a threshold
-			 obj.rift_penalty_threshold=0;
+			 self.rift_penalty_threshold=0;
 
 			 %in some solutions, it might be needed to stop a run when only
 			 %a few constraints remain unstable. For thermal computation, this
 			 %parameter is often used.
-			 obj.rift_penalty_lock=10;
+			 self.rift_penalty_lock=10;
 
 			 %output default:
-			 obj.requested_outputs={'default'};
-
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			 self.requested_outputs={'default'};
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
 			if ~ismember(StressbalanceAnalysisEnum(),analyses), return; end
 
-			md = checkfield(md,'fieldname','stressbalance.spcvx','forcing',1);
-			md = checkfield(md,'fieldname','stressbalance.spcvy','forcing',1);
-			md = checkfield(md,'fieldname','stressbalance.spcvz','forcing',1);
+			md = checkfield(md,'fieldname','stressbalance.spcvx','timeseries',1);
+			md = checkfield(md,'fieldname','stressbalance.spcvy','timeseries',1);
+			md = checkfield(md,'fieldname','stressbalance.spcvz','timeseries',1);
 			md = checkfield(md,'fieldname','stressbalance.restol','size',[1 1],'>',0,'NaN',1);
 			md = checkfield(md,'fieldname','stressbalance.reltol','size',[1 1]);
@@ -141,5 +149,5 @@
 
 			%singular solution
-			if ~(any(~isnan(md.stressbalance.spcvx)) | any(~isnan(md.stressbalance.spcvy))),
+			if ((~(any(~isnan(md.stressbalance.spcvx)) | any(~isnan(md.stressbalance.spcvy)))) & ~any(md.mask.groundedice_levelset>0)),
 				md = checkmessage(md,['model is not well posed (singular). You need at least one node with fixed velocity!']);
 			end
@@ -175,68 +183,69 @@
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 
 			disp(sprintf('   StressBalance solution parameters:'));
 
 			disp(sprintf('\n      %s','Convergence criteria:'));
-			fielddisplay(obj,'restol','mechanical equilibrium residual convergence criterion');
-			fielddisplay(obj,'reltol','velocity relative convergence criterion, NaN: not applied');
-			fielddisplay(obj,'abstol','velocity absolute convergence criterion, NaN: not applied');
-			fielddisplay(obj,'isnewton','0: Picard''s fixed point, 1: Newton''s method, 2: hybrid');
-			fielddisplay(obj,'maxiter','maximum number of nonlinear iterations');
-			fielddisplay(obj,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)');
+			fielddisplay(self,'restol','mechanical equilibrium residual convergence criterion');
+			fielddisplay(self,'reltol','velocity relative convergence criterion, NaN: not applied');
+			fielddisplay(self,'abstol','velocity absolute convergence criterion, NaN: not applied');
+			fielddisplay(self,'isnewton','0: Picard''s fixed point, 1: Newton''s method, 2: hybrid');
+			fielddisplay(self,'maxiter','maximum number of nonlinear iterations');
+			fielddisplay(self,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)');
 
 			disp(sprintf('\n      %s','boundary conditions:'));
-			fielddisplay(obj,'spcvx','x-axis velocity constraint (NaN means no constraint) [m/yr]');
-			fielddisplay(obj,'spcvy','y-axis velocity constraint (NaN means no constraint) [m/yr]');
-			fielddisplay(obj,'spcvz','z-axis velocity constraint (NaN means no constraint) [m/yr]');
+			fielddisplay(self,'spcvx','x-axis velocity constraint (NaN means no constraint) [m/yr]');
+			fielddisplay(self,'spcvy','y-axis velocity constraint (NaN means no constraint) [m/yr]');
+			fielddisplay(self,'spcvz','z-axis velocity constraint (NaN means no constraint) [m/yr]');
 
 			disp(sprintf('\n      %s','Rift options:'));
-			fielddisplay(obj,'rift_penalty_threshold','threshold for instability of mechanical constraints');
-			fielddisplay(obj,'rift_penalty_lock','number of iterations before rift penalties are locked');
+			fielddisplay(self,'rift_penalty_threshold','threshold for instability of mechanical constraints');
+			fielddisplay(self,'rift_penalty_lock','number of iterations before rift penalties are locked');
 
 			disp(sprintf('\n      %s','Penalty options:'));
-			fielddisplay(obj,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset');
-			fielddisplay(obj,'vertex_pairing','pairs of vertices that are penalized');
+			fielddisplay(self,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset');
+			fielddisplay(self,'vertex_pairing','pairs of vertices that are penalized');
 
 			disp(sprintf('\n      %s','Other:'));
-			fielddisplay(obj,'shelf_dampening','use dampening for floating ice ? Only for FS model');
-			fielddisplay(obj,'FSreconditioning','multiplier for incompressibility equation. Only for FS model');
-			fielddisplay(obj,'referential','local referential');
-			fielddisplay(obj,'loadingforce','loading force applied on each point [N/m^3]');
-			fielddisplay(obj,'requested_outputs','additional outputs requested');
-
-		end % }}}
-		function marshall(obj,md,fid) % {{{
+			fielddisplay(self,'shelf_dampening','use dampening for floating ice ? Only for FS model');
+			fielddisplay(self,'FSreconditioning','multiplier for incompressibility equation. Only for FS model');
+			fielddisplay(self,'referential','local referential');
+			fielddisplay(self,'loadingforce','loading force applied on each point [N/m^3]');
+			fielddisplay(self,'requested_outputs','additional outputs requested');
+
+		end % }}}
+		function marshall(self,md,fid) % {{{
+
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','vertex_pairing','format','DoubleMat','mattype',3);
 
 			yts=365.0*24.0*3600.0;
 
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','restol','format','Double');
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','reltol','format','Double');
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','abstol','format','Double');
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','isnewton','format','Integer');
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','FSreconditioning','format','Double');
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','viscosity_overshoot','format','Double');
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','maxiter','format','Integer');
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','shelf_dampening','format','Integer');
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','vertex_pairing','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','penalty_factor','format','Double');
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','rift_penalty_lock','format','Integer');
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','rift_penalty_threshold','format','Integer');
-			WriteData(fid,'object',obj,'class','stressbalance','fieldname','referential','format','DoubleMat','mattype',1);
-
-			WriteData(fid,'data',obj.loadingforce(:,1),'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum);
-			WriteData(fid,'data',obj.loadingforce(:,2),'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum);
-			WriteData(fid,'data',obj.loadingforce(:,3),'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum);
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','restol','format','Double');
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','reltol','format','Double');
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','abstol','format','Double','scale',1./yts);
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','isnewton','format','Integer');
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','FSreconditioning','format','Double');
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','viscosity_overshoot','format','Double');
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','shelf_dampening','format','Integer');
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','rift_penalty_lock','format','Integer');
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','rift_penalty_threshold','format','Integer');
+			WriteData(fid,'object',self,'class','stressbalance','fieldname','referential','format','DoubleMat','mattype',1);
+
+			WriteData(fid,'data',self.loadingforce(:,1),'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum);
+			WriteData(fid,'data',self.loadingforce(:,2),'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum);
+			WriteData(fid,'data',self.loadingforce(:,3),'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum);
 
 			%process requested outputs
-			outputs = obj.requested_outputs;
+			outputs = self.requested_outputs;
 			pos  = find(ismember(outputs,'default'));
 			if ~isempty(pos),
 				outputs(pos) = [];                         %remove 'default' from outputs
-				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+				outputs      = [outputs defaultoutputs(self,md)]; %add defaults
 			end
 			WriteData(fid,'data',outputs,'enum',StressbalanceRequestedOutputsEnum,'format','StringArray');
Index: /issm/trunk/src/m/classes/stressbalance.py
===================================================================
--- /issm/trunk/src/m/classes/stressbalance.py	(revision 19104)
+++ /issm/trunk/src/m/classes/stressbalance.py	(revision 19105)
@@ -2,4 +2,5 @@
 import sys
 import copy
+from project3d import project3d
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -75,4 +76,13 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.spcvx=project3d(md,'vector',self.spcvx,'type','node')
+		self.spcvy=project3d(md,'vector',self.spcvy,'type','node')
+		self.spcvz=project3d(md,'vector',self.spcvz,'type','node')
+		self.referential=project3d(md,'vector',self.referential,'type','node')
+		self.loadingforce=project3d(md,'vector',self.loadingforce,'type','node')
+
+		return self
+	#}}}
 	def setdefaultparameters(self): # {{{
 		#maximum of non-linear iterations.
@@ -123,8 +133,8 @@
 			return md
 
-		md = checkfield(md,'fieldname','stressbalance.spcvx','forcing',1)
-		md = checkfield(md,'fieldname','stressbalance.spcvy','forcing',1)
+		md = checkfield(md,'fieldname','stressbalance.spcvx','timeseries',1)
+		md = checkfield(md,'fieldname','stressbalance.spcvy','timeseries',1)
 		if m.strcmp(md.mesh.domaintype(),'3D'):
-			md = checkfield(md,'fieldname','stressbalance.spcvz','forcing',1)
+			md = checkfield(md,'fieldname','stressbalance.spcvz','timeseries',1)
 		md = checkfield(md,'fieldname','stressbalance.restol','size',[1],'>',0)
 		md = checkfield(md,'fieldname','stressbalance.reltol','size',[1])
@@ -168,10 +178,10 @@
 		yts=365.0*24.0*3600.0
 
-		WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
 		WriteData(fid,'object',self,'class','stressbalance','fieldname','restol','format','Double')
 		WriteData(fid,'object',self,'class','stressbalance','fieldname','reltol','format','Double')
-		WriteData(fid,'object',self,'class','stressbalance','fieldname','abstol','format','Double')
+		WriteData(fid,'object',self,'class','stressbalance','fieldname','abstol','format','Double','scale',1./yts)
 		WriteData(fid,'object',self,'class','stressbalance','fieldname','isnewton','format','Integer')
 		WriteData(fid,'object',self,'class','stressbalance','fieldname','FSreconditioning','format','Double')
Index: /issm/trunk/src/m/classes/taoinversion.m
===================================================================
--- /issm/trunk/src/m/classes/taoinversion.m	(revision 19104)
+++ /issm/trunk/src/m/classes/taoinversion.m	(revision 19105)
@@ -26,47 +26,63 @@
 		vel_obs                     = NaN
 		thickness_obs               = NaN
+		surface_obs               = NaN
 	end
 	methods
-		function obj = taoinversion(varargin) % {{{
+		function self = extrude(self,md) % {{{
+			self.vx_obs=project3d(md,'vector',self.vx_obs,'type','node');
+			self.vy_obs=project3d(md,'vector',self.vy_obs,'type','node');
+			self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node');
+			self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node');
+			if numel(self.cost_functions_coefficients)>1,self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node');end;
+			if numel(self.min_parameters)>1,self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node');end;
+			if numel(self.max_parameters)>1,self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node');end;
+		end % }}}
+		function self = taoinversion(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				case 1
-					obj=structtoobj(taoinversion(),varargin{1});
+					self=structtoobj(taoinversion(),varargin{1});
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%default is incomplete adjoint for now
-			obj.incomplete_adjoint=1;
+			self.incomplete_adjoint=1;
 
 			%parameter to be inferred by control methods (only
 			%drag and B are supported yet)
-			obj.control_parameters={'FrictionCoefficient'};
+			self.control_parameters={'FrictionCoefficient'};
 
 			%number of iterations and steps
-			obj.maxsteps=20;
-			obj.maxiter =30;
+			self.maxsteps=20;
+			self.maxiter =30;
 
 			%default tolerances
-			obj.fatol = 0;
-			obj.frtol = 0;
-			obj.gatol = 0;
-			obj.grtol = 0;
-			obj.gttol = 1e-4;
+			self.fatol = 0;
+			self.frtol = 0;
+			self.gatol = 0;
+			self.grtol = 0;
+			self.gttol = 1e-4;
 
 			%minimization algorithm
-			obj.algorithm = 'tao_blmvm';
+			PETSCMAJOR = IssmConfig('_PETSC_MAJOR_');
+			PETSCMINOR = IssmConfig('_PETSC_MINOR_');
+			if(PETSCMAJOR>3 | (PETSCMAJOR==3 & PETSCMINOR>=5))
+				self.algorithm = 'blmvm';
+			else
+				self.algorithm = 'tao_blmvm';
+			end
 
 			%several responses can be used:
-			obj.cost_functions=101;
-
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			self.cost_functions=101;
+
+		end % }}}
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
-			if ~obj.iscontrol, return; end
+			if ~self.iscontrol, return; end
 
 			if ~IssmConfig('_HAVE_TAO_'),
@@ -79,6 +95,5 @@
 			md = checkfield(md,'fieldname','inversion.iscontrol','values',[0 1]);
 			md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0 1]);
-			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',...
-				{'BalancethicknessThickeningRate' 'FrictionCoefficient' 'MaterialsRheologyBbar' 'MaterialsRheologyZbar' 'Vx' 'Vy' 'Thickness'});
+			md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',supportedcontrols());
 			md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0);
 			md = checkfield(md,'fieldname','inversion.maxiter','numel',1,'>=',0);
@@ -88,6 +103,14 @@
 			md = checkfield(md,'fieldname','inversion.grtol','numel',1,'>=',0);
 			md = checkfield(md,'fieldname','inversion.gttol','numel',1,'>=',0);
-			md = checkfield(md,'fieldname','inversion.algorithm','values',{'tao_blmvm','tao_cg','tao_lmvm'});
-			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',[101:105 201 501:506]);
+
+			PETSCMAJOR = IssmConfig('_PETSC_MAJOR_');
+			PETSCMINOR = IssmConfig('_PETSC_MINOR_');
+			if(PETSCMAJOR>3 | (PETSCMAJOR==3 & PETSCMINOR>=5))
+				md = checkfield(md,'fieldname','inversion.algorithm','values',{'blmvm','cg','lmvm'});
+			else
+				md = checkfield(md,'fieldname','inversion.algorithm','values',{'tao_blmvm','tao_cg','tao_lmvm'});
+			end
+
+			md = checkfield(md,'fieldname','inversion.cost_functions','size',[1 num_costfunc],'values',supportedcostfunctions());
 			md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices num_costfunc],'>=',0);
 			md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
@@ -103,25 +126,26 @@
 			end
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   taoinversion parameters:'));
-			fielddisplay(obj,'iscontrol','is inversion activated?');
-			fielddisplay(obj,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
-			fielddisplay(obj,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
-			fielddisplay(obj,'maxsteps','maximum number of iterations (gradient computation)');
-			fielddisplay(obj,'maxiter','maximum number of Function evaluation (forward run)');
-			fielddisplay(obj,'fatol','convergence criterion: f(X)-f(X*) (X: current iteration, X*: "true" solution, f: cost function)');
-			fielddisplay(obj,'frtol','convergence criterion: |f(X)-f(X*)|/|f(X*)|');
-			fielddisplay(obj,'gatol','convergence criterion: ||g(X)|| (g: gradient of the cost function)');
-			fielddisplay(obj,'grtol','convergence criterion: ||g(X)||/|f(X)|');
-			fielddisplay(obj,'gttol','convergence criterion: ||g(X)||/||g(X0)|| (g(X0): gradient at initial guess X0)');
-			fielddisplay(obj,'algorithm','minimization algorithm: ''tao_blmvm'', ''tao_cg'', ''tao_lmvm''');
-			fielddisplay(obj,'cost_functions','indicate the type of response for each optimization step');
-			fielddisplay(obj,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
-			fielddisplay(obj,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
-			fielddisplay(obj,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
-			fielddisplay(obj,'vx_obs','observed velocity x component [m/yr]');
-			fielddisplay(obj,'vy_obs','observed velocity y component [m/yr]');
-			fielddisplay(obj,'vel_obs','observed velocity magnitude [m/yr]');
-			fielddisplay(obj,'thickness_obs','observed thickness [m]');
+			fielddisplay(self,'iscontrol','is inversion activated?');
+			fielddisplay(self,'incomplete_adjoint','1: linear viscosity, 0: non-linear viscosity');
+			fielddisplay(self,'control_parameters','ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}');
+			fielddisplay(self,'maxsteps','maximum number of iterations (gradient computation)');
+			fielddisplay(self,'maxiter','maximum number of Function evaluation (forward run)');
+			fielddisplay(self,'fatol','convergence criterion: f(X)-f(X*) (X: current iteration, X*: "true" solution, f: cost function)');
+			fielddisplay(self,'frtol','convergence criterion: |f(X)-f(X*)|/|f(X*)|');
+			fielddisplay(self,'gatol','convergence criterion: ||g(X)|| (g: gradient of the cost function)');
+			fielddisplay(self,'grtol','convergence criterion: ||g(X)||/|f(X)|');
+			fielddisplay(self,'gttol','convergence criterion: ||g(X)||/||g(X0)|| (g(X0): gradient at initial guess X0)');
+			fielddisplay(self,'algorithm','minimization algorithm: ''tao_blmvm'', ''tao_cg'', ''tao_lmvm''');
+			fielddisplay(self,'cost_functions','indicate the type of response for each optimization step');
+			fielddisplay(self,'cost_functions_coefficients','cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter');
+			fielddisplay(self,'min_parameters','absolute minimum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'max_parameters','absolute maximum acceptable value of the inversed parameter on each vertex');
+			fielddisplay(self,'vx_obs','observed velocity x component [m/yr]');
+			fielddisplay(self,'vy_obs','observed velocity y component [m/yr]');
+			fielddisplay(self,'vel_obs','observed velocity magnitude [m/yr]');
+			fielddisplay(self,'thickness_obs','observed thickness [m]');
+			fielddisplay(self,'surface_obs','observed surface elevation [m]');
 			disp('Available cost functions:');
 			disp('   101: SurfaceAbsVelMisfit');
@@ -135,33 +159,34 @@
 			disp('   503: ThicknessAbsGradient');
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
 			yts=365.0*24.0*3600.0;
 
-			WriteData(fid,'object',obj,'class','inversion','fieldname','iscontrol','format','Boolean');
+			WriteData(fid,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean');
 			WriteData(fid,'enum',InversionTypeEnum(),'data',1,'format','Integer');
-			if ~obj.iscontrol, return; end
-			WriteData(fid,'object',obj,'class','inversion','fieldname','incomplete_adjoint','format','Boolean');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','maxsteps','format','Integer');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','maxiter','format','Integer');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','fatol','format','Double');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','frtol','format','Double');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','gatol','format','Double');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','grtol','format','Double');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','gttol','format','Double');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','algorithm','format','String');
-			WriteData(fid,'object',obj,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1);
+			if ~self.iscontrol, return; end
+			WriteData(fid,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean');
+			WriteData(fid,'object',self,'class','inversion','fieldname','maxsteps','format','Integer');
+			WriteData(fid,'object',self,'class','inversion','fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',self,'class','inversion','fieldname','fatol','format','Double');
+			WriteData(fid,'object',self,'class','inversion','fieldname','frtol','format','Double');
+			WriteData(fid,'object',self,'class','inversion','fieldname','gatol','format','Double');
+			WriteData(fid,'object',self,'class','inversion','fieldname','grtol','format','Double');
+			WriteData(fid,'object',self,'class','inversion','fieldname','gttol','format','Double');
+			WriteData(fid,'object',self,'class','inversion','fieldname','algorithm','format','String');
+			WriteData(fid,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts);
+			WriteData(fid,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',1);
 
 			%process control parameters
-			num_control_parameters=numel(obj.control_parameters);
+			num_control_parameters=numel(self.control_parameters);
 			data=zeros(1,num_control_parameters);
 			for i=1:num_control_parameters,
-				data(i)=StringToEnum(obj.control_parameters{i});
+				data(i)=StringToEnum(self.control_parameters{i});
 			end
 			WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3);
@@ -169,19 +194,6 @@
 
 			%process cost functions
-			num_cost_functions=size(obj.cost_functions,2);
-			data=obj.cost_functions;
-			pos=find(obj.cost_functions==101); data(pos)=SurfaceAbsVelMisfitEnum();
-			pos=find(obj.cost_functions==102); data(pos)=SurfaceRelVelMisfitEnum();
-			pos=find(obj.cost_functions==103); data(pos)=SurfaceLogVelMisfitEnum();
-			pos=find(obj.cost_functions==104); data(pos)=SurfaceLogVxVyMisfitEnum();
-			pos=find(obj.cost_functions==105); data(pos)=SurfaceAverageVelMisfitEnum();
-			pos=find(obj.cost_functions==201); data(pos)=ThicknessAbsMisfitEnum();
-			pos=find(obj.cost_functions==501); data(pos)=DragCoefficientAbsGradientEnum();
-			pos=find(obj.cost_functions==502); data(pos)=RheologyBbarAbsGradientEnum();
-			pos=find(obj.cost_functions==503); data(pos)=ThicknessAbsGradientEnum();
-			pos=find(obj.cost_functions==504); data(pos)=ThicknessAlongGradientEnum();
-			pos=find(obj.cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
-			pos=find(obj.cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
-			pos=find(obj.cost_functions==507); data(pos)=Balancethickness2MisfitEnum();
+			num_cost_functions=size(self.cost_functions,2);
+			data=marshallcostfunctions(self.cost_functions);
 			WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3);
 			WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer');
Index: /issm/trunk/src/m/classes/thermal.m
===================================================================
--- /issm/trunk/src/m/classes/thermal.m	(revision 19104)
+++ /issm/trunk/src/m/classes/thermal.m	(revision 19105)
@@ -9,4 +9,5 @@
 		penalty_threshold = 0;
 		stabilization     = 0;
+		reltol				= 0;
 		maxiter           = 0;
 		penalty_lock      = 0;
@@ -17,31 +18,40 @@
 	end
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '<!-- thermal -->\n');            
-                    
-            % thermal solution parameters
-            fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Thermal solution parameters">','<section name="thermal" />');                    
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="spctemperature" type="',class(obj.spctemperature),'" default="',convert2str(obj.spctemperature),'">','     <section name="thermal" />','     <help> temperature constraints (NaN means no constraint) [K] </help>','  </parameter>');
-                
-            % penalty_threshold drop-down (0, 1, or 2)
-            fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="penalty_threshold" type="alternative"  optional="false">','     <section name="thermal" />','     <help> 0: no, 1: artificial_diffusivity, 2: SUPG </help>');
-            fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
-            fprintf(fid,'%s\n','       <option value="1" type="string" default="false"> </option>');
-            fprintf(fid,'%s\n%s\n','       <option value="2" type="string" default="false"> </option>','</parameter>');
+		function createxml(self,fid) % {{{
+			fprintf(fid, '<!-- thermal -->\n');            
 
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="stabilization" type="',class(obj.stabilization),'" default="',convert2str(obj.stabilization),'">','     <section name="thermal" />','     <help> maximum number of non linear iterations </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="maxiter" type="',class(obj.maxiter),'" default="',convert2str(obj.maxiter),'">','     <section name="thermal" />','     <help> stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="penalty_lock" type="',class(obj.penalty_lock),'" default="',convert2str(obj.penalty_lock),'">','     <section name="thermal" />','     <help> threshold to declare convergence of thermal solution (default is 0)  </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="penalty_factor" type="',class(obj.penalty_factor),'" default="',convert2str(obj.penalty_factor),'">','     <section name="thermal" />','     <help> scaling exponent (default is 3) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isenthalpy" type="',class(obj.isenthalpy),'" default="',convert2str(obj.isenthalpy),'">','     <section name="thermal" />','     <help> use an enthalpy formulation to include temperate ice (default is 0) </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isdynamicbasalspc" type="',class(obj.isdynamicbasalspc),'" default="',convert2str(obj.isdynamicbasalspc),'">','     <section name="thermal" />','     <help> enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)  </help>','  </parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="requested_outputs" type="',class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','     <section name="thermal" />','     <help> additional outputs requested </help>','  </parameter>');
-            fprintf(fid,'%s\n%s\n','</frame>');    
-        
-        end % }}}
-		function obj = thermal(varargin) % {{{
+			% thermal solution parameters
+			fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="Thermal solution parameters">','<section name="thermal" />');                    
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="spctemperature" type="',class(self.spctemperature),'" default="',convert2str(self.spctemperature),'">','     <section name="thermal" />','     <help> temperature constraints (NaN means no constraint) [K] </help>','  </parameter>');
+
+			% penalty_threshold drop-down (0, 1, or 2)
+			fprintf(fid,'%s\n%s\n%s\n%s\n','  <parameter key ="penalty_threshold" type="alternative"  optional="false">','     <section name="thermal" />','     <help> 0: no, 1: artificial_diffusivity, 2: SUPG </help>');
+			fprintf(fid,'%s\n','       <option value="0" type="string" default="true"> </option>');
+			fprintf(fid,'%s\n','       <option value="1" type="string" default="false"> </option>');
+			fprintf(fid,'%s\n%s\n','       <option value="2" type="string" default="false"> </option>','</parameter>');
+
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="stabilization" type="',class(self.stabilization),'" default="',convert2str(self.stabilization),'">','     <section name="thermal" />','     <help> maximum number of non linear iterations </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="reltol" type="',class(self.reltol),'" default="',convert2str(self.reltol),'">','     <section name="steadystate" />','     <help> relative tolerance criterion [K] </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="maxiter" type="',class(self.maxiter),'" default="',convert2str(self.maxiter),'">','     <section name="thermal" />','     <help> stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="penalty_lock" type="',class(self.penalty_lock),'" default="',convert2str(self.penalty_lock),'">','     <section name="thermal" />','     <help> threshold to declare convergence of thermal solution (default is 0)  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="penalty_factor" type="',class(self.penalty_factor),'" default="',convert2str(self.penalty_factor),'">','     <section name="thermal" />','     <help> scaling exponent (default is 3) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isenthalpy" type="',class(self.isenthalpy),'" default="',convert2str(self.isenthalpy),'">','     <section name="thermal" />','     <help> use an enthalpy formulation to include temperate ice (default is 0) </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isdynamicbasalspc" type="',class(self.isdynamicbasalspc),'" default="',convert2str(self.isdynamicbasalspc),'">','     <section name="thermal" />','     <help> enable dynamic setting of basal forcing. recommended for enthalpy formulation (default is 0)  </help>','  </parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="requested_outputs" type="',class(self.requested_outputs),'" default="',convert2str(self.requested_outputs),'">','     <section name="thermal" />','     <help> additional outputs requested </help>','  </parameter>');
+			fprintf(fid,'%s\n%s\n','</frame>');    
+
+		end % }}}
+		function self = extrude(self,md) % {{{
+			self.spctemperature=project3d(md,'vector',self.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',NaN);
+			if (length(md.initialization.temperature)==md.mesh.numberofvertices),
+				self.spctemperature=NaN(md.mesh.numberofvertices,1);
+				pos=find(md.mesh.vertexonsurface);
+				self.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+			end
+		end % }}}
+		function self = thermal(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
@@ -57,28 +67,31 @@
 
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%Number of unstable constraints acceptable
-			obj.penalty_threshold=0;
+			self.penalty_threshold=0;
 
 			%Type of stabilization used
-			obj.stabilization=1;
+			self.stabilization=1;
+
+			%Relative tolerance for the enthalpy convergence
+			self.reltol=0.01;
 
 			%Maximum number of iterations
-			obj.maxiter=100;
+			self.maxiter=100;
 
 			%factor used to compute the values of the penalties: kappa=max(stiffness matrix)*10^penalty_factor
-			obj.penalty_factor=3;
+			self.penalty_factor=3;
 
 			%Should we use cold ice (default) or enthalpy formulation
-			obj.isenthalpy=0;
+			self.isenthalpy=0;
 
 			%will basal boundary conditions be set dynamically
-			obj.isdynamicbasalspc=0;
+			self.isdynamicbasalspc=0;
 
 			%default output
-			obj.requested_outputs={'default'};
+			self.requested_outputs={'default'};
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
@@ -86,13 +99,16 @@
 
 			md = checkfield(md,'fieldname','thermal.stabilization','numel',[1],'values',[0 1 2]);
-			md = checkfield(md,'fieldname','thermal.spctemperature','forcing',1);
+			md = checkfield(md,'fieldname','thermal.spctemperature','timeseries',1);
 			if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy & dimension(md.mesh)==3),
 				pos=find(md.thermal.spctemperature(1:md.mesh.numberofvertices,:)~=NaN);
 				replicate=repmat(md.geometry.surface-md.mesh.z,1,size(md.thermal.spctemperature,2));
-				md = checkfield(md,'fieldname','thermal.spctemperature(find(md.thermal.spctemperature(1:md.mesh.numberofvertices,:)~=NaN))','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate(pos),'message','spctemperature should be below the adjusted melting point');
+				md = checkfield(md,'fieldname','thermal.spctemperature(find(md.thermal.spctemperature(1:md.mesh.numberofvertices,:)~=NaN))','<=',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate(pos)+10^-5,'message','spctemperature should be less or equal than the adjusted melting point');
 				md = checkfield(md,'fieldname','thermal.isenthalpy','numel',[1],'values',[0 1]);
 				md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel', [1],'values',[0 1]);
 				if(md.thermal.isenthalpy)
-					md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel', [1],'values',[1], 'message',['for enthalpy run thermal.isdynamicbasalspc should be 1']);
+					if isnan(md.stressbalance.reltol),
+						md = checkmessage(md,['for a steadystate computation, thermal.reltol (relative convergence criterion) must be defined!']);
+					end 
+					md = checkfield(md,'fieldname','thermal.reltol','>',0.,'message','reltol must be larger than zero');
 				end
 	    end
@@ -100,34 +116,36 @@
 		 md = checkfield(md,'fieldname','thermal.requested_outputs','stringrow',1);
     end % }}} 
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   Thermal solution parameters:'));
 
-			fielddisplay(obj,'spctemperature','temperature constraints (NaN means no constraint) [K]');
-			fielddisplay(obj,'stabilization','0: no, 1: artificial_diffusivity, 2: SUPG');
-			fielddisplay(obj,'maxiter','maximum number of non linear iterations');
-			fielddisplay(obj,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
-			fielddisplay(obj,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)');
-			fielddisplay(obj,'penalty_factor','scaling exponent (default is 3)');
-			fielddisplay(obj,'isenthalpy','use an enthalpy formulation to include temperate ice (default is 0)');
-			fielddisplay(obj,'isdynamicbasalspc',['enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)']);
-			fielddisplay(obj,'requested_outputs','additional outputs requested');
+			fielddisplay(self,'spctemperature','temperature constraints (NaN means no constraint) [K]');
+			fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: SUPG');
+			fielddisplay(self,'reltol','relative tolerance convergence criterion for enthalpy');
+			fielddisplay(self,'maxiter','maximum number of non linear iterations');
+			fielddisplay(self,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)');
+			fielddisplay(self,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)');
+			fielddisplay(self,'penalty_factor','scaling exponent (default is 3)');
+			fielddisplay(self,'isenthalpy','use an enthalpy formulation to include temperate ice (default is 0)');
+			fielddisplay(self,'isdynamicbasalspc',['enable dynamic setting of basal forcing. required for enthalpy formulation (default is 0)']);
+			fielddisplay(self,'requested_outputs','additional outputs requested');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','spctemperature','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'fieldname','penalty_threshold','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','stabilization','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','penalty_lock','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
-			WriteData(fid,'object',obj,'fieldname','isenthalpy','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isdynamicbasalspc','format','Boolean');
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer');
+			WriteData(fid,'object',self,'fieldname','stabilization','format','Integer');
+			WriteData(fid,'object',self,'fieldname','reltol','format','Double');
+			WriteData(fid,'object',self,'fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer');
+			WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',self,'fieldname','isenthalpy','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','isdynamicbasalspc','format','Boolean');
 
 			%process requested outputs
-			outputs = obj.requested_outputs;
+			outputs = self.requested_outputs;
 			pos  = find(ismember(outputs,'default'));
 			if ~isempty(pos),
 				outputs(pos) = [];                         %remove 'default' from outputs
-				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+				outputs      = [outputs defaultoutputs(self,md)]; %add defaults
 			end
 			WriteData(fid,'data',outputs,'enum',ThermalRequestedOutputsEnum(),'format','StringArray');
Index: /issm/trunk/src/m/classes/thermal.py
===================================================================
--- /issm/trunk/src/m/classes/thermal.py	(revision 19104)
+++ /issm/trunk/src/m/classes/thermal.py	(revision 19105)
@@ -1,3 +1,4 @@
 import numpy
+from project3d import project3d
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -18,4 +19,5 @@
 		self.penalty_threshold = 0
 		self.stabilization     = 0
+		self.reltol            = 0
 		self.maxiter           = 0
 		self.penalty_lock      = 0
@@ -34,4 +36,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: SUPG'))
 		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of non linear iterations'))
+		string="%s\n%s"%(string,fielddisplay(self,'reltol','relative tolerance criterion'))
 		string="%s\n%s"%(string,fielddisplay(self,'penalty_lock','stabilize unstable thermal constraints that keep zigzagging after n iteration (default is 0, no stabilization)'))
 		string="%s\n%s"%(string,fielddisplay(self,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)'))
@@ -41,4 +44,12 @@
 		return string
 		#}}}
+	def extrude(self,md): # {{{
+		self.spctemperature=project3d(md,'vector',self.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',numpy.nan)
+		if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
+			self.spctemperature=numpy.nan*numpy.ones((md.mesh.numberofvertices,1))
+			pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
+			self.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
+		return self
+	#}}}
 	def defaultoutputs(self,md): # {{{
 
@@ -56,4 +67,7 @@
 		#Type of stabilization used
 		self.stabilization=1
+
+		#Relative tolerance for the enthalpy convergence
+		self.reltol=0.01
 
 		#Maximum number of iterations
@@ -81,5 +95,5 @@
 
 		md = checkfield(md,'fieldname','thermal.stabilization','numel',[1],'values',[0,1,2])
-		md = checkfield(md,'fieldname','thermal.spctemperature','forcing',1)
+		md = checkfield(md,'fieldname','thermal.spctemperature','timeseries',1)
 		if EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy and md.mesh.dimension()==3:
 			pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices])))
@@ -89,5 +103,7 @@
 			md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel',[1],'values',[0,1]);
 			if(md.thermal.isenthalpy):
-				md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel', [1],'values',[1], 'message',"for enthalpy run thermal.isdynamicbasalspc should be true")
+				if numpy.isnan(md.stressbalance.reltol):
+					md.checkmessage("for a steadystate computation, thermal.reltol (relative convergence criterion) must be defined!")
+				md = checkfield(md,'fieldname','thermal.reltol','>',0.,'message',"reltol must be larger than zero");
 		md = checkfield(md,'fieldname','thermal.requested_outputs','stringrow',1)
 
@@ -95,7 +111,8 @@
 	# }}}
 	def marshall(self,md,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
+		WriteData(fid,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
 		WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer')
 		WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
+		WriteData(fid,'object',self,'fieldname','reltol','format','Double');
 		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
 		WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer')
Index: /issm/trunk/src/m/classes/timestepping.m
===================================================================
--- /issm/trunk/src/m/classes/timestepping.m	(revision 19104)
+++ /issm/trunk/src/m/classes/timestepping.m	(revision 19105)
@@ -12,44 +12,48 @@
 		cfl_coefficient = 0.;
 		interp_forcings = 1;
+		in_years        = 1;
 	end
 	methods
-       function createxml(obj,fid) % {{{
+       function createxml(self,fid) % {{{
             fprintf(fid, '\n\n');
             fprintf(fid, '%s\n', '<!-- Timestepping -->');
-			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="start_time" type="',              class(obj.start_time),'" default="',                  convert2str(obj.start_time),'">',              '     <section name="timestepping" />','     <help> simulation starting time [yr] </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="final_time" type="',            class(obj.final_time),'" default="',                convert2str(obj.final_time),'">',   '     <section name="timestepping" />','     <help> final time to stop the simulation [yr] </help>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="time_step" type="',      class(obj.time_step),'" default="',          convert2str(obj.time_step),'">',            '     <section name="timestepping" />','     <help> length of time steps [yr] </help>','</parameter>');
+			fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="start_time" type="',              class(self.start_time),'" default="',                  convert2str(self.start_time),'">',              '     <section name="timestepping" />','     <help> simulation starting time [yr] </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="final_time" type="',            class(self.final_time),'" default="',                convert2str(self.final_time),'">',   '     <section name="timestepping" />','     <help> final time to stop the simulation [yr] </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',        '<parameter key ="time_step" type="',      class(self.time_step),'" default="',          convert2str(self.time_step),'">',            '     <section name="timestepping" />','     <help> length of time steps [yr] </help>','</parameter>');
             % time_adapt 0 or 1 drop down
             fprintf(fid,'%s\n%s\n%s\n%s\n','<parameter key ="time_adapt" type="alternative" optional="false">','     <section name="timestepping" />','     <help> use cfl condition to define time step ? (0 or 1)  </help>');
             fprintf(fid, '%s\n',   '       <option value="0" type="string" default="true"></option>');
             fprintf(fid, '%s\n%s\n',   '       <option value="1" type="string" default="false"></option>','</parameter>');
-            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="cfl_coefficient" type="',       class(obj.cfl_coefficient),'" default="',              convert2str(obj.cfl_coefficient),'">',              '     <section name="timestepping" />','     <help> coefficient applied to cfl condition </help>','</parameter>');
+            fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n',    '<parameter key ="cfl_coefficient" type="',       class(self.cfl_coefficient),'" default="',              convert2str(self.cfl_coefficient),'">',              '     <section name="timestepping" />','     <help> coefficient applied to cfl condition </help>','</parameter>');
             
         end % }}}
         
-		function obj = timestepping(varargin) % {{{
+		function self = timestepping(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self=setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%time between 2 time steps
-			obj.time_step=1./2.;
+			self.time_step=1./2.;
 
 			%final time
-			obj.final_time=10.*obj.time_step;
+			self.final_time=10.*self.time_step;
 
 			%time adaptation? 
-			obj.time_adapt=0;
-			obj.cfl_coefficient=0.5;
+			self.time_adapt=0;
+			self.cfl_coefficient=0.5;
 
 			%should we interpolate forcings between timesteps?
-			obj.interp_forcings=1;
+			self.interp_forcings=1;
+
+			%In years by default
+			self.in_years = 1;
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			md = checkfield(md,'fieldname','timestepping.start_time','numel',[1],'NaN',1);
@@ -59,29 +63,38 @@
 			md = checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1);
 			md = checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0 1]);
-			if obj.final_time-obj.start_time<0,
+			if self.final_time-self.start_time<0,
 				md = checkmessage(md,'timestepping.final_time should be larger than timestepping.start_time');
 			end 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   timestepping parameters:'));
 
-			fielddisplay(obj,'start_time','simulation starting time [yr]');
-			fielddisplay(obj,'final_time','final time to stop the simulation [yr]');
-			fielddisplay(obj,'time_step','length of time steps [yr]');
-			fielddisplay(obj,'time_adapt','use cfl condition to define time step ? (0 or 1) ');
-			fielddisplay(obj,'cfl_coefficient','coefficient applied to cfl condition');
-			fielddisplay(obj,'interp_forcings','interpolate in time between requested forcing values ? (0 or 1)');
+			if(self.in_years)
+				unit = 'yr';
+			else
+				unit = 's';
+			end
+			fielddisplay(self,'start_time',['simulation starting time [' unit ']']);
+			fielddisplay(self,'final_time',['final time to stop the simulation [' unit ']']);
+			fielddisplay(self,'time_step',['length of time steps [' unit ']']);
+			fielddisplay(self,'time_adapt','use cfl condition to define time step ? (0 or 1) ');
+			fielddisplay(self,'cfl_coefficient','coefficient applied to cfl condition');
+			fielddisplay(self,'interp_forcings','interpolate in time between requested forcing values ? (0 or 1)');
+			fielddisplay(self,'in_years','time unit, 1: years, 0: seconds');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
+		function marshall(self,md,fid) % {{{
 
-			yts=365.0*24.0*3600.0;
-
-			WriteData(fid,'object',obj,'fieldname','start_time','format','Double','scale',yts);
-			WriteData(fid,'object',obj,'fieldname','final_time','format','Double','scale',yts);
-			WriteData(fid,'object',obj,'fieldname','time_step','format','Double','scale',yts);
-			WriteData(fid,'object',obj,'fieldname','time_adapt','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','cfl_coefficient','format','Double');
-			WriteData(fid,'object',obj,'fieldname','interp_forcings','format','Boolean');
+			if self.in_years,
+				scale = 365.0*24.0*3600.0;
+			else
+				scale = 1.;
+			end
+			WriteData(fid,'object',self,'fieldname','start_time','format','Double','scale',scale);
+			WriteData(fid,'object',self,'fieldname','final_time','format','Double','scale',scale);
+			WriteData(fid,'object',self,'fieldname','time_step','format','Double','scale',scale);
+			WriteData(fid,'object',self,'fieldname','time_adapt','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','cfl_coefficient','format','Double');
+			WriteData(fid,'object',self,'fieldname','interp_forcings','format','Boolean');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/toolkits.m
===================================================================
--- /issm/trunk/src/m/classes/toolkits.m	(revision 19104)
+++ /issm/trunk/src/m/classes/toolkits.m	(revision 19105)
@@ -2,5 +2,5 @@
 %
 %   Usage:
-%      obj=toolkits();
+%      self=toolkits();
 
 classdef toolkits < dynamicprops
@@ -10,15 +10,15 @@
 	 end
 	 methods
-		 function obj = toolkits(varargin) % {{{
+		 function self = toolkits(varargin) % {{{
 			 switch nargin
 				 case 0
-					 obj=setdefaultparameters(obj);
+					 self=setdefaultparameters(self);
 				 case 1
-					 obj=structtoobj(obj,varargin{1});
+					 self=structtoobj(self,varargin{1});
 				 otherwise
 					 error('constructor not supported');
 				 end
 			 end % }}}
-		 function obj = addoptions(obj,analysis,varargin) % {{{
+		 function self = addoptions(self,analysis,varargin) % {{{
 		 % Usage example:
 		 %    md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum(),FSoptions());
@@ -29,13 +29,13 @@
 
 			 %Create dynamic property if property does not exist yet
-			 if ~ismember(analysis,properties(obj)),
-				 obj.addprop(analysis);
+			 if ~ismember(analysis,properties(self)),
+				 self.addprop(analysis);
 			 end
 
 			 %Add toolkits options to analysis
-			 if nargin==3, obj.(analysis) = varargin{1}; end
+			 if nargin==3, self.(analysis) = varargin{1}; end
 		 end
 		 %}}}
-		 function obj = setdefaultparameters(obj) % {{{
+		 function self = setdefaultparameters(self) % {{{
 
 			 %default toolkits: 
@@ -43,13 +43,13 @@
 				 %MUMPS is the default toolkits
 				 if IssmConfig('_HAVE_MUMPS_'),
-					 obj.DefaultAnalysis           = mumpsoptions();
+					 self.DefaultAnalysis           = mumpsoptions();
 				 else
-					 obj.DefaultAnalysis           = iluasmoptions(); 
+					 self.DefaultAnalysis           = iluasmoptions(); 
 				 end
 			 else
 				 if IssmConfig('_HAVE_MUMPS_'),
-					 obj.DefaultAnalysis           = issmmumpssolver(); 
+					 self.DefaultAnalysis           = issmmumpssolver(); 
 				 elseif IssmConfig('_HAVE_GSL_'),
-					 obj.DefaultAnalysis           = issmgslsolver(); 
+					 self.DefaultAnalysis           = issmgslsolver(); 
 				 else 
 					 error('Need at least Mumps or Gsl to define an issm solver type');
@@ -58,17 +58,17 @@
 
 		 end % }}}
-		 function disp(obj) % {{{
-			 analyses=properties(obj);
+		 function disp(self) % {{{
+			 analyses=properties(self);
 			 disp(sprintf('List of toolkits options per analysis:\n'));
 			 for i=1:numel(analyses),
 				 analysis=analyses{i};
 				 disp([analysis ':']);
-				 disp(obj.(analysis));
+				 disp(self.(analysis));
 			 end
 		 end % }}}
-		 function md = checkconsistency(obj,md,solution,analyses) % {{{
-			 analyses=properties(obj);
+		 function md = checkconsistency(self,md,solution,analyses) % {{{
+			 analyses=properties(self);
 			 for i=1:numel(analyses),
-				 if isempty(fieldnames(obj.(analyses{i})))
+				 if isempty(fieldnames(self.(analyses{i})))
 					 md = checkmessage(md,['md.toolkits.' analyses{i} ' is empty']);
 				 end
Index: /issm/trunk/src/m/classes/toolkits.py
===================================================================
--- /issm/trunk/src/m/classes/toolkits.py	(revision 19104)
+++ /issm/trunk/src/m/classes/toolkits.py	(revision 19105)
@@ -12,5 +12,5 @@
 
 	   Usage:
-	      obj=toolkits();
+	      self=toolkits();
 	"""
 
Index: /issm/trunk/src/m/classes/transient.m
===================================================================
--- /issm/trunk/src/m/classes/transient.m	(revision 19104)
+++ /issm/trunk/src/m/classes/transient.m	(revision 19105)
@@ -13,61 +13,65 @@
 		isdamageevolution = 0;
 		islevelset        = 0;
+		iscalving         = 0;
 		ishydrology       = 0;
 		requested_outputs = {};
 	end
 	methods
-        function createxml(obj,fid) % {{{
+        function createxml(self,fid) % {{{
             fprintf(fid, '<!-- transient -->\n');            
                     
             % transient solution parameters
             fprintf(fid,'%s\n%s\n%s\n','<frame key="1" label="transient solution parameters">','<section name="transient" />');                    
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="ismasstransport" type="',class(obj.ismasstransport),'" default="',convert2str(obj.ismasstransport),'">','     <section name="transient" />','     <help> indicates whether a masstransport solution is used in the transient </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isstressbalance" type="',class(obj.isstressbalance),'" default="',convert2str(obj.isstressbalance),'">','     <section name="transient" />','     <help> indicates whether a stressbalance solution is used in the transient </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isthermal" type="',class(obj.isthermal),'" default="',convert2str(obj.isthermal),'">','     <section name="transient" />','     <help> indicates whether a thermal solution is used in the transient </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isgroundingline" type="',class(obj.isgroundingline),'" default="',convert2str(obj.isgroundingline),'">','     <section name="transient" />','     <help> indicates whether a groundingline migration is used in the transient </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isgia" type="',class(obj.isgia),'" default="',convert2str(obj.isgia),'">','     <section name="transient" />','     <help> indicates whether a postglacial rebound model is used in the transient </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isdamageevolution" type="',class(obj.isdamageevolution),'" default="',convert2str(obj.isdamageevolution),'">','     <section name="transient" />','     <help> indicates whether damage evolution is used in the transient </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="islevelset" type="',class(obj.islevelset),'" default="',convert2str(obj.islevelset),'">','     <section name="transient" />','     <help> LEVEL SET DESCRIPTION...  </help>','  </parameter>');
-                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="requested_outputs" type="',class(obj.requested_outputs),'" default="',convert2str(obj.requested_outputs),'">','     <section name="transient" />','     <help> list of additional outputs requested </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="ismasstransport" type="',class(self.ismasstransport),'" default="',convert2str(self.ismasstransport),'">','     <section name="transient" />','     <help> indicates whether a masstransport solution is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isstressbalance" type="',class(self.isstressbalance),'" default="',convert2str(self.isstressbalance),'">','     <section name="transient" />','     <help> indicates whether a stressbalance solution is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isthermal" type="',class(self.isthermal),'" default="',convert2str(self.isthermal),'">','     <section name="transient" />','     <help> indicates whether a thermal solution is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isgroundingline" type="',class(self.isgroundingline),'" default="',convert2str(self.isgroundingline),'">','     <section name="transient" />','     <help> indicates whether a groundingline migration is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isgia" type="',class(self.isgia),'" default="',convert2str(self.isgia),'">','     <section name="transient" />','     <help> indicates whether a postglacial rebound model is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="isdamageevolution" type="',class(self.isdamageevolution),'" default="',convert2str(self.isdamageevolution),'">','     <section name="transient" />','     <help> indicates whether damage evolution is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="islevelset" type="',class(self.islevelset),'" default="',convert2str(self.islevelset),'">','     <section name="transient" />','     <help> LEVEL SET DESCRIPTION...  </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="iscalving" type="',class(self.iscalving),'" default="',convert2str(self.iscalving),'">','     <section name="transient" />','     <help> indicates whether calving is used in the transient </help>','  </parameter>');
+                fprintf(fid,'%s%s%s%s%s\n%s\n%s\n%s\n','  <parameter key ="requested_outputs" type="',class(self.requested_outputs),'" default="',convert2str(self.requested_outputs),'">','     <section name="transient" />','     <help> list of additional outputs requested </help>','  </parameter>');
             fprintf(fid,'%s\n%s\n','</frame>');    
         
         end % }}}
-		function obj = transient(varargin) % {{{
+		function self = transient(varargin) % {{{
 			switch nargin
 				case 0
-					obj=setdefaultparameters(obj);
+					self = setdefaultparameters(self);
 				otherwise
 					error('constructor not supported');
 			end
 		end % }}}
-		function obj = deactivateall(obj) % {{{
+		function self = deactivateall(self) % {{{
 
 			%full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
-			obj.ismasstransport = 0;
-			obj.isstressbalance = 0;
-			obj.isthermal       = 0;
-			obj.isgroundingline = 0;
-			obj.isgia           = 0;
-			obj.isdamageevolution = 0;
-			obj.islevelset      = 0;
-			obj.ishydrology     = 0;
+			self.ismasstransport = 0;
+			self.isstressbalance = 0;
+			self.isthermal       = 0;
+			self.isgroundingline = 0;
+			self.isgia           = 0;
+			self.isdamageevolution = 0;
+			self.islevelset      = 0;
+			self.iscalving       =0;
+			self.ishydrology     = 0;
 
 			%default output
-			obj.requested_outputs={};
+			self.requested_outputs={};
 		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
+		function self = setdefaultparameters(self) % {{{
 
 			%full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
-			obj.ismasstransport = 1;
-			obj.isstressbalance = 1;
-			obj.isthermal       = 1;
-			obj.isgroundingline = 0;
-			obj.isgia           = 0;
-			obj.isdamageevolution = 0;
-			obj.islevelset      = 0;
-			obj.ishydrology     = 0;
+			self.ismasstransport = 1;
+			self.isstressbalance = 1;
+			self.isthermal       = 1;
+			self.isgroundingline = 0;
+			self.isgia           = 0;
+			self.isdamageevolution = 0;
+			self.islevelset      = 0;
+			self.iscalving       = 0;
+			self.ishydrology     = 0;
 
 			%default output
-			obj.requested_outputs={'default'};
+			self.requested_outputs={'default'};
 		end % }}}
 		function list = defaultoutputs(self,md) % {{{
@@ -78,5 +82,5 @@
 			end
 		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 			%Early return
@@ -90,38 +94,41 @@
 			md = checkfield(md,'fieldname','transient.isdamageevolution','numel',[1],'values',[0 1]);
 			md = checkfield(md,'fieldname','transient.islevelset','numel',[1],'values',[0 1]);
+			md = checkfield(md,'fieldname','transient.iscalving','numel',[1],'values',[0 1]);
 			md = checkfield(md,'fieldname','transient.ishydrology','numel',[1],'values',[0 1]);
 			md = checkfield(md,'fieldname','transient.requested_outputs','stringrow',1);
 
 		end % }}}
-		function disp(obj) % {{{
+		function disp(self) % {{{
 			disp(sprintf('   transient solution parameters:'));
 
-			fielddisplay(obj,'ismasstransport','indicates whether a masstransport solution is used in the transient');
-			fielddisplay(obj,'isstressbalance','indicates whether a stressbalance solution is used in the transient');
-			fielddisplay(obj,'isthermal','indicates whether a thermal solution is used in the transient');
-			fielddisplay(obj,'isgroundingline','indicates whether a groundingline migration is used in the transient');
-			fielddisplay(obj,'isgia','indicates whether a postglacial rebound model is used in the transient');
-			fielddisplay(obj,'isdamageevolution','indicates whether damage evolution is used in the transient');
-			fielddisplay(obj,'islevelset','LEVEL SET DESCRIPTION...');
-			fielddisplay(obj,'ishydrology','indicates whether an hydrology model is used');
-			fielddisplay(obj,'requested_outputs','list of additional outputs requested');
+			fielddisplay(self,'ismasstransport','indicates whether a masstransport solution is used in the transient');
+			fielddisplay(self,'isstressbalance','indicates whether a stressbalance solution is used in the transient');
+			fielddisplay(self,'isthermal','indicates whether a thermal solution is used in the transient');
+			fielddisplay(self,'isgroundingline','indicates whether a groundingline migration is used in the transient');
+			fielddisplay(self,'isgia','indicates whether a postglacial rebound model is used in the transient');
+			fielddisplay(self,'isdamageevolution','indicates whether damage evolution is used in the transient');
+			fielddisplay(self,'islevelset','LEVEL SET DESCRIPTION...');
+			fielddisplay(self,'iscalving','indicates whether calving is used in the transient');
+			fielddisplay(self,'ishydrology','indicates whether an hydrology model is used');
+			fielddisplay(self,'requested_outputs','list of additional outputs requested');
 
 		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','ismasstransport','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isstressbalance','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isthermal','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isgroundingline','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isgia','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isdamageevolution','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','ishydrology','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','islevelset','format','Boolean');
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'object',self,'fieldname','ismasstransport','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','isstressbalance','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','isthermal','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','isgroundingline','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','isgia','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','isdamageevolution','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','ishydrology','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','islevelset','format','Boolean');
+			WriteData(fid,'object',self,'fieldname','iscalving','format','Boolean');
 
 			%process requested outputs
-			outputs = obj.requested_outputs;
+			outputs = self.requested_outputs;
 			pos  = find(ismember(outputs,'default'));
 			if ~isempty(pos),
 				outputs(pos) = [];                         %remove 'default' from outputs
-				outputs      = [outputs defaultoutputs(obj,md)]; %add defaults
+				outputs      = [outputs defaultoutputs(self,md)]; %add defaults
 			end
 			WriteData(fid,'data',outputs,'enum',TransientRequestedOutputsEnum,'format','StringArray');
Index: /issm/trunk/src/m/classes/transient.py
===================================================================
--- /issm/trunk/src/m/classes/transient.py	(revision 19104)
+++ /issm/trunk/src/m/classes/transient.py	(revision 19105)
@@ -20,4 +20,5 @@
 		self.isdamageevolution = False
 		self.islevelset        = False
+		self.iscalving         = False
 		self.ishydrology       = False
 		self.requested_outputs = []
@@ -36,4 +37,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,'isdamageevolution','indicates whether damage evolution is used in the transient'))
 		string="%s\n%s"%(string,fielddisplay(self,'islevelset','LEVELSET METHOD DESCRIPTION'))
+		string="%s\n%s"%(string,fielddisplay(self,'iscalving','indicates whether calving is used in the transient'))
 		string="%s\n%s"%(string,fielddisplay(self,'ishydrology','indicates whether an hydrology model is used'))
 		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','list of additional outputs requested'))
@@ -51,12 +53,13 @@
 		
 		#Nothing done
-		self.ismasstransport = False
-		self.isstressbalance = False
-		self.isthermal       = False
-		self.isgroundingline = False
-		self.isgia           = False
+		self.ismasstransport   = False
+		self.isstressbalance   = False
+		self.isthermal         = False
+		self.isgroundingline   = False
+		self.isgia             = False
 		self.isdamageevolution = False
-		self.islevelset      = False
-                self.ishydrology     = False
+		self.islevelset        = False
+		self.iscalving         = False
+		self.ishydrology       = False
 
 		#default output
@@ -74,5 +77,6 @@
 		self.isdamageevolution = False
 		self.islevelset      = False
-                self.ishydrology     = False
+		self.iscalving       = False
+		self.ishydrology     = False
 
 		#default output
@@ -94,4 +98,5 @@
 		md = checkfield(md,'fieldname','transient.islevelset','numel',[1],'values',[0,1])
 		md = checkfield(md,'fieldname','transient.ishydrology','numel',[1],'values',[0,1])
+		md = checkfield(md,'fieldname','transient.iscalving','numel',[1],'values',[0,1]);
 		md = checkfield(md,'fieldname','transient.requested_outputs','stringrow',1)
 
@@ -107,4 +112,5 @@
 		WriteData(fid,'object',self,'fieldname','islevelset','format','Boolean')
 		WriteData(fid,'object',self,'fieldname','ishydrology','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','iscalving','format','Boolean')
 
 		#process requested outputs
Index: /issm/trunk/src/m/classes/verbose.m
===================================================================
--- /issm/trunk/src/m/classes/verbose.m	(revision 19104)
+++ /issm/trunk/src/m/classes/verbose.m	(revision 19105)
@@ -38,19 +38,19 @@
 	%}}}
 	methods
-        function createxml(obj,fid) % {{{
-            fprintf(fid, '\n\n');
-            fprintf(fid, '%s\n', '<!-- verbose -->');
-             
-             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="mprocessor" type="',              class(obj.mprocessor),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.mprocessor),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
-             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="module" type="',              class(obj.module),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.module),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
-             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="solution" type="',              class(obj.solution),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.solution),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
-             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="solver" type="',              class(obj.solver),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.solver),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
-             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="convergence" type="',              class(obj.convergence),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.convergence),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
-             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="control" type="',              class(obj.control),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.control),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
-             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="qmu" type="',              class(obj.qmu),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.qmu),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
-             fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n',    '<parameter key ="autodiff" type="',              class(obj.autodiff),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(obj.autodiff),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
-             
-             
-        end % }}}
+		function createxml(self,fid) % {{{
+			fprintf(fid, '\n\n');
+			fprintf(fid, '%s\n', '<!-- verbose -->');
+
+			fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="mprocessor" type="',              class(self.mprocessor),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(self.mprocessor),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+			fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="module" type="',              class(self.module),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(self.module),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+			fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="solution" type="',              class(self.solution),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(self.solution),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+			fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="solver" type="',              class(self.solver),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(self.solver),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+			fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="convergence" type="',              class(self.convergence),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(self.convergence),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+			fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="control" type="',              class(self.control),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(self.control),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+			fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n%s\n',    '<parameter key ="qmu" type="',              class(self.qmu),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(self.qmu),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+			fprintf(fid,'%s%s%s\n%s\n%s%s%s\n%s\n',    '<parameter key ="autodiff" type="',              class(self.autodiff),'" optional="false">',              '     <section name="verbose" />','        <option value="',convert2str(self.autodiff),'" type="string" default="true"></option>','     <help>  </help>','</parameter>');
+
+
+		end % }}}
 		function verbose=verbose(varargin) % {{{
 
@@ -123,5 +123,5 @@
 		end
 		%}}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
+		function md = checkconsistency(self,md,solution,analyses) % {{{
 
 		end % }}}
@@ -142,6 +142,6 @@
 		end
 		%}}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'data',VerboseToBinary(obj),'enum',VerboseEnum(),'format','Integer');
+		function marshall(self,md,fid) % {{{
+			WriteData(fid,'data',VerboseToBinary(self),'enum',VerboseEnum(),'format','Integer');
 		end % }}}
 	end
Index: /issm/trunk/src/m/consistency/checkfield.m
===================================================================
--- /issm/trunk/src/m/consistency/checkfield.m	(revision 19104)
+++ /issm/trunk/src/m/consistency/checkfield.m	(revision 19105)
@@ -14,5 +14,5 @@
 %      - <=: smaller or equal to provided value
 %      - < vec:  smallerthan provided values on each vertex
-%      - forcing: 1 if check forcing consistency (size and time)
+%      - timeseries: 1 if check time series consistency (size and time)
 %      - values: cell of strings or vector of acceptable values
 %      - numel: list of acceptable number of elements
@@ -198,5 +198,5 @@
 
 %Check forcings (size and times)
-if getfieldvalue(options,'forcing',0),
+if getfieldvalue(options,'timeseries',0),
 	if size(field,1)==md.mesh.numberofvertices,
 		if ~size(field,2)==1,
Index: /issm/trunk/src/m/consistency/checkfield.py
===================================================================
--- /issm/trunk/src/m/consistency/checkfield.py	(revision 19104)
+++ /issm/trunk/src/m/consistency/checkfield.py	(revision 19105)
@@ -21,5 +21,5 @@
 	      - <=: smaller or equal to provided value
 	      - < vec:  smallerthan provided values on each vertex
-	      - forcing: 1 if check forcing consistency (size and time)
+	      - timeseries: 1 if check time series consistency (size and time)
 	      - values: cell of strings or vector of acceptable values
 	      - numel: list of acceptable number of elements
@@ -151,5 +151,5 @@
 
 	#Check forcings (size and times)
-	if options.getfieldvalue('forcing',0):
+	if options.getfieldvalue('timeseries',0):
 		if   numpy.size(field,0)==md.mesh.numberofvertices:
 			if numpy.ndim(field)>1 and not numpy.size(field,1)==1:
Index: /issm/trunk/src/m/contrib/bamg/gmsh3d.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/gmsh3d.m	(revision 19104)
+++ /issm/trunk/src/m/contrib/bamg/gmsh3d.m	(revision 19105)
@@ -97,5 +97,5 @@
 %call gmsh
 fprintf('%s\n','      call gmsh...');
-system([issmdir() '/externalpackages/gmsh/install/gmsh -3 model.geo']);
+system([issmdir() '/externalpackages/gmsh/install/gmsh -3 -v 0 model.geo']);
 
 %plug new mesh
Index: /issm/trunk/src/m/contrib/gravity/Makefile
===================================================================
--- /issm/trunk/src/m/contrib/gravity/Makefile	(revision 19105)
+++ /issm/trunk/src/m/contrib/gravity/Makefile	(revision 19105)
@@ -0,0 +1,11 @@
+all:
+		g++ vfsa_mpi.cpp  \
+			-I$(ISSM_DIR)/externalpackages/gsl/install/include \
+			-L$(ISSM_DIR)/externalpackages/gsl/install/lib -lgsl -lgslcblas \
+		   -I$(ISSM_DIR)/externalpackages/mpich/install/include/ \
+		   -L$(ISSM_DIR)/externalpackages/mpich/install/lib/ -lmpich -lpmpich -lmpl -o forward.exe 
+
+forward:
+	   mpirun -np 4 ./forward.exe
+clean:
+		rm ./forward.exe
Index: /issm/trunk/src/m/contrib/gravity/code_densite/Makefile
===================================================================
--- /issm/trunk/src/m/contrib/gravity/code_densite/Makefile	(revision 19105)
+++ /issm/trunk/src/m/contrib/gravity/code_densite/Makefile	(revision 19105)
@@ -0,0 +1,11 @@
+all:
+		g++ density_rock_uneven.cpp  \
+			-I$(ISSM_DIR)/externalpackages/gsl/install/include \
+			-L$(ISSM_DIR)/externalpackages/gsl/install/lib -lgsl -lgslcblas \
+		   -I$(ISSM_DIR)/externalpackages/mpich/install/include/ \
+		   -L$(ISSM_DIR)/externalpackages/mpich/install/lib/ -lmpich -lpmpich -lmpl -o forward.exe 
+
+forward:
+	   mpirun -np 4 ./forward.exe
+run -np 4 ./forward.execlean:
+		rm ./forward.exe
Index: /issm/trunk/src/m/contrib/gravity/code_densite/density_rock.cpp
===================================================================
--- /issm/trunk/src/m/contrib/gravity/code_densite/density_rock.cpp	(revision 19105)
+++ /issm/trunk/src/m/contrib/gravity/code_densite/density_rock.cpp	(revision 19105)
@@ -0,0 +1,510 @@
+#include <iostream>
+#include <cmath>
+#include <fstream>
+#include <string>
+#include <cstdio>
+#include <cstdlib>
+#include <time.h>
+#include <cassert>
+#include <gsl/gsl_multifit.h>
+#include "mpi.h"
+using namespace std;
+
+class Matrix{/*{{{*/
+	private:
+		int     M;        /*Number of lines   */
+		int     N;        /*Number if Columns */
+		double *values;
+	public:
+		Matrix(int m_in,int n_in){/*{{{*/
+			this->M = m_in;
+			this->N = n_in;
+			this->values = new double[M*N]();
+		}/*}}}*/
+		~Matrix(){/*{{{*/
+			delete [] this->values;
+		}/*}}}*/
+		void Echo(void){/*{{{*/
+			for(int i=0;i<M;i++){
+				for(int j=0;j<N;j++){
+					cout << " " << this->values[i*N+j];
+				}
+				cout << endl;
+			}
+		}/*}}}*/
+		void SetValue(int i,int j,double value){/*{{{*/
+			this->values[i*N+j] = value;
+		}/*}}}*/
+		double GetValue(int i,int j){/*{{{*/
+			return this->values[i*N+j];
+		}/*}}}*/
+		void GetSize(int* pM,int* pN){/*{{{*/
+			*pM = this->M;
+			*pN = this->N;
+		}/*}}}*/
+		double* GetPointer(void){/*{{{*/
+			return this->values;
+		}/*}}}*/
+		void MatrixSum(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) + B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixDiff(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) - B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixAbs(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,fabs(A->GetValue(i,j)));
+				}
+			}
+		}/*}}}*/
+		void MatrixEqual(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		double MatrixInternSum(){/*{{{*/
+			double sum=0;
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					sum+=this->GetValue(i,j);
+				}
+			}
+			return sum;
+		}/*}}}*/
+		void ExtractLine(Matrix* A,int i){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(M_A==1 && this->N==N_A);
+			for(int j=0;j<this->N;j++){
+				A->SetValue(0,j,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void ExtractColumn(Matrix* A,int j){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(N_A==1 && this->M==M_A);
+			for(int i=0;i<this->M;i++){
+				A->SetValue(i,0,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void AddNumber(double a){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,this->GetValue(i,j) + a);
+				}
+			}
+		}/*}}}*/
+};/*}}}*/
+
+/*Local prototypes{{{*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy);
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny);
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,double dlevel);
+void plouff(Matrix *g,Matrix *Pobs,Matrix *Pp,Matrix * mesh,Matrix *rho,int dx,int dy, int dn,int m,int n,int l,Matrix *evalid,int my_rank,int num_procs);
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny);
+void reshape(Matrix* V,Matrix* V1,int nx,int ny);
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,double dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my,int my_rank,int num_procs);
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B);
+/*}}}*/
+
+int main(int argc,char *argv[]){/*{{{*/
+
+	int my_rank,num_procs;
+
+	MPI_Init(&argc, &argv);
+
+	MPI_Comm_size(MPI_COMM_WORLD,&num_procs);
+	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
+
+	/* Define the variables {{{*/
+
+	int    dx     = 1000;   /* prism dimension in x-direction                           */
+	int    dy     = 1000;   /* prism dimension in y-direction                           */
+	int    mx     = 99;    /* number of prisms in x-direction                          */
+	int    my     = 99;    /* number of prisms in y-direction                          */
+	int    nx     = 99;    /* number of data points in x-direction                     */
+	int    ny     = 99;    /* number of data points in y-direction                     */
+	int    dn     = 15000; /* distance for neighbouting prisms for gravity calculation */
+
+	Matrix *Pobs=new Matrix(nx*ny,2); /* data positions */
+	makep(Pobs,nx,ny,dx,dy);
+	// Pobs->Echo();
+
+
+
+	Matrix *Pp=new Matrix(mx*my,2); /* prisms positions */
+	makep(Pp,mx,my,dx,dy);
+	// Pp->Echo();
+
+	double  rhoi = 917;           /* ice density     */
+	double  rhow = 1030;          /* water density   */
+	// double  rhos = 2013;		      /* sediment density */
+
+	double rhoc_min=2000.;
+	double rhoc_max=3000.;
+
+	Matrix *Rho  = new Matrix(1,2);
+	Rho->SetValue(0,0,rhoi);
+	Rho->SetValue(0,1,rhow);
+	Matrix *rho1  = new Matrix(1,3);
+	rho1->SetValue(0,0,rhoi);
+	rho1->SetValue(0,1,rhow);
+	rho1->SetValue(0,2,rhoc_min);
+	Matrix *rho2  = new Matrix(1,2);
+	rho2->SetValue(0,0,rhoi-rhoc_min);
+	rho2->SetValue(0,1,rhow-rhoc_min);
+
+	double dlevel=3134;         /* level of data acquisition */
+
+
+	Matrix *xobs= new Matrix(ny,nx);
+	Matrix *yobs= new Matrix(ny,nx);
+
+	vec2grid(Pobs,xobs,yobs,nx,ny);
+	//	xobs->Echo();
+	//	yobs->Echo();
+
+
+	/*}}}*/     
+	/* load the data {{{*/
+
+
+	double inputnumber;
+
+	/* Observed gravity anomaly */
+
+	ifstream file1("gravityraw.txt");
+	Matrix * gobs= new Matrix(nx*ny,1);
+	for(int i=0;i<ny*nx; i++){ 
+		file1 >> inputnumber;
+		gobs->SetValue(i,0, inputnumber*1e-5);
+	}
+	file1.close();
+	//	gobs->Echo();
+
+
+	/* id of grid to evaluate misfit */
+
+
+	ifstream file4("evalid1.txt");
+	Matrix * evalid= new Matrix(nx*ny,1);
+	for(int s=0;s<nx*ny; s++){ 
+		file4 >> inputnumber;
+		evalid->SetValue(s,0,inputnumber);
+	}
+	file4.close();
+	//	evalid->Echo();
+
+	/* initial guess of the model */
+
+	ifstream file5("m0_102714contzach.txt");
+	Matrix * mesh_ini= new Matrix(mx*my,3);
+	for(int s=0;s<mx*my; s++){ 
+		for(int j=0;j<3;j++){
+			file5 >> inputnumber;
+			mesh_ini->SetValue(s,j,inputnumber);
+		}
+	}
+	file5.close();
+	//	mesh_ini->Echo();
+	/*}}}*/
+	/* Test {{{ */
+
+
+	double rhoc=rhoc_min;
+	double rhoc_opti=rhoc_min;
+	double E=misfit(mesh_ini,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my,my_rank,num_procs);
+	double E_opti=E;
+
+	for(int i=rhoc_min;i<rhoc_max+1;i++){
+		rhoc=i;
+		rho1->SetValue(0,2,rhoc);
+		rho2->SetValue(0,0,rhoi-rhoc);
+		rho2->SetValue(0,1,rhow-rhoc);
+
+		E=misfit(mesh_ini,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my,my_rank,num_procs);
+
+		if(E<E_opti){
+			E_opti=E;
+			rhoc_opti=rhoc;
+		}
+		if(my_rank==0){
+			cout<<rhoc<<"  "<<rhoc_opti<<"  "<<E<<"  "<<E_opti<<endl;
+		}
+	}
+
+
+
+
+	delete Pobs;
+	delete Pp;
+	delete Rho;
+	delete rho1;
+	delete rho2;
+	delete xobs;
+	delete yobs;
+	delete mesh_ini;
+	delete evalid;
+	delete gobs;
+
+	/*}}}*/
+
+	MPI_Finalize();
+
+	return 0;
+}/*}}}*/
+
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B){/*{{{*/
+
+	/*GSL Matrices and vectors: */
+	int    M,N;
+	double chisq;
+	/*Get system size*/
+	A->GetSize(&M,&N);
+
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix* a = gsl_matrix_alloc(M,N);
+	for(int i=0;i<M;i++){
+		for(int j=0;j<N;j++){
+			gsl_matrix_set (a,i,j,A->GetValue(i,j));
+		}
+	}
+	gsl_vector* b = gsl_vector_alloc(M);
+	for(int i=0;i<M;i++){
+		gsl_vector_set(b,i,B->GetValue(i,0));
+	}
+
+	gsl_vector* x = gsl_vector_alloc(N);
+	gsl_matrix* cov = gsl_matrix_alloc(N,N);
+
+	/*Least square fit: */
+	gsl_multifit_linear_workspace* work = gsl_multifit_linear_alloc(M,N);
+	gsl_multifit_linear (a, b, x, cov, &chisq, work);
+	gsl_multifit_linear_free (work);
+
+	/*Clean up and assign output pointer*/
+	Matrix* X = new Matrix(N,1);
+	for(int j=0;j<N;j++){
+		X->SetValue(j,0,gsl_vector_get(x,j));
+	}
+	*pX = X;
+
+	gsl_matrix_free(a);
+	gsl_vector_free(x);
+	gsl_vector_free(b);
+	gsl_matrix_free(cov);
+
+}/*}}}*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			Pobs->SetValue(j+nx*i,0,j*dx);
+			Pobs->SetValue(j+nx*i,1,i*dy);
+		}
+	}
+}/*}}}*/
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+			V2->SetValue(i,j, V->GetValue(j+nx*i,1));
+		}
+	}
+}/*}}}*/
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,double dlevel){/*{{{*/
+	int sizem1,sizem2;
+	m->GetSize(&sizem1,&sizem2);
+	for(int i=0;i<sizem1;i++){
+		for(int j=0;j<sizem2+1;j++){
+			if(j<sizem2){
+				m1->SetValue(i,j,1e-10*(sizem2+1-j));
+				m2->SetValue(i,j,m->GetValue(i,j));
+				if(m->GetValue(i,j)<0){
+					m1->SetValue(i,j,m->GetValue(i,j));
+					m2->SetValue(i,j,i*1e-10);
+				}
+				m1->SetValue(i,j,m1->GetValue(i,j));
+				m2->SetValue(i,j,m2->GetValue(i,j));
+			}
+			else{
+				m1->SetValue(i,j,1e-10);
+			}
+		}
+	}
+	m1->AddNumber(dlevel);
+	m2->AddNumber(dlevel);
+}/*}}}*/
+void plouff(Matrix *g,Matrix *Pobs,Matrix *Pp,Matrix * mesh,Matrix *rho,int dx,int dy, int dn,int m,int n,int l,Matrix *evalid,int my_rank,int num_procs){/*{{{*/
+	double gg=6.673e-11;
+	int si,sj,id,s;
+	double R,Q,P;
+	Matrix *xp= new Matrix(1,2);
+	Matrix *yp= new Matrix(1,2);
+	Matrix *xpp= new Matrix(1,2);
+	Matrix *ypp= new Matrix(1,2);
+	Matrix *U= new Matrix(l,4);
+	Matrix *U1=new Matrix(1,4);
+	Matrix *U2=new Matrix(1,4);
+	Matrix *gl= new Matrix(1,l-1);
+	bool test=true;
+
+	double *glocal=new double[n]();
+
+	for(int c=my_rank;c<n;c+=num_procs){
+		glocal[c]=0;
+		if(evalid->GetValue(c,0)==1){
+			for(int a=0;a<m;a++){
+				test=true;
+				xp->SetValue(0,0,Pp->GetValue(a,0)-Pobs->GetValue(c,0));
+				xp->SetValue(0,1,Pp->GetValue(a,0)-Pobs->GetValue(c,0)+dx);
+				if(xp->GetValue(0,0)<0 && xp->GetValue(0,0)<xp->GetValue(0,1) && xp->GetValue(0,0)*xp->GetValue(0,1)>=0){
+					xpp->SetValue(0,0,xp->GetValue(0,1));
+					xpp->SetValue(0,1,xp->GetValue(0,0));
+					xp->MatrixAbs(xpp);
+				}
+				yp->SetValue(0,0,Pp->GetValue(a,1)-Pobs->GetValue(c,1));
+				yp->SetValue(0,1,Pp->GetValue(a,1)-Pobs->GetValue(c,1)+dy);
+				if(yp->GetValue(0,0)<0 && yp->GetValue(0,0)<yp->GetValue(0,1) && yp->GetValue(0,0)*yp->GetValue(0,1)>=0){
+					ypp->SetValue(0,0,yp->GetValue(0,1));
+					ypp->SetValue(0,1,yp->GetValue(0,0));
+					yp->MatrixAbs(ypp);
+				}
+				P=sqrt(xp->GetValue(0,0)*xp->GetValue(0,0)+yp->GetValue(0,0)*yp->GetValue(0,0));
+				if(P>dn){
+					test=false;
+					for(int i=0;i<l-1;i++){
+						gl->SetValue(0,i,0);
+					}
+				}
+				if(test==true){
+					si=1;
+					sj=1;
+					id=0;
+					for(int i=0;i<2;i++){
+						si*=-1;
+						for(int j=0;j<2;j++){
+							sj*=-1;
+							s=si*sj;
+							for(int k=0;k<l;k++){
+								R=sqrt(xp->GetValue(0,i)*xp->GetValue(0,i)+yp->GetValue(0,j)*yp->GetValue(0,j)+mesh->GetValue(a,k)*mesh->GetValue(a,k));
+								Q=atan(xp->GetValue(0,i)*yp->GetValue(0,j)/(mesh->GetValue(a,k)*R));
+								U->SetValue(k,id,s*(mesh->GetValue(a,k)*Q-xp->GetValue(0,i)*log(R+yp->GetValue(0,j))-yp->GetValue(0,j)*log(R+xp->GetValue(0,i))));
+							}
+							id++;
+						}
+					}
+					for(int b=0;b<l-1;b++){
+						U->ExtractLine(U1,b);
+						U->ExtractLine(U2,b+1);
+						gl->SetValue(0,b,rho->GetValue(0,b)*(U1->MatrixInternSum()*(-1)+U2->MatrixInternSum()));
+					}
+				}
+				glocal[c]=glocal[c]+gg*gl->MatrixInternSum();
+			}
+		}
+	}
+
+	MPI_Allreduce(glocal,g->GetPointer(),n,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+
+	delete xp;
+	delete yp;
+	delete xpp;
+	delete ypp;
+	delete gl;
+	delete U;
+	delete U1;
+	delete U2;
+	delete []glocal;
+}/*}}}*/
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+		}
+	}
+}/*}}}*/
+void reshape(Matrix* V,Matrix* V1,int nx,int ny){/*{{{*/
+	for (int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			V1->SetValue(j+nx*i,0,V->GetValue(i,j));
+		}
+	}
+}/*}}}*/
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,double dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my,int my_rank,int num_procs){/*{{{*/
+	Matrix* m1=new Matrix(mx*my,4);
+	Matrix* m2=new Matrix(mx*my,3);
+	Matrix* g1=new Matrix(nx*ny,1);
+	Matrix* g2=new Matrix(nx*ny,1);
+	Matrix* g=new Matrix(nx*ny,1);
+	Matrix* gcalgr=new Matrix(ny,nx);
+	Matrix* gcalvec=new Matrix(nx*ny,1);
+	Matrix* df=new Matrix(nx*ny,1);
+	Matrix* G=new Matrix(nx*ny,3);
+	double a=0;
+	double b=0;
+	double e=0;
+	msplit(m0,m1,m2,dlevel);
+	plouff(g1,Pobs,Pp,m1,rho1,dx,dy,dn,mx*my,nx*ny,4,evalid, my_rank, num_procs);
+	plouff(g2,Pobs,Pp,m2,rho2,dx,dy,dn,mx*my,nx*ny,3,evalid, my_rank, num_procs);
+	g->MatrixSum(g1,g2);
+	vec2gridsimple(g,gcalgr,nx,ny);
+	reshape(gcalgr,gcalvec,nx,ny);
+	for (int i=0;i<nx*ny;i++){
+		df->SetValue(i,0,evalid->GetValue(i,0)*(gobs->GetValue(i,0)-gcalvec->GetValue(i,0)));
+		G->SetValue(i,0,evalid->GetValue(i,0)*Pobs->GetValue(i,0));
+		G->SetValue(i,1,evalid->GetValue(i,0)*Pobs->GetValue(i,1));
+		G->SetValue(i,2,evalid->GetValue(i,0));
+	}
+	Matrix* M = NULL;
+	GSLsquarefit(&M,G,df);
+
+	for (int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			gcalgr->SetValue(i,j,gcalgr->GetValue(i,j)+xobs->GetValue(i,j)*M->GetValue(0,0)+yobs->GetValue(i,j)*M->GetValue(1,0)+M->GetValue(2,0));
+		}
+	}
+	reshape(gcalgr,g,nx,ny);
+	for (int i=0;i<nx*ny;i++){
+		a=a+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)-g->GetValue(i,0)));
+		b=b+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)+g->GetValue(i,0)));
+	}
+	e=2*a/(a+b);
+
+	delete m1;
+	delete m2;
+	delete g1;
+	delete g2;
+	delete g;
+	delete gcalgr;
+	delete gcalvec;
+	delete df;
+	delete G;
+	delete M;
+
+	return e;
+}/*}}}*/
Index: /issm/trunk/src/m/contrib/gravity/code_densite/density_rock_uneven.cpp
===================================================================
--- /issm/trunk/src/m/contrib/gravity/code_densite/density_rock_uneven.cpp	(revision 19105)
+++ /issm/trunk/src/m/contrib/gravity/code_densite/density_rock_uneven.cpp	(revision 19105)
@@ -0,0 +1,516 @@
+#include <iostream>
+#include <cmath>
+#include <fstream>
+#include <string>
+#include <cstdio>
+#include <cstdlib>
+#include <time.h>
+#include <cassert>
+#include <gsl/gsl_multifit.h>
+#include "mpi.h"
+using namespace std;
+
+class Matrix{/*{{{*/
+	private:
+		int     M;        /*Number of lines   */
+		int     N;        /*Number if Columns */
+		double *values;
+	public:
+		Matrix(int m_in,int n_in){/*{{{*/
+			this->M = m_in;
+			this->N = n_in;
+			this->values = new double[M*N]();
+		}/*}}}*/
+		~Matrix(){/*{{{*/
+			delete [] this->values;
+		}/*}}}*/
+		void Echo(void){/*{{{*/
+			for(int i=0;i<M;i++){
+				for(int j=0;j<N;j++){
+					cout << " " << this->values[i*N+j];
+				}
+				cout << endl;
+			}
+		}/*}}}*/
+		void SetValue(int i,int j,double value){/*{{{*/
+			this->values[i*N+j] = value;
+		}/*}}}*/
+		double GetValue(int i,int j){/*{{{*/
+			return this->values[i*N+j];
+		}/*}}}*/
+		void GetSize(int* pM,int* pN){/*{{{*/
+			*pM = this->M;
+			*pN = this->N;
+		}/*}}}*/
+		double* GetPointer(void){/*{{{*/
+			return this->values;
+		}/*}}}*/
+		void MatrixSum(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) + B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixDiff(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) - B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixAbs(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,fabs(A->GetValue(i,j)));
+				}
+			}
+		}/*}}}*/
+		void MatrixEqual(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		double MatrixInternSum(){/*{{{*/
+			double sum=0;
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					sum+=this->GetValue(i,j);
+				}
+			}
+			return sum;
+		}/*}}}*/
+		void ExtractLine(Matrix* A,int i){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(M_A==1 && this->N==N_A);
+			for(int j=0;j<this->N;j++){
+				A->SetValue(0,j,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void ExtractColumn(Matrix* A,int j){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(N_A==1 && this->M==M_A);
+			for(int i=0;i<this->M;i++){
+				A->SetValue(i,0,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void AddNumber(double a){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,this->GetValue(i,j) + a);
+				}
+			}
+		}/*}}}*/
+};/*}}}*/
+
+/*Local prototypes{{{*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy);
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny);
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,Matrix *dlevel);
+void plouff(Matrix *g,Matrix *Pobs,Matrix *Pp,Matrix * mesh,Matrix *rho,int dx,int dy, int dn,int m,int n,int l,Matrix *evalid,int my_rank,int num_procs);
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny);
+void reshape(Matrix* V,Matrix* V1,int nx,int ny);
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,Matrix *dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my,int my_rank,int num_procs);
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B);
+/*}}}*/
+
+int main(int argc,char *argv[]){/*{{{*/
+
+	int my_rank,num_procs;
+
+	MPI_Init(&argc, &argv);
+
+	MPI_Comm_size(MPI_COMM_WORLD,&num_procs);
+	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
+
+	/* Define the variables {{{*/
+
+	int    dx     = 1000;   /* prism dimension in x-direction                           */
+	int    dy     = 1000;   /* prism dimension in y-direction                           */
+	int    mx     = 99;    /* number of prisms in x-direction                          */
+	int    my     = 99;    /* number of prisms in y-direction                          */
+	int    nx     = 99;    /* number of data points in x-direction                     */
+	int    ny     = 99;    /* number of data points in y-direction                     */
+	int    dn     = 15000; /* distance for neighbouting prisms for gravity calculation */
+
+	Matrix *Pobs=new Matrix(nx*ny,2); /* data positions */
+	makep(Pobs,nx,ny,dx,dy);
+	// Pobs->Echo();
+
+
+
+	Matrix *Pp=new Matrix(mx*my,2); /* prisms positions */
+	makep(Pp,mx,my,dx,dy);
+	// Pp->Echo();
+
+	double  rhoi = 917;           /* ice density     */
+	double  rhow = 1030;          /* water density   */
+	// double  rhos = 2013;		      /* sediment density */
+
+	double rhoc_min=2000.;
+	double rhoc_max=3000.;
+
+	Matrix *Rho  = new Matrix(1,2);
+	Rho->SetValue(0,0,rhoi);
+	Rho->SetValue(0,1,rhow);
+	Matrix *rho1  = new Matrix(1,3);
+	rho1->SetValue(0,0,rhoi);
+	rho1->SetValue(0,1,rhow);
+	rho1->SetValue(0,2,rhoc_min);
+	Matrix *rho2  = new Matrix(1,2);
+	rho2->SetValue(0,0,rhoi-rhoc_min);
+	rho2->SetValue(0,1,rhow-rhoc_min);
+
+
+	Matrix *xobs= new Matrix(ny,nx);
+	Matrix *yobs= new Matrix(ny,nx);
+
+	vec2grid(Pobs,xobs,yobs,nx,ny);
+	//	xobs->Echo();
+	//	yobs->Echo();
+
+
+	/*}}}*/     
+	/* load the data {{{*/
+
+
+	double inputnumber;
+
+	/* Levels of data acquisition */
+
+	ifstream file0("dataalti.txt");
+	Matrix * dlevel= new Matrix(nx*ny,1);
+	for(int i=0;i<ny*nx; i++){
+		file0 >> inputnumber;
+		dlevel->SetValue(i,0,inputnumber);
+	}
+	file0.close();
+
+	/* Observed gravity anomaly */
+
+	ifstream file1("gravityraw.txt");
+	Matrix * gobs= new Matrix(nx*ny,1);
+	for(int i=0;i<ny*nx; i++){ 
+		file1 >> inputnumber;
+		gobs->SetValue(i,0, inputnumber*1e-5);
+	}
+	file1.close();
+	//	gobs->Echo();
+
+
+	/* id of grid to evaluate misfit */
+
+
+	ifstream file4("evalid1.txt");
+	Matrix * evalid= new Matrix(nx*ny,1);
+	for(int s=0;s<nx*ny; s++){ 
+		file4 >> inputnumber;
+		evalid->SetValue(s,0,inputnumber);
+	}
+	file4.close();
+	//	evalid->Echo();
+
+	/* initial guess of the model */
+
+	ifstream file5("m0_102714contzach.txt");
+	Matrix * mesh_ini= new Matrix(mx*my,3);
+	for(int s=0;s<mx*my; s++){ 
+		for(int j=0;j<3;j++){
+			file5 >> inputnumber;
+			mesh_ini->SetValue(s,j,inputnumber);
+		}
+	}
+	file5.close();
+	//	mesh_ini->Echo();
+	/*}}}*/
+	/* Test {{{ */
+
+
+	double rhoc=rhoc_min;
+	double rhoc_opti=rhoc_min;
+	double E=misfit(mesh_ini,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my,my_rank,num_procs);
+	double E_opti=E;
+
+	for(int i=rhoc_min;i<rhoc_max+1;i++){
+		rhoc=i;
+		rho1->SetValue(0,2,rhoc);
+		rho2->SetValue(0,0,rhoi-rhoc);
+		rho2->SetValue(0,1,rhow-rhoc);
+
+		E=misfit(mesh_ini,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my,my_rank,num_procs);
+
+		if(E<E_opti){
+			E_opti=E;
+			rhoc_opti=rhoc;
+		}
+		if(my_rank==0){
+			cout<<rhoc<<"  "<<rhoc_opti<<"  "<<E<<"  "<<E_opti<<endl;
+		}
+	}
+
+
+
+
+	delete Pobs;
+	delete Pp;
+	delete Rho;
+	delete rho1;
+	delete rho2;
+	delete xobs;
+	delete yobs;
+	delete mesh_ini;
+	delete evalid;
+	delete gobs;
+
+	/*}}}*/
+
+	MPI_Finalize();
+
+	return 0;
+}/*}}}*/
+
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B){/*{{{*/
+
+	/*GSL Matrices and vectors: */
+	int    M,N;
+	double chisq;
+	/*Get system size*/
+	A->GetSize(&M,&N);
+
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix* a = gsl_matrix_alloc(M,N);
+	for(int i=0;i<M;i++){
+		for(int j=0;j<N;j++){
+			gsl_matrix_set (a,i,j,A->GetValue(i,j));
+		}
+	}
+	gsl_vector* b = gsl_vector_alloc(M);
+	for(int i=0;i<M;i++){
+		gsl_vector_set(b,i,B->GetValue(i,0));
+	}
+
+	gsl_vector* x = gsl_vector_alloc(N);
+	gsl_matrix* cov = gsl_matrix_alloc(N,N);
+
+	/*Least square fit: */
+	gsl_multifit_linear_workspace* work = gsl_multifit_linear_alloc(M,N);
+	gsl_multifit_linear (a, b, x, cov, &chisq, work);
+	gsl_multifit_linear_free (work);
+
+	/*Clean up and assign output pointer*/
+	Matrix* X = new Matrix(N,1);
+	for(int j=0;j<N;j++){
+		X->SetValue(j,0,gsl_vector_get(x,j));
+	}
+	*pX = X;
+
+	gsl_matrix_free(a);
+	gsl_vector_free(x);
+	gsl_vector_free(b);
+	gsl_matrix_free(cov);
+
+}/*}}}*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			Pobs->SetValue(j+nx*i,0,j*dx);
+			Pobs->SetValue(j+nx*i,1,i*dy);
+		}
+	}
+}/*}}}*/
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+			V2->SetValue(i,j, V->GetValue(j+nx*i,1));
+		}
+	}
+}/*}}}*/
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,Matrix* dlevel){/*{{{*/
+	int sizem1,sizem2;
+	m->GetSize(&sizem1,&sizem2);
+	for(int i=0;i<sizem1;i++){
+		for(int j=0;j<sizem2+1;j++){
+			if(j<sizem2){
+				m1->SetValue(i,j,1e-10*(sizem2+1-j));
+				m2->SetValue(i,j,m->GetValue(i,j));
+				if(m->GetValue(i,j)<0){
+					m1->SetValue(i,j,m->GetValue(i,j));
+					m2->SetValue(i,j,i*1e-10);
+				}
+				m1->SetValue(i,j,m1->GetValue(i,j)+dlevel->GetValue(i,1));
+				m2->SetValue(i,j,m2->GetValue(i,j)+dlevel->GetValue(i,1));
+			}
+			else{
+				m1->SetValue(i,j,1e-10+dlevel->GetValue(i,1));
+			}
+		}
+	}
+}/*}}}*/
+void plouff(Matrix *g,Matrix *Pobs,Matrix *Pp,Matrix * mesh,Matrix *rho,int dx,int dy, int dn,int m,int n,int l,Matrix *evalid,int my_rank,int num_procs){/*{{{*/
+	double gg=6.673e-11;
+	int si,sj,id,s;
+	double R,Q,P;
+	Matrix *xp= new Matrix(1,2);
+	Matrix *yp= new Matrix(1,2);
+	Matrix *xpp= new Matrix(1,2);
+	Matrix *ypp= new Matrix(1,2);
+	Matrix *U= new Matrix(l,4);
+	Matrix *U1=new Matrix(1,4);
+	Matrix *U2=new Matrix(1,4);
+	Matrix *gl= new Matrix(1,l-1);
+	bool test=true;
+
+	double *glocal=new double[n]();
+
+	for(int c=my_rank;c<n;c+=num_procs){
+		glocal[c]=0;
+		if(evalid->GetValue(c,0)==1){
+			for(int a=0;a<m;a++){
+				test=true;
+				xp->SetValue(0,0,Pp->GetValue(a,0)-Pobs->GetValue(c,0));
+				xp->SetValue(0,1,Pp->GetValue(a,0)-Pobs->GetValue(c,0)+dx);
+				if(xp->GetValue(0,0)<0 && xp->GetValue(0,0)<xp->GetValue(0,1) && xp->GetValue(0,0)*xp->GetValue(0,1)>=0){
+					xpp->SetValue(0,0,xp->GetValue(0,1));
+					xpp->SetValue(0,1,xp->GetValue(0,0));
+					xp->MatrixAbs(xpp);
+				}
+				yp->SetValue(0,0,Pp->GetValue(a,1)-Pobs->GetValue(c,1));
+				yp->SetValue(0,1,Pp->GetValue(a,1)-Pobs->GetValue(c,1)+dy);
+				if(yp->GetValue(0,0)<0 && yp->GetValue(0,0)<yp->GetValue(0,1) && yp->GetValue(0,0)*yp->GetValue(0,1)>=0){
+					ypp->SetValue(0,0,yp->GetValue(0,1));
+					ypp->SetValue(0,1,yp->GetValue(0,0));
+					yp->MatrixAbs(ypp);
+				}
+				P=sqrt(xp->GetValue(0,0)*xp->GetValue(0,0)+yp->GetValue(0,0)*yp->GetValue(0,0));
+				if(P>dn){
+					test=false;
+					for(int i=0;i<l-1;i++){
+						gl->SetValue(0,i,0);
+					}
+				}
+				if(test==true){
+					si=1;
+					sj=1;
+					id=0;
+					for(int i=0;i<2;i++){
+						si*=-1;
+						for(int j=0;j<2;j++){
+							sj*=-1;
+							s=si*sj;
+							for(int k=0;k<l;k++){
+								R=sqrt(xp->GetValue(0,i)*xp->GetValue(0,i)+yp->GetValue(0,j)*yp->GetValue(0,j)+mesh->GetValue(a,k)*mesh->GetValue(a,k));
+								Q=atan(xp->GetValue(0,i)*yp->GetValue(0,j)/(mesh->GetValue(a,k)*R));
+								U->SetValue(k,id,s*(mesh->GetValue(a,k)*Q-xp->GetValue(0,i)*log(R+yp->GetValue(0,j))-yp->GetValue(0,j)*log(R+xp->GetValue(0,i))));
+							}
+							id++;
+						}
+					}
+					for(int b=0;b<l-1;b++){
+						U->ExtractLine(U1,b);
+						U->ExtractLine(U2,b+1);
+						gl->SetValue(0,b,rho->GetValue(0,b)*(U1->MatrixInternSum()*(-1)+U2->MatrixInternSum()));
+					}
+				}
+				glocal[c]=glocal[c]+gg*gl->MatrixInternSum();
+			}
+		}
+	}
+
+	MPI_Allreduce(glocal,g->GetPointer(),n,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+
+	delete xp;
+	delete yp;
+	delete xpp;
+	delete ypp;
+	delete gl;
+	delete U;
+	delete U1;
+	delete U2;
+	delete []glocal;
+}/*}}}*/
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+		}
+	}
+}/*}}}*/
+void reshape(Matrix* V,Matrix* V1,int nx,int ny){/*{{{*/
+	for (int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			V1->SetValue(j+nx*i,0,V->GetValue(i,j));
+		}
+	}
+}/*}}}*/
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,Matrix *dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my,int my_rank,int num_procs){/*{{{*/
+	Matrix* m1=new Matrix(mx*my,4);
+	Matrix* m2=new Matrix(mx*my,3);
+	Matrix* g1=new Matrix(nx*ny,1);
+	Matrix* g2=new Matrix(nx*ny,1);
+	Matrix* g=new Matrix(nx*ny,1);
+	Matrix* gcalgr=new Matrix(ny,nx);
+	Matrix* gcalvec=new Matrix(nx*ny,1);
+	Matrix* df=new Matrix(nx*ny,1);
+	Matrix* G=new Matrix(nx*ny,3);
+	double a=0;
+	double b=0;
+	double e=0;
+	msplit(m0,m1,m2,dlevel);
+	plouff(g1,Pobs,Pp,m1,rho1,dx,dy,dn,mx*my,nx*ny,4,evalid, my_rank, num_procs);
+	plouff(g2,Pobs,Pp,m2,rho2,dx,dy,dn,mx*my,nx*ny,3,evalid, my_rank, num_procs);
+	g->MatrixSum(g1,g2);
+	vec2gridsimple(g,gcalgr,nx,ny);
+	reshape(gcalgr,gcalvec,nx,ny);
+	for (int i=0;i<nx*ny;i++){
+		df->SetValue(i,0,evalid->GetValue(i,0)*(gobs->GetValue(i,0)-gcalvec->GetValue(i,0)));
+		G->SetValue(i,0,evalid->GetValue(i,0)*Pobs->GetValue(i,0));
+		G->SetValue(i,1,evalid->GetValue(i,0)*Pobs->GetValue(i,1));
+		G->SetValue(i,2,evalid->GetValue(i,0));
+	}
+	Matrix* M = NULL;
+	GSLsquarefit(&M,G,df);
+
+	for (int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			gcalgr->SetValue(i,j,gcalgr->GetValue(i,j)+xobs->GetValue(i,j)*M->GetValue(0,0)+yobs->GetValue(i,j)*M->GetValue(1,0)+M->GetValue(2,0));
+		}
+	}
+	reshape(gcalgr,g,nx,ny);
+	for (int i=0;i<nx*ny;i++){
+		a=a+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)-g->GetValue(i,0)));
+		b=b+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)+g->GetValue(i,0)));
+	}
+	e=2*a/(a+b);
+
+	delete m1;
+	delete m2;
+	delete g1;
+	delete g2;
+	delete g;
+	delete gcalgr;
+	delete gcalvec;
+	delete df;
+	delete G;
+	delete M;
+
+	return e;
+}/*}}}*/
Index: /issm/trunk/src/m/contrib/gravity/code_inversion/vfsa_mpi.cpp
===================================================================
--- /issm/trunk/src/m/contrib/gravity/code_inversion/vfsa_mpi.cpp	(revision 19105)
+++ /issm/trunk/src/m/contrib/gravity/code_inversion/vfsa_mpi.cpp	(revision 19105)
@@ -0,0 +1,876 @@
+#include <iostream>
+#include <cmath>
+#include <fstream>
+#include <string>
+#include <cstdio>
+#include <cstdlib>
+#include <time.h>
+#include <cassert>
+#include <gsl/gsl_multifit.h>
+#include "mpi.h"
+using namespace std;
+
+class Matrix{/*{{{*/
+	private:
+		int     M;        /*Number of lines   */
+		int     N;        /*Number if Columns */
+		double *values;
+	public:
+		Matrix(int m_in,int n_in){/*{{{*/
+			this->M = m_in;
+			this->N = n_in;
+			this->values = new double[M*N]();
+		}/*}}}*/
+		~Matrix(){/*{{{*/
+			delete [] this->values;
+		}/*}}}*/
+		void Echo(void){/*{{{*/
+			for(int i=0;i<M;i++){
+				for(int j=0;j<N;j++){
+					cout << " " << this->values[i*N+j];
+				}
+				cout << endl;
+			}
+		}/*}}}*/
+		void SetValue(int i,int j,double value){/*{{{*/
+			this->values[i*N+j] = value;
+		}/*}}}*/
+		double GetValue(int i,int j){/*{{{*/
+			return this->values[i*N+j];
+		}/*}}}*/
+		void GetSize(int* pM,int* pN){/*{{{*/
+			*pM = this->M;
+			*pN = this->N;
+		}/*}}}*/
+		double* GetPointer(void){/*{{{*/
+			return this->values;
+		}/*}}}*/
+		void MatrixSum(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) + B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixDiff(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) - B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixAbs(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,fabs(A->GetValue(i,j)));
+				}
+			}
+		}/*}}}*/
+		void MatrixEqual(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		double MatrixInternSum(){/*{{{*/
+			double sum=0;
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					sum+=this->GetValue(i,j);
+				}
+			}
+			return sum;
+		}/*}}}*/
+		void ExtractLine(Matrix* A,int i){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(M_A==1 && this->N==N_A);
+			for(int j=0;j<this->N;j++){
+				A->SetValue(0,j,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void ExtractColumn(Matrix* A,int j){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(N_A==1 && this->M==M_A);
+			for(int i=0;i<this->M;i++){
+				A->SetValue(i,0,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void AddNumber(double a){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,this->GetValue(i,j) + a);
+				}
+			}
+		}/*}}}*/
+};/*}}}*/
+
+/*Local prototypes{{{*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy);
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny);
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,double dlevel);
+void plouff(Matrix *g,Matrix *Pobs,Matrix *Pp,Matrix * mesh,Matrix *rho,int dx,int dy, int dn,int m,int n,int l,Matrix *evalid,int my_rank,int num_procs);
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny);
+void reshape(Matrix* V,Matrix* V1,int nx,int ny);
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,double dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my,int my_rank,int num_procs);
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B);
+double signe(double a);
+void filtergrav(Matrix* A,Matrix* Ain,double ctr,double sd,int mx,int my);
+void newmodelgen(Matrix* m0,Matrix* m1,Matrix* bathy,Matrix* icethick,int mx,int my,double T,double ptval,double mmax,double mmax2,double ctr,double sd, Matrix *landmask);
+double coolshed(double T0,double k,double c,double D);
+/*}}}*/
+
+int main(int argc,char *argv[]){/*{{{*/
+	
+	int my_rank,num_procs;
+
+	MPI_Init(&argc, &argv);
+
+	MPI_Comm_size(MPI_COMM_WORLD,&num_procs);
+	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
+
+	/* Seed the random number generator {{{*/
+		srand (time(NULL));            /*}}}*/
+	/* Define the variables {{{*/
+
+	int    dx     = 1000;   /* prism dimension in x-direction                           */
+	int    dy     = 1000;   /* prism dimension in y-direction                           */
+	int    mx     = 99;    /* number of prisms in x-direction                          */
+	int    my     = 99;    /* number of prisms in y-direction                          */
+	int    nx     = 99;    /* number of data points in x-direction                     */
+	int    ny     = 99;    /* number of data points in y-direction                     */
+	int    dn     = 15000; /* distance for neighbouting prisms for gravity calculation */
+	double ptval  = 100.;  /* max. amount to perturb model                             */
+	double ptval2 = 100.;
+
+	Matrix *Pobs=new Matrix(nx*ny,2); /* data positions */
+	makep(Pobs,nx,ny,dx,dy);
+	// Pobs->Echo();
+
+
+	Matrix *Pp=new Matrix(mx*my,2); /* prisms positions */
+	makep(Pp,mx,my,dx,dy);
+	// Pp->Echo();
+
+	double  rhoi = 917;           /* ice density     */
+	double  rhow = 1030;          /* water density   */
+	// double  rhos = 2013;		      /* sediment density */
+	double  rhoc = 2670;          /* bedrock density */
+
+	Matrix *Rho  = new Matrix(1,2);
+	Rho->SetValue(0,0,rhoi);
+	Rho->SetValue(0,1,rhow);
+	Matrix *rho1  = new Matrix(1,3);
+	rho1->SetValue(0,0,rhoi);
+	rho1->SetValue(0,1,rhow);
+	rho1->SetValue(0,2,rhoc);
+	Matrix *rho2  = new Matrix(1,2);
+	rho2->SetValue(0,0,rhoi-rhoc);
+	rho2->SetValue(0,1,rhow-rhoc);
+
+	double dlevel=3134;         /* level of data acquisition */
+
+	double ctr=1;            /* parameter for filtering */
+	double sd=0.1;
+
+	Matrix *xobs= new Matrix(ny,nx);
+	Matrix *yobs= new Matrix(ny,nx);
+
+	vec2grid(Pobs,xobs,yobs,nx,ny);
+	//	xobs->Echo();
+	//	yobs->Echo();
+
+
+	double mmax  = 1000;               /* max value for layer interfaces */
+	double mmax2 = 1000;
+	double mmax3 = 1000;
+
+	/* control parameter for temperature schedule  */
+
+	double ca=0.9;                    /* for acceptance */
+	double cm=0.5;                    /* for model perturbation */
+
+	double T0a          = 0.1;      /* initial temperature for acceptance           */
+	double T0m          = 0.9;      /* initial temperature for model perturbation   */
+	double D            = 2;        /* dimension of the model                       */
+	int    maxconsecrej = 1000;     /* max consecutive rejection                    */
+	int    maxsuccess   = 100;      /* max number of success within one temperature */
+	double T_min        = 1e-10;    /* stopping temp                                */
+	double Tred         = 1;
+	double E_min        = -1000000;
+	double E_exp        = 0.0291;   /* expected misfit                              */
+	int    maxiter      = 10000;
+	int    maxtotaliter = 1000000;
+	double Tol          = 1e-10;    /* tolerance on misfit                          */
+	int    sfreq        = 100;
+
+	/*}}}*/     
+	/* load the data {{{*/
+
+	/*landmask */
+
+	ifstream file("landmaskzach.txt");
+	Matrix * landmask= new Matrix(nx*ny,1);
+	double inputnumber;
+	for(int i=0;i<ny*nx; i++){ 
+		file >> inputnumber;
+		landmask->SetValue(i,0,inputnumber);
+	}
+	file.close();
+
+	/* Observed gravity anomaly */
+
+	ifstream file1("gravityzach.txt");
+	Matrix * gobs= new Matrix(nx*ny,1);
+	for(int i=0;i<ny*nx; i++){ 
+		file1 >> inputnumber;
+		gobs->SetValue(i,0, inputnumber*1e-5);
+	}
+	file1.close();
+	//	gobs->Echo();
+
+	/* load data about the ice thickness */
+
+	ifstream file2("icethickzach.txt");
+	Matrix * icethick= new Matrix(mx*my,1);
+	for(int s=0;s<mx*my; s++){ 
+		file2 >> inputnumber;
+		icethick->SetValue(s,0,inputnumber);
+	}
+	file2.close();
+	//	icethick->Echo();
+
+	/* load the batimethry data */
+
+	ifstream file3("bathymetryzach.txt");
+	Matrix * bathy= new Matrix(mx*my,1);
+	for(int s=0;s<mx*my; s++){ 
+		file3 >> inputnumber;
+		bathy->SetValue(s,0,inputnumber);
+	}
+	file3.close();
+	//	bathy->Echo();
+
+	/* id of grid to evaluate misfit */
+
+
+	ifstream file4("evalidzach.txt");
+	Matrix * evalid= new Matrix(nx*ny,1);
+	for(int s=0;s<nx*ny; s++){ 
+		file4 >> inputnumber;
+		evalid->SetValue(s,0,inputnumber);
+	}
+	file4.close();
+	//	evalid->Echo();
+
+	/* initial guess of the model */
+
+	ifstream file5("m0_102714contzach.txt");
+	Matrix * mesh_ini= new Matrix(mx*my,3);
+	for(int s=0;s<mx*my; s++){ 
+		for(int j=0;j<3;j++){
+			file5 >> inputnumber;
+			mesh_ini->SetValue(s,j,inputnumber);
+		}
+	}
+	file5.close();
+	//	mesh_ini->Echo();
+	/*}}}*/
+	/* VFSA {{{ */
+
+	/* name of the files to save results */
+	std::ofstream savefile1 ("r_zach.txt");
+	std::ofstream savefile2("m_zach.txt");
+
+	/* counters initialization */
+	int    success   = 0;
+	int    finished  = 0;
+	int    consec    = 0;
+	double Ta        = T0a;
+	double Tm        = T0m;
+	int    iterT     = 0;   /* iteration within a T      */
+	int    total     = 0;   /* total number of iteration */
+	int    totaliter = 0;
+	int    msave     = 0;
+	double E_new;
+	double E_final;
+	double dE;
+	double P;
+	double rn;
+	Matrix* m_old    = new Matrix(mx *my,3);
+	Matrix* m_min    = new Matrix(mx *my,3);
+	Matrix* m_new    = new Matrix(mx *my,3);
+	m_old->MatrixEqual(mesh_ini);
+
+	/* calculate initial misfit */
+	double E_old=misfit(m_old,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my, my_rank, num_procs);
+	/* record initial settings */
+	if(!my_rank){
+		savefile1 << "P     "<< "Ta    "<< "Tm    "<< "Eold  "<< "totaliter "<< "Tred   "<< endl;
+		savefile1 << "nan   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+		savefile2 << totaliter<< endl;
+		for(int i=0;i<mx*my;i++){
+			savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+		}
+		savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+	}
+	/* beginning of the loop */
+
+	while(finished==0){
+		iterT++;
+		totaliter++;
+
+		/* stop or reduce T */
+		if(iterT>=maxiter || success>maxsuccess){
+			if(Ta<T_min || total>maxtotaliter || fabs(E_old)<=Tol){
+				finished=1;
+				total+=iterT;
+				break;
+			}
+			else{ /* reduce T */
+				Ta=coolshed(T0a,Tred,ca,D);
+				Tm=coolshed(T0m,Tred,cm,D);
+				total+=iterT;
+				iterT=0;
+				success=1;
+				Tred++;
+				consec=0;
+			}
+		}
+
+		/* update model and calculate energy */
+
+		newmodelgen(m_old,m_new,bathy,icethick,mx,my,Tm,ptval,mmax,mmax2,ctr,sd, landmask);  /* new model */
+		E_new=misfit(m_new,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my, my_rank, num_procs); /* new energy */
+		dE=E_new-E_old;                                        /* energy difference */
+
+		/* acceptance probability */
+
+		P=exp(-dE/Ta);
+
+		/* stop if energy is lower than specified minimum */
+		if (E_new<E_min){
+			m_old->MatrixEqual(m_new);
+			E_old=E_new;
+			break;
+		}
+
+		rn=rand()/double (RAND_MAX);
+
+		/* accept new model or not */
+		if(dE<=0){
+			m_old->MatrixEqual(m_new);
+			E_old=E_new;
+			E_final=E_old;
+			success++;
+			consec=0;
+			if(!my_rank){
+				savefile1 << P<<"   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+			}
+			if(Ta<1e-3){
+				if(!my_rank){
+					savefile2 << totaliter<< endl;
+					for(int i=0;i<mx*my;i++){
+						savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+					}
+					savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+				}
+			}
+		}
+		else{
+			if(P>rn){
+				m_old->MatrixEqual(m_new);
+				E_old=E_new;
+				success++;
+				consec=0;
+				if(!my_rank){
+					savefile1 << P<<"   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+					if(Ta<1e-3){
+						savefile2 << totaliter<< endl;
+						for(int i=0;i<mx*my;i++){
+							savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+						}
+						savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+					}
+				}
+			}
+			else{
+				consec++;
+			}
+		}
+	}
+
+	m_min->MatrixEqual(m_old);
+	if(!my_rank){
+		savefile1 << "nan"<<"   "<<  "nan"<<"   "<< "nan"<<"   "<< E_final<<"     "<< "nan"<<"         "<< "nan" <<"  "<< endl;
+		savefile2 << " Mesh final"<< endl;
+		for(int i=0;i<mx*my;i++){
+			savefile2 << m_min->GetValue(i,0)<<"   "<< m_min->GetValue(i,1)<<"   "<< m_min->GetValue(i,2)<<endl;
+		}
+	}
+	savefile1.close();
+	savefile2.close();
+
+	delete m_old;
+	delete m_min;
+	delete m_new;
+	delete Pobs;
+	delete Pp;
+	delete Rho;
+	delete rho1;
+	delete rho2;
+	delete xobs;
+	delete yobs;
+	delete mesh_ini;
+	delete bathy;
+	delete icethick;
+	delete evalid;
+	delete gobs;
+	delete landmask;
+
+	/*}}}*/
+
+   MPI_Finalize();
+
+	return 0;
+}/*}}}*/
+
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B){/*{{{*/
+
+	/*GSL Matrices and vectors: */
+	int    M,N;
+	double chisq;
+	/*Get system size*/
+	A->GetSize(&M,&N);
+
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix* a = gsl_matrix_alloc(M,N);
+	for(int i=0;i<M;i++){
+		for(int j=0;j<N;j++){
+			gsl_matrix_set (a,i,j,A->GetValue(i,j));
+		}
+	}
+	gsl_vector* b = gsl_vector_alloc(M);
+	for(int i=0;i<M;i++){
+		gsl_vector_set(b,i,B->GetValue(i,0));
+	}
+
+	gsl_vector* x = gsl_vector_alloc(N);
+	gsl_matrix* cov = gsl_matrix_alloc(N,N);
+
+	/*Least square fit: */
+	gsl_multifit_linear_workspace* work = gsl_multifit_linear_alloc(M,N);
+	gsl_multifit_linear (a, b, x, cov, &chisq, work);
+	gsl_multifit_linear_free (work);
+
+	/*Clean up and assign output pointer*/
+	Matrix* X = new Matrix(N,1);
+	for(int j=0;j<N;j++){
+		X->SetValue(j,0,gsl_vector_get(x,j));
+	}
+	*pX = X;
+
+	gsl_matrix_free(a);
+	gsl_vector_free(x);
+	gsl_vector_free(b);
+	gsl_matrix_free(cov);
+
+}/*}}}*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			Pobs->SetValue(j+nx*i,0,j*dx);
+			Pobs->SetValue(j+nx*i,1,i*dy);
+		}
+	}
+}/*}}}*/
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+			V2->SetValue(i,j, V->GetValue(j+nx*i,1));
+		}
+	}
+}/*}}}*/
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,double dlevel){/*{{{*/
+	int sizem1,sizem2;
+	m->GetSize(&sizem1,&sizem2);
+	for(int i=0;i<sizem1;i++){
+		for(int j=0;j<sizem2+1;j++){
+			if(j<sizem2){
+				m1->SetValue(i,j,1e-10*(sizem2+1-j));
+				m2->SetValue(i,j,m->GetValue(i,j));
+				if(m->GetValue(i,j)<0){
+					m1->SetValue(i,j,m->GetValue(i,j));
+					m2->SetValue(i,j,i*1e-10);
+				}
+				m1->SetValue(i,j,m1->GetValue(i,j));
+				m2->SetValue(i,j,m2->GetValue(i,j));
+			}
+			else{
+				m1->SetValue(i,j,1e-10);
+			}
+		}
+	}
+	m1->AddNumber(dlevel);
+	m2->AddNumber(dlevel);
+}/*}}}*/
+void plouff(Matrix *g,Matrix *Pobs,Matrix *Pp,Matrix * mesh,Matrix *rho,int dx,int dy, int dn,int m,int n,int l,Matrix* evalid,int my_rank,int num_procs){/*{{{*/
+	double gg=6.673e-11;
+	int si,sj,id,s;
+	double R,Q,P;
+	Matrix *xp= new Matrix(1,2);
+	Matrix *yp= new Matrix(1,2);
+	Matrix *xpp= new Matrix(1,2);
+	Matrix *ypp= new Matrix(1,2);
+	Matrix *U= new Matrix(l,4);
+	Matrix *U1=new Matrix(1,4);
+	Matrix *U2=new Matrix(1,4);
+	Matrix *gl= new Matrix(1,l-1);
+	bool test=true;
+
+	double *glocal=new double[n]();
+
+	for(int c=my_rank;c<n;c+=num_procs){
+		glocal[c]=0;
+		if(evalid->GetValue(i,0)==1){
+			for(int a=0;a<m;a++){
+				test=true;
+				xp->SetValue(0,0,Pp->GetValue(a,0)-Pobs->GetValue(c,0));
+				xp->SetValue(0,1,Pp->GetValue(a,0)-Pobs->GetValue(c,0)+dx);
+				if(xp->GetValue(0,0)<0 && xp->GetValue(0,0)<xp->GetValue(0,1) && xp->GetValue(0,0)*xp->GetValue(0,1)>=0){
+					xpp->SetValue(0,0,xp->GetValue(0,1));
+					xpp->SetValue(0,1,xp->GetValue(0,0));
+					xp->MatrixAbs(xpp);
+				}
+				yp->SetValue(0,0,Pp->GetValue(a,1)-Pobs->GetValue(c,1));
+				yp->SetValue(0,1,Pp->GetValue(a,1)-Pobs->GetValue(c,1)+dy);
+				if(yp->GetValue(0,0)<0 && yp->GetValue(0,0)<yp->GetValue(0,1) && yp->GetValue(0,0)*yp->GetValue(0,1)>=0){
+					ypp->SetValue(0,0,yp->GetValue(0,1));
+					ypp->SetValue(0,1,yp->GetValue(0,0));
+					yp->MatrixAbs(ypp);
+				}
+				P=sqrt(xp->GetValue(0,0)*xp->GetValue(0,0)+yp->GetValue(0,0)*yp->GetValue(0,0));
+				if(P>dn){
+					test=false;
+					for(int i=0;i<l-1;i++){
+						gl->SetValue(0,i,0);
+					}
+				}
+				if(test==true){
+					si=1;
+					sj=1;
+					id=0;
+					for(int i=0;i<2;i++){
+						si*=-1;
+						for(int j=0;j<2;j++){
+							sj*=-1;
+							s=si*sj;
+							for(int k=0;k<l;k++){
+								R=sqrt(xp->GetValue(0,i)*xp->GetValue(0,i)+yp->GetValue(0,j)*yp->GetValue(0,j)+mesh->GetValue(a,k)*mesh->GetValue(a,k));
+								Q=atan(xp->GetValue(0,i)*yp->GetValue(0,j)/(mesh->GetValue(a,k)*R));
+								U->SetValue(k,id,s*(mesh->GetValue(a,k)*Q-xp->GetValue(0,i)*log(R+yp->GetValue(0,j))-yp->GetValue(0,j)*log(R+xp->GetValue(0,i))));
+							}
+							id++;
+						}
+					}
+					for(int b=0;b<l-1;b++){
+						U->ExtractLine(U1,b);
+						U->ExtractLine(U2,b+1);
+						gl->SetValue(0,b,rho->GetValue(0,b)*(U1->MatrixInternSum()*(-1)+U2->MatrixInternSum()));
+					}
+				}
+				glocal[c]=glocal[c]+gg*gl->MatrixInternSum();
+			}
+		}
+	}
+
+	MPI_Allreduce(glocal,g->GetPointer(),n,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+
+	delete xp;
+	delete yp;
+	delete xpp;
+	delete ypp;
+	delete gl;
+	delete U;
+	delete U1;
+	delete U2;
+	delete []glocal;
+}/*}}}*/
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+		}
+	}
+}/*}}}*/
+void reshape(Matrix* V,Matrix* V1,int nx,int ny){/*{{{*/
+	for (int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			V1->SetValue(j+nx*i,0,V->GetValue(i,j));
+		}
+	}
+}/*}}}*/
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,double dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my,int my_rank,int num_procs){/*{{{*/
+	Matrix* m1=new Matrix(mx*my,4);
+	Matrix* m2=new Matrix(mx*my,3);
+	Matrix* g1=new Matrix(nx*ny,1);
+	Matrix* g2=new Matrix(nx*ny,1);
+	Matrix* g=new Matrix(nx*ny,1);
+	Matrix* gcalgr=new Matrix(ny,nx);
+	Matrix* gcalvec=new Matrix(nx*ny,1);
+	Matrix* df=new Matrix(nx*ny,1);
+	Matrix* G=new Matrix(nx*ny,3);
+	double a=0;
+	double b=0;
+	double e=0;
+	msplit(m0,m1,m2,dlevel);
+	plouff(g1,Pobs,Pp,m1,rho1,dx,dy,dn,mx*my,nx*ny,4,evalid, my_rank, num_procs);
+	plouff(g2,Pobs,Pp,m2,rho2,dx,dy,dn,mx*my,nx*ny,3,evalid, my_rank, num_procs);
+	g->MatrixSum(g1,g2);
+	vec2gridsimple(g,gcalgr,nx,ny);
+	reshape(gcalgr,gcalvec,nx,ny);
+	for (int i=0;i<nx*ny;i++){
+		df->SetValue(i,0,evalid->GetValue(i,0)*(gobs->GetValue(i,0)-gcalvec->GetValue(i,0)));
+		G->SetValue(i,0,evalid->GetValue(i,0)*Pobs->GetValue(i,0));
+		G->SetValue(i,1,evalid->GetValue(i,0)*Pobs->GetValue(i,1));
+		G->SetValue(i,2,evalid->GetValue(i,0));
+	}
+	Matrix* M = NULL;
+	GSLsquarefit(&M,G,df);
+
+	for (int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			gcalgr->SetValue(i,j,gcalgr->GetValue(i,j)+xobs->GetValue(i,j)*M->GetValue(0,0)+yobs->GetValue(i,j)*M->GetValue(1,0)+M->GetValue(2,0));
+		}
+	}
+	reshape(gcalgr,g,nx,ny);
+	for (int i=0;i<nx*ny;i++){
+		a=a+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)-g->GetValue(i,0)));
+		b=b+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)+g->GetValue(i,0)));
+	}
+	e=2*a/(a+b);
+
+	delete m1;
+	delete m2;
+	delete g1;
+	delete g2;
+	delete g;
+	delete gcalgr;
+	delete gcalvec;
+	delete df;
+	delete G;
+	delete M;
+
+	return e;
+}/*}}}*/
+void newmodelgen(Matrix* m0,Matrix* m1,Matrix* bathy,Matrix* icethick,int mx,int my,double T,double ptval,double mmax,double mmax2,double ctr,double sd, Matrix *landmask){/*{{{*/
+	Matrix* m1gr=new Matrix(my,mx);
+	Matrix* m1grsm=new Matrix(my,mx);
+	Matrix* m1col=new Matrix(mx*my,1);
+	Matrix* m1gr2=new Matrix(my,mx);
+	Matrix* m1grsm2=new Matrix(my,mx);
+	Matrix* m1col2=new Matrix(mx*my,1);
+	Matrix* nptflag= new Matrix(mx*my,1);
+	double u=0;
+	double y=0;
+	m1->MatrixEqual(m0);
+	nptflag->MatrixSum(icethick,bathy);
+	/* first layer: ice */
+	for (int i=0;i<mx*my;i++){
+		if(landmask->GetValue(i,0)==2){
+			if(nptflag->GetValue(i,0)==0){
+				u=double(rand())/double(RAND_MAX);
+				y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+				m1->SetValue(i,1,m0->GetValue(i,1)+y*ptval);
+				m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+				if(m1->GetValue(i,1)>=m1->GetValue(i,0)+mmax){
+					m1->SetValue(i,1,m1->GetValue(i,0)+mmax);
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+			}
+		}
+		else if(landmask->GetValue(i,0)==0){
+			if(nptflag->GetValue(i,0)==0){
+				u=double(rand())/double(RAND_MAX);
+				y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+				m1->SetValue(i,2,m0->GetValue(i,2)+y*ptval);
+				if(m1->GetValue(i,2)<=m1->GetValue(i,0)){
+					m1->SetValue(i,2,m1->GetValue(i,0)+1e-10);
+				}
+				if(m1->GetValue(i,2)>=m1->GetValue(i,0)+mmax2){
+					m1->SetValue(i,2,m1->GetValue(i,0)+mmax2);
+				}
+			}
+		}
+		else if(landmask->GetValue(i,0)==3){
+			if(nptflag->GetValue(i,0)==0){
+				u=double(rand())/double(RAND_MAX);
+				y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+				m1->SetValue(i,1,m0->GetValue(i,1)+y*ptval);
+				if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+				}
+				if(m1->GetValue(i,1)>=m1->GetValue(i,0)+mmax){
+					m1->SetValue(i,1,m1->GetValue(i,0)+mmax);
+				}
+				u=double(rand())/double(RAND_MAX);
+				y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+				m1->SetValue(i,2,m0->GetValue(i,2)+y*ptval);
+				if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+				if(m1->GetValue(i,2)>=m1->GetValue(i,1)+mmax2){
+					m1->SetValue(i,2,m1->GetValue(i,1)+mmax2);
+				}
+			}
+		}
+	}
+
+	m1->ExtractColumn(m1col,1);
+	vec2gridsimple(m1col,m1gr,mx,my);
+	filtergrav(m1grsm,m1gr,ctr,sd,mx,my);
+	reshape(m1grsm,m1col,mx,my);
+	m1->ExtractColumn(m1col2,2);
+	vec2gridsimple(m1col2,m1gr2,mx,my);
+	filtergrav(m1grsm2,m1gr2,ctr,sd,mx,my);
+	reshape(m1grsm2,m1col2,mx,my);
+
+	for (int i=0;i<mx*my;i++){
+		if(landmask->GetValue(i,0)==2){
+			if(nptflag->GetValue(i,0)==0){
+				m1->SetValue(i,1,m1col->GetValue(i,0));
+				m1->SetValue(i,2,m1col2->GetValue(i,0));
+				if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+				if(fabs(m1->GetValue(i,2)-m1->GetValue(i,1))>1){
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+			}
+			else{
+				m1->SetValue(i,1,m0->GetValue(i,1));
+				m1->SetValue(i,2,m0->GetValue(i,2));
+			}
+		}
+		else if(landmask->GetValue(i,0)==0){
+			if(nptflag->GetValue(i,0)==0){
+				m1->SetValue(i,2,m1col2->GetValue(i,0));
+				if(m1->GetValue(i,2)<=m1->GetValue(i,0)){
+					m1->SetValue(i,2,m1->GetValue(i,0)+1e-10);
+				}
+				if(fabs(m1->GetValue(i,0)-m1->GetValue(i,1))>1){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+				}
+			}
+			else{
+				m1->SetValue(i,1,m0->GetValue(i,1));
+				m1->SetValue(i,2,m0->GetValue(i,2));
+			}
+		}
+		else if(landmask->GetValue(i,0)==3){
+			if(nptflag->GetValue(i,0)==0){
+				m1->SetValue(i,1,m1col->GetValue(i,0));
+				m1->SetValue(i,2,m1col2->GetValue(i,0));
+				if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+				}
+				if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+			}
+			else{
+				m1->SetValue(i,1,m0->GetValue(i,1));
+				m1->SetValue(i,2,m0->GetValue(i,2));
+			}
+		}
+		else {
+			if(nptflag->GetValue(i,0)==0){
+				if(fabs(m1->GetValue(i,0)-m1->GetValue(i,1))>1){
+					m1->SetValue(i,1,m1->GetValue(i,0));
+				}
+				if(fabs(m1->GetValue(i,0)-m1->GetValue(i,2))>1){
+					m1->SetValue(i,2,m1->GetValue(i,0));
+				}
+			}
+			else{
+				m1->SetValue(i,1,m0->GetValue(i,1));
+				m1->SetValue(i,2,m0->GetValue(i,2));
+			}
+		}
+	}
+
+				/* second layer: water */
+//	for (int i=0;i<mx*my;i++){
+//		if(bathy->GetValue(i,0)==0){
+//			u=double (rand())/ double(RAND_MAX);
+//			y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+//			m1->SetValue(i,2,m0->GetValue(i,2)+y*ptval);
+//			if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+//				m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+//			}
+//			if(m1->GetValue(i,2)>=m1->GetValue(i,1)+mmax2){
+//				m1->SetValue(i,2,m1->GetValue(i,1)+mmax2);
+//			}
+//		}
+//	}
+//	m1->ExtractColumn(m1col,2);
+//	vec2gridsimple(m1col,m1gr,mx,my);
+//	filtergrav(m1grsm,m1gr,ctr,sd,mx,my);
+//	reshape(m1grsm,m1col,mx,my);
+//	for (int i=0;i<mx*my;i++){
+//		if(bathy->GetValue(i,0)==0){
+//			m1->SetValue(i,2,m1col->GetValue(i,0));
+//		}
+//		else{
+//			m1->SetValue(i,2,m0->GetValue(i,2));
+//		}
+//		if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+//			m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+//		}
+//	}
+	delete m1gr;
+	delete m1grsm;
+	delete m1col;
+	delete m1gr2;
+	delete m1grsm2;
+	delete m1col2;
+	delete nptflag;
+}/*}}}*/
+double signe(double a){/*{{{*/
+	if(a<0){return -1;}
+	else{return 1;}
+}/*}}}*/
+void filtergrav(Matrix* A,Matrix* Ain,double ctr,double sd,int mx,int my){/*{{{*/
+	A->MatrixEqual(Ain);
+	for (int i=1;i<my-1;i++){
+		for(int j=1;j<mx-1;j++){
+			A->SetValue(i,j,(ctr*Ain->GetValue(i,j)+sd*(Ain->GetValue(i-1,j)+Ain->GetValue(i+1,j)+Ain->GetValue(i,j-1)+Ain->GetValue(i,j+1)))/(ctr+4*sd));
+		}
+	}
+}/*}}}*/
+double coolshed(double T0,double k,double c,double D){/*{{{*/
+	double T1=T0*exp(-c*pow(k,1/D));
+	return T1;
+}/*}}}*/
Index: /issm/trunk/src/m/contrib/gravity/code_inversion/vfsa_mpi_uneven.cpp
===================================================================
--- /issm/trunk/src/m/contrib/gravity/code_inversion/vfsa_mpi_uneven.cpp	(revision 19105)
+++ /issm/trunk/src/m/contrib/gravity/code_inversion/vfsa_mpi_uneven.cpp	(revision 19105)
@@ -0,0 +1,882 @@
+#include <iostream>
+#include <cmath>
+#include <fstream>
+#include <string>
+#include <cstdio>
+#include <cstdlib>
+#include <time.h>
+#include <cassert>
+#include <gsl/gsl_multifit.h>
+#include "mpi.h"
+using namespace std;
+
+class Matrix{/*{{{*/
+	private:
+		int     M;        /*Number of lines   */
+		int     N;        /*Number if Columns */
+		double *values;
+	public:
+		Matrix(int m_in,int n_in){/*{{{*/
+			this->M = m_in;
+			this->N = n_in;
+			this->values = new double[M*N]();
+		}/*}}}*/
+		~Matrix(){/*{{{*/
+			delete [] this->values;
+		}/*}}}*/
+		void Echo(void){/*{{{*/
+			for(int i=0;i<M;i++){
+				for(int j=0;j<N;j++){
+					cout << " " << this->values[i*N+j];
+				}
+				cout << endl;
+			}
+		}/*}}}*/
+		void SetValue(int i,int j,double value){/*{{{*/
+			this->values[i*N+j] = value;
+		}/*}}}*/
+		double GetValue(int i,int j){/*{{{*/
+			return this->values[i*N+j];
+		}/*}}}*/
+		void GetSize(int* pM,int* pN){/*{{{*/
+			*pM = this->M;
+			*pN = this->N;
+		}/*}}}*/
+		double* GetPointer(void){/*{{{*/
+			return this->values;
+		}/*}}}*/
+		void MatrixSum(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) + B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixDiff(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) - B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixAbs(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,fabs(A->GetValue(i,j)));
+				}
+			}
+		}/*}}}*/
+		void MatrixEqual(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		double MatrixInternSum(){/*{{{*/
+			double sum=0;
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					sum+=this->GetValue(i,j);
+				}
+			}
+			return sum;
+		}/*}}}*/
+		void ExtractLine(Matrix* A,int i){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(M_A==1 && this->N==N_A);
+			for(int j=0;j<this->N;j++){
+				A->SetValue(0,j,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void ExtractColumn(Matrix* A,int j){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(N_A==1 && this->M==M_A);
+			for(int i=0;i<this->M;i++){
+				A->SetValue(i,0,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void AddNumber(double a){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,this->GetValue(i,j) + a);
+				}
+			}
+		}/*}}}*/
+};/*}}}*/
+
+/*Local prototypes{{{*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy);
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny);
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,Matrix *dlevel);
+void plouff(Matrix *g,Matrix *Pobs,Matrix *Pp,Matrix * mesh,Matrix *rho,int dx,int dy, int dn,int m,int n,int l,Matrix *evalid,int my_rank,int num_procs);
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny);
+void reshape(Matrix* V,Matrix* V1,int nx,int ny);
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,Matrix *dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my,int my_rank,int num_procs);
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B);
+double signe(double a);
+void filtergrav(Matrix* A,Matrix* Ain,double ctr,double sd,int mx,int my);
+void newmodelgen(Matrix* m0,Matrix* m1,Matrix* bathy,Matrix* icethick,int mx,int my,double T,double ptval,double mmax,double mmax2,double ctr,double sd, Matrix *landmask);
+double coolshed(double T0,double k,double c,double D);
+/*}}}*/
+
+int main(int argc,char *argv[]){/*{{{*/
+	
+	int my_rank,num_procs;
+
+	MPI_Init(&argc, &argv);
+
+	MPI_Comm_size(MPI_COMM_WORLD,&num_procs);
+	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
+
+	/* Seed the random number generator {{{*/
+		srand (time(NULL));            /*}}}*/
+	/* Define the variables {{{*/
+
+	int    dx     = 1000;   /* prism dimension in x-direction                           */
+	int    dy     = 1000;   /* prism dimension in y-direction                           */
+	int    mx     = 99;    /* number of prisms in x-direction                          */
+	int    my     = 99;    /* number of prisms in y-direction                          */
+	int    nx     = 99;    /* number of data points in x-direction                     */
+	int    ny     = 99;    /* number of data points in y-direction                     */
+	int    dn     = 15000; /* distance for neighbouting prisms for gravity calculation */
+	double ptval  = 100.;  /* max. amount to perturb model                             */
+	double ptval2 = 100.;
+
+	Matrix *Pobs=new Matrix(nx*ny,2); /* data positions */
+	makep(Pobs,nx,ny,dx,dy);
+	// Pobs->Echo();
+
+
+	Matrix *Pp=new Matrix(mx*my,2); /* prisms positions */
+	makep(Pp,mx,my,dx,dy);
+	// Pp->Echo();
+
+	double  rhoi = 917;           /* ice density     */
+	double  rhow = 1030;          /* water density   */
+	// double  rhos = 2013;		      /* sediment density */
+	double  rhoc = 2670;          /* bedrock density */
+
+	Matrix *Rho  = new Matrix(1,2);
+	Rho->SetValue(0,0,rhoi);
+	Rho->SetValue(0,1,rhow);
+	Matrix *rho1  = new Matrix(1,3);
+	rho1->SetValue(0,0,rhoi);
+	rho1->SetValue(0,1,rhow);
+	rho1->SetValue(0,2,rhoc);
+	Matrix *rho2  = new Matrix(1,2);
+	rho2->SetValue(0,0,rhoi-rhoc);
+	rho2->SetValue(0,1,rhow-rhoc);
+
+	double ctr=1;            /* parameter for filtering */
+	double sd=0.1;
+
+	Matrix *xobs= new Matrix(ny,nx);
+	Matrix *yobs= new Matrix(ny,nx);
+
+	vec2grid(Pobs,xobs,yobs,nx,ny);
+	//	xobs->Echo();
+	//	yobs->Echo();
+
+
+	double mmax  = 1000;               /* max value for layer interfaces */
+	double mmax2 = 1000;
+	double mmax3 = 1000;
+
+	/* control parameter for temperature schedule  */
+
+	double ca=0.9;                    /* for acceptance */
+	double cm=0.5;                    /* for model perturbation */
+
+	double T0a          = 0.1;      /* initial temperature for acceptance           */
+	double T0m          = 0.9;      /* initial temperature for model perturbation   */
+	double D            = 2;        /* dimension of the model                       */
+	int    maxconsecrej = 1000;     /* max consecutive rejection                    */
+	int    maxsuccess   = 100;      /* max number of success within one temperature */
+	double T_min        = 1e-10;    /* stopping temp                                */
+	double Tred         = 1;
+	double E_min        = -1000000;
+	double E_exp        = 0.0291;   /* expected misfit                              */
+	int    maxiter      = 10000;
+	int    maxtotaliter = 1000000;
+	double Tol          = 1e-10;    /* tolerance on misfit                          */
+	int    sfreq        = 100;
+
+	/*}}}*/     
+	/* load the data {{{*/
+
+	/*landmask */
+
+	ifstream file("landmaskzach.txt");
+	Matrix * landmask= new Matrix(nx*ny,1);
+	double inputnumber;
+	for(int i=0;i<ny*nx; i++){ 
+		file >> inputnumber;
+		landmask->SetValue(i,0,inputnumber);
+	}
+	file.close();
+
+	/* Levels of data acquisition */
+
+	ifstream file0("altizach.txt");
+	Matrix * dlevel= new Matrix(nx*ny,1);
+	for(int i=0;i<ny*nx; i++){
+		file0 >> inputnumber;
+		dlevel->SetValue(i,0,inputnumber);
+	}
+	file0.close();
+
+	/* Observed gravity anomaly */
+
+	ifstream file1("gravityzach.txt");
+	Matrix * gobs= new Matrix(nx*ny,1);
+	for(int i=0;i<ny*nx; i++){ 
+		file1 >> inputnumber;
+		gobs->SetValue(i,0, inputnumber*1e-5);
+	}
+	file1.close();
+	//	gobs->Echo();
+
+	/* load data about the ice thickness */
+
+	ifstream file2("icethickzach.txt");
+	Matrix * icethick= new Matrix(mx*my,1);
+	for(int s=0;s<mx*my; s++){ 
+		file2 >> inputnumber;
+		icethick->SetValue(s,0,inputnumber);
+	}
+	file2.close();
+	//	icethick->Echo();
+
+	/* load the batimethry data */
+
+	ifstream file3("bathymetryzach.txt");
+	Matrix * bathy= new Matrix(mx*my,1);
+	for(int s=0;s<mx*my; s++){ 
+		file3 >> inputnumber;
+		bathy->SetValue(s,0,inputnumber);
+	}
+	file3.close();
+	//	bathy->Echo();
+
+	/* id of grid to evaluate misfit */
+
+
+	ifstream file4("evalidzach.txt");
+	Matrix * evalid= new Matrix(nx*ny,1);
+	for(int s=0;s<nx*ny; s++){ 
+		file4 >> inputnumber;
+		evalid->SetValue(s,0,inputnumber);
+	}
+	file4.close();
+	//	evalid->Echo();
+
+	/* initial guess of the model */
+
+	ifstream file5("m0_102714contzach.txt");
+	Matrix * mesh_ini= new Matrix(mx*my,3);
+	for(int s=0;s<mx*my; s++){ 
+		for(int j=0;j<3;j++){
+			file5 >> inputnumber;
+			mesh_ini->SetValue(s,j,inputnumber);
+		}
+	}
+	file5.close();
+	//	mesh_ini->Echo();
+	/*}}}*/
+	/* VFSA {{{ */
+
+	/* name of the files to save results */
+	std::ofstream savefile1 ("r_zach.txt");
+	std::ofstream savefile2("m_zach.txt");
+
+	/* counters initialization */
+	int    success   = 0;
+	int    finished  = 0;
+	int    consec    = 0;
+	double Ta        = T0a;
+	double Tm        = T0m;
+	int    iterT     = 0;   /* iteration within a T      */
+	int    total     = 0;   /* total number of iteration */
+	int    totaliter = 0;
+	int    msave     = 0;
+	double E_new;
+	double E_final;
+	double dE;
+	double P;
+	double rn;
+	Matrix* m_old    = new Matrix(mx *my,3);
+	Matrix* m_min    = new Matrix(mx *my,3);
+	Matrix* m_new    = new Matrix(mx *my,3);
+	m_old->MatrixEqual(mesh_ini);
+
+	/* calculate initial misfit */
+	double E_old=misfit(m_old,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my, my_rank, num_procs);
+	/* record initial settings */
+	if(!my_rank){
+		savefile1 << "P     "<< "Ta    "<< "Tm    "<< "Eold  "<< "totaliter "<< "Tred   "<< endl;
+		savefile1 << "nan   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+		savefile2 << totaliter<< endl;
+		for(int i=0;i<mx*my;i++){
+			savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+		}
+		savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+	}
+	/* beginning of the loop */
+
+	while(finished==0){
+		iterT++;
+		totaliter++;
+
+		/* stop or reduce T */
+		if(iterT>=maxiter || success>maxsuccess){
+			if(Ta<T_min || total>maxtotaliter || fabs(E_old)<=Tol){
+				finished=1;
+				total+=iterT;
+				break;
+			}
+			else{ /* reduce T */
+				Ta=coolshed(T0a,Tred,ca,D);
+				Tm=coolshed(T0m,Tred,cm,D);
+				total+=iterT;
+				iterT=0;
+				success=1;
+				Tred++;
+				consec=0;
+			}
+		}
+
+		/* update model and calculate energy */
+
+		newmodelgen(m_old,m_new,bathy,icethick,mx,my,Tm,ptval,mmax,mmax2,ctr,sd, landmask);  /* new model */
+		E_new=misfit(m_new,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my, my_rank, num_procs); /* new energy */
+		dE=E_new-E_old;                                        /* energy difference */
+
+		/* acceptance probability */
+
+		P=exp(-dE/Ta);
+
+		/* stop if energy is lower than specified minimum */
+		if (E_new<E_min){
+			m_old->MatrixEqual(m_new);
+			E_old=E_new;
+			break;
+		}
+
+		rn=rand()/double (RAND_MAX);
+
+		/* accept new model or not */
+		if(dE<=0){
+			m_old->MatrixEqual(m_new);
+			E_old=E_new;
+			E_final=E_old;
+			success++;
+			consec=0;
+			if(!my_rank){
+				savefile1 << P<<"   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+			}
+			if(Ta<1e-3){
+				if(!my_rank){
+					savefile2 << totaliter<< endl;
+					for(int i=0;i<mx*my;i++){
+						savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+					}
+					savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+				}
+			}
+		}
+		else{
+			if(P>rn){
+				m_old->MatrixEqual(m_new);
+				E_old=E_new;
+				success++;
+				consec=0;
+				if(!my_rank){
+					savefile1 << P<<"   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+					if(Ta<1e-3){
+						savefile2 << totaliter<< endl;
+						for(int i=0;i<mx*my;i++){
+							savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+						}
+						savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+					}
+				}
+			}
+			else{
+				consec++;
+			}
+		}
+	}
+
+	m_min->MatrixEqual(m_old);
+	if(!my_rank){
+		savefile1 << "nan"<<"   "<<  "nan"<<"   "<< "nan"<<"   "<< E_final<<"     "<< "nan"<<"         "<< "nan" <<"  "<< endl;
+		savefile2 << " Mesh final"<< endl;
+		for(int i=0;i<mx*my;i++){
+			savefile2 << m_min->GetValue(i,0)<<"   "<< m_min->GetValue(i,1)<<"   "<< m_min->GetValue(i,2)<<endl;
+		}
+	}
+	savefile1.close();
+	savefile2.close();
+
+	delete m_old;
+	delete m_min;
+	delete m_new;
+	delete Pobs;
+	delete Pp;
+	delete Rho;
+	delete rho1;
+	delete rho2;
+	delete xobs;
+	delete yobs;
+	delete mesh_ini;
+	delete bathy;
+	delete icethick;
+	delete evalid;
+	delete gobs;
+	delete landmask;
+
+	/*}}}*/
+
+   MPI_Finalize();
+
+	return 0;
+}/*}}}*/
+
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B){/*{{{*/
+
+	/*GSL Matrices and vectors: */
+	int    M,N;
+	double chisq;
+	/*Get system size*/
+	A->GetSize(&M,&N);
+
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix* a = gsl_matrix_alloc(M,N);
+	for(int i=0;i<M;i++){
+		for(int j=0;j<N;j++){
+			gsl_matrix_set (a,i,j,A->GetValue(i,j));
+		}
+	}
+	gsl_vector* b = gsl_vector_alloc(M);
+	for(int i=0;i<M;i++){
+		gsl_vector_set(b,i,B->GetValue(i,0));
+	}
+
+	gsl_vector* x = gsl_vector_alloc(N);
+	gsl_matrix* cov = gsl_matrix_alloc(N,N);
+
+	/*Least square fit: */
+	gsl_multifit_linear_workspace* work = gsl_multifit_linear_alloc(M,N);
+	gsl_multifit_linear (a, b, x, cov, &chisq, work);
+	gsl_multifit_linear_free (work);
+
+	/*Clean up and assign output pointer*/
+	Matrix* X = new Matrix(N,1);
+	for(int j=0;j<N;j++){
+		X->SetValue(j,0,gsl_vector_get(x,j));
+	}
+	*pX = X;
+
+	gsl_matrix_free(a);
+	gsl_vector_free(x);
+	gsl_vector_free(b);
+	gsl_matrix_free(cov);
+
+}/*}}}*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			Pobs->SetValue(j+nx*i,0,j*dx);
+			Pobs->SetValue(j+nx*i,1,i*dy);
+		}
+	}
+}/*}}}*/
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+			V2->SetValue(i,j, V->GetValue(j+nx*i,1));
+		}
+	}
+}/*}}}*/
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,Matrix* dlevel){/*{{{*/
+	int sizem1,sizem2;
+	m->GetSize(&sizem1,&sizem2);
+	for(int i=0;i<sizem1;i++){
+		for(int j=0;j<sizem2+1;j++){
+			if(j<sizem2){
+				m1->SetValue(i,j,1e-10*(sizem2+1-j));
+				m2->SetValue(i,j,m->GetValue(i,j));
+				if(m->GetValue(i,j)<0){
+					m1->SetValue(i,j,m->GetValue(i,j));
+					m2->SetValue(i,j,i*1e-10);
+				}
+				m1->SetValue(i,j,m1->GetValue(i,j)+dlevel->GetValue(i,1));
+				m2->SetValue(i,j,m2->GetValue(i,j)+dlevel->GetValue(i,1));
+			}
+			else{
+				m1->SetValue(i,j,1e-10+dlevel->GetValue(i,1));
+			}
+		}
+	}
+}/*}}}*/
+void plouff(Matrix *g,Matrix *Pobs,Matrix *Pp,Matrix * mesh,Matrix *rho,int dx,int dy, int dn,int m,int n,int l,Matrix* evalid,int my_rank,int num_procs){/*{{{*/
+	double gg=6.673e-11;
+	int si,sj,id,s;
+	double R,Q,P;
+	Matrix *xp= new Matrix(1,2);
+	Matrix *yp= new Matrix(1,2);
+	Matrix *xpp= new Matrix(1,2);
+	Matrix *ypp= new Matrix(1,2);
+	Matrix *U= new Matrix(l,4);
+	Matrix *U1=new Matrix(1,4);
+	Matrix *U2=new Matrix(1,4);
+	Matrix *gl= new Matrix(1,l-1);
+	bool test=true;
+
+	double *glocal=new double[n]();
+
+	for(int c=my_rank;c<n;c+=num_procs){
+		glocal[c]=0;
+		if(evalid->GetValue(i,0)==1){
+			for(int a=0;a<m;a++){
+				test=true;
+				xp->SetValue(0,0,Pp->GetValue(a,0)-Pobs->GetValue(c,0));
+				xp->SetValue(0,1,Pp->GetValue(a,0)-Pobs->GetValue(c,0)+dx);
+				if(xp->GetValue(0,0)<0 && xp->GetValue(0,0)<xp->GetValue(0,1) && xp->GetValue(0,0)*xp->GetValue(0,1)>=0){
+					xpp->SetValue(0,0,xp->GetValue(0,1));
+					xpp->SetValue(0,1,xp->GetValue(0,0));
+					xp->MatrixAbs(xpp);
+				}
+				yp->SetValue(0,0,Pp->GetValue(a,1)-Pobs->GetValue(c,1));
+				yp->SetValue(0,1,Pp->GetValue(a,1)-Pobs->GetValue(c,1)+dy);
+				if(yp->GetValue(0,0)<0 && yp->GetValue(0,0)<yp->GetValue(0,1) && yp->GetValue(0,0)*yp->GetValue(0,1)>=0){
+					ypp->SetValue(0,0,yp->GetValue(0,1));
+					ypp->SetValue(0,1,yp->GetValue(0,0));
+					yp->MatrixAbs(ypp);
+				}
+				P=sqrt(xp->GetValue(0,0)*xp->GetValue(0,0)+yp->GetValue(0,0)*yp->GetValue(0,0));
+				if(P>dn){
+					test=false;
+					for(int i=0;i<l-1;i++){
+						gl->SetValue(0,i,0);
+					}
+				}
+				if(test==true){
+					si=1;
+					sj=1;
+					id=0;
+					for(int i=0;i<2;i++){
+						si*=-1;
+						for(int j=0;j<2;j++){
+							sj*=-1;
+							s=si*sj;
+							for(int k=0;k<l;k++){
+								R=sqrt(xp->GetValue(0,i)*xp->GetValue(0,i)+yp->GetValue(0,j)*yp->GetValue(0,j)+mesh->GetValue(a,k)*mesh->GetValue(a,k));
+								Q=atan(xp->GetValue(0,i)*yp->GetValue(0,j)/(mesh->GetValue(a,k)*R));
+								U->SetValue(k,id,s*(mesh->GetValue(a,k)*Q-xp->GetValue(0,i)*log(R+yp->GetValue(0,j))-yp->GetValue(0,j)*log(R+xp->GetValue(0,i))));
+							}
+							id++;
+						}
+					}
+					for(int b=0;b<l-1;b++){
+						U->ExtractLine(U1,b);
+						U->ExtractLine(U2,b+1);
+						gl->SetValue(0,b,rho->GetValue(0,b)*(U1->MatrixInternSum()*(-1)+U2->MatrixInternSum()));
+					}
+				}
+				glocal[c]=glocal[c]+gg*gl->MatrixInternSum();
+			}
+		}
+	}
+
+	MPI_Allreduce(glocal,g->GetPointer(),n,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+
+	delete xp;
+	delete yp;
+	delete xpp;
+	delete ypp;
+	delete gl;
+	delete U;
+	delete U1;
+	delete U2;
+	delete []glocal;
+}/*}}}*/
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+		}
+	}
+}/*}}}*/
+void reshape(Matrix* V,Matrix* V1,int nx,int ny){/*{{{*/
+	for (int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			V1->SetValue(j+nx*i,0,V->GetValue(i,j));
+		}
+	}
+}/*}}}*/
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,Matrix *dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my,int my_rank,int num_procs){/*{{{*/
+	Matrix* m1=new Matrix(mx*my,4);
+	Matrix* m2=new Matrix(mx*my,3);
+	Matrix* g1=new Matrix(nx*ny,1);
+	Matrix* g2=new Matrix(nx*ny,1);
+	Matrix* g=new Matrix(nx*ny,1);
+	Matrix* gcalgr=new Matrix(ny,nx);
+	Matrix* gcalvec=new Matrix(nx*ny,1);
+	Matrix* df=new Matrix(nx*ny,1);
+	Matrix* G=new Matrix(nx*ny,3);
+	double a=0;
+	double b=0;
+	double e=0;
+	msplit(m0,m1,m2,dlevel);
+	plouff(g1,Pobs,Pp,m1,rho1,dx,dy,dn,mx*my,nx*ny,4,evalid, my_rank, num_procs);
+	plouff(g2,Pobs,Pp,m2,rho2,dx,dy,dn,mx*my,nx*ny,3,evalid, my_rank, num_procs);
+	g->MatrixSum(g1,g2);
+	vec2gridsimple(g,gcalgr,nx,ny);
+	reshape(gcalgr,gcalvec,nx,ny);
+	for (int i=0;i<nx*ny;i++){
+		df->SetValue(i,0,evalid->GetValue(i,0)*(gobs->GetValue(i,0)-gcalvec->GetValue(i,0)));
+		G->SetValue(i,0,evalid->GetValue(i,0)*Pobs->GetValue(i,0));
+		G->SetValue(i,1,evalid->GetValue(i,0)*Pobs->GetValue(i,1));
+		G->SetValue(i,2,evalid->GetValue(i,0));
+	}
+	Matrix* M = NULL;
+	GSLsquarefit(&M,G,df);
+
+	for (int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			gcalgr->SetValue(i,j,gcalgr->GetValue(i,j)+xobs->GetValue(i,j)*M->GetValue(0,0)+yobs->GetValue(i,j)*M->GetValue(1,0)+M->GetValue(2,0));
+		}
+	}
+	reshape(gcalgr,g,nx,ny);
+	for (int i=0;i<nx*ny;i++){
+		a=a+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)-g->GetValue(i,0)));
+		b=b+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)+g->GetValue(i,0)));
+	}
+	e=2*a/(a+b);
+
+	delete m1;
+	delete m2;
+	delete g1;
+	delete g2;
+	delete g;
+	delete gcalgr;
+	delete gcalvec;
+	delete df;
+	delete G;
+	delete M;
+
+	return e;
+}/*}}}*/
+void newmodelgen(Matrix* m0,Matrix* m1,Matrix* bathy,Matrix* icethick,int mx,int my,double T,double ptval,double mmax,double mmax2,double ctr,double sd, Matrix *landmask){/*{{{*/
+	Matrix* m1gr=new Matrix(my,mx);
+	Matrix* m1grsm=new Matrix(my,mx);
+	Matrix* m1col=new Matrix(mx*my,1);
+	Matrix* m1gr2=new Matrix(my,mx);
+	Matrix* m1grsm2=new Matrix(my,mx);
+	Matrix* m1col2=new Matrix(mx*my,1);
+	Matrix* nptflag= new Matrix(mx*my,1);
+	double u=0;
+	double y=0;
+	m1->MatrixEqual(m0);
+	nptflag->MatrixSum(icethick,bathy);
+	/* first layer: ice */
+	for (int i=0;i<mx*my;i++){
+		if(landmask->GetValue(i,0)==2){
+			if(nptflag->GetValue(i,0)==0){
+				u=double(rand())/double(RAND_MAX);
+				y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+				m1->SetValue(i,1,m0->GetValue(i,1)+y*ptval);
+				m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+				if(m1->GetValue(i,1)>=m1->GetValue(i,0)+mmax){
+					m1->SetValue(i,1,m1->GetValue(i,0)+mmax);
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+			}
+		}
+		else if(landmask->GetValue(i,0)==0){
+			if(nptflag->GetValue(i,0)==0){
+				u=double(rand())/double(RAND_MAX);
+				y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+				m1->SetValue(i,2,m0->GetValue(i,2)+y*ptval);
+				if(m1->GetValue(i,2)<=m1->GetValue(i,0)){
+					m1->SetValue(i,2,m1->GetValue(i,0)+1e-10);
+				}
+				if(m1->GetValue(i,2)>=m1->GetValue(i,0)+mmax2){
+					m1->SetValue(i,2,m1->GetValue(i,0)+mmax2);
+				}
+			}
+		}
+		else if(landmask->GetValue(i,0)==3){
+			if(nptflag->GetValue(i,0)==0){
+				u=double(rand())/double(RAND_MAX);
+				y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+				m1->SetValue(i,1,m0->GetValue(i,1)+y*ptval);
+				if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+				}
+				if(m1->GetValue(i,1)>=m1->GetValue(i,0)+mmax){
+					m1->SetValue(i,1,m1->GetValue(i,0)+mmax);
+				}
+				u=double(rand())/double(RAND_MAX);
+				y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+				m1->SetValue(i,2,m0->GetValue(i,2)+y*ptval);
+				if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+				if(m1->GetValue(i,2)>=m1->GetValue(i,1)+mmax2){
+					m1->SetValue(i,2,m1->GetValue(i,1)+mmax2);
+				}
+			}
+		}
+	}
+
+	m1->ExtractColumn(m1col,1);
+	vec2gridsimple(m1col,m1gr,mx,my);
+	filtergrav(m1grsm,m1gr,ctr,sd,mx,my);
+	reshape(m1grsm,m1col,mx,my);
+	m1->ExtractColumn(m1col2,2);
+	vec2gridsimple(m1col2,m1gr2,mx,my);
+	filtergrav(m1grsm2,m1gr2,ctr,sd,mx,my);
+	reshape(m1grsm2,m1col2,mx,my);
+
+	for (int i=0;i<mx*my;i++){
+		if(landmask->GetValue(i,0)==2){
+			if(nptflag->GetValue(i,0)==0){
+				m1->SetValue(i,1,m1col->GetValue(i,0));
+				m1->SetValue(i,2,m1col2->GetValue(i,0));
+				if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+				if(fabs(m1->GetValue(i,2)-m1->GetValue(i,1))>1){
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+			}
+			else{
+				m1->SetValue(i,1,m0->GetValue(i,1));
+				m1->SetValue(i,2,m0->GetValue(i,2));
+			}
+		}
+		else if(landmask->GetValue(i,0)==0){
+			if(nptflag->GetValue(i,0)==0){
+				m1->SetValue(i,2,m1col2->GetValue(i,0));
+				if(m1->GetValue(i,2)<=m1->GetValue(i,0)){
+					m1->SetValue(i,2,m1->GetValue(i,0)+1e-10);
+				}
+				if(fabs(m1->GetValue(i,0)-m1->GetValue(i,1))>1){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+				}
+			}
+			else{
+				m1->SetValue(i,1,m0->GetValue(i,1));
+				m1->SetValue(i,2,m0->GetValue(i,2));
+			}
+		}
+		else if(landmask->GetValue(i,0)==3){
+			if(nptflag->GetValue(i,0)==0){
+				m1->SetValue(i,1,m1col->GetValue(i,0));
+				m1->SetValue(i,2,m1col2->GetValue(i,0));
+				if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+				}
+				if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+			}
+			else{
+				m1->SetValue(i,1,m0->GetValue(i,1));
+				m1->SetValue(i,2,m0->GetValue(i,2));
+			}
+		}
+		else {
+			if(nptflag->GetValue(i,0)==0){
+				if(fabs(m1->GetValue(i,0)-m1->GetValue(i,1))>1){
+					m1->SetValue(i,1,m1->GetValue(i,0));
+				}
+				if(fabs(m1->GetValue(i,0)-m1->GetValue(i,2))>1){
+					m1->SetValue(i,2,m1->GetValue(i,0));
+				}
+			}
+			else{
+				m1->SetValue(i,1,m0->GetValue(i,1));
+				m1->SetValue(i,2,m0->GetValue(i,2));
+			}
+		}
+	}
+
+				/* second layer: water */
+//	for (int i=0;i<mx*my;i++){
+//		if(bathy->GetValue(i,0)==0){
+//			u=double (rand())/ double(RAND_MAX);
+//			y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+//			m1->SetValue(i,2,m0->GetValue(i,2)+y*ptval);
+//			if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+//				m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+//			}
+//			if(m1->GetValue(i,2)>=m1->GetValue(i,1)+mmax2){
+//				m1->SetValue(i,2,m1->GetValue(i,1)+mmax2);
+//			}
+//		}
+//	}
+//	m1->ExtractColumn(m1col,2);
+//	vec2gridsimple(m1col,m1gr,mx,my);
+//	filtergrav(m1grsm,m1gr,ctr,sd,mx,my);
+//	reshape(m1grsm,m1col,mx,my);
+//	for (int i=0;i<mx*my;i++){
+//		if(bathy->GetValue(i,0)==0){
+//			m1->SetValue(i,2,m1col->GetValue(i,0));
+//		}
+//		else{
+//			m1->SetValue(i,2,m0->GetValue(i,2));
+//		}
+//		if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+//			m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+//		}
+//	}
+	delete m1gr;
+	delete m1grsm;
+	delete m1col;
+	delete m1gr2;
+	delete m1grsm2;
+	delete m1col2;
+	delete nptflag;
+}/*}}}*/
+double signe(double a){/*{{{*/
+	if(a<0){return -1;}
+	else{return 1;}
+}/*}}}*/
+void filtergrav(Matrix* A,Matrix* Ain,double ctr,double sd,int mx,int my){/*{{{*/
+	A->MatrixEqual(Ain);
+	for (int i=1;i<my-1;i++){
+		for(int j=1;j<mx-1;j++){
+			A->SetValue(i,j,(ctr*Ain->GetValue(i,j)+sd*(Ain->GetValue(i-1,j)+Ain->GetValue(i+1,j)+Ain->GetValue(i,j-1)+Ain->GetValue(i,j+1)))/(ctr+4*sd));
+		}
+	}
+}/*}}}*/
+double coolshed(double T0,double k,double c,double D){/*{{{*/
+	double T1=T0*exp(-c*pow(k,1/D));
+	return T1;
+}/*}}}*/
Index: /issm/trunk/src/m/contrib/gravity/vfsa.cpp
===================================================================
--- /issm/trunk/src/m/contrib/gravity/vfsa.cpp	(revision 19105)
+++ /issm/trunk/src/m/contrib/gravity/vfsa.cpp	(revision 19105)
@@ -0,0 +1,823 @@
+#include <iostream>
+#include <cmath>
+#include <fstream>
+#include <string>
+#include <cstdio>
+#include <cstdlib>
+#include <time.h>
+#include <cassert>
+#include <gsl/gsl_multifit.h>
+#include <pthread.h>
+
+using namespace std;
+
+class Matrix{/*{{{*/
+	private:
+		int     M;        /*Number of lines   */
+		int     N;        /*Number if Columns */
+		double *values;
+	public:
+		Matrix(int m_in,int n_in){/*{{{*/
+			this->M = m_in;
+			this->N = n_in;
+			this->values = new double[M*N];
+		}/*}}}*/
+		~Matrix(){/*{{{*/
+			delete [] this->values;
+		}/*}}}*/
+		void Echo(void){/*{{{*/
+			for(int i=0;i<M;i++){
+				for(int j=0;j<N;j++){
+					cout << " " << this->values[i*N+j];
+				}
+				cout << endl;
+			}
+		}/*}}}*/
+		void SetValue(int i,int j,double value){/*{{{*/
+			this->values[i*N+j] = value;
+		}/*}}}*/
+		double GetValue(int i,int j){/*{{{*/
+			return this->values[i*N+j];
+		}/*}}}*/
+		void GetSize(int* pM,int* pN){/*{{{*/
+			*pM = this->M;
+			*pN = this->N;
+		}/*}}}*/
+		double* GetPointer(void){/*{{{*/
+			return this->values;
+		}/*}}}*/
+		void MatrixSum(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) + B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixDiff(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) - B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixAbs(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,fabs(A->GetValue(i,j)));
+				}
+			}
+		}/*}}}*/
+		void MatrixEqual(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		double MatrixInternSum(){/*{{{*/
+			double sum=0;
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					sum+=this->GetValue(i,j);
+				}
+			}
+			return sum;
+		}/*}}}*/
+		void ExtractLine(Matrix* A,int i){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(M_A==1 && this->N==N_A);
+			for(int j=0;j<this->N;j++){
+				A->SetValue(0,j,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void ExtractColumn(Matrix* A,int j){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(N_A==1 && this->M==M_A);
+			for(int i=0;i<this->M;i++){
+				A->SetValue(i,0,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void AddNumber(double a){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,this->GetValue(i,j) + a);
+				}
+			}
+		}/*}}}*/
+};/*}}}*/
+
+/*Local prototypes{{{*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy);
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny);
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,double dlevel);
+void* plouffT(void* vpthread_handle);
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny);
+void reshape(Matrix* V,Matrix* V1,int nx,int ny);
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,double dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my);
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B);
+double signe(double a);
+void filtergrav(Matrix* A,Matrix* Ain,double ctr,double sd,int mx,int my);
+void newmodelgen(Matrix* m0,Matrix* m1,Matrix* bathy,Matrix* icethick,int mx,int my,double T,double ptval,double mmax,double mmax2,double ctr,double sd);
+double coolshed(double T0,double k,double c,double D);
+void   LaunchThread(void* function(void*), void* usr,int num_threads);
+/*}}}*/
+
+/*Multithreading structures {{{*/
+typedef struct{
+	void* usr;
+	int   my_thread;
+	int   num_threads;
+} pthread_handle;
+
+typedef struct{
+	Matrix *g;
+	Matrix *Pobs;
+	Matrix *Pp;
+	Matrix *mesh;
+	Matrix *rho;
+	int dx;
+	int dy;
+	int dn;
+	int m;
+	int n;
+	int l;
+} AppStruct;
+/*}}}*/
+
+int main(){/*{{{*/
+
+	/* Seed the random number generator {{{*/
+	srand (time(NULL));               /*}}}*/
+	/* Define the variables {{{*/
+
+	int    dx     = 500;   /* prism dimension in x-direction                           */
+	int    dy     = 500;   /* prism dimension in y-direction                           */
+	int    mx     = 39;    /* number of prisms in x-direction                          */
+	int    my     = 60;    /* number of prisms in y-direction                          */
+	int    nx     = 39;    /* number of data points in x-direction                     */
+	int    ny     = 60;    /* number of data points in y-direction                     */
+	int    dn     = 15000; /* distance for neighbouting prisms for gravity calculation */
+	double ptval  = 100.;  /* max. amount to perturb model                             */
+	double ptval2 = 100.;
+
+	Matrix *Pobs=new Matrix(nx*ny,2); /* data positions */
+	makep(Pobs,nx,ny,dx,dy);
+// Pobs->Echo();
+
+
+	Matrix *Pp=new Matrix(mx*my,2); /* data positions */
+	makep(Pp,mx,my,dx,dy);
+// Pp->Echo();
+
+	double  rhoi = 890;           /* ice density     */
+	double  rhow = 1030;          /* water density   */
+// double  rhos = 2013;		      /* sediment density */
+	double  rhoc = 2670;          /* bedrock density */
+	
+	Matrix *Rho  = new Matrix(1,2);
+	Rho->SetValue(0,0,rhoi);
+	Rho->SetValue(0,1,rhow);
+	Matrix *rho1  = new Matrix(1,3);
+	rho1->SetValue(0,0,rhoi);
+	rho1->SetValue(0,1,rhow);
+	rho1->SetValue(0,2,rhoc);
+	Matrix *rho2  = new Matrix(1,2);
+	rho2->SetValue(0,0,rhoi-rhoc);
+	rho2->SetValue(0,1,rhow-rhoc);
+	
+	double ctr=1;            /* parameter for filtering */
+	double sd=0.1;
+
+	Matrix *xobs= new Matrix(ny,nx);
+	Matrix *yobs= new Matrix(ny,nx);
+
+	vec2grid(Pobs,xobs,yobs,nx,ny);
+//	xobs->Echo();
+//	yobs->Echo();
+
+	double dlevel= 860;                /* mean level of data acquisition */
+
+	double mmax  = 1000;               /* max value for layer interfaces */
+	double mmax2 = 1000;
+	double mmax3 = 1000;
+
+	/* control parameter for temperature schedule  */
+
+	double ca=0.9;                    /* for acceptance */
+	double cm=0.5;                    /* for model perturbation */
+
+	double T0a          = 0.1;      /* initial temperature for acceptance           */
+	double T0m          = 0.9;      /* initial temperature for model perturbation   */
+	double D            = 2;        /* dimension of the model                       */
+	int    maxconsecrej = 1000;     /* max consecutive rejection                    */
+	int    maxsuccess   = 100;      /* max number of success within one temperature */
+	double T_min        = 1e-10;    /* stopping temp                                */
+	double Tred         = 1;
+	double E_min        = -1000000;
+	double E_exp        = 0.0291;   /* expected misfit                              */
+	int    maxiter      = 10000;
+	int    maxtotaliter = 1000000;
+	double Tol          = 1e-10;    /* tolerance on misfit                          */
+	int    sfreq        = 100;
+
+	                     /*}}}*/     
+	/* load the data {{{*/
+
+	/* Observed gravity anomaly */
+
+	ifstream file1("store_fa500_36s.txt");
+	Matrix * gobs= new Matrix(nx*ny,1);
+	double inputnumber;
+	for(int i=0;i<ny*nx; i++){ 
+		file1 >> inputnumber;
+		gobs->SetValue(i,0, inputnumber*1e-5);
+	}
+	file1.close();
+//	gobs->Echo();
+	
+	/* load data about the ice thickness */
+
+	ifstream file2("store_flag_icethick500.txt");
+	Matrix * icethick= new Matrix(mx*my,1);
+	for(int s=0;s<mx*my; s++){ 
+		file2 >> inputnumber;
+		icethick->SetValue(s,0,inputnumber);
+	}
+	file2.close();
+//	icethick->Echo();
+
+	/* load the batimethry data */
+
+	ifstream file3("store_flag_bathy500.txt");
+	Matrix * bathy= new Matrix(mx*my,1);
+	for(int s=0;s<mx*my; s++){ 
+		file3 >> inputnumber;
+		bathy->SetValue(s,0,inputnumber);
+	}
+	file3.close();
+//	bathy->Echo();
+	
+	/* id of grid to evaluate misfit */
+
+
+	ifstream file4("store_flag_eval500.txt");
+	Matrix * evalid= new Matrix(mx*my,1);
+	for(int s=0;s<mx*my; s++){ 
+		file4 >> inputnumber;
+		evalid->SetValue(s,0,inputnumber);
+	}
+	file4.close();
+//	evalid->Echo();
+	
+	/* initial guess of the model */
+
+	ifstream file5("m0_140114b.txt");
+	Matrix * mesh_ini= new Matrix(mx*my,3);
+	for(int s=0;s<mx*my; s++){ 
+		for(int j=0;j<3;j++){
+		file5 >> inputnumber;
+		mesh_ini->SetValue(s,j,inputnumber);
+	}
+	}
+	file5.close();
+//	mesh_ini->Echo();
+                           /*}}}*/
+		/* VFSA {{{ */
+
+	/* name of the files to save results */
+	std::ofstream savefile1 ("r_140114b.txt");
+	std::ofstream savefile2("m_140114b.txt");
+
+	/* counters initialization */
+	int    success   = 0;
+	int    finished  = 0;
+	int    consec    = 0;
+	double Ta        = T0a;
+	double Tm        = T0m;
+	int    iterT     = 0;   /* iteration within a T      */
+	int    total     = 0;   /* total number of iteration */
+	int    totaliter = 0;
+	int    msave     = 0;
+	double E_new;
+	double E_final;
+	double dE;
+	double P;
+	double rn;
+	Matrix* m_old    = new Matrix(mx *my,3);
+	Matrix* m_min    = new Matrix(mx *my,3);
+	Matrix* m_new    = new Matrix(mx *my,3);
+	m_old->MatrixEqual(mesh_ini);
+
+	/* calculate initial misfit */
+	double E_old=misfit(m_old,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my);
+
+	/* record initial settings */
+	savefile1 << "P     "<< "Ta    "<< "Tm    "<< "Eold  "<< "totaliter "<< "Tred   "<< endl;
+	savefile1 << "nan   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+	savefile2 << totaliter<< endl;
+	for(int i=0;i<mx*my;i++){
+		savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+	}
+	savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+
+	/* beginning of the loop */
+
+	while(finished==0){
+
+		iterT++;
+		totaliter++;
+
+		/* stop or reduce T */
+		if(iterT>=maxiter || success>maxsuccess){
+			if(Ta<T_min || total>maxtotaliter || fabs(E_old)<=Tol){
+				finished=1;
+				total+=iterT;
+				break;
+			}
+			else{ /* reduce T */
+				Ta=coolshed(T0a,Tred,ca,D);
+				Tm=coolshed(T0m,Tred,cm,D);
+				total+=iterT;
+				iterT=0;
+				success=1;
+				Tred++;
+				consec=0;
+			}
+		}
+
+		/* update model and calculate energy */
+
+		newmodelgen(m_old,m_new,bathy,icethick,mx,my,Tm,ptval,mmax,mmax2,ctr,sd);  /* new model */
+		E_new=misfit(m_new,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my); /* new energy */
+		dE=E_new-E_old;                                        /* energy difference */
+
+		/* acceptance probability */
+
+		P=exp(-dE/Ta);
+
+		/* stop if energy is lower than specified minimum */
+		if (E_new<E_min){
+			m_old->MatrixEqual(m_new);
+			E_old=E_new;
+			break;
+		}
+
+		rn=rand()/double (RAND_MAX);
+
+		/* accept new model or not */
+		if(dE<=0){
+			m_old->MatrixEqual(m_new);
+			E_old=E_new;
+			success++;
+			consec=0;
+			savefile1 << P<<"   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+			if(Ta<1e-3){
+				savefile2 << totaliter<< endl;
+				for(int i=0;i<mx*my;i++){
+					savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+				}
+				savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+			}
+		}
+		else{
+			if(P>rn){
+				m_old->MatrixEqual(m_new);
+				E_old=E_new;
+				success++;
+				consec=0;
+				savefile1 << P<<"   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+				if(Ta<1e-3){
+					savefile2 << totaliter<< endl;
+					for(int i=0;i<mx*my;i++){
+						savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+					}
+					savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+				}
+			}
+			else{
+				consec++;
+			}
+		}
+	cout<<totaliter<<endl;
+	}
+
+	m_min->MatrixEqual(m_old);
+	E_final=E_old;
+	savefile1 << "nan"<<"   "<<  "nan"<<"   "<< "nan"<<"   "<< E_final<<"     "<< "nan"<<"         "<< "nan" <<"  "<< endl;
+	savefile2 << " Mesh final"<< endl;
+	for(int i=0;i<mx*my;i++){
+		savefile2 << m_min->GetValue(i,0)<<"   "<< m_min->GetValue(i,1)<<"   "<< m_min->GetValue(i,2)<<endl;
+	}
+	savefile1.close();
+	savefile2.close();
+
+	delete m_old;
+	delete m_min;
+	delete m_new;
+	delete Pobs;
+	delete Pp;
+	delete Rho;
+	delete rho1;
+	delete rho2;
+	delete xobs;
+	delete yobs;
+	delete mesh_ini;
+	delete bathy;
+	delete icethick;
+	delete evalid;
+
+			/*}}}*/
+	return 0;
+}/*}}}*/
+
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B){/*{{{*/
+
+	/*GSL Matrices and vectors: */
+	int    M,N;
+	double chisq;
+
+	/*Get system size*/
+	A->GetSize(&M,&N);
+
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix* a = gsl_matrix_alloc(M,N);
+	for(int i=0;i<M;i++){
+		for(int j=0;j<N;j++){
+			gsl_matrix_set (a,i,j,A->GetValue(i,j));
+		}
+	}
+	gsl_vector* b = gsl_vector_alloc(M);
+	for(int i=0;i<M;i++){
+		gsl_vector_set(b,i,B->GetValue(i,0));
+	}
+
+	gsl_vector* x = gsl_vector_alloc(N);
+	gsl_matrix* cov = gsl_matrix_alloc(N,N);
+
+	/*Least square fit: */
+	gsl_multifit_linear_workspace* work = gsl_multifit_linear_alloc(M,N);
+	gsl_multifit_linear (a, b, x, cov, &chisq, work);
+	gsl_multifit_linear_free (work);
+
+	/*Clean up and assign output pointer*/
+	Matrix* X = new Matrix(N,1);
+	for(int j=0;j<N;j++){
+		X->SetValue(j,0,gsl_vector_get(x,j));
+	}
+	*pX = X;
+
+	gsl_matrix_free(a);
+	gsl_vector_free(b);
+	gsl_vector_free(x);
+	gsl_matrix_free(cov);
+
+}/*}}}*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			Pobs->SetValue(j+nx*i,0,j*dx);
+			Pobs->SetValue(j+nx*i,1,i*dy);
+		}
+	}
+}/*}}}*/
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+			V2->SetValue(i,j, V->GetValue(j+nx*i,1));
+		}
+	}
+}/*}}}*/
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,double dlevel){/*{{{*/
+	int sizem1,sizem2;
+	m->GetSize(&sizem1,&sizem2);
+	for(int i=0;i<sizem1;i++){
+		for(int j=0;j<sizem2+1;j++){
+			if(j<sizem2){
+				m1->SetValue(i,j,1e-10*(sizem2+1-j));
+				m2->SetValue(i,j,m->GetValue(i,j));
+				if(m->GetValue(i,j)<0){
+					m1->SetValue(i,j,m->GetValue(i,j));
+					m2->SetValue(i,j,i*1e-10);
+				}
+			}
+			else{
+				m1->SetValue(i,j,1e-10);
+			}
+		}
+	}
+	m1->AddNumber(dlevel);
+	m2->AddNumber(dlevel);
+}/*}}}*/
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+		}
+	}
+}/*}}}*/
+void reshape(Matrix* V,Matrix* V1,int nx,int ny){/*{{{*/
+	for (int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			V1->SetValue(j+nx*i,0,V->GetValue(i,j));
+		}
+	}
+}/*}}}*/
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,double dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my){/*{{{*/
+	Matrix* m1=new Matrix(mx*my,4);
+	Matrix* m2=new Matrix(mx*my,3);
+	Matrix* g1=new Matrix(nx*ny,1);
+	Matrix* g2=new Matrix(nx*ny,1);
+	Matrix* g=new Matrix(nx*ny,1);
+	Matrix* gcalgr=new Matrix(ny,nx);
+	Matrix* gcalvec=new Matrix(mx*my,1);
+	Matrix* df=new Matrix(mx*my,1);
+	Matrix* G=new Matrix(mx*my,3);
+	double a=0;
+	double b=0;
+	double e=0;
+	msplit(m0,m1,m2,dlevel);
+	
+	/*Multithreaded core*/
+	int       num_threads = 8;
+	AppStruct usr;
+	usr.g = g1;
+	usr.Pobs = Pobs;
+	usr.Pp=Pp;
+	usr.mesh= m1;
+	usr.rho= rho1;
+	usr.dx=dx;
+	usr.dy=dy;
+	usr.dn=dn;
+	usr.m=mx*my;
+	usr.n=nx*ny;
+	usr.l=4;
+	LaunchThread(plouffT,(void*)&usr,num_threads);
+	usr.g = g2;
+	usr.mesh= m2;
+	usr.rho= rho2;
+	usr.l=3;
+	LaunchThread(plouffT,(void*)&usr,num_threads);
+	g->MatrixSum(g1,g2);
+	vec2gridsimple(g,gcalgr,nx,ny);
+	reshape(gcalgr,gcalvec,mx,my);
+	for (int i=0;i<mx*my;i++){
+		df->SetValue(i,0,evalid->GetValue(i,0)*(gobs->GetValue(i,0)-gcalvec->GetValue(i,0)));
+		G->SetValue(i,0,evalid->GetValue(i,0)*Pobs->GetValue(i,0));
+		G->SetValue(i,1,evalid->GetValue(i,0)*Pobs->GetValue(i,1));
+		G->SetValue(i,2,evalid->GetValue(i,0));
+	}
+	Matrix* M = NULL;
+	GSLsquarefit(&M,G,df);
+
+	for (int i=0;i<my;i++){
+		for(int j=0;j<mx;j++){
+			gcalgr->SetValue(i,j,gcalgr->GetValue(i,j)+xobs->GetValue(i,j)*M->GetValue(0,0)+yobs->GetValue(i,j)*M->GetValue(1,0)+M->GetValue(2,0));
+		}
+	}
+	reshape(gcalgr,g,mx,my);
+	for (int i=0;i<mx*my;i++){
+		a=a+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)-g->GetValue(i,0)));
+		b=b+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)+g->GetValue(i,0)));
+	}
+	e=2*a/(a+b);
+
+	delete m1;
+	delete m2;
+	delete g1;
+	delete g2;
+	delete g;
+	delete gcalgr;
+	delete gcalvec;
+	delete df;
+	delete G;
+	delete M;
+
+	return e;
+}/*}}}*/
+void newmodelgen(Matrix* m0,Matrix* m1,Matrix* bathy,Matrix* icethick,int mx,int my,double T,double ptval,double mmax,double mmax2,double ctr,double sd){/*{{{*/
+	Matrix* m1gr=new Matrix(my,mx);
+	Matrix* m1grsm=new Matrix(my,mx);
+	Matrix* m1col=new Matrix(mx*my,1);
+	double u=0;
+	double y=0;
+	m1->MatrixEqual(m0);
+	for (int i=0;i<mx*my;i++){
+		if(icethick->GetValue(i,0)==0){
+			u=double (rand())/ double(RAND_MAX);
+			y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+			m1->SetValue(i,1,m0->GetValue(i,1)+y*ptval);
+			if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+				m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+			}
+			if(m1->GetValue(i,1)>=m1->GetValue(i,0)+mmax){
+				m1->SetValue(i,1,m1->GetValue(i,0)+mmax);
+			}
+		}
+	}
+	m1->ExtractColumn(m1col,1);
+	vec2gridsimple(m1col,m1gr,mx,my);
+	filtergrav(m1grsm,m1gr,ctr,sd,mx,my);
+	reshape(m1grsm,m1col,mx,my);
+	for (int i=0;i<mx*my;i++){
+		if(icethick->GetValue(i,0)==0){
+			m1->SetValue(i,1,m1col->GetValue(i,0));
+		}
+		else{
+			m1->SetValue(i,1,m0->GetValue(i,1));
+		}
+		if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+			m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+		}
+	}
+
+	for (int i=0;i<mx*my;i++){
+		if(bathy->GetValue(i,0)==0){
+			u=double (rand())/ double(RAND_MAX);
+			y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+			m1->SetValue(i,2,m0->GetValue(i,2)+y*ptval);
+			if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+				m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+			}
+			if(m1->GetValue(i,2)>=m1->GetValue(i,1)+mmax2){
+				m1->SetValue(i,2,m1->GetValue(i,1)+mmax2);
+			}
+		}
+	}
+	m1->ExtractColumn(m1col,2);
+	vec2gridsimple(m1col,m1gr,mx,my);
+	filtergrav(m1grsm,m1gr,ctr,sd,mx,my);
+	reshape(m1grsm,m1col,mx,my);
+	for (int i=0;i<mx*my;i++){
+		if(bathy->GetValue(i,0)==0){
+			m1->SetValue(i,2,m1col->GetValue(i,0));
+		}
+		else{
+			m1->SetValue(i,2,m0->GetValue(i,2));
+		}
+		if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+			m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+		}
+	}
+	delete m1gr;
+	delete m1grsm;
+	delete m1col;
+}/*}}}*/
+double signe(double a){/*{{{*/
+	if(a<0){return -1;}
+	else{return 1;}
+}/*}}}*/
+void filtergrav(Matrix* A,Matrix* Ain,double ctr,double sd,int mx,int my){/*{{{*/
+	A->MatrixEqual(Ain);
+	for (int i=1;i<my-1;i++){
+		for(int j=1;j<mx-1;j++){
+			A->SetValue(i,j,(ctr*Ain->GetValue(i,j)+sd*(Ain->GetValue(i-1,j)+Ain->GetValue(i+1,j)+Ain->GetValue(i,j-1)+Ain->GetValue(i,j+1)))/(ctr+4*sd));
+		}
+	}
+}/*}}}*/
+double coolshed(double T0,double k,double c,double D){/*{{{*/
+	double T1=T0*exp(-c*pow(k,1/D));
+	return T1;
+}/*}}}*/
+void* plouffT(void* vpthread_handle){/*{{{*/
+
+	/*recover this thread info*/
+	pthread_handle *handle = (pthread_handle*)vpthread_handle;
+	int my_thread   = handle->my_thread;
+	int num_threads = handle->num_threads;
+
+	/*Recover struct*/
+	AppStruct *usr = (AppStruct*)handle->usr;
+	Matrix *g = usr->g;
+	Matrix *Pobs = usr->Pobs;
+	Matrix *Pp = usr->Pp;
+	Matrix *mesh = usr->mesh;
+	Matrix *rho = usr->rho;
+	int dx =usr->dx;
+	int dy =usr->dy;
+	int dn =usr->dn;
+	int m =usr->m;
+	int n =usr->n;
+	int l =usr->l;
+
+	double gg=6.673e-11;
+	int si,sj,id,s;
+	double R,Q,P;
+	Matrix *xp= new Matrix(1,2);
+	Matrix *yp= new Matrix(1,2);
+	Matrix *xpp= new Matrix(1,2);
+	Matrix *ypp= new Matrix(1,2);
+	Matrix *U= new Matrix(l,4);
+	Matrix *U1=new Matrix(1,4);
+	Matrix *U2=new Matrix(1,4);
+	Matrix *gl= new Matrix(1,l-1);
+	bool test=true;
+	for(int c=my_thread;c<n;c+=num_threads){
+		g->SetValue(c,0,0);
+		for(int a=0;a<m;a++){
+			test=true;
+			xp->SetValue(0,0,Pp->GetValue(a,0)-Pobs->GetValue(c,0));
+			xp->SetValue(0,1,Pp->GetValue(a,0)-Pobs->GetValue(c,0)+dx);
+			if(xp->GetValue(0,0)<0 && xp->GetValue(0,0)<xp->GetValue(0,1) && xp->GetValue(0,0)*xp->GetValue(0,1)>=0){
+				xpp->SetValue(0,0,xp->GetValue(0,1));
+				xpp->SetValue(0,1,xp->GetValue(0,0));
+				xp->MatrixAbs(xpp);
+			}
+			yp->SetValue(0,0,Pp->GetValue(a,1)-Pobs->GetValue(c,1));
+			yp->SetValue(0,1,Pp->GetValue(a,1)-Pobs->GetValue(c,1)+dy);
+			if(yp->GetValue(0,0)<0 && yp->GetValue(0,0)<yp->GetValue(0,1) && yp->GetValue(0,0)*yp->GetValue(0,1)>=0){
+				ypp->SetValue(0,0,yp->GetValue(0,1));
+				ypp->SetValue(0,1,yp->GetValue(0,0));
+				yp->MatrixAbs(ypp);
+			}
+			P=sqrt(xp->GetValue(0,0)*xp->GetValue(0,0)+yp->GetValue(0,0)*yp->GetValue(0,0));
+			if(P>dn){
+				test=false;
+				for(int i=0;i<l-1;i++){
+					gl->SetValue(0,i,0);
+				}
+			}
+			if(test==true){
+				si=1;
+				sj=1;
+				id=0;
+				for(int i=0;i<2;i++){
+					si*=-1;
+					for(int j=0;j<2;j++){
+						si*=-1;
+						s=si*sj;
+						for(int k=0;k<l;k++){
+							R=sqrt(xp->GetValue(0,i)*xp->GetValue(0,i)+yp->GetValue(0,j)*yp->GetValue(0,j)+mesh->GetValue(a,k)*mesh->GetValue(a,k));
+							Q=atan(xp->GetValue(0,i)*yp->GetValue(0,j)/(mesh->GetValue(a,k)*R));
+							U->SetValue(k,id,s*(mesh->GetValue(a,k)*Q-xp->GetValue(0,i)*log(R+yp->GetValue(0,j))-yp->GetValue(0,j)*log(R+xp->GetValue(0,i))));
+						}
+						id++;
+					}
+				}
+				for(int b=0;b<l-1;b++){
+					U->ExtractLine(U1,b);
+					U->ExtractLine(U2,b+1);
+					gl->SetValue(0,b,rho->GetValue(0,b)*(U1->MatrixInternSum()*(-1)+U2->MatrixInternSum()));
+				}
+			}
+			g->SetValue(c,0,g->GetValue(c,0)+gg*gl->MatrixInternSum());
+		}
+	}
+	delete xp;
+	delete yp;
+	delete xpp;
+	delete ypp;
+	delete gl;
+	delete U;
+	delete U1;
+	delete U2;
+
+	return NULL;
+}/*}}}*/
+void LaunchThread(void* function(void*), void* usr,int num_threads){/*{{{*/
+
+	int i;
+	int            *status  = NULL;
+	pthread_t      *threads = NULL;
+	pthread_handle *handles = NULL;
+
+	/*dynamically allocate: */
+	threads=(pthread_t*)malloc(num_threads*sizeof(pthread_t));
+	handles=(pthread_handle*)malloc(num_threads*sizeof(pthread_handle));
+
+	for(i=0;i<num_threads;i++){
+		handles[i].usr=usr;
+		handles[i].my_thread  =i;
+		handles[i].num_threads=num_threads;
+	}
+	for(i=0;i<num_threads;i++){
+		if(pthread_create(threads+i,NULL,function,(void*)(handles+i))){
+			std::cerr<<"pthread_create error";
+		}
+	}
+	for(i=0;i<num_threads;i++){
+		if(pthread_join(threads[i],(void**)&status)){
+			std::cerr<<"pthread_join error";
+		}
+	}
+
+	/*Free ressources:*/
+	delete threads;
+	delete handles;
+}/*}}}*/
Index: /issm/trunk/src/m/contrib/gravity/vfsa_mpi.cpp
===================================================================
--- /issm/trunk/src/m/contrib/gravity/vfsa_mpi.cpp	(revision 19105)
+++ /issm/trunk/src/m/contrib/gravity/vfsa_mpi.cpp	(revision 19105)
@@ -0,0 +1,835 @@
+#include <iostream>
+#include <cmath>
+#include <fstream>
+#include <string>
+#include <cstdio>
+#include <cstdlib>
+#include <time.h>
+#include <cassert>
+#include <gsl/gsl_multifit.h>
+#include "mpi.h"
+using namespace std;
+
+class Matrix{/*{{{*/
+	private:
+		int     M;        /*Number of lines   */
+		int     N;        /*Number if Columns */
+		double *values;
+	public:
+		Matrix(int m_in,int n_in){/*{{{*/
+			this->M = m_in;
+			this->N = n_in;
+			this->values = new double[M*N]();
+		}/*}}}*/
+		~Matrix(){/*{{{*/
+			delete [] this->values;
+		}/*}}}*/
+		void Echo(void){/*{{{*/
+			for(int i=0;i<M;i++){
+				for(int j=0;j<N;j++){
+					cout << " " << this->values[i*N+j];
+				}
+				cout << endl;
+			}
+		}/*}}}*/
+		void SetValue(int i,int j,double value){/*{{{*/
+			this->values[i*N+j] = value;
+		}/*}}}*/
+		double GetValue(int i,int j){/*{{{*/
+			return this->values[i*N+j];
+		}/*}}}*/
+		void GetSize(int* pM,int* pN){/*{{{*/
+			*pM = this->M;
+			*pN = this->N;
+		}/*}}}*/
+		double* GetPointer(void){/*{{{*/
+			return this->values;
+		}/*}}}*/
+		void MatrixSum(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) + B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixDiff(Matrix* A,Matrix* B){/*{{{*/
+			/*Check that sizes are compatible*/
+			int M_B,N_B,M_A,N_A;
+			B->GetSize(&M_B,&N_B);
+			A->GetSize(&M_A,&N_A);
+			assert(this->M==M_B && this->N==N_B);
+			assert(this->M==M_A && this->N==N_A);
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j) - B->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		void MatrixAbs(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,fabs(A->GetValue(i,j)));
+				}
+			}
+		}/*}}}*/
+		void MatrixEqual(Matrix* A){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,A->GetValue(i,j));
+				}
+			}
+		}/*}}}*/
+		double MatrixInternSum(){/*{{{*/
+			double sum=0;
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					sum+=this->GetValue(i,j);
+				}
+			}
+			return sum;
+		}/*}}}*/
+		void ExtractLine(Matrix* A,int i){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(M_A==1 && this->N==N_A);
+			for(int j=0;j<this->N;j++){
+				A->SetValue(0,j,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void ExtractColumn(Matrix* A,int j){/*{{{*/
+			/* Check that the size of A is compatible */
+			int M_A,N_A;
+			A->GetSize(&M_A,&N_A);
+			assert(N_A==1 && this->M==M_A);
+			for(int i=0;i<this->M;i++){
+				A->SetValue(i,0,this->GetValue(i,j));
+			}
+		}/*}}}*/
+		void AddNumber(double a){/*{{{*/
+			for(int i=0;i<this->M;i++){
+				for(int j=0;j<this->N;j++){
+					this->SetValue(i,j,this->GetValue(i,j) + a);
+				}
+			}
+		}/*}}}*/
+};/*}}}*/
+
+/*Local prototypes{{{*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy);
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny);
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,double dlevel);
+void plouff(Matrix *g,Matrix *Pobs,Matrix *Pp,Matrix * mesh,Matrix *rho,int dx,int dy, int dn,int m,int n,int l,int my_rank,int num_procs);
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny);
+void reshape(Matrix* V,Matrix* V1,int nx,int ny);
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,double dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my,int my_rank,int num_procs);
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B);
+double signe(double a);
+void filtergrav(Matrix* A,Matrix* Ain,double ctr,double sd,int mx,int my);
+void newmodelgen(Matrix* m0,Matrix* m1,Matrix* bathy,Matrix* icethick,int mx,int my,double T,double ptval,double mmax,double mmax2,double ctr,double sd, Matrix *landmask);
+double coolshed(double T0,double k,double c,double D);
+/*}}}*/
+
+int main(int argc,char *argv[]){/*{{{*/
+	
+	int my_rank,num_procs;
+
+	MPI_Init(&argc, &argv);
+
+	MPI_Comm_size(MPI_COMM_WORLD,&num_procs);
+	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
+
+	/* Seed the random number generator {{{*/
+		srand (time(NULL));            /*}}}*/
+	/* Define the variables {{{*/
+
+	int    dx     = 1000;   /* prism dimension in x-direction                           */
+	int    dy     = 1000;   /* prism dimension in y-direction                           */
+	int    mx     = 99;    /* number of prisms in x-direction                          */
+	int    my     = 99;    /* number of prisms in y-direction                          */
+	int    nx     = 99;    /* number of data points in x-direction                     */
+	int    ny     = 99;    /* number of data points in y-direction                     */
+	int    dn     = 15000; /* distance for neighbouting prisms for gravity calculation */
+	double ptval  = 100.;  /* max. amount to perturb model                             */
+	double ptval2 = 100.;
+
+	Matrix *Pobs=new Matrix(nx*ny,2); /* data positions */
+	makep(Pobs,nx,ny,dx,dy);
+	// Pobs->Echo();
+
+
+	Matrix *Pp=new Matrix(mx*my,2); /* prisms positions */
+	makep(Pp,mx,my,dx,dy);
+	// Pp->Echo();
+
+	double  rhoi = 917;           /* ice density     */
+	double  rhow = 1030;          /* water density   */
+	// double  rhos = 2013;		      /* sediment density */
+	double  rhoc = 2670;          /* bedrock density */
+
+	Matrix *Rho  = new Matrix(1,2);
+	Rho->SetValue(0,0,rhoi);
+	Rho->SetValue(0,1,rhow);
+	Matrix *rho1  = new Matrix(1,3);
+	rho1->SetValue(0,0,rhoi);
+	rho1->SetValue(0,1,rhow);
+	rho1->SetValue(0,2,rhoc);
+	Matrix *rho2  = new Matrix(1,2);
+	rho2->SetValue(0,0,rhoi-rhoc);
+	rho2->SetValue(0,1,rhow-rhoc);
+
+	double dlevel=2400;         /* level of data acquisition */
+
+	double ctr=1;            /* parameter for filtering */
+	double sd=0.1;
+
+	Matrix *xobs= new Matrix(ny,nx);
+	Matrix *yobs= new Matrix(ny,nx);
+
+	vec2grid(Pobs,xobs,yobs,nx,ny);
+	//	xobs->Echo();
+	//	yobs->Echo();
+
+
+	double mmax  = 2000;               /* max value for layer interfaces */
+	double mmax2 = 2000;
+	double mmax3 = 2000;
+
+	/* control parameter for temperature schedule  */
+
+	double ca=0.9;                    /* for acceptance */
+	double cm=0.5;                    /* for model perturbation */
+
+	double T0a          = 0.1;      /* initial temperature for acceptance           */
+	double T0m          = 0.9;      /* initial temperature for model perturbation   */
+	double D            = 2;        /* dimension of the model                       */
+	int    maxconsecrej = 1000;     /* max consecutive rejection                    */
+	int    maxsuccess   = 100;      /* max number of success within one temperature */
+	double T_min        = 1e-10;    /* stopping temp                                */
+	double Tred         = 1;
+	double E_min        = -1000000;
+	double E_exp        = 0.0291;   /* expected misfit                              */
+	int    maxiter      = 10000;
+	int    maxtotaliter = 1000000;
+	double Tol          = 1e-10;    /* tolerance on misfit                          */
+	int    sfreq        = 100;
+
+	/*}}}*/     
+	/* load the data {{{*/
+
+	/*landmask */
+
+	ifstream file("landmaskzach.txt");
+	Matrix * landmask= new Matrix(nx*ny,1);
+	double inputnumber;
+	for(int i=0;i<ny*nx; i++){ 
+		file >> inputnumber;
+		landmask->SetValue(i,0,inputnumber);
+	}
+	file.close();
+
+	/* Observed gravity anomaly */
+
+	ifstream file1("gravityzach.txt");
+	Matrix * gobs= new Matrix(nx*ny,1);
+	for(int i=0;i<ny*nx; i++){ 
+		file1 >> inputnumber;
+		gobs->SetValue(i,0, inputnumber*1e-5);
+	}
+	file1.close();
+	//	gobs->Echo();
+
+	/* load data about the ice thickness */
+
+	ifstream file2("icethickzach.txt");
+	Matrix * icethick= new Matrix(mx*my,1);
+	for(int s=0;s<mx*my; s++){ 
+		file2 >> inputnumber;
+		icethick->SetValue(s,0,inputnumber);
+	}
+	file2.close();
+	//	icethick->Echo();
+
+	/* load the batimethry data */
+
+	ifstream file3("bathymetryzach.txt");
+	Matrix * bathy= new Matrix(mx*my,1);
+	for(int s=0;s<mx*my; s++){ 
+		file3 >> inputnumber;
+		bathy->SetValue(s,0,inputnumber);
+	}
+	file3.close();
+	//	bathy->Echo();
+
+	/* id of grid to evaluate misfit */
+
+
+	ifstream file4("evalidzach.txt");
+	Matrix * evalid= new Matrix(nx*ny,1);
+	for(int s=0;s<nx*ny; s++){ 
+		file4 >> inputnumber;
+		evalid->SetValue(s,0,inputnumber);
+	}
+	file4.close();
+	//	evalid->Echo();
+
+	/* initial guess of the model */
+
+	ifstream file5("m0_092614zach.txt");
+	Matrix * mesh_ini= new Matrix(mx*my,3);
+	for(int s=0;s<mx*my; s++){ 
+		for(int j=0;j<3;j++){
+			file5 >> inputnumber;
+			mesh_ini->SetValue(s,j,inputnumber);
+		}
+	}
+	file5.close();
+	//	mesh_ini->Echo();
+	/*}}}*/
+	/* VFSA {{{ */
+
+	/* name of the files to save results */
+	std::ofstream savefile1 ("r_zach.txt");
+	std::ofstream savefile2("m_zach.txt");
+
+	/* counters initialization */
+	int    success   = 0;
+	int    finished  = 0;
+	int    consec    = 0;
+	double Ta        = T0a;
+	double Tm        = T0m;
+	int    iterT     = 0;   /* iteration within a T      */
+	int    total     = 0;   /* total number of iteration */
+	int    totaliter = 0;
+	int    msave     = 0;
+	double E_new;
+	double E_final;
+	double dE;
+	double P;
+	double rn;
+	Matrix* m_old    = new Matrix(mx *my,3);
+	Matrix* m_min    = new Matrix(mx *my,3);
+	Matrix* m_new    = new Matrix(mx *my,3);
+	m_old->MatrixEqual(mesh_ini);
+
+	/* calculate initial misfit */
+	double E_old=misfit(m_old,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my, my_rank, num_procs);
+	/* record initial settings */
+	if(!my_rank){
+		savefile1 << "P     "<< "Ta    "<< "Tm    "<< "Eold  "<< "totaliter "<< "Tred   "<< endl;
+		savefile1 << "nan   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+		savefile2 << totaliter<< endl;
+		for(int i=0;i<mx*my;i++){
+			savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+		}
+		savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+	}
+	/* beginning of the loop */
+
+	while(finished==0){
+		iterT++;
+		totaliter++;
+
+		/* stop or reduce T */
+		if(iterT>=maxiter || success>maxsuccess){
+			if(Ta<T_min || total>maxtotaliter || fabs(E_old)<=Tol){
+				finished=1;
+				total+=iterT;
+				break;
+			}
+			else{ /* reduce T */
+				Ta=coolshed(T0a,Tred,ca,D);
+				Tm=coolshed(T0m,Tred,cm,D);
+				total+=iterT;
+				iterT=0;
+				success=1;
+				Tred++;
+				consec=0;
+			}
+		}
+
+		/* update model and calculate energy */
+
+		newmodelgen(m_old,m_new,bathy,icethick,mx,my,Tm,ptval,mmax,mmax2,ctr,sd, landmask);  /* new model */
+		E_new=misfit(m_new,evalid,gobs,dlevel,Pobs,xobs,yobs,Pp,rho1,rho2,dx,dy,dn,nx,ny,mx,my, my_rank, num_procs); /* new energy */
+		dE=E_new-E_old;                                        /* energy difference */
+
+		/* acceptance probability */
+
+		P=exp(-dE/Ta);
+
+		/* stop if energy is lower than specified minimum */
+		if (E_new<E_min){
+			m_old->MatrixEqual(m_new);
+			E_old=E_new;
+			break;
+		}
+
+		rn=rand()/double (RAND_MAX);
+
+		/* accept new model or not */
+		if(dE<=0){
+			m_old->MatrixEqual(m_new);
+			E_old=E_new;
+			success++;
+			consec=0;
+			if(!my_rank){
+				savefile1 << P<<"   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+			}
+			if(Ta<1e-3){
+				if(!my_rank){
+					savefile2 << totaliter<< endl;
+					for(int i=0;i<mx*my;i++){
+						savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+					}
+					savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+				}
+			}
+		}
+		else{
+			if(P>rn){
+				m_old->MatrixEqual(m_new);
+				E_old=E_new;
+				success++;
+				consec=0;
+				if(!my_rank){
+					savefile1 << P<<"   "<<  Ta<<"   "<< Tm<<"   "<< E_old<<"     "<< totaliter<<"         "<< Tred <<"  "<< endl;
+					if(Ta<1e-3){
+						savefile2 << totaliter<< endl;
+						for(int i=0;i<mx*my;i++){
+							savefile2 << m_old->GetValue(i,0)<<"   "<< m_old->GetValue(i,1)<<"   "<< m_old->GetValue(i,2)<<endl;
+						}
+						savefile2 << "111111111111111111111111111111111111111111111111111111111111111111111111111"<< endl;
+					}
+				}
+			}
+			else{
+				consec++;
+			}
+		}
+	}
+
+	m_min->MatrixEqual(m_old);
+	E_final=E_old;
+	if(!my_rank){
+		savefile1 << "nan"<<"   "<<  "nan"<<"   "<< "nan"<<"   "<< E_final<<"     "<< "nan"<<"         "<< "nan" <<"  "<< endl;
+		savefile2 << " Mesh final"<< endl;
+		for(int i=0;i<mx*my;i++){
+			savefile2 << m_min->GetValue(i,0)<<"   "<< m_min->GetValue(i,1)<<"   "<< m_min->GetValue(i,2)<<endl;
+		}
+	}
+	savefile1.close();
+	savefile2.close();
+
+	delete m_old;
+	delete m_min;
+	delete m_new;
+	delete Pobs;
+	delete Pp;
+	delete Rho;
+	delete rho1;
+	delete rho2;
+	delete xobs;
+	delete yobs;
+	delete mesh_ini;
+	delete bathy;
+	delete icethick;
+	delete evalid;
+
+	/*}}}*/
+
+   MPI_Finalize();
+
+	return 0;
+}/*}}}*/
+
+void GSLsquarefit(Matrix** pX,Matrix* A,Matrix* B){/*{{{*/
+
+	/*GSL Matrices and vectors: */
+	int    M,N;
+	double chisq;
+	/*Get system size*/
+	A->GetSize(&M,&N);
+
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix* a = gsl_matrix_alloc(M,N);
+	for(int i=0;i<M;i++){
+		for(int j=0;j<N;j++){
+			gsl_matrix_set (a,i,j,A->GetValue(i,j));
+		}
+	}
+	gsl_vector* b = gsl_vector_alloc(M);
+	for(int i=0;i<M;i++){
+		gsl_vector_set(b,i,B->GetValue(i,0));
+	}
+
+	gsl_vector* x = gsl_vector_alloc(N);
+	gsl_matrix* cov = gsl_matrix_alloc(N,N);
+
+	/*Least square fit: */
+	gsl_multifit_linear_workspace* work = gsl_multifit_linear_alloc(M,N);
+	gsl_multifit_linear (a, b, x, cov, &chisq, work);
+	gsl_multifit_linear_free (work);
+
+	/*Clean up and assign output pointer*/
+	Matrix* X = new Matrix(N,1);
+	for(int j=0;j<N;j++){
+		X->SetValue(j,0,gsl_vector_get(x,j));
+	}
+	*pX = X;
+
+	gsl_matrix_free(a);
+	gsl_vector_free(x);
+	gsl_vector_free(b);
+	gsl_matrix_free(cov);
+
+}/*}}}*/
+void makep(Matrix *Pobs,int nx,int ny, int dx, int dy){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			Pobs->SetValue(j+nx*i,0,j*dx);
+			Pobs->SetValue(j+nx*i,1,i*dy);
+		}
+	}
+}/*}}}*/
+void vec2grid(Matrix *V,Matrix *V1,Matrix *V2,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+			V2->SetValue(i,j, V->GetValue(j+nx*i,1));
+		}
+	}
+}/*}}}*/
+void msplit( Matrix *m, Matrix *m1,Matrix *m2,double dlevel){/*{{{*/
+	int sizem1,sizem2;
+	m->GetSize(&sizem1,&sizem2);
+	for(int i=0;i<sizem1;i++){
+		for(int j=0;j<sizem2+1;j++){
+			if(j<sizem2){
+				m1->SetValue(i,j,1e-10*(sizem2+1-j));
+				m2->SetValue(i,j,m->GetValue(i,j));
+				if(m->GetValue(i,j)<0){
+					m1->SetValue(i,j,m->GetValue(i,j));
+					m2->SetValue(i,j,i*1e-10);
+				}
+				m1->SetValue(i,j,m1->GetValue(i,j));
+				m2->SetValue(i,j,m2->GetValue(i,j));
+			}
+			else{
+				m1->SetValue(i,j,1e-10);
+			}
+		}
+	}
+	m1->AddNumber(dlevel);
+	m2->AddNumber(dlevel);
+}/*}}}*/
+void plouff(Matrix *g,Matrix *Pobs,Matrix *Pp,Matrix * mesh,Matrix *rho,int dx,int dy, int dn,int m,int n,int l,int my_rank,int num_procs){/*{{{*/
+	double gg=6.673e-11;
+	int si,sj,id,s;
+	double R,Q,P;
+	Matrix *xp= new Matrix(1,2);
+	Matrix *yp= new Matrix(1,2);
+	Matrix *xpp= new Matrix(1,2);
+	Matrix *ypp= new Matrix(1,2);
+	Matrix *U= new Matrix(l,4);
+	Matrix *U1=new Matrix(1,4);
+	Matrix *U2=new Matrix(1,4);
+	Matrix *gl= new Matrix(1,l-1);
+	bool test=true;
+
+	double *glocal=new double[n]();
+
+	for(int c=my_rank;c<n;c+=num_procs){
+		glocal[c]=0;
+		for(int a=0;a<m;a++){
+			test=true;
+			xp->SetValue(0,0,Pp->GetValue(a,0)-Pobs->GetValue(c,0));
+			xp->SetValue(0,1,Pp->GetValue(a,0)-Pobs->GetValue(c,0)+dx);
+			if(xp->GetValue(0,0)<0 && xp->GetValue(0,0)<xp->GetValue(0,1) && xp->GetValue(0,0)*xp->GetValue(0,1)>=0){
+				xpp->SetValue(0,0,xp->GetValue(0,1));
+				xpp->SetValue(0,1,xp->GetValue(0,0));
+				xp->MatrixAbs(xpp);
+			}
+			yp->SetValue(0,0,Pp->GetValue(a,1)-Pobs->GetValue(c,1));
+			yp->SetValue(0,1,Pp->GetValue(a,1)-Pobs->GetValue(c,1)+dy);
+			if(yp->GetValue(0,0)<0 && yp->GetValue(0,0)<yp->GetValue(0,1) && yp->GetValue(0,0)*yp->GetValue(0,1)>=0){
+				ypp->SetValue(0,0,yp->GetValue(0,1));
+				ypp->SetValue(0,1,yp->GetValue(0,0));
+				yp->MatrixAbs(ypp);
+			}
+			P=sqrt(xp->GetValue(0,0)*xp->GetValue(0,0)+yp->GetValue(0,0)*yp->GetValue(0,0));
+			if(P>dn){
+				test=false;
+				for(int i=0;i<l-1;i++){
+					gl->SetValue(0,i,0);
+				}
+			}
+			if(test==true){
+				si=1;
+				sj=1;
+				id=0;
+				for(int i=0;i<2;i++){
+					si*=-1;
+					for(int j=0;j<2;j++){
+						sj*=-1;
+						s=si*sj;
+						for(int k=0;k<l;k++){
+							R=sqrt(xp->GetValue(0,i)*xp->GetValue(0,i)+yp->GetValue(0,j)*yp->GetValue(0,j)+mesh->GetValue(a,k)*mesh->GetValue(a,k));
+							Q=atan(xp->GetValue(0,i)*yp->GetValue(0,j)/(mesh->GetValue(a,k)*R));
+							U->SetValue(k,id,s*(mesh->GetValue(a,k)*Q-xp->GetValue(0,i)*log(R+yp->GetValue(0,j))-yp->GetValue(0,j)*log(R+xp->GetValue(0,i))));
+						}
+						id++;
+					}
+				}
+				for(int b=0;b<l-1;b++){
+					U->ExtractLine(U1,b);
+					U->ExtractLine(U2,b+1);
+					gl->SetValue(0,b,rho->GetValue(0,b)*(U1->MatrixInternSum()*(-1)+U2->MatrixInternSum()));
+				}
+			}
+			glocal[c]=glocal[c]+gg*gl->MatrixInternSum();
+
+		}
+	}
+
+	MPI_Allreduce(glocal,g->GetPointer(),n,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+
+	delete xp;
+	delete yp;
+	delete xpp;
+	delete ypp;
+	delete gl;
+	delete U;
+	delete U1;
+	delete U2;
+	delete []glocal;
+}/*}}}*/
+void vec2gridsimple(Matrix *V,Matrix *V1,int nx, int ny){/*{{{*/
+	for(int i=0;i<ny;i++){
+		for (int j=0;j<nx;j++){
+			V1->SetValue(i,j, V->GetValue(j+nx*i,0));
+		}
+	}
+}/*}}}*/
+void reshape(Matrix* V,Matrix* V1,int nx,int ny){/*{{{*/
+	for (int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			V1->SetValue(j+nx*i,0,V->GetValue(i,j));
+		}
+	}
+}/*}}}*/
+double misfit(Matrix* m0,Matrix* evalid,Matrix* gobs,double dlevel,Matrix* Pobs,Matrix* xobs,Matrix* yobs,Matrix* Pp,Matrix* rho1, Matrix* rho2,int dx,int dy,int dn,int nx,int ny, int mx,int my,int my_rank,int num_procs){/*{{{*/
+	Matrix* m1=new Matrix(mx*my,4);
+	Matrix* m2=new Matrix(mx*my,3);
+	Matrix* g1=new Matrix(nx*ny,1);
+	Matrix* g2=new Matrix(nx*ny,1);
+	Matrix* g=new Matrix(nx*ny,1);
+	Matrix* gcalgr=new Matrix(ny,nx);
+	Matrix* gcalvec=new Matrix(nx*ny,1);
+	Matrix* df=new Matrix(nx*ny,1);
+	Matrix* G=new Matrix(nx*ny,3);
+	double a=0;
+	double b=0;
+	double e=0;
+	msplit(m0,m1,m2,dlevel);
+	plouff(g1,Pobs,Pp,m1,rho1,dx,dy,dn,mx*my,nx*ny,4, my_rank, num_procs);
+	plouff(g2,Pobs,Pp,m2,rho2,dx,dy,dn,mx*my,nx*ny,3, my_rank, num_procs);
+	g->MatrixSum(g1,g2);
+	vec2gridsimple(g,gcalgr,nx,ny);
+	reshape(gcalgr,gcalvec,nx,ny);
+	for (int i=0;i<nx*ny;i++){
+		df->SetValue(i,0,evalid->GetValue(i,0)*(gobs->GetValue(i,0)-gcalvec->GetValue(i,0)));
+		G->SetValue(i,0,evalid->GetValue(i,0)*Pobs->GetValue(i,0));
+		G->SetValue(i,1,evalid->GetValue(i,0)*Pobs->GetValue(i,1));
+		G->SetValue(i,2,evalid->GetValue(i,0));
+	}
+	Matrix* M = NULL;
+	GSLsquarefit(&M,G,df);
+
+	for (int i=0;i<ny;i++){
+		for(int j=0;j<nx;j++){
+			gcalgr->SetValue(i,j,gcalgr->GetValue(i,j)+xobs->GetValue(i,j)*M->GetValue(0,0)+yobs->GetValue(i,j)*M->GetValue(1,0)+M->GetValue(2,0));
+		}
+	}
+	reshape(gcalgr,g,nx,ny);
+	for (int i=0;i<nx*ny;i++){
+		a=a+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)-g->GetValue(i,0)));
+		b=b+fabs(evalid->GetValue(i,0)*(gobs->GetValue(i,0)+g->GetValue(i,0)));
+	}
+	e=2*a/(a+b);
+
+	delete m1;
+	delete m2;
+	delete g1;
+	delete g2;
+	delete g;
+	delete gcalgr;
+	delete gcalvec;
+	delete df;
+	delete G;
+	delete M;
+
+	return e;
+}/*}}}*/
+void newmodelgen(Matrix* m0,Matrix* m1,Matrix* bathy,Matrix* icethick,int mx,int my,double T,double ptval,double mmax,double mmax2,double ctr,double sd, Matrix *landmask){/*{{{*/
+	Matrix* m1gr=new Matrix(my,mx);
+	Matrix* m1grsm=new Matrix(my,mx);
+	Matrix* m1col=new Matrix(mx*my,1);
+	Matrix* m1gr2=new Matrix(my,mx);
+	Matrix* m1grsm2=new Matrix(my,mx);
+	Matrix* m1col2=new Matrix(mx*my,1);
+	Matrix* nptflag= new Matrix(mx*my,1);
+	double u=0;
+	double y=0;
+	m1->MatrixEqual(m0);
+	nptflag->MatrixSum(icethick,bathy);
+	/* first layer: ice */
+	for (int i=0;i<mx*my;i++){
+		if(landmask->GetValue(i,0)==2){
+			if(nptflag->GetValue(i,0)==0){
+				u=double(rand())/double(RAND_MAX);
+				y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+				m1->SetValue(i,1,m0->GetValue(i,1)+y*ptval);
+				m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+				if(m1->GetValue(i,1)>=m1->GetValue(i,0)+mmax){
+					m1->SetValue(i,1,m1->GetValue(i,0)+mmax);
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+			}
+		}
+		else if(landmask->GetValue(i,0)==0){
+			if(nptflag->GetValue(i,0)==0){
+				u=double(rand())/double(RAND_MAX);
+				y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+				m1->SetValue(i,2,m0->GetValue(i,2)+y*ptval);
+				if(m1->GetValue(i,2)<=m1->GetValue(i,0)){
+					m1->SetValue(i,2,m1->GetValue(i,0)+1e-10);
+				}
+				if(m1->GetValue(i,2)>=m1->GetValue(i,0)+mmax2){
+					m1->SetValue(i,2,m1->GetValue(i,0)+mmax2);
+				}
+			}
+		}
+	}
+
+	m1->ExtractColumn(m1col,1);
+	vec2gridsimple(m1col,m1gr,mx,my);
+	filtergrav(m1grsm,m1gr,ctr,sd,mx,my);
+	reshape(m1grsm,m1col,mx,my);
+	m1->ExtractColumn(m1col2,2);
+	vec2gridsimple(m1col2,m1gr2,mx,my);
+	filtergrav(m1grsm2,m1gr2,ctr,sd,mx,my);
+	reshape(m1grsm2,m1col2,mx,my);
+
+	for (int i=0;i<mx*my;i++){
+		if(landmask->GetValue(i,0)==2){
+			if(nptflag->GetValue(i,0)==0){
+				m1->SetValue(i,1,m1col->GetValue(i,0));
+				m1->SetValue(i,2,m1col2->GetValue(i,0));
+				if(m1->GetValue(i,1)<=m1->GetValue(i,0)){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+				if(fabs(m1->GetValue(i,2)-m1->GetValue(i,1))>1){
+					m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+				}
+			}
+			else{
+				m1->SetValue(i,1,m0->GetValue(i,1));
+				m1->SetValue(i,2,m0->GetValue(i,2));
+			}
+		}
+		else if(landmask->GetValue(i,0)==0){
+			if(nptflag->GetValue(i,0)==0){
+				m1->SetValue(i,2,m1col2->GetValue(i,0));
+				if(m1->GetValue(i,2)<=m1->GetValue(i,0)){
+					m1->SetValue(i,2,m1->GetValue(i,0)+1e-10);
+				}
+				if(fabs(m1->GetValue(i,0)-m1->GetValue(i,1))>1){
+					m1->SetValue(i,1,m1->GetValue(i,0)+1e-10);
+				}
+			}
+			else{
+				m1->SetValue(i,1,m0->GetValue(i,1));
+				m1->SetValue(i,2,m0->GetValue(i,2));
+			}
+		}
+		else {
+			if(nptflag->GetValue(i,0)==0){
+				if(fabs(m1->GetValue(i,0)-m1->GetValue(i,1))>1){
+					m1->SetValue(i,1,m1->GetValue(i,0));
+				}
+				if(fabs(m1->GetValue(i,0)-m1->GetValue(i,2))>1){
+					m1->SetValue(i,2,m1->GetValue(i,0));
+				}
+			}
+			else{
+				m1->SetValue(i,1,m0->GetValue(i,1));
+				m1->SetValue(i,2,m0->GetValue(i,2));
+			}
+		}
+	}
+
+				/* second layer: water */
+//	for (int i=0;i<mx*my;i++){
+//		if(bathy->GetValue(i,0)==0){
+//			u=double (rand())/ double(RAND_MAX);
+//			y=signe(u-0.5)*T*(pow(1+1/T,fabs(2*u-1))-1);
+//			m1->SetValue(i,2,m0->GetValue(i,2)+y*ptval);
+//			if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+//				m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+//			}
+//			if(m1->GetValue(i,2)>=m1->GetValue(i,1)+mmax2){
+//				m1->SetValue(i,2,m1->GetValue(i,1)+mmax2);
+//			}
+//		}
+//	}
+//	m1->ExtractColumn(m1col,2);
+//	vec2gridsimple(m1col,m1gr,mx,my);
+//	filtergrav(m1grsm,m1gr,ctr,sd,mx,my);
+//	reshape(m1grsm,m1col,mx,my);
+//	for (int i=0;i<mx*my;i++){
+//		if(bathy->GetValue(i,0)==0){
+//			m1->SetValue(i,2,m1col->GetValue(i,0));
+//		}
+//		else{
+//			m1->SetValue(i,2,m0->GetValue(i,2));
+//		}
+//		if(m1->GetValue(i,2)<=m1->GetValue(i,1)){
+//			m1->SetValue(i,2,m1->GetValue(i,1)+1e-10);
+//		}
+//	}
+	delete m1gr;
+	delete m1grsm;
+	delete m1col;
+	delete m1gr2;
+	delete m1grsm2;
+	delete m1col2;
+	delete nptflag;
+}/*}}}*/
+double signe(double a){/*{{{*/
+	if(a<0){return -1;}
+	else{return 1;}
+}/*}}}*/
+void filtergrav(Matrix* A,Matrix* Ain,double ctr,double sd,int mx,int my){/*{{{*/
+	A->MatrixEqual(Ain);
+	for (int i=1;i<my-1;i++){
+		for(int j=1;j<mx-1;j++){
+			A->SetValue(i,j,(ctr*Ain->GetValue(i,j)+sd*(Ain->GetValue(i-1,j)+Ain->GetValue(i+1,j)+Ain->GetValue(i,j-1)+Ain->GetValue(i,j+1)))/(ctr+4*sd));
+		}
+	}
+}/*}}}*/
+double coolshed(double T0,double k,double c,double D){/*{{{*/
+	double T1=T0*exp(-c*pow(k,1/D));
+	return T1;
+}/*}}}*/
Index: /issm/trunk/src/m/contrib/gslib/gslib.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/gslib.m	(revision 19104)
+++ /issm/trunk/src/m/contrib/gslib/gslib.m	(revision 19105)
@@ -1,3 +1,3 @@
-function [B E] = gslib(x,y,data,xmin,ymin,nx,ny,deltax,deltay)
+function [B E] = gslib(x,y,data,xmin,ymin,nx,ny,deltax,deltay,varargin)
 %GSLIB - use gslib for Kriging
 %
@@ -5,13 +5,16 @@
 %      output = gslib(x,y,data,varargin)
 
+%process options
+options = pairoptions(varargin{:});
+
 %Variogram
-nugget=10;
-sill  =164;
-range =25763;
+nugget= getfieldvalue(options,'nugget',10);
+sill  = getfieldvalue(options,'sill',164);
+range = getfieldvalue(options,'range',25763);
 
 %Kriging options
-mindata = 1;
-maxdata = 50;
-maxsearchradius = 50000;
+mindata = getfieldvalue(options,'mindata',1);
+maxdata = getfieldvalue(options,'maxdata',50);
+maxsearchradius = getfieldvalue(options,'searchrange',50000);
 
 %Some intermediaries (Convert to gslib's parameters);
Index: /issm/trunk/src/m/contrib/hack/resultstomatrix.m
===================================================================
--- /issm/trunk/src/m/contrib/hack/resultstomatrix.m	(revision 19105)
+++ /issm/trunk/src/m/contrib/hack/resultstomatrix.m	(revision 19105)
@@ -0,0 +1,64 @@
+function matrix=resultstomatrix(md,resultname,field,varargin)
+%RESULTSTOMATRIX - go grab in the model results structure the vector results for each time step (which is not empty), 
+%                  and line them up in a matrix.  If time vector is provided, resample.
+%
+%   Usage:
+%      matrix=resultstomatrix(model,solutioname,fieldname)
+%
+%   Available options:
+%      - 'time'     : vector providing new time tags used to resample time
+%
+%   Example:
+%      vel=resultstomatrix(md,'TransientSolution','Vel');
+%      vel=resultstomatrix(md,'TransientSolution','Vel','time',2008:1/12:2014);
+%
+%   See also MODEL  resample
+
+
+	options=pairoptions(varargin{:});
+
+	results=md.results.(resultname);
+
+	%first, figure out the size: 
+	count=0;
+	nods=0;
+	for i=1:length(results),
+		if ~isempty(results(i).(field)),
+			count=count+1;
+			nods=size(results(i).(field),1);
+		end
+	end
+
+	if ~count, 
+		error(['could not find any result ' field ' in ' resultname]);
+	end
+
+	%initialize: 
+	matrix=zeros(nods+1,count);
+
+	%fill it up: 
+	count=0;
+	for i=1:length(results),
+		if ~isempty(results(i).(field)),
+			count=count+1;
+			matrix(1:end-1,count)=results(i).(field);
+			matrix(end,count)=results(i).time/md.constants.yts;
+		end
+	end
+
+	newtime=getfieldvalue(options,'time',[]);
+	if ~isempty(newtime),
+		newmatrix=zeros(nods+1,length(newtime));
+		newmatrix(end,:)=newtime;
+		%we are asked to reinterpolate to this new time: 
+
+		for i=1:nods,
+			warning off;
+			ts=timeseries(matrix(i,:), matrix(end,:));
+			ts=resample(ts,newtime);
+			warning on;
+			newmatrix(i,:)=ts.Data;
+		end
+
+		matrix=newmatrix;
+	end
Index: /issm/trunk/src/m/contrib/netCDF/ClassTry.py
===================================================================
--- /issm/trunk/src/m/contrib/netCDF/ClassTry.py	(revision 19105)
+++ /issm/trunk/src/m/contrib/netCDF/ClassTry.py	(revision 19105)
@@ -0,0 +1,122 @@
+#module imports {{{
+from netCDF4 import Dataset
+import time
+import collections
+from os import path, remove
+#}}}
+
+				
+class truc(object):
+	#properties
+	def __init__(self,*filename):#{{{
+
+		def netCDFread(filename):
+			def walktree(data):
+				keys = data.groups.keys()
+				yield keys
+				for key in keys:
+					for children in walktree(data.groups[str(key)]):
+						yield children
+
+			if path.exists(filename):
+				print ('Opening {} for reading '.format(filename))
+				NCData=Dataset(filename, 'r')
+				class_dict={}
+				
+				for children in walktree(NCData):
+					for child in children:
+						class_dict[str(child)]=str(getattr(NCData.groups[str(child)],'classtype'))
+
+				return class_dict
+
+		if filename:		
+			classtype=netCDFread(filename[0])
+		else:
+			classtype=self.default_prop()
+			
+		module=map(__import__,dict.values(classtype))
+
+		for i,mod in enumerate(dict.keys(classtype)):
+			self.__dict__[mod] = getattr(module[i],str(classtype[str(mod)]))()
+			
+		#}}}
+	def default_prop(self):    # {{{
+		# ordered list of properties since vars(self) is random
+		return {'mesh':'mesh2d',\
+		        'mask':'mask',\
+		        'geometry':'geometry',\
+		        'constants':'constants',\
+		        'surfaceforcings':'SMB',\
+		        'basalforcings':'basalforcings',\
+		        'materials':'matice',\
+		        'damage':'damage',\
+		        'friction':'friction',\
+		        'flowequation':'flowequation',\
+		        'timestepping':'timestepping',\
+		        'initialization':'initialization',\
+		        'rifts':'rifts',\
+		        'debug':'debug',\
+		        'verbose':'verbose',\
+		        'settings':'settings',\
+		        'toolkits':'toolkits',\
+		        'cluster':'generic',\
+		        'balancethickness':'balancethickness',\
+		        'stressbalance':'stressbalance',\
+		        'groundingline':'groundingline',\
+		        'hydrology':'hydrologyshreve',\
+		        'masstransport':'masstransport',\
+		        'thermal':'thermal',\
+		        'steadystate':'steadystate',\
+		        'transient':'transient',\
+		        'calving':'calving',\
+						'gia':'gia',\
+		        'autodiff':'autodiff',\
+		        'flaim':'flaim',\
+		        'inversion':'inversion',\
+		        'qmu':'qmu',\
+		        'outputdefinition':'outputdefinition',\
+		        'results':'results',\
+		        'radaroverlay':'radaroverlay',\
+		        'miscellaneous':'miscellaneous',\
+		        'private':'private'}
+	# }}}
+		
+	def __repr__(obj): #{{{
+		#print "Here %s the number: %d" % ("is", 37)
+		string="%19s: %-22s -- %s" % ("mesh","[%s,%s]" % ("1x1",obj.mesh.__class__.__name__),"mesh properties")
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("mask","[%s,%s]" % ("1x1",obj.mask.__class__.__name__),"defines grounded and floating elements"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("geometry","[%s,%s]" % ("1x1",obj.geometry.__class__.__name__),"surface elevation, bedrock topography, ice thickness,..."))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("constants","[%s,%s]" % ("1x1",obj.constants.__class__.__name__),"physical constants"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("surfaceforcings","[%s,%s]" % ("1x1",obj.surfaceforcings.__class__.__name__),"surface forcings"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("basalforcings","[%s,%s]" % ("1x1",obj.basalforcings.__class__.__name__),"bed forcings"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("materials","[%s,%s]" % ("1x1",obj.materials.__class__.__name__),"material properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("damage","[%s,%s]" % ("1x1",obj.damage.__class__.__name__),"damage propagation laws"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("friction","[%s,%s]" % ("1x1",obj.friction.__class__.__name__),"basal friction/drag properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flowequation","[%s,%s]" % ("1x1",obj.flowequation.__class__.__name__),"flow equations"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("timestepping","[%s,%s]" % ("1x1",obj.timestepping.__class__.__name__),"time stepping for transient models"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("initialization","[%s,%s]" % ("1x1",obj.initialization.__class__.__name__),"initial guess/state"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("rifts","[%s,%s]" % ("1x1",obj.rifts.__class__.__name__),"rifts properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("debug","[%s,%s]" % ("1x1",obj.debug.__class__.__name__),"debugging tools (valgrind, gprof)"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("verbose","[%s,%s]" % ("1x1",obj.verbose.__class__.__name__),"verbosity level in solve"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("settings","[%s,%s]" % ("1x1",obj.settings.__class__.__name__),"settings properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("toolkits","[%s,%s]" % ("1x1",obj.toolkits.__class__.__name__),"PETSc options for each solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("cluster","[%s,%s]" % ("1x1",obj.cluster.__class__.__name__),"cluster parameters (number of cpus...)"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("balancethickness","[%s,%s]" % ("1x1",obj.balancethickness.__class__.__name__),"parameters for balancethickness solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("stressbalance","[%s,%s]" % ("1x1",obj.stressbalance.__class__.__name__),"parameters for stressbalance solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("groundingline","[%s,%s]" % ("1x1",obj.groundingline.__class__.__name__),"parameters for groundingline solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("hydrology","[%s,%s]" % ("1x1",obj.hydrology.__class__.__name__),"parameters for hydrology solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("masstransport","[%s,%s]" % ("1x1",obj.masstransport.__class__.__name__),"parameters for masstransport solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("thermal","[%s,%s]" % ("1x1",obj.thermal.__class__.__name__),"parameters for thermal solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("steadystate","[%s,%s]" % ("1x1",obj.steadystate.__class__.__name__),"parameters for steadystate solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("transient","[%s,%s]" % ("1x1",obj.transient.__class__.__name__),"parameters for transient solution"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("calving","[%s,%s]" % ("1x1",obj.calving.__class__.__name__),"parameters for calving"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("autodiff","[%s,%s]" % ("1x1",obj.autodiff.__class__.__name__),"automatic differentiation parameters"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flaim","[%s,%s]" % ("1x1",obj.flaim.__class__.__name__),"flaim parameters"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("inversion","[%s,%s]" % ("1x1",obj.inversion.__class__.__name__),"parameters for inverse methods"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("qmu","[%s,%s]" % ("1x1",obj.qmu.__class__.__name__),"dakota properties"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("outputdefinition","[%s,%s]" % ("1x1",obj.outputdefinition.__class__.__name__),"output definition"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("results","[%s,%s]" % ("1x1",obj.results.__class__.__name__),"model results"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("radaroverlay","[%s,%s]" % ("1x1",obj.radaroverlay.__class__.__name__),"radar image for plot overlay"))
+		string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("miscellaneous","[%s,%s]" % ("1x1",obj.miscellaneous.__class__.__name__),"miscellaneous fields"))
+		return string
+	# }}}
Index: /issm/trunk/src/m/contrib/netCDF/export_netCDF.m
===================================================================
--- /issm/trunk/src/m/contrib/netCDF/export_netCDF.m	(revision 19105)
+++ /issm/trunk/src/m/contrib/netCDF/export_netCDF.m	(revision 19105)
@@ -0,0 +1,247 @@
+function export_netCDF(md,filename)	
+	
+%Now going on Real treatment
+	if exist(filename),
+		disp(sprintf('File %s allready exist', filename));
+		prompt = 'Give a new name or "delete" to replace: ';
+		newname = input(prompt,'s');
+		if strcmp(newname,'delete')
+			delete(filename)
+		else
+			disp(sprintf('New file name is %s ', newname));
+			filename=newname
+	  end
+  end
+	%open file and write description
+	mode = netcdf.getConstant('NC_NETCDF4');
+	mode = bitor(mode,netcdf.getConstant('NC_NOCLOBBER'));%NOCLOBBER to avoid overwrite
+	ncid = netcdf.create(filename,mode);
+	netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Title',['Results for run ' md.miscellaneous.name]);
+	netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'Date',['Created ' datestr(now)]);
+	
+	%gather geometry and timestepping as dimensions
+	Duration=md.timestepping.final_time-md.timestepping.start_time;
+	if Duration>0 && md.timestepping.time_step*md.settings.output_frequency>0,
+		StepNum=Duration/(md.timestepping.time_step*md.settings.output_frequency);
+	else
+		StepNum=1;
+  end							
+ 
+	%define netcdf dimensions
+	DimSize(1).index=netcdf.defDim(ncid,'Dimension1',md.mesh.numberofelements);
+	DimSize(2).index=netcdf.defDim(ncid,'Dimension2',md.mesh.numberofvertices);
+	DimSize(3).index=netcdf.defDim(ncid,'Dimension3',size(md.mesh.elements,2));
+	DimSize(4).index=netcdf.defDim(ncid,'Dimension4',StepNum);
+	DimSize(5).index=netcdf.defDim(ncid,'Dimension5',40);
+	DimSize(6).index=netcdf.defDim(ncid,'Dimension6',2);
+	
+	for i=1:length(DimSize),
+		[DimSize(i).name,DimSize(i).value]=netcdf.inqDim(ncid,DimSize(i).index);
+		DimValue(i)=DimSize(i).value;% putting vallues in an array for
+                                 % further use
+  end
+ 
+	%Needs a first turn arround for var def
+ 
+	%get all model classes and create respective groups
+	groups=fieldnames(md);
+	for i=1:length(groups),
+		disp(sprintf('group name in tree %s ',groups{i}));
+		groupID=netcdf.defGrp(ncid,groups{i});
+		%In each group gather the fields of the class
+		groupfields=fields(md.(groups{i}));
+		%Special treatment for the results
+		if strcmp(groups(i),'results'),
+			for j=1:length(groupfields)%looping on the differents solutions
+				netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype','results');
+				subgroupID=netcdf.defGrp(groupID,groupfields{j});
+				netcdf.putAtt(subgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',groupfields{j});
+				%disp(sprintf('=====Field name in tree %s ',groupfields{j}));
+				if length(md.results.(groupfields{j}))>1,
+					%the solution have several timestep get last timesteps and output frequency
+					last_step = length(md.results.(groupfields{j}));
+					%grab first time step
+					subfields=fields(md.results.(groupfields{j})(1));
+					for k=1:length(subfields),
+						if ~strcmp(subfields(k),'errlog') && ~strcmp(subfields(k),'outlog') && ~strcmp(subfields(k),'SolutionType'),
+							%disp(sprintf('==========SubField name in tree %s ',subfields{k}));
+							Var=md.results.(groupfields{j})(1).(subfields{k});
+							[DimSize,DimValue]=DefCreateVar(ncid,Var,subgroupID,subfields{k},DimSize,DimValue,true,last_step,md,groupfields{j});
+			      end
+		      end
+				elseif length(md.results.(groupfields{j}))==1,
+					%only one timestep
+					subfields=fields(md.results.(groupfields{j}));
+					for k=1:length(subfields),
+						%disp(sprintf('==========SubField name in tree %s ',subfields{k}));
+						if ~strcmp(subfields(k),'errlog') && ~strcmp(subfields(k),'outlog') && ~strcmp(subfields(k),'SolutionType'),
+							Var=md.results.(groupfields{1})(1).(subfields{k});
+							[DimSize,DimValue]=DefCreateVar(ncid,Var,groupID,subfields{k},DimSize,DimValue,false);
+			      end
+		      end
+				else
+					print 'Result format not suported'
+		    end
+	    end
+		else
+			for j=1:length(groupfields),
+				disp(sprintf('=====Field name in tree %s ',groupfields{j}));
+				netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype',class(md.(groups{i})));
+				Var=md.(groups{i}).(groupfields{j});
+				[DimSize,DimValue]=DefCreateVar(ncid,Var,groupID,groupfields{j},DimSize,DimValue,false);
+	    end
+	  end	
+  end
+	netcdf.close(ncid);
+end
+
+function [DimSize,DimValue]=DefCreateVar(ncid,Var,groupID,field,DimSize,DimValue,istime,last,md,midfield)
+	varclass=class(Var);
+	varsize=size(Var);
+	varlength=length(Var);
+	if isa(Var,'logical'),
+		if Var,
+			LogicString='True';
+		else,
+			LogicString='False';
+  	end
+		netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),field,LogicString);
+	elseif isa(Var,'char'),
+		netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),field,Var);
+	elseif isa(Var,'double'), %dealing with arrays
+		[dims,DimSize,DimValue]=GetDims(ncid,Var,groupID,field,DimSize,DimValue,istime);
+ 		varid = netcdf.defVar(groupID,field,'NC_DOUBLE',dims);
+		if istime,
+			VarTab=Var;
+			for i=2:last,
+				TimeVar=md.results.(midfield)(i).(field);
+				VarTab=[VarTab TimeVar];
+	    end
+			netcdf.putVar(groupID,varid,VarTab);
+		else
+			if length(Var)==0,
+				netcdf.putVar(groupID,varid,NaN);
+			else
+				netcdf.putVar(groupID,varid,Var);
+	    end
+	  end
+	elseif isa(Var,'cell'),
+		[dims,DimSize,DimValue]=GetDims(ncid,Var,groupID,field,DimSize,DimValue,istime);
+		%dirty hack to be able to pass strings
+		varid = netcdf.defVar(groupID,field,'NC_CHAR',dims);
+		if length(Var)==0,
+			netcdf.putVar(groupID,varid,0,9,'emptycell')
+		else
+			for i=1:length(Var),
+				startpoint=zeros(size(Var));
+				startpoint(:,i)=i-1;
+				if length(Var)>1,
+					endpoint=[min(length(Var{i}),40) 1];
+				else
+					endpoint=min(length(Var{i}),40);
+		    end
+				if length(Var{i})>40,
+					netcdf.putVar(groupID,varid,startpoint,endpoint,Var{i}(1:40))
+					disp(sprintf('some variable have been truncated'));
+			  else
+					netcdf.putVar(groupID,varid,startpoint,endpoint,Var{i})
+	      end
+	    end
+	  end
+	elseif isa(Var,'struct'),
+		%Start by getting the structure fields and size
+		locfields=fields(Var);
+		[dims,DimSize,DimValue]=GetDims(ncid,Var,groupID,locfields,DimSize,DimValue,istime);
+		varid = netcdf.defVar(groupID,field,'NC_CHAR',dims);
+		if length(locfields)==0,
+			netcdf.putVar(groupID,varid,[0,0],[11,1],'emptystruct')
+		else
+			for i=1:length(locfields),
+				for j=1:2,
+					if j==1,
+						startpoint=[0,0,i-1];
+						CharVar=locfields{i};
+					else
+						startpoint=[0,1,i-1];
+						if isa(Var.(locfields{i}),'char'),
+							CharVar=Var.(locfields{i});
+						else
+							CharVar=num2str(Var.(locfields{i}));
+			      end
+		      end
+					endpoint=[min(length(CharVar),40),1,1];
+					if length(CharVar)>40,
+						netcdf.putVar(groupID,varid,startpoint,endpoint,CharVar(1:40))
+						disp(sprintf('some variable have been truncated'));
+					else
+						netcdf.putVar(groupID,varid,startpoint,endpoint,CharVar)
+		      end
+		    end
+	    end
+		end
+	else
+		disp(sprintf('no support for class %s of field %s',varclass,field));
+  end
+	return
+end
+
+function [dims,DimSize,DimValue]=GetDims(ncid,Var,groupID,field,DimSize,DimValue,istime)
+	dims=[];
+	%specific treatment for structures
+	if isa(Var,'struct')
+		varsize=size(field); %we pass here the fields of the current structure
+		MatOrVec=varsize>1; %checking if we have a matrix (1 1) or vector (1 0)
+		for i=1:sum(MatOrVec), %loop on the number of (non 1) dimensions
+			currentdim=varsize(i);
+			dimexist=DimValue==currentdim;
+			if sum(dimexist)==0, %dimension is new to us, need to create it
+				dimname=strcat('Dimension',int2str(length(DimValue)+1));
+				dimindex=length(DimSize)+1;
+				DimSize(dimindex).index=netcdf.defDim(ncid,dimname,currentdim);
+				[DimSize(dimindex).name,DimSize(dimindex).value]=netcdf.inqDim(ncid,DimSize(dimindex).index);
+				dims(i)=DimSize(dimindex).index;
+				DimValue(dimindex)=currentdim;
+			else
+				dimindex=find(dimexist);
+				if DimSize(dimindex).value~=currentdim,
+					error('Indexation problem with the dimension structure')
+		    end
+	    end
+			dims(i)=DimSize(dimindex).index;
+	  end
+		dims=[DimSize(6).index dims];
+	else
+		%with a cell array need to grab the transposed size to work
+		if isa(Var,'cell'),
+			varsize=size(Var');
+		else
+			varsize=size(Var);
+    end
+		MatOrVec=varsize>1; %checking if we have a matrix (1 1) or vector (1 0)
+		for i=1:sum(MatOrVec), %loop on the number of (non 1) dimensions
+			currentdim=varsize(i);
+			dimexist=DimValue==currentdim;
+			if sum(dimexist)==0, %dimension is new to us, need to create it
+				dimname=strcat('Dimension',int2str(length(DimValue)+1));
+				dimindex=length(DimSize)+1;
+				DimSize(dimindex).index=netcdf.defDim(ncid,dimname,currentdim);
+				[DimSize(dimindex).name,DimSize(dimindex).value]=netcdf.inqDim(ncid,DimSize(dimindex).index);
+				dims(i)=DimSize(dimindex).index;
+				DimValue(dimindex)=currentdim;
+			else
+				dimindex=find(dimexist);
+				if DimSize(dimindex).value~=currentdim,
+					error('Indexation problem with the dimension structure')
+		    end
+	    end
+			dims(i)=DimSize(dimindex).index;
+    end
+  end
+	if istime,
+		dims=[dims DimSize(4).index];%adding the time dimension if necessary
+  end
+	%if we have a cell variable we need to add a stringlength dimension 
+	if isa(Var,'cell') || isa(Var,'struct'),
+		dims=[DimSize(5).index dims]
+  end
+end
Index: /issm/trunk/src/m/contrib/netCDF/export_netCDF.py
===================================================================
--- /issm/trunk/src/m/contrib/netCDF/export_netCDF.py	(revision 19105)
+++ /issm/trunk/src/m/contrib/netCDF/export_netCDF.py	(revision 19105)
@@ -0,0 +1,194 @@
+from netCDF4 import Dataset
+import numpy
+import time
+import collections
+from mesh2d import *
+from mesh3dprisms import *
+from results import *
+from os import path, remove
+
+def export_netCDF(md,filename):
+	#Now going on Real treatment
+	if path.exists(filename):
+		print ('File {} allready exist'.format(filename))
+		newname=raw_input('Give a new name or "delete" to replace: ')
+		if newname=='delete':
+			remove(filename)
+		else:
+			print ('New file name is {}'.format(newname))
+			filename=newname
+			
+	NCData=Dataset(filename, 'w', format='NETCDF4')
+	NCData.description = 'Results for run' + md.miscellaneous.name
+	NCData.history = 'Created ' + time.ctime(time.time())
+
+	#gather geometry and timestepping as dimensions
+	Duration=md.timestepping.final_time-md.timestepping.start_time
+	if Duration>0 and md.timestepping.time_step*md.settings.output_frequency>0:
+		StepNum=Duration/(md.timestepping.time_step*md.settings.output_frequency)
+	else:
+		StepNum=1
+		
+	Dimension1=NCData.createDimension('Dimension1',md.mesh.numberofelements)
+	Dimension2=NCData.createDimension('Dimension2',md.mesh.numberofvertices)
+	Dimension3=NCData.createDimension('Dimension3',numpy.shape(md.mesh.elements)[1])
+	Dimension4=NCData.createDimension('Dimension4',StepNum)
+	Dimension5=NCData.createDimension('Dimension5',2) 
+
+	DimDict = {len(Dimension1):'Dimension1',
+						 len(Dimension2):'Dimension2',
+						 len(Dimension3):'Dimension3',
+						 len(Dimension4):'Dimension4',
+						 len(Dimension5):'Dimension5'}
+
+	#get all model classes and create respective groups
+	groups=dict.keys(md.__dict__)
+	for group in groups:
+		NCgroup=NCData.createGroup(str(group))
+		#In each group gather the fields of the class
+		fields=dict.keys(md.__dict__[group].__dict__)
+
+		#Special treatment for the results
+		if str(group)=='results':
+			for supfield in fields:#looping on the different solutions
+				NCgroup.__setattr__('classtype', "results")
+				Subgroup=NCgroup.createGroup(str(supfield))
+				Subgroup.__setattr__('classtype',str(supfield))
+				if type(md.results.__dict__[supfield])==list:#the solution have several timestep
+					#get last timesteps and output frequency
+					last_step = numpy.size(md.results.__dict__[supfield])
+					step_freq = md.settings.output_frequency
+					#grab first time step
+					subfields=dict.keys(md.results.__dict__[supfield].__getitem__(0).__dict__)
+					for field in subfields:
+						if str(field)!='errlog' and str(field)!='outlog' and str(field)!='SolutionType':
+							Var=md.results.__dict__[supfield].__getitem__(0).__dict__[field]
+							DimDict=CreateVar(NCData,Var,field,Subgroup,DimDict,True,last_step,step_freq,md,supfield)
+					
+				elif type(md.results.__dict__[supfield])==results:#only one timestep
+					subfields=dict.keys(md.results.__dict__[supfield].__dict__)
+					for field in subfields:
+						if str(field)!='errlog' and str(field)!='outlog' and str(field)!='SolutionType':
+							print 'Treating '+str(group)+'.'+str(supfield)+'.'+str(field)
+							Var=md.results.__dict__[supfield].__dict__[field]
+							DimDict=CreateVar(NCData,Var,field,NCgroup,DimDict,False)
+				else:
+					print 'Result format not suported'
+		else:
+			
+			for field in fields:
+				print 'Treating ' +str(group)+'.'+str(field)
+				NCgroup.__setattr__('classtype', md.__dict__[group].__class__.__name__)
+				Var=md.__dict__[group].__dict__[field]
+				DimDict=CreateVar(NCData,Var,field,NCgroup,DimDict,False)
+	NCData.close()
+
+#============================================================================
+#Define the variables
+def CreateVar(NCData,var,field,Group,DimDict,istime,*step_args):
+	#grab type
+	try:
+		val_type=str(var.dtype)
+	except AttributeError:
+		val_type=type(var)
+		#grab dimension
+	try:
+		val_shape=dict.keys(var)
+	except TypeError:
+		val_shape=numpy.shape(var)
+
+
+	TypeDict = {float:'f8',
+							'float64':'f8',
+							int:'i8',
+							'int64':'i8'}
+		
+	val_dim=numpy.shape(val_shape)[0]
+	#Now define and fill up variable
+	#treating scalar string or bool as atribute
+	if val_type==str or val_type==bool:
+		Group.__setattr__(str(field), str(var))
+
+	#treating list as string table
+	#matlab does not recognise strings so we have to settle down with char arrays
+	elif val_type==list:
+		dimensions,DimDict=GetDim(NCData,var,val_shape,DimDict,val_dim,istime)
+		ncvar = Group.createVariable(str(field),str,dimensions,zlib=True)
+		for elt in range(0,val_dim):
+			try:
+				ncvar[elt] = var[elt]
+			except IndexError:
+				ncvar[0]= " "
+				#treating bool tables as string tables
+	elif val_type=='bool':
+		dimensions,DimDict=GetDim(NCData,var,val_shape,DimDict,val_dim,istime)
+		ncvar = Group.createVariable(str(field),str,dimensions,zlib=True)
+		for elt in range(0,val_shape[0]):
+			ncvar[elt] = str(var[elt])
+			#treating dictionaries as string tables of dim 2
+	elif val_type==collections.OrderedDict:
+		dimensions,DimDict=GetDim(NCData,var,val_shape,DimDict,val_dim,istime)
+		ncvar = Group.createVariable(str(field),str,dimensions,zlib=True)
+		for elt in range(0,val_dim):
+			ncvar[elt,0]=dict.keys(var)[elt]
+			ncvar[elt,1]=str(dict.values(var)[elt]) #converting to str to avoid potential problems
+			#Now dealing with numeric variables
+	else:
+		dimensions,DimDict=GetDim(NCData,var,val_shape,DimDict,val_dim,istime)
+		ncvar = Group.createVariable(str(field),TypeDict[val_type],dimensions,zlib=True)
+		
+		if istime:
+			last=step_args[0]
+			freq=step_args[1]
+			md=step_args[2]
+			supfield=step_args[3]
+			vartab=var
+			for time in range(freq-1,last,freq):
+				if time!=0:
+					timevar=md.results.__dict__[supfield].__getitem__(time).__dict__[field]
+					print 'Treating results.'+str(supfield)+'.'+str(field)+' for time '+str(time)
+					vartab=numpy.column_stack((vartab,timevar))
+			print numpy.shape(vartab)
+			try:
+				ncvar[:,:]=vartab[:,:]
+			except ValueError:
+				ncvar[:]=vartab.T[:]
+		else:
+			try:
+				nan_val=numpy.isnan(var)
+				if nan_val.all():
+					ncvar [:] = 'NaN'
+				else:
+					ncvar[:] = var
+			except TypeError: #type does not accept nan, get vallue of the variable
+				ncvar[:] = var
+	return DimDict
+
+#============================================================================
+#retriev the dimension tuple from a dictionnary
+def GetDim(NCData,var,shape,DimDict,i,istime):
+	output=[]
+	for dim in range(0,i): #loop on the dimensions
+		if type(shape[0])==int: 
+			try:
+				output=output+[str(DimDict[shape[dim]])] #test if the dimension allready exist
+			except KeyError: #if not create it
+				if (shape[dim])>1:
+					index=len(DimDict)+1
+					NewDim=NCData.createDimension('Dimension'+str(index),(shape[dim]))
+					DimDict[len(NewDim)]='Dimension'+str(index)
+					output=output+[str(DimDict[shape[dim]])]
+					print 'Defining dimension ' +'Dimension'+str(index)
+		elif type(shape[0])==str:#dealling with a dictionnary
+			try:
+				output=[str(DimDict[numpy.shape(shape)[0]])]+['DictDim']
+			except KeyError:
+				index=len(DimDict)+1
+				NewDim=NCData.createDimension('Dimension'+str(index),numpy.shape(shape)[0])
+				DimDict[len(NewDim)]='Dimension'+str(index)
+				output=[str(DimDict[numpy.shape(dict.keys(var))[0]])]+['Dimension5']
+				print 'Defining dimension ' +'Dimension'+str(index)
+			break
+	if istime:
+		output=output+['Dimension4']
+	return tuple(output), DimDict
Index: /issm/trunk/src/m/contrib/netCDF/read_netCDF.m
===================================================================
--- /issm/trunk/src/m/contrib/netCDF/read_netCDF.m	(revision 19105)
+++ /issm/trunk/src/m/contrib/netCDF/read_netCDF.m	(revision 19105)
@@ -0,0 +1,134 @@
+function self=read_netCDF(filename)
+
+% Different types in the netcdf standard are:
+%   2 for char
+%   4 for integer
+%   6 for doubles	
+	
+	ncid=netcdf.open(filename,'NC_NOWRITE');
+	groupIDs=netcdf.inqGrps(ncid);%retrieve group IDs
+	self=model;
+	%loop on groups
+	for i=1:length(groupIDs)
+		whichclass = netcdf.getAtt(groupIDs(i),netcdf.getConstant('NC_GLOBAL'),'classtype');
+		groupName = netcdf.inqGrpName(groupIDs(i));		
+		%results needs a special treatment as it is a structure
+		if strcmp(whichclass,'results'),
+			subgroupIDs=netcdf.inqGrps(groupIDs(i));%retrieve group IDs
+			%define the model structure
+			self=setfield(self,groupName,struct);
+			for j=1:length(subgroupIDs)
+				subclass = netcdf.getAtt(subgroupIDs(j),netcdf.getConstant('NC_GLOBAL'),'classtype');
+				self.results=setfield(self.results,subclass,struct);
+				[ndims nvar natts]=netcdf.inq(groupIDs(j));
+				varIDs=netcdf.inqVarIDs(subgroupIDs(j));
+				%first loop on group atributes
+				for k=1:natts,
+					attname = netcdf.inqAttName(subgroupIDs(j),netcdf.getConstant('NC_GLOBAL'),k-1);
+					[xtype,attlen] = netcdf.inqAtt(subgroupIDs(j),netcdf.getConstant('NC_GLOBAL'),attname);
+					%disp(sprintf('In %s, Treating attribute %s of type %i',subclass,attname,xtype));
+					%classtype have done is job, no need to keep it any more
+					if ~strcmp(attname,'classtype'),
+						attval=netcdf.getAtt(subgroupIDs(i),netcdf.getConstant('NC_GLOBAL'),attname);
+						if strcmp(attval,'False'),
+							self.(groupName).(subclass).(attname)=false;
+						elseif strcmp(attval,'True')
+							self.(groupName).(subclass).(attname)=true;
+						else
+							self.(groupName).(subclass).(attname)=attval;
+			      end
+		      end
+		    end
+				%now loop on variable in group
+				for k=1:length(varIDs),
+					[varname, xtype, varDimIDs, varAtts] =netcdf.inqVar(subgroupIDs(j),varIDs(k));
+					%disp(sprintf('In %s, Treating variable %s of type %i',whichclass,varname,xtype));
+					%time dimension seems to be last in our construction
+					for l=1:length(varDimIDs),
+						[dimname, dimlen] = netcdf.inqDim(ncid,varDimIDs(l));
+						count(l)=[dimlen];
+		      end
+					startpoint=zeros(size(varDimIDs));
+					timestep=count(end);
+					count(end)=1;
+					for l=1:timestep,
+						data=netcdf.getVar(subgroupIDs(j),varIDs(k),startpoint,count);
+						self.(groupName).(subclass)(l).(varname)=data;
+						startpoint(end)=startpoint(end)+1;
+						self.(groupName).(subclass)(l).('errlog')='';
+						self.(groupName).(subclass)(l).('outlog')='';
+						self.(groupName).(subclass)(l).('SolutionType')=subclass;
+		     end
+				 clear count
+		    end
+	    end
+			%toolkits too require a specific treatment
+		elseif strcmp(whichclass,'toolkits'),
+			%just one variable here
+			varID=netcdf.inqVarIDs(groupIDs(i));
+			[varname, xtype, varDimIDs, varAtts] =netcdf.inqVar(groupIDs(i),varID);
+			%disp(sprintf('In %s, Treating variable %s of type %i',whichclass,varname,xtype));
+			[dimname,numoffields] = netcdf.inqDim(ncid,varDimIDs(end));
+			self.(groupName)=eval(whichclass);
+			for j=1:numoffields,
+				varval=netcdf.getVar(groupIDs(i),varID,[0,1,j-1],[40,1,1])';
+				fieldname=netcdf.getVar(groupIDs(i),varID,[0,0,j-1],[40,1,1])';
+				varval=cellstr(varval);
+				fieldname=cellstr(fieldname);
+				[val, status]=str2num(varval{1});
+				if strcmp(varval{1},'false') |strcmp(varval{1},'true')  ,
+					status=0;
+		    end
+				if status==1,
+					self.(groupName).(varname).(fieldname{1})=val;
+				else
+					self.(groupName).(varname).(fieldname{1})=varval{1};
+			 end
+	   end
+			%Now for the other fields
+
+		else,
+			%define the model structure
+			self.(groupName)=eval(whichclass);
+			varIDs=netcdf.inqVarIDs(groupIDs(i));
+			[ndims nvar natts]=netcdf.inq(groupIDs(i));
+			%first loop on group atributes
+			for j=1:natts,
+				attname = netcdf.inqAttName(groupIDs(i),netcdf.getConstant('NC_GLOBAL'),j-1);
+				[xtype,attlen] = netcdf.inqAtt(groupIDs(i),netcdf.getConstant('NC_GLOBAL'),attname);
+				%disp(sprintf('In %s, Treating attribute %s of type %i',whichclass,attname,xtype));
+				%classtype have done is job, no need to keep it any more
+				if ~strcmp(attname,'classtype'),
+					attval=netcdf.getAtt(groupIDs(i),netcdf.getConstant('NC_GLOBAL'),attname);
+					if strcmp(attval,'False'),
+						self.(groupName).(attname)=false;
+					elseif strcmp(attval,'True')
+						self.(groupName).(attname)=true;
+					else
+					self.(groupName).(attname)=attval;
+		    end
+		  end
+	  end
+			%now loop on variable in group
+			for j=1:length(varIDs),
+				[varname, xtype, varDimIDs, varAtts] =netcdf.inqVar(groupIDs(i),varIDs(j));
+				%disp(sprintf('In %s, Treating variable %s of type %i',whichclass,varname,xtype));			
+				%if the value is a single string, we need to transpose it (cross check with python file is necessary)
+				if xtype==2
+					varval=netcdf.getVar(groupIDs(i),varIDs(j))';
+					varval=cellstr(varval)';
+					if strcmp(varval{1},'emptystruct'),
+						self.(groupName).(varname)=struct;
+					elseif strcmp(varval{1},'emptycell'),
+						self.(groupName).(varname)=cell(0,0);
+					else
+						self.(groupName).(varname)=varval;
+					end
+				else
+					self.(groupName).(varname)=netcdf.getVar(groupIDs(i),varIDs(j));
+		    end
+		  end
+	  end
+  end
+	netcdf.close(ncid)
+end
Index: /issm/trunk/src/m/contrib/paraview/enveloppeVTK.m
===================================================================
--- /issm/trunk/src/m/contrib/paraview/enveloppeVTK.m	(revision 19105)
+++ /issm/trunk/src/m/contrib/paraview/enveloppeVTK.m	(revision 19105)
@@ -0,0 +1,155 @@
+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);
+	[point_per_elt]=size(model.mesh.elements,2);
+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);
+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);
+  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
+			fieldnames=fields(sol_struct{j}(timestep));
+			num_of_fields=length(fieldnames);
+			
+			%check which field is a real result and print
+			for k=1:num_of_fields
+				if ((numel(sol_struct{j}(timestep).(fieldnames{k})))==tot_points);
+					%paraview does not like NaN, replacing
+					nanval=find(isnan(sol_struct{j}(timestep).(fieldnames{k})));
+					sol_struct{j}(timestep).(fieldnames{k})(nanval)=-9999;
+					%also checking for verry small value that mess up
+					smallval=(abs(sol_struct{j}(timestep).(fieldnames{k}))<1.0e-20);
+					sol_struct{j}(timestep).(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,sol_struct{j}(timestep).(fieldnames{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));
+	    end		
+		end 
+	end
+	fclose(fid);
+end
Index: /issm/trunk/src/m/contrib/paraview/exportVTK.m
===================================================================
--- /issm/trunk/src/m/contrib/paraview/exportVTK.m	(revision 19104)
+++ /issm/trunk/src/m/contrib/paraview/exportVTK.m	(revision 19105)
@@ -25,11 +25,14 @@
 if dimension(model.mesh)==2,
 	points=[model.mesh.x model.mesh.y zeros(model.mesh.numberofvertices,1)];
+	[num_of_points,dim]=size(points);
+	[num_of_elt]=size(model.mesh.elements,1);
+	[point_per_elt]=size(model.mesh.elements,2);
 else
 	points=[model.mesh.x model.mesh.y model.mesh.z];
+	[num_of_points,dim]=size(points);
+	[num_of_elt]=size(model.mesh.elements,1);
+	[point_per_elt]=size(model.mesh.elements,2);
 end
 
-[num_of_points,dim]=size(points);
-[num_of_elt]=size(model.mesh.elements,1);
-[point_per_elt]=size(model.mesh.elements,2);
 
 %Select the type of element function of the number of nodes per elements
@@ -65,5 +68,5 @@
 	timestep=step;
 
-	fid = fopen(strcat(path,filesep,name,filesep,name,'.vtk',int2str(timestep),'.vtk'),'w+');
+	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);
@@ -86,5 +89,5 @@
   end
 	s=cell2mat(horzcat(s,{'\n'}));
-	fprintf(fid,s,[(point_per_elt)*ones(num_of_elt,1) model.mesh.elements-1]');
+		fprintf(fid,s,[(point_per_elt)*ones(num_of_elt,1)	model.mesh.elements-1]');
 	
 	fprintf(fid,'CELL_TYPES %d\n',num_of_elt);
Index: /issm/trunk/src/m/contrib/paraview/exportVTK.py
===================================================================
--- /issm/trunk/src/m/contrib/paraview/exportVTK.py	(revision 19105)
+++ /issm/trunk/src/m/contrib/paraview/exportVTK.py	(revision 19105)
@@ -0,0 +1,163 @@
+import numpy
+import os
+import model
+import glob
+def exportVTK(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=raw_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__):
+		points=numpy.column_stack((model.mesh.x,model.mesh.y,model.mesh.z))
+		dim=3
+	else:
+		points=numpy.column_stack((model.mesh.x,model.mesh.y,numpy.zeros(numpy.shape(model.mesh.x))))
+		dim=2
+
+	num_of_points=numpy.size(model.mesh.x)
+	num_of_elt=numpy.shape(model.mesh.elements)[0]
+	point_per_elt=numpy.shape(model.mesh.elements)[1]
+		
+	#Select the type of element function of the number of nodes per elements
+	if point_per_elt==3:
+		celltype=5 #triangles
+	elif point_per_elt==6:
+		celltype=13 #wedges
+	else:
+		error('Your Element definition is not taken into account \n')
+
+	#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
+		out_freq=model.settings.output_frequency
+		#%building solutionstructure 
+		for solution in solnames:
+			#looking for multiple time steps
+			if (numpy.size(res_struct.__dict__[solution])>num_of_timesteps):
+				num_of_timesteps=numpy.size(res_struct.__dict__[solution])
+				num_of_timesteps=int(num_of_timesteps/out_freq)+1
+	else:
+		num_of_timesteps=1
+
+	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)
+		if(dim==3):
+			for point in points:
+				fid.write('%f %f %f \n'%(point[0], point[1], point[2]))
+		elif(dim==2):
+			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)))
+		
+		if point_per_elt==3:
+			for elt in range(0, num_of_elt):
+				fid.write('3 %d %d %d\n' %(model.mesh.elements[elt,0]-1,model.mesh.elements[elt,1]-1,model.mesh.elements[elt,2]-1))
+		elif point_per_elt==6:
+			for elt in range(0, num_of_elt):
+				fid.write('6 %d %d %d %d %d %d\n' %(model.mesh.elements[elt,0]-1,model.mesh.elements[elt,1]-1,model.mesh.elements[elt,2]-1,model.mesh.elements[elt,3]-1,model.mesh.elements[elt,4]-1,model.mesh.elements[elt,5]-1))
+		else:
+			print 'Number of nodes per element not supported'
+
+		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(numpy.size(res_struct.__dict__[sol])>timestep):
+					timestep = step
+				else:
+					timestep = numpy.size(res_struct.__dict__[sol])
+				
+				#getting the  fields in the solution
+				if(numpy.size(res_struct.__dict__[sol])>1):
+					fieldnames=dict.keys(res_struct.__dict__[sol].__getitem__(timestep*out_freq-1).__dict__)
+				else:
+					fieldnames=dict.keys(res_struct.__dict__[sol].__dict__)
+				#check which field is a real result and print
+				for field in fieldnames:
+					if(numpy.size(res_struct.__dict__[sol])>1):
+						fieldstruct=res_struct.__dict__[sol].__getitem__(timestep*out_freq-1).__dict__[field]
+					else:
+						fieldstruct=res_struct.__dict__[sol].__dict__[field]
+
+					if ((numpy.size(fieldstruct))==num_of_points):
+						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 numpy.isnan(fieldstruct[node]):
+								fid.write('%e\n' % -9999.9999)
+							#also checking for verry small value that mess up
+							elif (abs(fieldstruct[node])<1.0e-20):
+								fid.write('%e\n' % 0.0)
+							else:
+								fid.write('%e\n' % fieldstruct[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 ((numpy.size(other_struct.__dict__[field]))==num_of_points):
+					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 numpy.isnan(other_struct.__dict__[field][node]):
+							fid.write('%e\n' % -9999.9999)
+						#also checking for verry small value that mess up
+						elif (abs(other_struct.__dict__[field][node])<1.0e-20):
+							fid.write('%e\n' % 0.0)
+						else:
+							fid.write('%e\n' % other_struct.__dict__[field][node])
+	fid.close();
Index: /issm/trunk/src/m/coordsystems/ll2utm.m
===================================================================
--- /issm/trunk/src/m/coordsystems/ll2utm.m	(revision 19105)
+++ /issm/trunk/src/m/coordsystems/ll2utm.m	(revision 19105)
@@ -0,0 +1,226 @@
+function [x,y,f]=ll2utm(varargin)
+%LL2UTM Lat/Lon to UTM coordinates precise conversion.
+%	[X,Y]=LL2UTM2(LAT,LON) or LL2UTM([LAT,LON]) converts coordinates 
+%	LAT,LON (in degrees) to UTM X and Y (in meters). Default datum is WGS84.
+%
+%	LAT and LON can be scalars, vectors or matrix. Outputs X and Y will
+%	have the same size as inputs.
+%
+%	LL2UTM(...,DATUM) uses specific DATUM for conversion. DATUM can be one
+%	of the following char strings:
+%		'wgs84': World Geodetic System 1984 (default)
+%		'nad27': North American Datum 1927
+%		'clk66': Clarke 1866
+%		'nad83': North American Datum 1983
+%		'grs80': Geodetic Reference System 1980
+%		'int24': International 1924 / Hayford 1909
+%	or DATUM can be a 2-element vector [A,F] where A is semimajor axis (in
+%	meters)	and F is flattening of the user-defined ellipsoid.
+%
+%	LL2UTM(...,ZONE) forces the UTM ZONE (scalar integer) instead of
+%	automatic set.
+%
+%	[X,Y,ZONE]=LL2UTM(...) returns also the computed UTM ZONE (negative
+%	value for southern hemisphere points).
+%
+%
+%	XY=LL2UTM(...) or without any output argument returns a 2-column 
+%	matrix [X,Y].
+%
+%	Note:
+%		- LL2UTM does not perform cross-datum conversion.
+%		- precision is near a millimeter.
+%
+%
+%	Reference:
+%		I.G.N., Projection cartographique Mercator Transverse: Algorithmes,
+%		   Notes Techniques NT/G 76, janvier 1995.
+%
+%	Acknowledgments: Mathieu.
+%
+%
+%	Author: Francois Beauducel, <beauducel@ipgp.fr>
+%	Created: 2003-12-02
+%	Updated: 2014-08-24
+
+
+%	Copyright (c) 2001-2014, François Beauducel, covered by BSD License.
+%	All rights reserved.
+%
+%	Redistribution and use in source and binary forms, with or without 
+%	modification, are permitted provided that the following conditions are 
+%	met:
+%
+%	   * Redistributions of source code must retain the above copyright 
+%	     notice, this list of conditions and the following disclaimer.
+%	   * Redistributions in binary form must reproduce the above copyright 
+%	     notice, this list of conditions and the following disclaimer in 
+%	     the documentation and/or other materials provided with the distribution
+%	                           
+%	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
+%	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+%	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+%	ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+%	LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
+%	CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+%	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+%	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+%	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
+%	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+%	POSSIBILITY OF SUCH DAMAGE.
+
+% Available datums
+datums = [ ...
+	{ 'wgs84', 6378137.0, 298.257223563 };
+	{ 'nad83', 6378137.0, 298.257222101 };
+	{ 'grs80', 6378137.0, 298.257222101 };
+	{ 'nad27', 6378206.4, 294.978698214 };
+	{ 'int24', 6378388.0, 297.000000000 };
+	{ 'clk66', 6378206.4, 294.978698214 };
+];
+
+% constants
+D0 = 180/pi;	% conversion rad to deg
+K0 = 0.9996;	% UTM scale factor
+X0 = 500000;	% UTM false East (m)
+
+% defaults
+datum = 'wgs84';
+zone = [];
+
+if nargin < 1
+	error('Not enough input arguments.')
+end
+
+if isnumeric(varargin{1}) & size(varargin{1},2) == 2
+	lat = varargin{1}(:,1);
+	lon = varargin{1}(:,2);
+	v = 1;
+elseif nargin > 1 & isnumeric(varargin{2})
+	lat = varargin{1};
+	lon = varargin{2};
+	v = 2;
+else
+	error('Single input argument must be a 2-column matrix [LAT,LON].')
+end
+
+if all([numel(lat),numel(lon)] > 1) && any(size(lat) ~= size(lon))
+	error('LAT and LON must be the same size or scalars.')
+end
+
+for n = (v+1):nargin
+	% LL2UTM(...,DATUM)
+	if ischar(varargin{n}) | (isnumeric(varargin{n}) & numel(varargin{n})==2)
+		datum = varargin{n};
+	% LL2UTM(...,ZONE)
+	elseif isnumeric(varargin{n}) & isscalar(varargin{n})
+			zone = round(varargin{n});
+	else
+		error('Unknown argument #%d. See documentation.',n)
+	end
+end
+
+if ischar(datum)
+	% LL2UTM(...,DATUM) with DATUM as char
+	if ~any(strcmpi(datum,datums(:,1)))
+		error('Unkown DATUM name "%s"',datum);
+	end
+	k = find(strcmpi(datum,datums(:,1)));
+	A1 = datums{k,2};
+	F1 = datums{k,3};	
+else
+	% LL2UTM(...,DATUM) with DATUM as [A,F] user-defined
+	A1 = datum(1);
+	F1 = datum(2);
+end
+
+p1 = lat/D0;			% Phi = Latitude (rad)
+l1 = lon/D0;			% Lambda = Longitude (rad)
+
+% UTM zone automatic setting
+if isempty(zone)
+	F0 = round((l1*D0 + 183)/6);
+else
+	F0 = zone;
+end
+
+B1 = A1*(1 - 1/F1);
+E1 = sqrt((A1*A1 - B1*B1)/(A1*A1));
+P0 = 0/D0;
+L0 = (6*F0 - 183)/D0;		% UTM origin longitude (rad)
+Y0 = 1e7*(p1 < 0);		% UTM false northern (m)
+N = K0*A1;
+
+C = coef(E1,0);
+B = C(1)*P0 + C(2)*sin(2*P0) + C(3)*sin(4*P0) + C(4)*sin(6*P0) + C(5)*sin(8*P0);
+YS = Y0 - N*B;
+
+C = coef(E1,2);
+L = log(tan(pi/4 + p1/2).*(((1 - E1*sin(p1))./(1 + E1*sin(p1))).^(E1/2)));
+z = complex(atan(sinh(L)./cos(l1 - L0)),log(tan(pi/4 + asin(sin(l1 - L0)./cosh(L))/2)));
+Z = N.*C(1).*z + N.*(C(2)*sin(2*z) + C(3)*sin(4*z) + C(4)*sin(6*z) + C(5)*sin(8*z));
+xs = imag(Z) + X0;
+ys = real(Z) + YS;
+
+% outputs zone if needed: scalar value if unique, or vector/matrix of the
+% same size as x/y in case of crossed zones
+if nargout > 2
+	fu = unique(F0.*sign(lat));
+	if isscalar(fu)
+		f = fu;
+	else
+		f = F0;
+	end
+end
+
+if nargout < 2
+	x = [xs(:),ys(:)];
+else
+	x = xs;
+	y = ys;
+end
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function c = coef(e,m)
+%COEF Projection coefficients
+%	COEF(E,M) returns a vector of 5 coefficients from:
+%		E = first ellipsoid excentricity
+%		M = 0 for transverse mercator
+%		M = 1 for transverse mercator reverse coefficients
+%		M = 2 for merdian arc
+
+
+if nargin < 2
+	m = 0;
+end
+
+switch m
+	case 0
+	c0 = [-175/16384, 0,   -5/256, 0,  -3/64, 0, -1/4, 0, 1;
+           -105/4096, 0, -45/1024, 0,  -3/32, 0, -3/8, 0, 0;
+           525/16384, 0,  45/1024, 0, 15/256, 0,    0, 0, 0;
+          -175/12288, 0, -35/3072, 0,      0, 0,    0, 0, 0;
+          315/131072, 0,        0, 0,      0, 0,    0, 0, 0];
+	  
+	case 1
+	c0 = [-175/16384, 0,   -5/256, 0,  -3/64, 0, -1/4, 0, 1;
+             1/61440, 0,   7/2048, 0,   1/48, 0,  1/8, 0, 0;
+          559/368640, 0,   3/1280, 0,  1/768, 0,    0, 0, 0;
+          283/430080, 0, 17/30720, 0,      0, 0,    0, 0, 0;
+       4397/41287680, 0,        0, 0,      0, 0,    0, 0, 0];
+
+	case 2
+	c0 = [-175/16384, 0,   -5/256, 0,  -3/64, 0, -1/4, 0, 1;
+         -901/184320, 0,  -9/1024, 0,  -1/96, 0,  1/8, 0, 0;
+         -311/737280, 0,  17/5120, 0, 13/768, 0,    0, 0, 0;
+          899/430080, 0, 61/15360, 0,      0, 0,    0, 0, 0;
+      49561/41287680, 0,        0, 0,      0, 0,    0, 0, 0];
+   
+end
+c = zeros(size(c0,1),1);
+
+for i = 1:size(c0,1)
+    c(i) = polyval(c0(i,:),e);
+end
Index: /issm/trunk/src/m/coordsystems/utm2ll.m
===================================================================
--- /issm/trunk/src/m/coordsystems/utm2ll.m	(revision 19104)
+++ /issm/trunk/src/m/coordsystems/utm2ll.m	(revision 19105)
@@ -1,117 +1,191 @@
-function  [Lat,Lon] = utm2ll(xx,yy,utmzone)
-% -------------------------------------------------------------------------
-% [Lat,Lon] = utm2ll(x,y,utmzone)
+function [lat,lon]=utm2ll(x,y,f,datum,varargin)
+%UTM2LL UTM to Lat/Lon coordinates precise conversion.
+%	[LAT,LON]=UTM2LL(X,Y,ZONE) converts UTM coordinates X,Y (in meters)
+%	defined in the UTM ZONE (integer) to latitude LAT and longitude LON 
+%	(in degrees). Default datum is WGS84.
 %
-% Description: Function to convert vectors of UTM coordinates into Lat/Lon vectors (WGS84).
-% Some code has been extracted from UTMIP.m function by Gabriel Ruiz Martinez.
+%	X and Y can be scalars, vectors or matrix. Outputs LAT and LON will
+%	have the same size as inputs.
 %
-% Inputs:on)
-%    -3.485713    7.801235 -119.955246  -17.759537  -94.799019  121.640266
+%	For southern hemisphere points, use negative zone -ZONE.
 %
-% Example 2: If you need Lat/Lon coordinates in Degrees, Minutes and Seconds
-% [Lat, Lon]=utm2ll(x,y,utmzone);
-% LatDMS=dms2mat(deg2dms(Lat))
-%LatDMS =
-%    40.00         18.00         55.55
-%    46.00         17.00          2.01
-%    37.00         34.00         40.17
-%    28.00         38.00         44.33
-%    38.00         51.00         19.96
-%    25.00          3.00         42.41
-% LonDMS=dms2mat(deg2dms(Lon))
-%LonDMS =
-%    -3.00         29.00          8.61
-%     7.00         48.00          4.40
-%  -119.00         57.00         18.93
-%   -17.00         45.00         34.33
-%   -94.00         47.00         56.47
-%   121.00         38.00         24.96
+%	UTM2LL(X,Y,ZONE,DATUM) uses specific DATUM for conversion. DATUM can be
+%	a string in the following list:
+%		'wgs84': World Geodetic System 1984 (default)
+%		'nad27': North American Datum 1927
+%		'clk66': Clarke 1866
+%		'nad83': North American Datum 1983
+%		'grs80': Geodetic Reference System 1980
+%		'int24': International 1924 / Hayford 1909
+%	or DATUM can be a 2-element vector [A,F] where A is semimajor axis (in
+%	meters)	and F is flattening of the user-defined ellipsoid.
 %
-% Author:
-%   Rafael Palacios
-%   Universidad Pontificia Comillas
-%   Madrid, Spain
-% Version: Apr/06, Jun/06, Aug/06
-% Aug/06: corrected m-Lint warnings
-%-------------------------------------------------------------------------
+%	Notice:
+%		- UTM2LL does not perform cross-datum conversion.
+%		- precision is near a millimeter.
+%
+%
+%	Reference:
+%		I.G.N., Projection cartographique Mercator Transverse: Algorithmes,
+%		   Notes Techniques NT/G 76, janvier 1995.
+%
+%	Author: Francois Beauducel, <beauducel@ipgp.fr>
+%	Created: 2001-08-23
+%	Updated: 2014-04-20
 
-% Argument checking
+
+%	Copyright (c) 2001-2014, François Beauducel, covered by BSD License.
+%	All rights reserved.
 %
-error(nargchk(3, 3, nargin)); %3 arguments required
-n1=length(xx);
-n2=length(yy);
-n3=size(utmzone,1);
-if (n1~=n2 || n1~=n3)
-	error('x,y and utmzone vectors should have the same number or rows');
-end
-c=size(utmzone,2);
-if (c~=4)
-	error('utmzone should be a vector of strings like "30 T"');
+%	Redistribution and use in source and binary forms, with or without 
+%	modification, are permitted provided that the following conditions are 
+%	met:
+%
+%	   * Redistributions of source code must retain the above copyright 
+%	     notice, this list of conditions and the following disclaimer.
+%	   * Redistributions in binary form must reproduce the above copyright 
+%	     notice, this list of conditions and the following disclaimer in 
+%	     the documentation and/or other materials provided with the distribution
+%	                           
+%	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
+%	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+%	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+%	ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+%	LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
+%	CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+%	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+%	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+%	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
+%	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+%	POSSIBILITY OF SUCH DAMAGE.
+
+% Available datums
+datums = [ ...
+	{ 'wgs84', 6378137.0, 298.257223563 };
+	{ 'nad83', 6378137.0, 298.257222101 };
+	{ 'grs80', 6378137.0, 298.257222101 };
+	{ 'nad27', 6378206.4, 294.978698214 };
+	{ 'int24', 6378388.0, 297.000000000 };
+	{ 'clk66', 6378206.4, 294.978698214 };
+];
+
+if nargin < 3
+	error('Not enough input arguments.')
 end
 
-% Memory pre-allocation
-%
-Lat=zeros(n1,1);
-Lon=zeros(n1,1);
+if all([numel(x),numel(y)] > 1) && any(size(x) ~= size(y))
+	error('X and Y must be the same size or scalars.')
+end
 
-% Main Loop
-%
-for i=1:n1
-	if (utmzone(i,4)>'X' || utmzone(i,4)<'C')
-		fprintf('utm2ll: Warning utmzone should be a vector of strings like "30 T", not "30 t"\n');
+if ~isnumeric(f) || ~isscalar(f) || f ~= round(f)
+	error('ZONE must be a scalar integer.')
+end
+
+if nargin < 4
+	datum = 'wgs84';
+end
+
+if ischar(datum)
+	if ~any(strcmpi(datum,datums(:,1)))
+		error('Unkown DATUM name "%s"',datum);
 	end
-	if (utmzone(i,4)>'M')
-		hemis='N';   % Northern hemisphere
-	else
-		hemis='S';
+	k = find(strcmpi(datum,datums(:,1)));
+	A1 = datums{k,2};
+	F1 = datums{k,3};	
+else
+	if numel(datum) ~= 2
+		error('User defined DATUM must be a vector [A,F].');
 	end
+	A1 = datum(1);
+	F1 = datum(2);
+end
 
-	x=xx(i);
-	y=yy(i);
-	zone=str2double(utmzone(i,1:2));
+% constants
+D0 = 180/pi;	% conversion rad to deg
+maxiter = 100;	% maximum iteration for latitude computation
+eps = 1e-11;	% minimum residue for latitude computation
 
-	sa = 6378137.000000 ; sb = 6356752.314245;
+K0 = 0.9996;					% UTM scale factor
+X0 = 500000;					% UTM false East (m)
+Y0 = 1e7*(f < 0);				% UTM false North (m)
+P0 = 0;						% UTM origin latitude (rad)
+L0 = (6*abs(f) - 183)/D0;			% UTM origin longitude (rad)
+E1 = sqrt((A1^2 - (A1*(1 - 1/F1))^2)/A1^2);	% ellpsoid excentricity
+N = K0*A1;
 
-	%   e = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sa;
-	e2 = ( ( ( sa ^ 2 ) - ( sb ^ 2 ) ) ^ 0.5 ) / sb;
-	e2cuadrada = e2 ^ 2;
-	c = ( sa ^ 2 ) / sb;
-	%   alpha = ( sa - sb ) / sa;             %f
-	%   ablandamiento = 1 / alpha;   % 1/f
+% computing parameters for Mercator Transverse projection
+C = coef(E1,0);
+YS = Y0 - N*(C(1)*P0 + C(2)*sin(2*P0) + C(3)*sin(4*P0) + C(4)*sin(6*P0) + C(5)*sin(8*P0));
 
-	X = x - 500000;
+C = coef(E1,1);
+zt = complex((y - YS)/N/C(1),(x - X0)/N/C(1));
+z = zt - C(2)*sin(2*zt) - C(3)*sin(4*zt) - C(4)*sin(6*zt) - C(5)*sin(8*zt);
+L = real(z);
+LS = imag(z);
 
-	if hemis == 'S' || hemis == 's'
-		Y = y - 10000000;
-	else
-		Y = y;
-	end
+l = L0 + atan(sinh(LS)./cos(L));
+p = asin(sin(L)./cosh(LS));
 
-	S = ( ( zone * 6 ) - 183 );
-	lat =  Y / ( 6366197.724 * 0.9996 );
-	v = ( c / ( ( 1 + ( e2cuadrada * ( cos(lat) ) ^ 2 ) ) ) ^ 0.5 ) * 0.9996;
-	a = X / v;
-	a1 = sin( 2 * lat );
-	a2 = a1 * ( cos(lat) ) ^ 2;
-	j2 = lat + ( a1 / 2 );
-	j4 = ( ( 3 * j2 ) + a2 ) / 4;
-	j6 = ( ( 5 * j4 ) + ( a2 * ( cos(lat) ) ^ 2) ) / 3;
-	alfa = ( 3 / 4 ) * e2cuadrada;
-	beta = ( 5 / 3 ) * alfa ^ 2;
-	gama = ( 35 / 27 ) * alfa ^ 3;
-	Bm = 0.9996 * c * ( lat - alfa * j2 + beta * j4 - gama * j6 );
-	b = ( Y - Bm ) / v;
-	Epsi = ( ( e2cuadrada * a^ 2 ) / 2 ) * ( cos(lat) )^ 2;
-	Eps = a * ( 1 - ( Epsi / 3 ) );
-	nab = ( b * ( 1 - Epsi ) ) + lat;
-	senoheps = ( exp(Eps) - exp(-Eps) ) / 2;
-	Delt = atan(senoheps / (cos(nab) ) );
-	TaO = atan(cos(Delt) * tan(nab));
-	longitude = (Delt *(180 / pi ) ) + S;
-	latitude = ( lat + ( 1 + e2cuadrada* (cos(lat)^ 2) - ( 3 / 2 ) * e2cuadrada * sin(lat) * cos(lat) * ( TaO - lat ) ) * ( TaO - lat ) ) * ...
-		(180 / pi);
+L = log(tan(pi/4 + p/2));
 
-	Lat(i)=latitude;
-	Lon(i)=longitude;
+% calculates latitude from the isometric latitude
+p = 2*atan(exp(L)) - pi/2;
+p0 = NaN;
+n = 0;
+while any(isnan(p0) | abs(p - p0) > eps) & n < maxiter
+	p0 = p;
+	es = E1*sin(p0);
+	p = 2*atan(((1 + es)./(1 - es)).^(E1/2).*exp(L)) - pi/2;
+	n = n + 1;
+end
 
+if nargout < 2
+	lat = D0*[p(:),l(:)];
+else
+	lat = p*D0;
+	lon = l*D0;
 end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+function c = coef(e,m)
+%COEF Projection coefficients
+%	COEF(E,M) returns a vector of 5 coefficients from:
+%		E = first ellipsoid excentricity
+%		M = 0 for transverse mercator
+%		M = 1 for transverse mercator reverse coefficients
+%		M = 2 for merdian arc
+
+
+if nargin < 2
+	m = 0;
+end
+
+switch m
+	case 0
+	c0 = [-175/16384, 0,   -5/256, 0,  -3/64, 0, -1/4, 0, 1;
+           -105/4096, 0, -45/1024, 0,  -3/32, 0, -3/8, 0, 0;
+           525/16384, 0,  45/1024, 0, 15/256, 0,    0, 0, 0;
+          -175/12288, 0, -35/3072, 0,      0, 0,    0, 0, 0;
+          315/131072, 0,        0, 0,      0, 0,    0, 0, 0];
+	  
+	case 1
+	c0 = [-175/16384, 0,   -5/256, 0,  -3/64, 0, -1/4, 0, 1;
+             1/61440, 0,   7/2048, 0,   1/48, 0,  1/8, 0, 0;
+          559/368640, 0,   3/1280, 0,  1/768, 0,    0, 0, 0;
+          283/430080, 0, 17/30720, 0,      0, 0,    0, 0, 0;
+       4397/41287680, 0,        0, 0,      0, 0,    0, 0, 0];
+
+	case 2
+	c0 = [-175/16384, 0,   -5/256, 0,  -3/64, 0, -1/4, 0, 1;
+         -901/184320, 0,  -9/1024, 0,  -1/96, 0,  1/8, 0, 0;
+         -311/737280, 0,  17/5120, 0, 13/768, 0,    0, 0, 0;
+          899/430080, 0, 61/15360, 0,      0, 0,    0, 0, 0;
+      49561/41287680, 0,        0, 0,      0, 0,    0, 0, 0];
+   
+end
+c = zeros(size(c0,1),1);
+
+for i = 1:size(c0,1)
+    c(i) = polyval(c0(i,:),e);
+end
Index: /issm/trunk/src/m/dev/issmversion.m
===================================================================
--- /issm/trunk/src/m/dev/issmversion.m	(revision 19104)
+++ /issm/trunk/src/m/dev/issmversion.m	(revision 19105)
@@ -15,5 +15,7 @@
 disp([' ']);
 disp(['Build date: ' IssmConfig('PACKAGE_BUILD_DATE')]);
-disp(['Copyright (c) 2009-2014 California Institute of Technology']);
+disp(['Compiled on ' IssmConfig('HOST_VENDOR') ' ' IssmConfig('HOST_OS') ' ' IssmConfig('HOST_ARCH') ' by ' IssmConfig('USER_NAME')]);
+disp([' ']);
+disp(['Copyright (c) 2009-2015 California Institute of Technology']);
 disp([' ']);
 disp(['    to get started type: issmdoc']);
Index: /issm/trunk/src/m/enum/BalancethicknessCmuEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessCmuEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/BalancethicknessCmuEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessCmuEnum()
+%BALANCETHICKNESSCMUENUM - Enum of BalancethicknessCmu
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessCmuEnum()
+
+macro=StringToEnum('BalancethicknessCmu');
Index: /issm/trunk/src/m/enum/BalancethicknessD0Enum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessD0Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/BalancethicknessD0Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessD0Enum()
+%BALANCETHICKNESSD0ENUM - Enum of BalancethicknessD0
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessD0Enum()
+
+macro=StringToEnum('BalancethicknessD0');
Index: /issm/trunk/src/m/enum/BalancethicknessDiffusionCoefficientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessDiffusionCoefficientEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/BalancethicknessDiffusionCoefficientEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessDiffusionCoefficientEnum()
+%BALANCETHICKNESSDIFFUSIONCOEFFICIENTENUM - Enum of BalancethicknessDiffusionCoefficient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessDiffusionCoefficientEnum()
+
+macro=StringToEnum('BalancethicknessDiffusionCoefficient');
Index: sm/trunk/src/m/enum/BalancethicknessNuxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessNuxEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BalancethicknessNuxEnum()
-%BALANCETHICKNESSNUXENUM - Enum of BalancethicknessNux
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BalancethicknessNuxEnum()
-
-macro=StringToEnum('BalancethicknessNux');
Index: sm/trunk/src/m/enum/BalancethicknessNuyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessNuyEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BalancethicknessNuyEnum()
-%BALANCETHICKNESSNUYENUM - Enum of BalancethicknessNuy
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BalancethicknessNuyEnum()
-
-macro=StringToEnum('BalancethicknessNuy');
Index: /issm/trunk/src/m/enum/BalancethicknessOmegaEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessOmegaEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/BalancethicknessOmegaEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=BalancethicknessOmegaEnum()
+%BALANCETHICKNESSOMEGAENUM - Enum of BalancethicknessOmega
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=BalancethicknessOmegaEnum()
+
+macro=StringToEnum('BalancethicknessOmega');
Index: sm/trunk/src/m/enum/BalancethicknessThicknessObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessThicknessObsEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BalancethicknessThicknessObsEnum()
-%BALANCETHICKNESSTHICKNESSOBSENUM - Enum of BalancethicknessThicknessObs
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BalancethicknessThicknessObsEnum()
-
-macro=StringToEnum('BalancethicknessThicknessObs');
Index: sm/trunk/src/m/enum/BalancethicknessVxObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessVxObsEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BalancethicknessVxObsEnum()
-%BALANCETHICKNESSVXOBSENUM - Enum of BalancethicknessVxObs
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BalancethicknessVxObsEnum()
-
-macro=StringToEnum('BalancethicknessVxObs');
Index: sm/trunk/src/m/enum/BalancethicknessVyObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancethicknessVyObsEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=BalancethicknessVyObsEnum()
-%BALANCETHICKNESSVYOBSENUM - Enum of BalancethicknessVyObs
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=BalancethicknessVyObsEnum()
-
-macro=StringToEnum('BalancethicknessVyObs');
Index: /issm/trunk/src/m/enum/CalvingCalvingrateEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingCalvingrateEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingCalvingrateEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingCalvingrateEnum()
+%CALVINGCALVINGRATEENUM - Enum of CalvingCalvingrate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingCalvingrateEnum()
+
+macro=StringToEnum('CalvingCalvingrate');
Index: /issm/trunk/src/m/enum/CalvingDevEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingDevEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingDevEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingDevEnum()
+%CALVINGDEVENUM - Enum of CalvingDev
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingDevEnum()
+
+macro=StringToEnum('CalvingDev');
Index: /issm/trunk/src/m/enum/CalvingLawEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingLawEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingLawEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingLawEnum()
+%CALVINGLAWENUM - Enum of CalvingLaw
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingLawEnum()
+
+macro=StringToEnum('CalvingLaw');
Index: /issm/trunk/src/m/enum/CalvingLevermannEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingLevermannEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingLevermannEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingLevermannEnum()
+%CALVINGLEVERMANNENUM - Enum of CalvingLevermann
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingLevermannEnum()
+
+macro=StringToEnum('CalvingLevermann');
Index: /issm/trunk/src/m/enum/CalvingMeltingrateEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingMeltingrateEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingMeltingrateEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingMeltingrateEnum()
+%CALVINGMELTINGRATEENUM - Enum of CalvingMeltingrate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingMeltingrateEnum()
+
+macro=StringToEnum('CalvingMeltingrate');
Index: /issm/trunk/src/m/enum/CalvingPiEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingPiEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingPiEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingPiEnum()
+%CALVINGPIENUM - Enum of CalvingPi
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingPiEnum()
+
+macro=StringToEnum('CalvingPi');
Index: /issm/trunk/src/m/enum/CalvingRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingRequestedOutputsEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingRequestedOutputsEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingRequestedOutputsEnum()
+%CALVINGREQUESTEDOUTPUTSENUM - Enum of CalvingRequestedOutputs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingRequestedOutputsEnum()
+
+macro=StringToEnum('CalvingRequestedOutputs');
Index: /issm/trunk/src/m/enum/CalvinglevermannCoeffEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvinglevermannCoeffEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvinglevermannCoeffEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvinglevermannCoeffEnum()
+%CALVINGLEVERMANNCOEFFENUM - Enum of CalvinglevermannCoeff
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvinglevermannCoeffEnum()
+
+macro=StringToEnum('CalvinglevermannCoeff');
Index: /issm/trunk/src/m/enum/CalvinglevermannMeltingrateEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvinglevermannMeltingrateEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvinglevermannMeltingrateEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvinglevermannMeltingrateEnum()
+%CALVINGLEVERMANNMELTINGRATEENUM - Enum of CalvinglevermannMeltingrate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvinglevermannMeltingrateEnum()
+
+macro=StringToEnum('CalvinglevermannMeltingrate');
Index: /issm/trunk/src/m/enum/CalvingpiCoeffEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingpiCoeffEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingpiCoeffEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingpiCoeffEnum()
+%CALVINGPICOEFFENUM - Enum of CalvingpiCoeff
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingpiCoeffEnum()
+
+macro=StringToEnum('CalvingpiCoeff');
Index: /issm/trunk/src/m/enum/CalvingpiMeltingrateEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingpiMeltingrateEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingpiMeltingrateEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingpiMeltingrateEnum()
+%CALVINGPIMELTINGRATEENUM - Enum of CalvingpiMeltingrate
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingpiMeltingrateEnum()
+
+macro=StringToEnum('CalvingpiMeltingrate');
Index: /issm/trunk/src/m/enum/CalvingratexAverageEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingratexAverageEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingratexAverageEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingratexAverageEnum()
+%CALVINGRATEXAVERAGEENUM - Enum of CalvingratexAverage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingratexAverageEnum()
+
+macro=StringToEnum('CalvingratexAverage');
Index: /issm/trunk/src/m/enum/CalvingratexEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingratexEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingratexEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingratexEnum()
+%CALVINGRATEXENUM - Enum of Calvingratex
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingratexEnum()
+
+macro=StringToEnum('Calvingratex');
Index: /issm/trunk/src/m/enum/CalvingrateyAverageEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingrateyAverageEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingrateyAverageEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingrateyAverageEnum()
+%CALVINGRATEYAVERAGEENUM - Enum of CalvingrateyAverage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingrateyAverageEnum()
+
+macro=StringToEnum('CalvingrateyAverage');
Index: /issm/trunk/src/m/enum/CalvingrateyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/CalvingrateyEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/CalvingrateyEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=CalvingrateyEnum()
+%CALVINGRATEYENUM - Enum of Calvingratey
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=CalvingrateyEnum()
+
+macro=StringToEnum('Calvingratey');
Index: /issm/trunk/src/m/enum/ConstantsOmegaEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ConstantsOmegaEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/ConstantsOmegaEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=ConstantsOmegaEnum()
+%CONSTANTSOMEGAENUM - Enum of ConstantsOmega
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ConstantsOmegaEnum()
+
+macro=StringToEnum('ConstantsOmega');
Index: /issm/trunk/src/m/enum/DamageEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DamageEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/DamageEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=DamageEnum()
+%DAMAGEENUM - Enum of Damage
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DamageEnum()
+
+macro=StringToEnum('Damage');
Index: /issm/trunk/src/m/enum/DefaultCalvingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DefaultCalvingEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/DefaultCalvingEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=DefaultCalvingEnum()
+%DEFAULTCALVINGENUM - Enum of DefaultCalving
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DefaultCalvingEnum()
+
+macro=StringToEnum('DefaultCalving');
Index: /issm/trunk/src/m/enum/DrivingStressXEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DrivingStressXEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/DrivingStressXEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=DrivingStressXEnum()
+%DRIVINGSTRESSXENUM - Enum of DrivingStressX
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DrivingStressXEnum()
+
+macro=StringToEnum('DrivingStressX');
Index: /issm/trunk/src/m/enum/DrivingStressYEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DrivingStressYEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/DrivingStressYEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=DrivingStressYEnum()
+%DRIVINGSTRESSYENUM - Enum of DrivingStressY
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=DrivingStressYEnum()
+
+macro=StringToEnum('DrivingStressY');
Index: /issm/trunk/src/m/enum/EnumDefinitions.py
===================================================================
--- /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 19104)
+++ /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 19105)
@@ -50,4 +50,5 @@
 def BaseEnum(): return StringToEnum("Base")[0]
 def ConstantsGEnum(): return StringToEnum("ConstantsG")[0]
+def ConstantsOmegaEnum(): return StringToEnum("ConstantsOmega")[0]
 def ConstantsReferencetemperatureEnum(): return StringToEnum("ConstantsReferencetemperature")[0]
 def ConstantsYtsEnum(): return StringToEnum("ConstantsYts")[0]
@@ -87,4 +88,5 @@
 def FlowequationFeFSEnum(): return StringToEnum("FlowequationFeFS")[0]
 def FlowequationVertexEquationEnum(): return StringToEnum("FlowequationVertexEquation")[0]
+def FrictionAsEnum(): return StringToEnum("FrictionAs")[0]
 def FrictionCoefficientEnum(): return StringToEnum("FrictionCoefficient")[0]
 def FrictionPEnum(): return StringToEnum("FrictionP")[0]
@@ -93,4 +95,7 @@
 def FrictionCEnum(): return StringToEnum("FrictionC")[0]
 def FrictionLawEnum(): return StringToEnum("FrictionLaw")[0]
+def FrictionGammaEnum(): return StringToEnum("FrictionGamma")[0]
+def FrictionWaterLayerEnum(): return StringToEnum("FrictionWaterLayer")[0]
+def FrictionEffectivePressureEnum(): return StringToEnum("FrictionEffectivePressure")[0]
 def GeometryHydrostaticRatioEnum(): return StringToEnum("GeometryHydrostaticRatio")[0]
 def HydrologyModelEnum(): return StringToEnum("HydrologyModel")[0]
@@ -107,4 +112,5 @@
 def EplHeadSlopeXEnum(): return StringToEnum("EplHeadSlopeX")[0]
 def EplHeadSlopeYEnum(): return StringToEnum("EplHeadSlopeY")[0]
+def EplZigZagCounterEnum(): return StringToEnum("EplZigZagCounter")[0]
 def HydrologydcMaxIterEnum(): return StringToEnum("HydrologydcMaxIter")[0]
 def HydrologydcRelTolEnum(): return StringToEnum("HydrologydcRelTol")[0]
@@ -121,7 +127,9 @@
 def HydrologydcEplPorosityEnum(): return StringToEnum("HydrologydcEplPorosity")[0]
 def HydrologydcEplInitialThicknessEnum(): return StringToEnum("HydrologydcEplInitialThickness")[0]
+def HydrologydcEplColapseThicknessEnum(): return StringToEnum("HydrologydcEplColapseThickness")[0]
 def HydrologydcEplMaxThicknessEnum(): return StringToEnum("HydrologydcEplMaxThickness")[0]
 def HydrologydcEplThicknessEnum(): return StringToEnum("HydrologydcEplThickness")[0]
 def HydrologydcEplThicknessOldEnum(): return StringToEnum("HydrologydcEplThicknessOld")[0]
+def HydrologydcEplThickCompEnum(): return StringToEnum("HydrologydcEplThickComp")[0]
 def HydrologydcEplConductivityEnum(): return StringToEnum("HydrologydcEplConductivity")[0]
 def HydrologydcIsefficientlayerEnum(): return StringToEnum("HydrologydcIsefficientlayer")[0]
@@ -132,4 +140,5 @@
 def HydrologydcPenaltyFactorEnum(): return StringToEnum("HydrologydcPenaltyFactor")[0]
 def HydrologydcPenaltyLockEnum(): return StringToEnum("HydrologydcPenaltyLock")[0]
+def HydrologydcEplflipLockEnum(): return StringToEnum("HydrologydcEplflipLock")[0]
 def HydrologydcBasalMoulinInputEnum(): return StringToEnum("HydrologydcBasalMoulinInput")[0]
 def HydrologyLayerEnum(): return StringToEnum("HydrologyLayer")[0]
@@ -139,4 +148,5 @@
 def IndependentObjectEnum(): return StringToEnum("IndependentObject")[0]
 def InversionControlParametersEnum(): return StringToEnum("InversionControlParameters")[0]
+def InversionControlScalingFactorsEnum(): return StringToEnum("InversionControlScalingFactors")[0]
 def InversionCostFunctionThresholdEnum(): return StringToEnum("InversionCostFunctionThreshold")[0]
 def InversionCostFunctionsCoefficientsEnum(): return StringToEnum("InversionCostFunctionsCoefficients")[0]
@@ -163,9 +173,9 @@
 def InversionStepThresholdEnum(): return StringToEnum("InversionStepThreshold")[0]
 def InversionThicknessObsEnum(): return StringToEnum("InversionThicknessObs")[0]
+def InversionSurfaceObsEnum(): return StringToEnum("InversionSurfaceObs")[0]
 def InversionVxObsEnum(): return StringToEnum("InversionVxObs")[0]
 def InversionVyObsEnum(): return StringToEnum("InversionVyObs")[0]
 def InversionVzObsEnum(): return StringToEnum("InversionVzObs")[0]
 def MaskIceLevelsetEnum(): return StringToEnum("MaskIceLevelset")[0]
-def QmuMaskIceLevelsetEnum(): return StringToEnum("QmuMaskIceLevelset")[0]
 def MaterialsBetaEnum(): return StringToEnum("MaterialsBeta")[0]
 def MaterialsHeatcapacityEnum(): return StringToEnum("MaterialsHeatcapacity")[0]
@@ -180,5 +190,4 @@
 def DamageDEnum(): return StringToEnum("DamageD")[0]
 def DamageFEnum(): return StringToEnum("DamageF")[0]
-def QmuDamageDEnum(): return StringToEnum("QmuDamageD")[0]
 def DamageDbarEnum(): return StringToEnum("DamageDbar")[0]
 def DamageLawEnum(): return StringToEnum("DamageLaw")[0]
@@ -200,5 +209,26 @@
 def DamageEvolutionNumRequestedOutputsEnum(): return StringToEnum("DamageEvolutionNumRequestedOutputs")[0]
 def DamageEvolutionRequestedOutputsEnum(): return StringToEnum("DamageEvolutionRequestedOutputs")[0]
+def DamageEnum(): return StringToEnum("Damage")[0]
 def NewDamageEnum(): return StringToEnum("NewDamage")[0]
+def StressIntensityFactorEnum(): return StringToEnum("StressIntensityFactor")[0]
+def CalvingLawEnum(): return StringToEnum("CalvingLaw")[0]
+def CalvingCalvingrateEnum(): return StringToEnum("CalvingCalvingrate")[0]
+def CalvingMeltingrateEnum(): return StringToEnum("CalvingMeltingrate")[0]
+def CalvingLevermannEnum(): return StringToEnum("CalvingLevermann")[0]
+def CalvingPiEnum(): return StringToEnum("CalvingPi")[0]
+def CalvingDevEnum(): return StringToEnum("CalvingDev")[0]
+def DefaultCalvingEnum(): return StringToEnum("DefaultCalving")[0]
+def CalvingRequestedOutputsEnum(): return StringToEnum("CalvingRequestedOutputs")[0]
+def CalvinglevermannCoeffEnum(): return StringToEnum("CalvinglevermannCoeff")[0]
+def CalvinglevermannMeltingrateEnum(): return StringToEnum("CalvinglevermannMeltingrate")[0]
+def CalvingpiCoeffEnum(): return StringToEnum("CalvingpiCoeff")[0]
+def CalvingpiMeltingrateEnum(): return StringToEnum("CalvingpiMeltingrate")[0]
+def CalvingratexEnum(): return StringToEnum("Calvingratex")[0]
+def CalvingrateyEnum(): return StringToEnum("Calvingratey")[0]
+def CalvingratexAverageEnum(): return StringToEnum("CalvingratexAverage")[0]
+def CalvingrateyAverageEnum(): return StringToEnum("CalvingrateyAverage")[0]
+def StrainRateparallelEnum(): return StringToEnum("StrainRateparallel")[0]
+def StrainRateperpendicularEnum(): return StringToEnum("StrainRateperpendicular")[0]
+def StrainRateeffectiveEnum(): return StringToEnum("StrainRateeffective")[0]
 def MaterialsRhoIceEnum(): return StringToEnum("MaterialsRhoIce")[0]
 def MaterialsRhoSeawaterEnum(): return StringToEnum("MaterialsRhoSeawater")[0]
@@ -240,5 +270,4 @@
 def MasstransportPenaltyFactorEnum(): return StringToEnum("MasstransportPenaltyFactor")[0]
 def MasstransportSpcthicknessEnum(): return StringToEnum("MasstransportSpcthickness")[0]
-def MasstransportCalvingrateEnum(): return StringToEnum("MasstransportCalvingrate")[0]
 def MasstransportStabilizationEnum(): return StringToEnum("MasstransportStabilization")[0]
 def MasstransportVertexPairingEnum(): return StringToEnum("MasstransportVertexPairing")[0]
@@ -254,5 +283,4 @@
 def QmuResponsedescriptorsEnum(): return StringToEnum("QmuResponsedescriptors")[0]
 def QmuVariabledescriptorsEnum(): return StringToEnum("QmuVariabledescriptors")[0]
-def QmuMaterialsRheologyBEnum(): return StringToEnum("QmuMaterialsRheologyB")[0]
 def RiftsNumriftsEnum(): return StringToEnum("RiftsNumrifts")[0]
 def RiftsRiftstructEnum(): return StringToEnum("RiftsRiftstruct")[0]
@@ -274,4 +302,5 @@
 def ThermalIsenthalpyEnum(): return StringToEnum("ThermalIsenthalpy")[0]
 def ThermalIsdynamicbasalspcEnum(): return StringToEnum("ThermalIsdynamicbasalspc")[0]
+def ThermalReltolEnum(): return StringToEnum("ThermalReltol")[0]
 def ThermalMaxiterEnum(): return StringToEnum("ThermalMaxiter")[0]
 def ThermalPenaltyFactorEnum(): return StringToEnum("ThermalPenaltyFactor")[0]
@@ -298,4 +327,5 @@
 def TransientIsdamageevolutionEnum(): return StringToEnum("TransientIsdamageevolution")[0]
 def TransientIshydrologyEnum(): return StringToEnum("TransientIshydrology")[0]
+def TransientIscalvingEnum(): return StringToEnum("TransientIscalving")[0]
 def TransientNumRequestedOutputsEnum(): return StringToEnum("TransientNumRequestedOutputs")[0]
 def TransientRequestedOutputsEnum(): return StringToEnum("TransientRequestedOutputs")[0]
@@ -304,9 +334,8 @@
 def BalancethicknessApparentMassbalanceEnum(): return StringToEnum("BalancethicknessApparentMassbalance")[0]
 def Balancethickness2MisfitEnum(): return StringToEnum("Balancethickness2Misfit")[0]
-def BalancethicknessNuxEnum(): return StringToEnum("BalancethicknessNux")[0]
-def BalancethicknessNuyEnum(): return StringToEnum("BalancethicknessNuy")[0]
-def BalancethicknessVxObsEnum(): return StringToEnum("BalancethicknessVxObs")[0]
-def BalancethicknessVyObsEnum(): return StringToEnum("BalancethicknessVyObs")[0]
-def BalancethicknessThicknessObsEnum(): return StringToEnum("BalancethicknessThicknessObs")[0]
+def BalancethicknessDiffusionCoefficientEnum(): return StringToEnum("BalancethicknessDiffusionCoefficient")[0]
+def BalancethicknessCmuEnum(): return StringToEnum("BalancethicknessCmu")[0]
+def BalancethicknessOmegaEnum(): return StringToEnum("BalancethicknessOmega")[0]
+def BalancethicknessD0Enum(): return StringToEnum("BalancethicknessD0")[0]
 def SurfaceforcingsEnum(): return StringToEnum("Surfaceforcings")[0]
 def SMBEnum(): return StringToEnum("SMB")[0]
@@ -316,5 +345,7 @@
 def SurfaceforcingsDelta18oSurfaceEnum(): return StringToEnum("SurfaceforcingsDelta18oSurface")[0]
 def SurfaceforcingsIsdelta18oEnum(): return StringToEnum("SurfaceforcingsIsdelta18o")[0]
+def SurfaceforcingsIsmungsmEnum(): return StringToEnum("SurfaceforcingsIsmungsm")[0]
 def SurfaceforcingsPrecipitationsPresentdayEnum(): return StringToEnum("SurfaceforcingsPrecipitationsPresentday")[0]
+def SurfaceforcingsPrecipitationsLgmEnum(): return StringToEnum("SurfaceforcingsPrecipitationsLgm")[0]
 def SurfaceforcingsTemperaturesPresentdayEnum(): return StringToEnum("SurfaceforcingsTemperaturesPresentday")[0]
 def SurfaceforcingsTemperaturesLgmEnum(): return StringToEnum("SurfaceforcingsTemperaturesLgm")[0]
@@ -322,4 +353,10 @@
 def SurfaceforcingsDesfacEnum(): return StringToEnum("SurfaceforcingsDesfac")[0]
 def SurfaceforcingsS0pEnum(): return StringToEnum("SurfaceforcingsS0p")[0]
+def SurfaceforcingsS0tEnum(): return StringToEnum("SurfaceforcingsS0t")[0]
+def SurfaceforcingsRlapsEnum(): return StringToEnum("SurfaceforcingsRlaps")[0]
+def SurfaceforcingsRlapslgmEnum(): return StringToEnum("SurfaceforcingsRlapslgm")[0]
+def SurfaceforcingsPfacEnum(): return StringToEnum("SurfaceforcingsPfac")[0]
+def SurfaceforcingsTdiffEnum(): return StringToEnum("SurfaceforcingsTdiff")[0]
+def SurfaceforcingsSealevEnum(): return StringToEnum("SurfaceforcingsSealev")[0]
 def SMBgradientsEnum(): return StringToEnum("SMBgradients")[0]
 def SurfaceforcingsMonthlytemperaturesEnum(): return StringToEnum("SurfaceforcingsMonthlytemperatures")[0]
@@ -381,6 +418,5 @@
 def SteadystateSolutionEnum(): return StringToEnum("SteadystateSolution")[0]
 def SurfaceSlopeSolutionEnum(): return StringToEnum("SurfaceSlopeSolution")[0]
-def SmoothedSurfaceSlopeXAnalysisEnum(): return StringToEnum("SmoothedSurfaceSlopeXAnalysis")[0]
-def SmoothedSurfaceSlopeYAnalysisEnum(): return StringToEnum("SmoothedSurfaceSlopeYAnalysis")[0]
+def SmoothAnalysisEnum(): return StringToEnum("SmoothAnalysis")[0]
 def ThermalAnalysisEnum(): return StringToEnum("ThermalAnalysis")[0]
 def ThermalSolutionEnum(): return StringToEnum("ThermalSolution")[0]
@@ -392,4 +428,5 @@
 def MeshdeformationAnalysisEnum(): return StringToEnum("MeshdeformationAnalysis")[0]
 def LevelsetAnalysisEnum(): return StringToEnum("LevelsetAnalysis")[0]
+def LevelsetStabilizationEnum(): return StringToEnum("LevelsetStabilization")[0]
 def ExtrapolationAnalysisEnum(): return StringToEnum("ExtrapolationAnalysis")[0]
 def LsfReinitializationAnalysisEnum(): return StringToEnum("LsfReinitializationAnalysis")[0]
@@ -435,4 +472,6 @@
 def InputToL2ProjectEnum(): return StringToEnum("InputToL2Project")[0]
 def InputToDepthaverageEnum(): return StringToEnum("InputToDepthaverage")[0]
+def InputToSmoothEnum(): return StringToEnum("InputToSmooth")[0]
+def SmoothThicknessMultiplierEnum(): return StringToEnum("SmoothThicknessMultiplier")[0]
 def IntParamEnum(): return StringToEnum("IntParam")[0]
 def IntVecParamEnum(): return StringToEnum("IntVecParam")[0]
@@ -449,4 +488,15 @@
 def ProfilerEnum(): return StringToEnum("Profiler")[0]
 def MatrixParamEnum(): return StringToEnum("MatrixParam")[0]
+def MassconEnum(): return StringToEnum("Masscon")[0]
+def MassconNameEnum(): return StringToEnum("MassconName")[0]
+def MassconDefinitionenumEnum(): return StringToEnum("MassconDefinitionenum")[0]
+def MassconLevelsetEnum(): return StringToEnum("MassconLevelset")[0]
+def MassconaxpbyEnum(): return StringToEnum("Massconaxpby")[0]
+def MassconaxpbyNameEnum(): return StringToEnum("MassconaxpbyName")[0]
+def MassconaxpbyDefinitionenumEnum(): return StringToEnum("MassconaxpbyDefinitionenum")[0]
+def MassconaxpbyNamexEnum(): return StringToEnum("MassconaxpbyNamex")[0]
+def MassconaxpbyNameyEnum(): return StringToEnum("MassconaxpbyNamey")[0]
+def MassconaxpbyAlphaEnum(): return StringToEnum("MassconaxpbyAlpha")[0]
+def MassconaxpbyBetaEnum(): return StringToEnum("MassconaxpbyBeta")[0]
 def NodeSIdEnum(): return StringToEnum("NodeSId")[0]
 def VectorParamEnum(): return StringToEnum("VectorParam")[0]
@@ -496,15 +546,4 @@
 def PressureEnum(): return StringToEnum("Pressure")[0]
 def PressurePicardEnum(): return StringToEnum("PressurePicard")[0]
-def QmuPressureEnum(): return StringToEnum("QmuPressure")[0]
-def QmuVxEnum(): return StringToEnum("QmuVx")[0]
-def QmuVyEnum(): return StringToEnum("QmuVy")[0]
-def QmuVzEnum(): return StringToEnum("QmuVz")[0]
-def QmuThicknessEnum(): return StringToEnum("QmuThickness")[0]
-def QmuBaseEnum(): return StringToEnum("QmuBase")[0]
-def QmuSurfaceEnum(): return StringToEnum("QmuSurface")[0]
-def QmuMeltingEnum(): return StringToEnum("QmuMelting")[0]
-def QmuVxMeshEnum(): return StringToEnum("QmuVxMesh")[0]
-def QmuVyMeshEnum(): return StringToEnum("QmuVyMesh")[0]
-def QmuVzMeshEnum(): return StringToEnum("QmuVzMesh")[0]
 def AndroidFrictionCoefficientEnum(): return StringToEnum("AndroidFrictionCoefficient")[0]
 def ResetPenaltiesEnum(): return StringToEnum("ResetPenalties")[0]
@@ -521,4 +560,5 @@
 def TemperaturePicardEnum(): return StringToEnum("TemperaturePicard")[0]
 def ThicknessAbsMisfitEnum(): return StringToEnum("ThicknessAbsMisfit")[0]
+def SurfaceAbsMisfitEnum(): return StringToEnum("SurfaceAbsMisfit")[0]
 def VelEnum(): return StringToEnum("Vel")[0]
 def VelocityEnum(): return StringToEnum("Velocity")[0]
@@ -544,4 +584,5 @@
 def IntMatParamEnum(): return StringToEnum("IntMatParam")[0]
 def RheologyBbarAbsGradientEnum(): return StringToEnum("RheologyBbarAbsGradient")[0]
+def RheologyBAbsGradientEnum(): return StringToEnum("RheologyBAbsGradient")[0]
 def DragCoefficientAbsGradientEnum(): return StringToEnum("DragCoefficientAbsGradient")[0]
 def TransientInputEnum(): return StringToEnum("TransientInput")[0]
@@ -550,7 +591,8 @@
 def BasalFrictionEnum(): return StringToEnum("BasalFriction")[0]
 def ViscousHeatingEnum(): return StringToEnum("ViscousHeating")[0]
-def QmuTemperatureEnum(): return StringToEnum("QmuTemperature")[0]
 def HydrologyWaterVxEnum(): return StringToEnum("HydrologyWaterVx")[0]
 def HydrologyWaterVyEnum(): return StringToEnum("HydrologyWaterVy")[0]
+def DrivingStressXEnum(): return StringToEnum("DrivingStressX")[0]
+def DrivingStressYEnum(): return StringToEnum("DrivingStressY")[0]
 def SigmaNNEnum(): return StringToEnum("SigmaNN")[0]
 def StressTensorEnum(): return StringToEnum("StressTensor")[0]
@@ -561,4 +603,5 @@
 def StressTensoryzEnum(): return StringToEnum("StressTensoryz")[0]
 def StressTensorzzEnum(): return StringToEnum("StressTensorzz")[0]
+def StressMaxPrincipalEnum(): return StringToEnum("StressMaxPrincipal")[0]
 def DeviatoricStressEnum(): return StringToEnum("DeviatoricStress")[0]
 def DeviatoricStressxxEnum(): return StringToEnum("DeviatoricStressxx")[0]
@@ -576,4 +619,5 @@
 def StrainRatezzEnum(): return StringToEnum("StrainRatezz")[0]
 def DivergenceEnum(): return StringToEnum("Divergence")[0]
+def MaxDivergenceEnum(): return StringToEnum("MaxDivergence")[0]
 def GiaCrossSectionShapeEnum(): return StringToEnum("GiaCrossSectionShape")[0]
 def GiadWdtEnum(): return StringToEnum("GiadWdt")[0]
@@ -600,4 +644,5 @@
 def OneLayerP4zEnum(): return StringToEnum("OneLayerP4z")[0]
 def CrouzeixRaviartEnum(): return StringToEnum("CrouzeixRaviart")[0]
+def LACrouzeixRaviartEnum(): return StringToEnum("LACrouzeixRaviart")[0]
 def SaveResultsEnum(): return StringToEnum("SaveResults")[0]
 def BoolExternalResultEnum(): return StringToEnum("BoolExternalResult")[0]
@@ -611,12 +656,115 @@
 def WaterColumnOldEnum(): return StringToEnum("WaterColumnOld")[0]
 def OutputdefinitionEnum(): return StringToEnum("Outputdefinition")[0]
+def Outputdefinition1Enum(): return StringToEnum("Outputdefinition1")[0]
+def Outputdefinition2Enum(): return StringToEnum("Outputdefinition2")[0]
+def Outputdefinition3Enum(): return StringToEnum("Outputdefinition3")[0]
+def Outputdefinition4Enum(): return StringToEnum("Outputdefinition4")[0]
+def Outputdefinition5Enum(): return StringToEnum("Outputdefinition5")[0]
+def Outputdefinition6Enum(): return StringToEnum("Outputdefinition6")[0]
+def Outputdefinition7Enum(): return StringToEnum("Outputdefinition7")[0]
+def Outputdefinition8Enum(): return StringToEnum("Outputdefinition8")[0]
+def Outputdefinition9Enum(): return StringToEnum("Outputdefinition9")[0]
+def Outputdefinition10Enum(): return StringToEnum("Outputdefinition10")[0]
+def Outputdefinition11Enum(): return StringToEnum("Outputdefinition11")[0]
+def Outputdefinition12Enum(): return StringToEnum("Outputdefinition12")[0]
+def Outputdefinition13Enum(): return StringToEnum("Outputdefinition13")[0]
+def Outputdefinition14Enum(): return StringToEnum("Outputdefinition14")[0]
+def Outputdefinition15Enum(): return StringToEnum("Outputdefinition15")[0]
+def Outputdefinition16Enum(): return StringToEnum("Outputdefinition16")[0]
+def Outputdefinition17Enum(): return StringToEnum("Outputdefinition17")[0]
+def Outputdefinition18Enum(): return StringToEnum("Outputdefinition18")[0]
+def Outputdefinition19Enum(): return StringToEnum("Outputdefinition19")[0]
+def Outputdefinition20Enum(): return StringToEnum("Outputdefinition20")[0]
+def Outputdefinition21Enum(): return StringToEnum("Outputdefinition21")[0]
+def Outputdefinition22Enum(): return StringToEnum("Outputdefinition22")[0]
+def Outputdefinition23Enum(): return StringToEnum("Outputdefinition23")[0]
+def Outputdefinition24Enum(): return StringToEnum("Outputdefinition24")[0]
+def Outputdefinition25Enum(): return StringToEnum("Outputdefinition25")[0]
+def Outputdefinition26Enum(): return StringToEnum("Outputdefinition26")[0]
+def Outputdefinition27Enum(): return StringToEnum("Outputdefinition27")[0]
+def Outputdefinition28Enum(): return StringToEnum("Outputdefinition28")[0]
+def Outputdefinition29Enum(): return StringToEnum("Outputdefinition29")[0]
+def Outputdefinition30Enum(): return StringToEnum("Outputdefinition30")[0]
+def Outputdefinition31Enum(): return StringToEnum("Outputdefinition31")[0]
+def Outputdefinition32Enum(): return StringToEnum("Outputdefinition32")[0]
+def Outputdefinition33Enum(): return StringToEnum("Outputdefinition33")[0]
+def Outputdefinition34Enum(): return StringToEnum("Outputdefinition34")[0]
+def Outputdefinition35Enum(): return StringToEnum("Outputdefinition35")[0]
+def Outputdefinition36Enum(): return StringToEnum("Outputdefinition36")[0]
+def Outputdefinition37Enum(): return StringToEnum("Outputdefinition37")[0]
+def Outputdefinition38Enum(): return StringToEnum("Outputdefinition38")[0]
+def Outputdefinition39Enum(): return StringToEnum("Outputdefinition39")[0]
+def Outputdefinition40Enum(): return StringToEnum("Outputdefinition40")[0]
+def Outputdefinition41Enum(): return StringToEnum("Outputdefinition41")[0]
+def Outputdefinition42Enum(): return StringToEnum("Outputdefinition42")[0]
+def Outputdefinition43Enum(): return StringToEnum("Outputdefinition43")[0]
+def Outputdefinition44Enum(): return StringToEnum("Outputdefinition44")[0]
+def Outputdefinition45Enum(): return StringToEnum("Outputdefinition45")[0]
+def Outputdefinition46Enum(): return StringToEnum("Outputdefinition46")[0]
+def Outputdefinition47Enum(): return StringToEnum("Outputdefinition47")[0]
+def Outputdefinition48Enum(): return StringToEnum("Outputdefinition48")[0]
+def Outputdefinition49Enum(): return StringToEnum("Outputdefinition49")[0]
+def Outputdefinition50Enum(): return StringToEnum("Outputdefinition50")[0]
+def Outputdefinition51Enum(): return StringToEnum("Outputdefinition51")[0]
+def Outputdefinition52Enum(): return StringToEnum("Outputdefinition52")[0]
+def Outputdefinition53Enum(): return StringToEnum("Outputdefinition53")[0]
+def Outputdefinition54Enum(): return StringToEnum("Outputdefinition54")[0]
+def Outputdefinition55Enum(): return StringToEnum("Outputdefinition55")[0]
+def Outputdefinition56Enum(): return StringToEnum("Outputdefinition56")[0]
+def Outputdefinition57Enum(): return StringToEnum("Outputdefinition57")[0]
+def Outputdefinition58Enum(): return StringToEnum("Outputdefinition58")[0]
+def Outputdefinition59Enum(): return StringToEnum("Outputdefinition59")[0]
+def Outputdefinition60Enum(): return StringToEnum("Outputdefinition60")[0]
+def Outputdefinition61Enum(): return StringToEnum("Outputdefinition61")[0]
+def Outputdefinition62Enum(): return StringToEnum("Outputdefinition62")[0]
+def Outputdefinition63Enum(): return StringToEnum("Outputdefinition63")[0]
+def Outputdefinition64Enum(): return StringToEnum("Outputdefinition64")[0]
+def Outputdefinition65Enum(): return StringToEnum("Outputdefinition65")[0]
+def Outputdefinition66Enum(): return StringToEnum("Outputdefinition66")[0]
+def Outputdefinition67Enum(): return StringToEnum("Outputdefinition67")[0]
+def Outputdefinition68Enum(): return StringToEnum("Outputdefinition68")[0]
+def Outputdefinition69Enum(): return StringToEnum("Outputdefinition69")[0]
+def Outputdefinition70Enum(): return StringToEnum("Outputdefinition70")[0]
+def Outputdefinition71Enum(): return StringToEnum("Outputdefinition71")[0]
+def Outputdefinition72Enum(): return StringToEnum("Outputdefinition72")[0]
+def Outputdefinition73Enum(): return StringToEnum("Outputdefinition73")[0]
+def Outputdefinition74Enum(): return StringToEnum("Outputdefinition74")[0]
+def Outputdefinition75Enum(): return StringToEnum("Outputdefinition75")[0]
+def Outputdefinition76Enum(): return StringToEnum("Outputdefinition76")[0]
+def Outputdefinition77Enum(): return StringToEnum("Outputdefinition77")[0]
+def Outputdefinition78Enum(): return StringToEnum("Outputdefinition78")[0]
+def Outputdefinition79Enum(): return StringToEnum("Outputdefinition79")[0]
+def Outputdefinition80Enum(): return StringToEnum("Outputdefinition80")[0]
+def Outputdefinition81Enum(): return StringToEnum("Outputdefinition81")[0]
+def Outputdefinition82Enum(): return StringToEnum("Outputdefinition82")[0]
+def Outputdefinition83Enum(): return StringToEnum("Outputdefinition83")[0]
+def Outputdefinition84Enum(): return StringToEnum("Outputdefinition84")[0]
+def Outputdefinition85Enum(): return StringToEnum("Outputdefinition85")[0]
+def Outputdefinition86Enum(): return StringToEnum("Outputdefinition86")[0]
+def Outputdefinition87Enum(): return StringToEnum("Outputdefinition87")[0]
+def Outputdefinition88Enum(): return StringToEnum("Outputdefinition88")[0]
+def Outputdefinition89Enum(): return StringToEnum("Outputdefinition89")[0]
+def Outputdefinition90Enum(): return StringToEnum("Outputdefinition90")[0]
+def Outputdefinition91Enum(): return StringToEnum("Outputdefinition91")[0]
+def Outputdefinition92Enum(): return StringToEnum("Outputdefinition92")[0]
+def Outputdefinition93Enum(): return StringToEnum("Outputdefinition93")[0]
+def Outputdefinition94Enum(): return StringToEnum("Outputdefinition94")[0]
+def Outputdefinition95Enum(): return StringToEnum("Outputdefinition95")[0]
+def Outputdefinition96Enum(): return StringToEnum("Outputdefinition96")[0]
+def Outputdefinition97Enum(): return StringToEnum("Outputdefinition97")[0]
+def Outputdefinition98Enum(): return StringToEnum("Outputdefinition98")[0]
+def Outputdefinition99Enum(): return StringToEnum("Outputdefinition99")[0]
+def Outputdefinition100Enum(): return StringToEnum("Outputdefinition100")[0]
 def OutputdefinitionListEnum(): return StringToEnum("OutputdefinitionList")[0]
 def MassfluxatgateEnum(): return StringToEnum("Massfluxatgate")[0]
 def MassfluxatgateNameEnum(): return StringToEnum("MassfluxatgateName")[0]
+def MassfluxatgateDefinitionenumEnum(): return StringToEnum("MassfluxatgateDefinitionenum")[0]
 def MassfluxatgateSegmentsEnum(): return StringToEnum("MassfluxatgateSegments")[0]
 def MisfitNameEnum(): return StringToEnum("MisfitName")[0]
+def MisfitDefinitionenumEnum(): return StringToEnum("MisfitDefinitionenum")[0]
 def MisfitModelEnumEnum(): return StringToEnum("MisfitModelEnum")[0]
 def MisfitObservationEnum(): return StringToEnum("MisfitObservation")[0]
 def MisfitObservationEnumEnum(): return StringToEnum("MisfitObservationEnum")[0]
+def MisfitLocalEnum(): return StringToEnum("MisfitLocal")[0]
 def MisfitTimeinterpolationEnum(): return StringToEnum("MisfitTimeinterpolation")[0]
 def MisfitWeightsEnum(): return StringToEnum("MisfitWeights")[0]
@@ -624,4 +772,8 @@
 def SurfaceObservationEnum(): return StringToEnum("SurfaceObservation")[0]
 def WeightsSurfaceObservationEnum(): return StringToEnum("WeightsSurfaceObservation")[0]
+def VxObsEnum(): return StringToEnum("VxObs")[0]
+def WeightsVxObsEnum(): return StringToEnum("WeightsVxObs")[0]
+def VyObsEnum(): return StringToEnum("VyObs")[0]
+def WeightsVyObsEnum(): return StringToEnum("WeightsVyObs")[0]
 def MinVelEnum(): return StringToEnum("MinVel")[0]
 def MaxVelEnum(): return StringToEnum("MaxVel")[0]
@@ -635,4 +787,5 @@
 def MaxVzEnum(): return StringToEnum("MaxVz")[0]
 def MaxAbsVzEnum(): return StringToEnum("MaxAbsVz")[0]
+def IceMassEnum(): return StringToEnum("IceMass")[0]
 def IceVolumeEnum(): return StringToEnum("IceVolume")[0]
 def IceVolumeAboveFloatationEnum(): return StringToEnum("IceVolumeAboveFloatation")[0]
@@ -651,6 +804,6 @@
 def SubelementMigration2Enum(): return StringToEnum("SubelementMigration2")[0]
 def ContactEnum(): return StringToEnum("Contact")[0]
+def GroundingOnlyEnum(): return StringToEnum("GroundingOnly")[0]
 def MaskGroundediceLevelsetEnum(): return StringToEnum("MaskGroundediceLevelset")[0]
-def QmuMaskGroundediceLevelsetEnum(): return StringToEnum("QmuMaskGroundediceLevelset")[0]
 def GaussSegEnum(): return StringToEnum("GaussSeg")[0]
 def GaussTriaEnum(): return StringToEnum("GaussTria")[0]
@@ -674,5 +827,8 @@
 def OldGradientEnum(): return StringToEnum("OldGradient")[0]
 def OutputFilePointerEnum(): return StringToEnum("OutputFilePointer")[0]
+def ToolkitsFileNameEnum(): return StringToEnum("ToolkitsFileName")[0]
+def RootPathEnum(): return StringToEnum("RootPath")[0]
 def OutputFileNameEnum(): return StringToEnum("OutputFileName")[0]
+def InputFileNameEnum(): return StringToEnum("InputFileName")[0]
 def LockFileNameEnum(): return StringToEnum("LockFileName")[0]
 def ToolkitsOptionsAnalysesEnum(): return StringToEnum("ToolkitsOptionsAnalyses")[0]
Index: /issm/trunk/src/m/enum/EplZigZagCounterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/EplZigZagCounterEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/EplZigZagCounterEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=EplZigZagCounterEnum()
+%EPLZIGZAGCOUNTERENUM - Enum of EplZigZagCounter
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=EplZigZagCounterEnum()
+
+macro=StringToEnum('EplZigZagCounter');
Index: /issm/trunk/src/m/enum/FrictionAsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FrictionAsEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/FrictionAsEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=FrictionAsEnum()
+%FRICTIONASENUM - Enum of FrictionAs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FrictionAsEnum()
+
+macro=StringToEnum('FrictionAs');
Index: /issm/trunk/src/m/enum/FrictionEffectivePressureEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FrictionEffectivePressureEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/FrictionEffectivePressureEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=FrictionEffectivePressureEnum()
+%FRICTIONEFFECTIVEPRESSUREENUM - Enum of FrictionEffectivePressure
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FrictionEffectivePressureEnum()
+
+macro=StringToEnum('FrictionEffectivePressure');
Index: /issm/trunk/src/m/enum/FrictionGammaEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FrictionGammaEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/FrictionGammaEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=FrictionGammaEnum()
+%FRICTIONGAMMAENUM - Enum of FrictionGamma
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FrictionGammaEnum()
+
+macro=StringToEnum('FrictionGamma');
Index: /issm/trunk/src/m/enum/FrictionWaterLayerEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FrictionWaterLayerEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/FrictionWaterLayerEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=FrictionWaterLayerEnum()
+%FRICTIONWATERLAYERENUM - Enum of FrictionWaterLayer
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=FrictionWaterLayerEnum()
+
+macro=StringToEnum('FrictionWaterLayer');
Index: /issm/trunk/src/m/enum/GroundingOnlyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GroundingOnlyEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/GroundingOnlyEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=GroundingOnlyEnum()
+%GROUNDINGONLYENUM - Enum of GroundingOnly
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=GroundingOnlyEnum()
+
+macro=StringToEnum('GroundingOnly');
Index: /issm/trunk/src/m/enum/HydrologydcEplColapseThicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcEplColapseThicknessEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/HydrologydcEplColapseThicknessEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=HydrologydcEplColapseThicknessEnum()
+%HYDROLOGYDCEPLCOLAPSETHICKNESSENUM - Enum of HydrologydcEplColapseThickness
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcEplColapseThicknessEnum()
+
+macro=StringToEnum('HydrologydcEplColapseThickness');
Index: /issm/trunk/src/m/enum/HydrologydcEplThickCompEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcEplThickCompEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/HydrologydcEplThickCompEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=HydrologydcEplThickCompEnum()
+%HYDROLOGYDCEPLTHICKCOMPENUM - Enum of HydrologydcEplThickComp
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcEplThickCompEnum()
+
+macro=StringToEnum('HydrologydcEplThickComp');
Index: /issm/trunk/src/m/enum/HydrologydcEplflipLockEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HydrologydcEplflipLockEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/HydrologydcEplflipLockEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=HydrologydcEplflipLockEnum()
+%HYDROLOGYDCEPLFLIPLOCKENUM - Enum of HydrologydcEplflipLock
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=HydrologydcEplflipLockEnum()
+
+macro=StringToEnum('HydrologydcEplflipLock');
Index: /issm/trunk/src/m/enum/IceMassEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IceMassEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/IceMassEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=IceMassEnum()
+%ICEMASSENUM - Enum of IceMass
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=IceMassEnum()
+
+macro=StringToEnum('IceMass');
Index: /issm/trunk/src/m/enum/InputFileNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InputFileNameEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/InputFileNameEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=InputFileNameEnum()
+%INPUTFILENAMEENUM - Enum of InputFileName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InputFileNameEnum()
+
+macro=StringToEnum('InputFileName');
Index: /issm/trunk/src/m/enum/InputToSmoothEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InputToSmoothEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/InputToSmoothEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=InputToSmoothEnum()
+%INPUTTOSMOOTHENUM - Enum of InputToSmooth
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InputToSmoothEnum()
+
+macro=StringToEnum('InputToSmooth');
Index: /issm/trunk/src/m/enum/InversionControlScalingFactorsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionControlScalingFactorsEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/InversionControlScalingFactorsEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=InversionControlScalingFactorsEnum()
+%INVERSIONCONTROLSCALINGFACTORSENUM - Enum of InversionControlScalingFactors
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionControlScalingFactorsEnum()
+
+macro=StringToEnum('InversionControlScalingFactors');
Index: /issm/trunk/src/m/enum/InversionSurfaceObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/InversionSurfaceObsEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/InversionSurfaceObsEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=InversionSurfaceObsEnum()
+%INVERSIONSURFACEOBSENUM - Enum of InversionSurfaceObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=InversionSurfaceObsEnum()
+
+macro=StringToEnum('InversionSurfaceObs');
Index: /issm/trunk/src/m/enum/LACrouzeixRaviartEnum.m
===================================================================
--- /issm/trunk/src/m/enum/LACrouzeixRaviartEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/LACrouzeixRaviartEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=LACrouzeixRaviartEnum()
+%LACROUZEIXRAVIARTENUM - Enum of LACrouzeixRaviart
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LACrouzeixRaviartEnum()
+
+macro=StringToEnum('LACrouzeixRaviart');
Index: /issm/trunk/src/m/enum/LevelsetStabilizationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/LevelsetStabilizationEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/LevelsetStabilizationEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=LevelsetStabilizationEnum()
+%LEVELSETSTABILIZATIONENUM - Enum of LevelsetStabilization
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=LevelsetStabilizationEnum()
+
+macro=StringToEnum('LevelsetStabilization');
Index: /issm/trunk/src/m/enum/MassconDefinitionenumEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassconDefinitionenumEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassconDefinitionenumEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassconDefinitionenumEnum()
+%MASSCONDEFINITIONENUMENUM - Enum of MassconDefinitionenum
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassconDefinitionenumEnum()
+
+macro=StringToEnum('MassconDefinitionenum');
Index: /issm/trunk/src/m/enum/MassconEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassconEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassconEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassconEnum()
+%MASSCONENUM - Enum of Masscon
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassconEnum()
+
+macro=StringToEnum('Masscon');
Index: /issm/trunk/src/m/enum/MassconLevelsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassconLevelsetEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassconLevelsetEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassconLevelsetEnum()
+%MASSCONLEVELSETENUM - Enum of MassconLevelset
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassconLevelsetEnum()
+
+macro=StringToEnum('MassconLevelset');
Index: /issm/trunk/src/m/enum/MassconNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassconNameEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassconNameEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassconNameEnum()
+%MASSCONNAMEENUM - Enum of MassconName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassconNameEnum()
+
+macro=StringToEnum('MassconName');
Index: /issm/trunk/src/m/enum/MassconaxpbyAlphaEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassconaxpbyAlphaEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassconaxpbyAlphaEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassconaxpbyAlphaEnum()
+%MASSCONAXPBYALPHAENUM - Enum of MassconaxpbyAlpha
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassconaxpbyAlphaEnum()
+
+macro=StringToEnum('MassconaxpbyAlpha');
Index: /issm/trunk/src/m/enum/MassconaxpbyBetaEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassconaxpbyBetaEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassconaxpbyBetaEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassconaxpbyBetaEnum()
+%MASSCONAXPBYBETAENUM - Enum of MassconaxpbyBeta
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassconaxpbyBetaEnum()
+
+macro=StringToEnum('MassconaxpbyBeta');
Index: /issm/trunk/src/m/enum/MassconaxpbyDefinitionenumEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassconaxpbyDefinitionenumEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassconaxpbyDefinitionenumEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassconaxpbyDefinitionenumEnum()
+%MASSCONAXPBYDEFINITIONENUMENUM - Enum of MassconaxpbyDefinitionenum
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassconaxpbyDefinitionenumEnum()
+
+macro=StringToEnum('MassconaxpbyDefinitionenum');
Index: /issm/trunk/src/m/enum/MassconaxpbyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassconaxpbyEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassconaxpbyEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassconaxpbyEnum()
+%MASSCONAXPBYENUM - Enum of Massconaxpby
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassconaxpbyEnum()
+
+macro=StringToEnum('Massconaxpby');
Index: /issm/trunk/src/m/enum/MassconaxpbyNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassconaxpbyNameEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassconaxpbyNameEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassconaxpbyNameEnum()
+%MASSCONAXPBYNAMEENUM - Enum of MassconaxpbyName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassconaxpbyNameEnum()
+
+macro=StringToEnum('MassconaxpbyName');
Index: /issm/trunk/src/m/enum/MassconaxpbyNamexEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassconaxpbyNamexEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassconaxpbyNamexEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassconaxpbyNamexEnum()
+%MASSCONAXPBYNAMEXENUM - Enum of MassconaxpbyNamex
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassconaxpbyNamexEnum()
+
+macro=StringToEnum('MassconaxpbyNamex');
Index: /issm/trunk/src/m/enum/MassconaxpbyNameyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassconaxpbyNameyEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassconaxpbyNameyEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassconaxpbyNameyEnum()
+%MASSCONAXPBYNAMEYENUM - Enum of MassconaxpbyNamey
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassconaxpbyNameyEnum()
+
+macro=StringToEnum('MassconaxpbyNamey');
Index: /issm/trunk/src/m/enum/MassfluxatgateDefinitionenumEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassfluxatgateDefinitionenumEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MassfluxatgateDefinitionenumEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MassfluxatgateDefinitionenumEnum()
+%MASSFLUXATGATEDEFINITIONENUMENUM - Enum of MassfluxatgateDefinitionenum
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MassfluxatgateDefinitionenumEnum()
+
+macro=StringToEnum('MassfluxatgateDefinitionenum');
Index: sm/trunk/src/m/enum/MasstransportCalvingrateEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportCalvingrateEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MasstransportCalvingrateEnum()
-%MASSTRANSPORTCALVINGRATEENUM - Enum of MasstransportCalvingrate
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=MasstransportCalvingrateEnum()
-
-macro=StringToEnum('MasstransportCalvingrate');
Index: /issm/trunk/src/m/enum/MaxDivergenceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaxDivergenceEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MaxDivergenceEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MaxDivergenceEnum()
+%MAXDIVERGENCEENUM - Enum of MaxDivergence
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MaxDivergenceEnum()
+
+macro=StringToEnum('MaxDivergence');
Index: /issm/trunk/src/m/enum/MisfitDefinitionenumEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MisfitDefinitionenumEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MisfitDefinitionenumEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MisfitDefinitionenumEnum()
+%MISFITDEFINITIONENUMENUM - Enum of MisfitDefinitionenum
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MisfitDefinitionenumEnum()
+
+macro=StringToEnum('MisfitDefinitionenum');
Index: /issm/trunk/src/m/enum/MisfitLocalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MisfitLocalEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/MisfitLocalEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=MisfitLocalEnum()
+%MISFITLOCALENUM - Enum of MisfitLocal
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=MisfitLocalEnum()
+
+macro=StringToEnum('MisfitLocal');
Index: /issm/trunk/src/m/enum/Outputdefinition100Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition100Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition100Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition100Enum()
+%OUTPUTDEFINITION100ENUM - Enum of Outputdefinition100
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition100Enum()
+
+macro=StringToEnum('Outputdefinition100');
Index: /issm/trunk/src/m/enum/Outputdefinition10Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition10Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition10Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition10Enum()
+%OUTPUTDEFINITION10ENUM - Enum of Outputdefinition10
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition10Enum()
+
+macro=StringToEnum('Outputdefinition10');
Index: /issm/trunk/src/m/enum/Outputdefinition11Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition11Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition11Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition11Enum()
+%OUTPUTDEFINITION11ENUM - Enum of Outputdefinition11
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition11Enum()
+
+macro=StringToEnum('Outputdefinition11');
Index: /issm/trunk/src/m/enum/Outputdefinition12Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition12Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition12Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition12Enum()
+%OUTPUTDEFINITION12ENUM - Enum of Outputdefinition12
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition12Enum()
+
+macro=StringToEnum('Outputdefinition12');
Index: /issm/trunk/src/m/enum/Outputdefinition13Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition13Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition13Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition13Enum()
+%OUTPUTDEFINITION13ENUM - Enum of Outputdefinition13
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition13Enum()
+
+macro=StringToEnum('Outputdefinition13');
Index: /issm/trunk/src/m/enum/Outputdefinition14Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition14Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition14Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition14Enum()
+%OUTPUTDEFINITION14ENUM - Enum of Outputdefinition14
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition14Enum()
+
+macro=StringToEnum('Outputdefinition14');
Index: /issm/trunk/src/m/enum/Outputdefinition15Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition15Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition15Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition15Enum()
+%OUTPUTDEFINITION15ENUM - Enum of Outputdefinition15
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition15Enum()
+
+macro=StringToEnum('Outputdefinition15');
Index: /issm/trunk/src/m/enum/Outputdefinition16Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition16Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition16Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition16Enum()
+%OUTPUTDEFINITION16ENUM - Enum of Outputdefinition16
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition16Enum()
+
+macro=StringToEnum('Outputdefinition16');
Index: /issm/trunk/src/m/enum/Outputdefinition17Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition17Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition17Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition17Enum()
+%OUTPUTDEFINITION17ENUM - Enum of Outputdefinition17
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition17Enum()
+
+macro=StringToEnum('Outputdefinition17');
Index: /issm/trunk/src/m/enum/Outputdefinition18Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition18Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition18Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition18Enum()
+%OUTPUTDEFINITION18ENUM - Enum of Outputdefinition18
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition18Enum()
+
+macro=StringToEnum('Outputdefinition18');
Index: /issm/trunk/src/m/enum/Outputdefinition19Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition19Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition19Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition19Enum()
+%OUTPUTDEFINITION19ENUM - Enum of Outputdefinition19
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition19Enum()
+
+macro=StringToEnum('Outputdefinition19');
Index: /issm/trunk/src/m/enum/Outputdefinition1Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition1Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition1Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition1Enum()
+%OUTPUTDEFINITION1ENUM - Enum of Outputdefinition1
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition1Enum()
+
+macro=StringToEnum('Outputdefinition1');
Index: /issm/trunk/src/m/enum/Outputdefinition20Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition20Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition20Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition20Enum()
+%OUTPUTDEFINITION20ENUM - Enum of Outputdefinition20
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition20Enum()
+
+macro=StringToEnum('Outputdefinition20');
Index: /issm/trunk/src/m/enum/Outputdefinition21Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition21Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition21Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition21Enum()
+%OUTPUTDEFINITION21ENUM - Enum of Outputdefinition21
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition21Enum()
+
+macro=StringToEnum('Outputdefinition21');
Index: /issm/trunk/src/m/enum/Outputdefinition22Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition22Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition22Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition22Enum()
+%OUTPUTDEFINITION22ENUM - Enum of Outputdefinition22
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition22Enum()
+
+macro=StringToEnum('Outputdefinition22');
Index: /issm/trunk/src/m/enum/Outputdefinition23Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition23Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition23Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition23Enum()
+%OUTPUTDEFINITION23ENUM - Enum of Outputdefinition23
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition23Enum()
+
+macro=StringToEnum('Outputdefinition23');
Index: /issm/trunk/src/m/enum/Outputdefinition24Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition24Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition24Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition24Enum()
+%OUTPUTDEFINITION24ENUM - Enum of Outputdefinition24
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition24Enum()
+
+macro=StringToEnum('Outputdefinition24');
Index: /issm/trunk/src/m/enum/Outputdefinition25Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition25Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition25Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition25Enum()
+%OUTPUTDEFINITION25ENUM - Enum of Outputdefinition25
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition25Enum()
+
+macro=StringToEnum('Outputdefinition25');
Index: /issm/trunk/src/m/enum/Outputdefinition26Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition26Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition26Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition26Enum()
+%OUTPUTDEFINITION26ENUM - Enum of Outputdefinition26
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition26Enum()
+
+macro=StringToEnum('Outputdefinition26');
Index: /issm/trunk/src/m/enum/Outputdefinition27Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition27Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition27Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition27Enum()
+%OUTPUTDEFINITION27ENUM - Enum of Outputdefinition27
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition27Enum()
+
+macro=StringToEnum('Outputdefinition27');
Index: /issm/trunk/src/m/enum/Outputdefinition28Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition28Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition28Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition28Enum()
+%OUTPUTDEFINITION28ENUM - Enum of Outputdefinition28
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition28Enum()
+
+macro=StringToEnum('Outputdefinition28');
Index: /issm/trunk/src/m/enum/Outputdefinition29Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition29Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition29Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition29Enum()
+%OUTPUTDEFINITION29ENUM - Enum of Outputdefinition29
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition29Enum()
+
+macro=StringToEnum('Outputdefinition29');
Index: /issm/trunk/src/m/enum/Outputdefinition2Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition2Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition2Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition2Enum()
+%OUTPUTDEFINITION2ENUM - Enum of Outputdefinition2
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition2Enum()
+
+macro=StringToEnum('Outputdefinition2');
Index: /issm/trunk/src/m/enum/Outputdefinition30Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition30Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition30Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition30Enum()
+%OUTPUTDEFINITION30ENUM - Enum of Outputdefinition30
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition30Enum()
+
+macro=StringToEnum('Outputdefinition30');
Index: /issm/trunk/src/m/enum/Outputdefinition31Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition31Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition31Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition31Enum()
+%OUTPUTDEFINITION31ENUM - Enum of Outputdefinition31
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition31Enum()
+
+macro=StringToEnum('Outputdefinition31');
Index: /issm/trunk/src/m/enum/Outputdefinition32Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition32Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition32Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition32Enum()
+%OUTPUTDEFINITION32ENUM - Enum of Outputdefinition32
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition32Enum()
+
+macro=StringToEnum('Outputdefinition32');
Index: /issm/trunk/src/m/enum/Outputdefinition33Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition33Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition33Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition33Enum()
+%OUTPUTDEFINITION33ENUM - Enum of Outputdefinition33
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition33Enum()
+
+macro=StringToEnum('Outputdefinition33');
Index: /issm/trunk/src/m/enum/Outputdefinition34Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition34Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition34Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition34Enum()
+%OUTPUTDEFINITION34ENUM - Enum of Outputdefinition34
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition34Enum()
+
+macro=StringToEnum('Outputdefinition34');
Index: /issm/trunk/src/m/enum/Outputdefinition35Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition35Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition35Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition35Enum()
+%OUTPUTDEFINITION35ENUM - Enum of Outputdefinition35
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition35Enum()
+
+macro=StringToEnum('Outputdefinition35');
Index: /issm/trunk/src/m/enum/Outputdefinition36Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition36Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition36Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition36Enum()
+%OUTPUTDEFINITION36ENUM - Enum of Outputdefinition36
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition36Enum()
+
+macro=StringToEnum('Outputdefinition36');
Index: /issm/trunk/src/m/enum/Outputdefinition37Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition37Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition37Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition37Enum()
+%OUTPUTDEFINITION37ENUM - Enum of Outputdefinition37
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition37Enum()
+
+macro=StringToEnum('Outputdefinition37');
Index: /issm/trunk/src/m/enum/Outputdefinition38Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition38Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition38Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition38Enum()
+%OUTPUTDEFINITION38ENUM - Enum of Outputdefinition38
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition38Enum()
+
+macro=StringToEnum('Outputdefinition38');
Index: /issm/trunk/src/m/enum/Outputdefinition39Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition39Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition39Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition39Enum()
+%OUTPUTDEFINITION39ENUM - Enum of Outputdefinition39
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition39Enum()
+
+macro=StringToEnum('Outputdefinition39');
Index: /issm/trunk/src/m/enum/Outputdefinition3Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition3Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition3Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition3Enum()
+%OUTPUTDEFINITION3ENUM - Enum of Outputdefinition3
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition3Enum()
+
+macro=StringToEnum('Outputdefinition3');
Index: /issm/trunk/src/m/enum/Outputdefinition40Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition40Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition40Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition40Enum()
+%OUTPUTDEFINITION40ENUM - Enum of Outputdefinition40
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition40Enum()
+
+macro=StringToEnum('Outputdefinition40');
Index: /issm/trunk/src/m/enum/Outputdefinition41Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition41Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition41Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition41Enum()
+%OUTPUTDEFINITION41ENUM - Enum of Outputdefinition41
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition41Enum()
+
+macro=StringToEnum('Outputdefinition41');
Index: /issm/trunk/src/m/enum/Outputdefinition42Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition42Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition42Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition42Enum()
+%OUTPUTDEFINITION42ENUM - Enum of Outputdefinition42
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition42Enum()
+
+macro=StringToEnum('Outputdefinition42');
Index: /issm/trunk/src/m/enum/Outputdefinition43Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition43Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition43Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition43Enum()
+%OUTPUTDEFINITION43ENUM - Enum of Outputdefinition43
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition43Enum()
+
+macro=StringToEnum('Outputdefinition43');
Index: /issm/trunk/src/m/enum/Outputdefinition44Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition44Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition44Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition44Enum()
+%OUTPUTDEFINITION44ENUM - Enum of Outputdefinition44
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition44Enum()
+
+macro=StringToEnum('Outputdefinition44');
Index: /issm/trunk/src/m/enum/Outputdefinition45Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition45Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition45Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition45Enum()
+%OUTPUTDEFINITION45ENUM - Enum of Outputdefinition45
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition45Enum()
+
+macro=StringToEnum('Outputdefinition45');
Index: /issm/trunk/src/m/enum/Outputdefinition46Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition46Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition46Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition46Enum()
+%OUTPUTDEFINITION46ENUM - Enum of Outputdefinition46
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition46Enum()
+
+macro=StringToEnum('Outputdefinition46');
Index: /issm/trunk/src/m/enum/Outputdefinition47Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition47Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition47Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition47Enum()
+%OUTPUTDEFINITION47ENUM - Enum of Outputdefinition47
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition47Enum()
+
+macro=StringToEnum('Outputdefinition47');
Index: /issm/trunk/src/m/enum/Outputdefinition48Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition48Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition48Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition48Enum()
+%OUTPUTDEFINITION48ENUM - Enum of Outputdefinition48
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition48Enum()
+
+macro=StringToEnum('Outputdefinition48');
Index: /issm/trunk/src/m/enum/Outputdefinition49Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition49Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition49Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition49Enum()
+%OUTPUTDEFINITION49ENUM - Enum of Outputdefinition49
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition49Enum()
+
+macro=StringToEnum('Outputdefinition49');
Index: /issm/trunk/src/m/enum/Outputdefinition4Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition4Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition4Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition4Enum()
+%OUTPUTDEFINITION4ENUM - Enum of Outputdefinition4
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition4Enum()
+
+macro=StringToEnum('Outputdefinition4');
Index: /issm/trunk/src/m/enum/Outputdefinition50Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition50Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition50Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition50Enum()
+%OUTPUTDEFINITION50ENUM - Enum of Outputdefinition50
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition50Enum()
+
+macro=StringToEnum('Outputdefinition50');
Index: /issm/trunk/src/m/enum/Outputdefinition51Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition51Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition51Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition51Enum()
+%OUTPUTDEFINITION51ENUM - Enum of Outputdefinition51
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition51Enum()
+
+macro=StringToEnum('Outputdefinition51');
Index: /issm/trunk/src/m/enum/Outputdefinition52Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition52Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition52Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition52Enum()
+%OUTPUTDEFINITION52ENUM - Enum of Outputdefinition52
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition52Enum()
+
+macro=StringToEnum('Outputdefinition52');
Index: /issm/trunk/src/m/enum/Outputdefinition53Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition53Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition53Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition53Enum()
+%OUTPUTDEFINITION53ENUM - Enum of Outputdefinition53
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition53Enum()
+
+macro=StringToEnum('Outputdefinition53');
Index: /issm/trunk/src/m/enum/Outputdefinition54Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition54Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition54Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition54Enum()
+%OUTPUTDEFINITION54ENUM - Enum of Outputdefinition54
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition54Enum()
+
+macro=StringToEnum('Outputdefinition54');
Index: /issm/trunk/src/m/enum/Outputdefinition55Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition55Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition55Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition55Enum()
+%OUTPUTDEFINITION55ENUM - Enum of Outputdefinition55
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition55Enum()
+
+macro=StringToEnum('Outputdefinition55');
Index: /issm/trunk/src/m/enum/Outputdefinition56Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition56Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition56Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition56Enum()
+%OUTPUTDEFINITION56ENUM - Enum of Outputdefinition56
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition56Enum()
+
+macro=StringToEnum('Outputdefinition56');
Index: /issm/trunk/src/m/enum/Outputdefinition57Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition57Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition57Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition57Enum()
+%OUTPUTDEFINITION57ENUM - Enum of Outputdefinition57
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition57Enum()
+
+macro=StringToEnum('Outputdefinition57');
Index: /issm/trunk/src/m/enum/Outputdefinition58Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition58Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition58Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition58Enum()
+%OUTPUTDEFINITION58ENUM - Enum of Outputdefinition58
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition58Enum()
+
+macro=StringToEnum('Outputdefinition58');
Index: /issm/trunk/src/m/enum/Outputdefinition59Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition59Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition59Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition59Enum()
+%OUTPUTDEFINITION59ENUM - Enum of Outputdefinition59
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition59Enum()
+
+macro=StringToEnum('Outputdefinition59');
Index: /issm/trunk/src/m/enum/Outputdefinition5Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition5Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition5Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition5Enum()
+%OUTPUTDEFINITION5ENUM - Enum of Outputdefinition5
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition5Enum()
+
+macro=StringToEnum('Outputdefinition5');
Index: /issm/trunk/src/m/enum/Outputdefinition60Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition60Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition60Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition60Enum()
+%OUTPUTDEFINITION60ENUM - Enum of Outputdefinition60
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition60Enum()
+
+macro=StringToEnum('Outputdefinition60');
Index: /issm/trunk/src/m/enum/Outputdefinition61Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition61Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition61Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition61Enum()
+%OUTPUTDEFINITION61ENUM - Enum of Outputdefinition61
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition61Enum()
+
+macro=StringToEnum('Outputdefinition61');
Index: /issm/trunk/src/m/enum/Outputdefinition62Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition62Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition62Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition62Enum()
+%OUTPUTDEFINITION62ENUM - Enum of Outputdefinition62
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition62Enum()
+
+macro=StringToEnum('Outputdefinition62');
Index: /issm/trunk/src/m/enum/Outputdefinition63Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition63Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition63Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition63Enum()
+%OUTPUTDEFINITION63ENUM - Enum of Outputdefinition63
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition63Enum()
+
+macro=StringToEnum('Outputdefinition63');
Index: /issm/trunk/src/m/enum/Outputdefinition64Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition64Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition64Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition64Enum()
+%OUTPUTDEFINITION64ENUM - Enum of Outputdefinition64
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition64Enum()
+
+macro=StringToEnum('Outputdefinition64');
Index: /issm/trunk/src/m/enum/Outputdefinition65Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition65Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition65Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition65Enum()
+%OUTPUTDEFINITION65ENUM - Enum of Outputdefinition65
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition65Enum()
+
+macro=StringToEnum('Outputdefinition65');
Index: /issm/trunk/src/m/enum/Outputdefinition66Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition66Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition66Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition66Enum()
+%OUTPUTDEFINITION66ENUM - Enum of Outputdefinition66
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition66Enum()
+
+macro=StringToEnum('Outputdefinition66');
Index: /issm/trunk/src/m/enum/Outputdefinition67Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition67Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition67Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition67Enum()
+%OUTPUTDEFINITION67ENUM - Enum of Outputdefinition67
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition67Enum()
+
+macro=StringToEnum('Outputdefinition67');
Index: /issm/trunk/src/m/enum/Outputdefinition68Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition68Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition68Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition68Enum()
+%OUTPUTDEFINITION68ENUM - Enum of Outputdefinition68
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition68Enum()
+
+macro=StringToEnum('Outputdefinition68');
Index: /issm/trunk/src/m/enum/Outputdefinition69Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition69Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition69Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition69Enum()
+%OUTPUTDEFINITION69ENUM - Enum of Outputdefinition69
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition69Enum()
+
+macro=StringToEnum('Outputdefinition69');
Index: /issm/trunk/src/m/enum/Outputdefinition6Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition6Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition6Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition6Enum()
+%OUTPUTDEFINITION6ENUM - Enum of Outputdefinition6
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition6Enum()
+
+macro=StringToEnum('Outputdefinition6');
Index: /issm/trunk/src/m/enum/Outputdefinition70Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition70Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition70Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition70Enum()
+%OUTPUTDEFINITION70ENUM - Enum of Outputdefinition70
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition70Enum()
+
+macro=StringToEnum('Outputdefinition70');
Index: /issm/trunk/src/m/enum/Outputdefinition71Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition71Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition71Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition71Enum()
+%OUTPUTDEFINITION71ENUM - Enum of Outputdefinition71
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition71Enum()
+
+macro=StringToEnum('Outputdefinition71');
Index: /issm/trunk/src/m/enum/Outputdefinition72Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition72Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition72Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition72Enum()
+%OUTPUTDEFINITION72ENUM - Enum of Outputdefinition72
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition72Enum()
+
+macro=StringToEnum('Outputdefinition72');
Index: /issm/trunk/src/m/enum/Outputdefinition73Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition73Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition73Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition73Enum()
+%OUTPUTDEFINITION73ENUM - Enum of Outputdefinition73
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition73Enum()
+
+macro=StringToEnum('Outputdefinition73');
Index: /issm/trunk/src/m/enum/Outputdefinition74Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition74Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition74Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition74Enum()
+%OUTPUTDEFINITION74ENUM - Enum of Outputdefinition74
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition74Enum()
+
+macro=StringToEnum('Outputdefinition74');
Index: /issm/trunk/src/m/enum/Outputdefinition75Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition75Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition75Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition75Enum()
+%OUTPUTDEFINITION75ENUM - Enum of Outputdefinition75
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition75Enum()
+
+macro=StringToEnum('Outputdefinition75');
Index: /issm/trunk/src/m/enum/Outputdefinition76Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition76Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition76Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition76Enum()
+%OUTPUTDEFINITION76ENUM - Enum of Outputdefinition76
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition76Enum()
+
+macro=StringToEnum('Outputdefinition76');
Index: /issm/trunk/src/m/enum/Outputdefinition77Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition77Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition77Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition77Enum()
+%OUTPUTDEFINITION77ENUM - Enum of Outputdefinition77
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition77Enum()
+
+macro=StringToEnum('Outputdefinition77');
Index: /issm/trunk/src/m/enum/Outputdefinition78Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition78Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition78Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition78Enum()
+%OUTPUTDEFINITION78ENUM - Enum of Outputdefinition78
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition78Enum()
+
+macro=StringToEnum('Outputdefinition78');
Index: /issm/trunk/src/m/enum/Outputdefinition79Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition79Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition79Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition79Enum()
+%OUTPUTDEFINITION79ENUM - Enum of Outputdefinition79
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition79Enum()
+
+macro=StringToEnum('Outputdefinition79');
Index: /issm/trunk/src/m/enum/Outputdefinition7Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition7Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition7Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition7Enum()
+%OUTPUTDEFINITION7ENUM - Enum of Outputdefinition7
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition7Enum()
+
+macro=StringToEnum('Outputdefinition7');
Index: /issm/trunk/src/m/enum/Outputdefinition80Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition80Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition80Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition80Enum()
+%OUTPUTDEFINITION80ENUM - Enum of Outputdefinition80
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition80Enum()
+
+macro=StringToEnum('Outputdefinition80');
Index: /issm/trunk/src/m/enum/Outputdefinition81Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition81Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition81Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition81Enum()
+%OUTPUTDEFINITION81ENUM - Enum of Outputdefinition81
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition81Enum()
+
+macro=StringToEnum('Outputdefinition81');
Index: /issm/trunk/src/m/enum/Outputdefinition82Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition82Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition82Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition82Enum()
+%OUTPUTDEFINITION82ENUM - Enum of Outputdefinition82
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition82Enum()
+
+macro=StringToEnum('Outputdefinition82');
Index: /issm/trunk/src/m/enum/Outputdefinition83Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition83Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition83Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition83Enum()
+%OUTPUTDEFINITION83ENUM - Enum of Outputdefinition83
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition83Enum()
+
+macro=StringToEnum('Outputdefinition83');
Index: /issm/trunk/src/m/enum/Outputdefinition84Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition84Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition84Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition84Enum()
+%OUTPUTDEFINITION84ENUM - Enum of Outputdefinition84
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition84Enum()
+
+macro=StringToEnum('Outputdefinition84');
Index: /issm/trunk/src/m/enum/Outputdefinition85Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition85Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition85Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition85Enum()
+%OUTPUTDEFINITION85ENUM - Enum of Outputdefinition85
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition85Enum()
+
+macro=StringToEnum('Outputdefinition85');
Index: /issm/trunk/src/m/enum/Outputdefinition86Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition86Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition86Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition86Enum()
+%OUTPUTDEFINITION86ENUM - Enum of Outputdefinition86
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition86Enum()
+
+macro=StringToEnum('Outputdefinition86');
Index: /issm/trunk/src/m/enum/Outputdefinition87Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition87Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition87Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition87Enum()
+%OUTPUTDEFINITION87ENUM - Enum of Outputdefinition87
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition87Enum()
+
+macro=StringToEnum('Outputdefinition87');
Index: /issm/trunk/src/m/enum/Outputdefinition88Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition88Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition88Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition88Enum()
+%OUTPUTDEFINITION88ENUM - Enum of Outputdefinition88
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition88Enum()
+
+macro=StringToEnum('Outputdefinition88');
Index: /issm/trunk/src/m/enum/Outputdefinition89Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition89Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition89Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition89Enum()
+%OUTPUTDEFINITION89ENUM - Enum of Outputdefinition89
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition89Enum()
+
+macro=StringToEnum('Outputdefinition89');
Index: /issm/trunk/src/m/enum/Outputdefinition8Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition8Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition8Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition8Enum()
+%OUTPUTDEFINITION8ENUM - Enum of Outputdefinition8
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition8Enum()
+
+macro=StringToEnum('Outputdefinition8');
Index: /issm/trunk/src/m/enum/Outputdefinition90Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition90Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition90Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition90Enum()
+%OUTPUTDEFINITION90ENUM - Enum of Outputdefinition90
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition90Enum()
+
+macro=StringToEnum('Outputdefinition90');
Index: /issm/trunk/src/m/enum/Outputdefinition91Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition91Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition91Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition91Enum()
+%OUTPUTDEFINITION91ENUM - Enum of Outputdefinition91
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition91Enum()
+
+macro=StringToEnum('Outputdefinition91');
Index: /issm/trunk/src/m/enum/Outputdefinition92Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition92Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition92Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition92Enum()
+%OUTPUTDEFINITION92ENUM - Enum of Outputdefinition92
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition92Enum()
+
+macro=StringToEnum('Outputdefinition92');
Index: /issm/trunk/src/m/enum/Outputdefinition93Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition93Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition93Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition93Enum()
+%OUTPUTDEFINITION93ENUM - Enum of Outputdefinition93
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition93Enum()
+
+macro=StringToEnum('Outputdefinition93');
Index: /issm/trunk/src/m/enum/Outputdefinition94Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition94Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition94Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition94Enum()
+%OUTPUTDEFINITION94ENUM - Enum of Outputdefinition94
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition94Enum()
+
+macro=StringToEnum('Outputdefinition94');
Index: /issm/trunk/src/m/enum/Outputdefinition95Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition95Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition95Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition95Enum()
+%OUTPUTDEFINITION95ENUM - Enum of Outputdefinition95
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition95Enum()
+
+macro=StringToEnum('Outputdefinition95');
Index: /issm/trunk/src/m/enum/Outputdefinition96Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition96Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition96Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition96Enum()
+%OUTPUTDEFINITION96ENUM - Enum of Outputdefinition96
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition96Enum()
+
+macro=StringToEnum('Outputdefinition96');
Index: /issm/trunk/src/m/enum/Outputdefinition97Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition97Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition97Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition97Enum()
+%OUTPUTDEFINITION97ENUM - Enum of Outputdefinition97
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition97Enum()
+
+macro=StringToEnum('Outputdefinition97');
Index: /issm/trunk/src/m/enum/Outputdefinition98Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition98Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition98Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition98Enum()
+%OUTPUTDEFINITION98ENUM - Enum of Outputdefinition98
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition98Enum()
+
+macro=StringToEnum('Outputdefinition98');
Index: /issm/trunk/src/m/enum/Outputdefinition99Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition99Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition99Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition99Enum()
+%OUTPUTDEFINITION99ENUM - Enum of Outputdefinition99
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition99Enum()
+
+macro=StringToEnum('Outputdefinition99');
Index: /issm/trunk/src/m/enum/Outputdefinition9Enum.m
===================================================================
--- /issm/trunk/src/m/enum/Outputdefinition9Enum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/Outputdefinition9Enum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=Outputdefinition9Enum()
+%OUTPUTDEFINITION9ENUM - Enum of Outputdefinition9
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=Outputdefinition9Enum()
+
+macro=StringToEnum('Outputdefinition9');
Index: sm/trunk/src/m/enum/QmuBaseEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuBaseEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuBaseEnum()
-%QMUBASEENUM - Enum of QmuBase
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuBaseEnum()
-
-macro=StringToEnum('QmuBase');
Index: sm/trunk/src/m/enum/QmuDamageDEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuDamageDEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuDamageDEnum()
-%QMUDAMAGEDENUM - Enum of QmuDamageD
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuDamageDEnum()
-
-macro=StringToEnum('QmuDamageD');
Index: sm/trunk/src/m/enum/QmuMaskGroundediceLevelsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuMaskGroundediceLevelsetEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuMaskGroundediceLevelsetEnum()
-%QMUMASKGROUNDEDICELEVELSETENUM - Enum of QmuMaskGroundediceLevelset
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuMaskGroundediceLevelsetEnum()
-
-macro=StringToEnum('QmuMaskGroundediceLevelset');
Index: sm/trunk/src/m/enum/QmuMaskIceLevelsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuMaskIceLevelsetEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuMaskIceLevelsetEnum()
-%QMUMASKICELEVELSETENUM - Enum of QmuMaskIceLevelset
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuMaskIceLevelsetEnum()
-
-macro=StringToEnum('QmuMaskIceLevelset');
Index: sm/trunk/src/m/enum/QmuMaterialsRheologyBEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuMaterialsRheologyBEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuMaterialsRheologyBEnum()
-%QMUMATERIALSRHEOLOGYBENUM - Enum of QmuMaterialsRheologyB
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuMaterialsRheologyBEnum()
-
-macro=StringToEnum('QmuMaterialsRheologyB');
Index: sm/trunk/src/m/enum/QmuMeltingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuMeltingEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuMeltingEnum()
-%QMUMELTINGENUM - Enum of QmuMelting
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuMeltingEnum()
-
-macro=StringToEnum('QmuMelting');
Index: sm/trunk/src/m/enum/QmuPressureEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuPressureEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuPressureEnum()
-%QMUPRESSUREENUM - Enum of QmuPressure
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuPressureEnum()
-
-macro=StringToEnum('QmuPressure');
Index: sm/trunk/src/m/enum/QmuSurfaceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuSurfaceEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuSurfaceEnum()
-%QMUSURFACEENUM - Enum of QmuSurface
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuSurfaceEnum()
-
-macro=StringToEnum('QmuSurface');
Index: sm/trunk/src/m/enum/QmuTemperatureEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuTemperatureEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuTemperatureEnum()
-%QMUTEMPERATUREENUM - Enum of QmuTemperature
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuTemperatureEnum()
-
-macro=StringToEnum('QmuTemperature');
Index: sm/trunk/src/m/enum/QmuThicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuThicknessEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuThicknessEnum()
-%QMUTHICKNESSENUM - Enum of QmuThickness
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuThicknessEnum()
-
-macro=StringToEnum('QmuThickness');
Index: sm/trunk/src/m/enum/QmuVxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVxEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuVxEnum()
-%QMUVXENUM - Enum of QmuVx
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuVxEnum()
-
-macro=StringToEnum('QmuVx');
Index: sm/trunk/src/m/enum/QmuVxMeshEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVxMeshEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuVxMeshEnum()
-%QMUVXMESHENUM - Enum of QmuVxMesh
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuVxMeshEnum()
-
-macro=StringToEnum('QmuVxMesh');
Index: sm/trunk/src/m/enum/QmuVyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVyEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuVyEnum()
-%QMUVYENUM - Enum of QmuVy
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuVyEnum()
-
-macro=StringToEnum('QmuVy');
Index: sm/trunk/src/m/enum/QmuVyMeshEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVyMeshEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuVyMeshEnum()
-%QMUVYMESHENUM - Enum of QmuVyMesh
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuVyMeshEnum()
-
-macro=StringToEnum('QmuVyMesh');
Index: sm/trunk/src/m/enum/QmuVzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVzEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuVzEnum()
-%QMUVZENUM - Enum of QmuVz
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuVzEnum()
-
-macro=StringToEnum('QmuVz');
Index: sm/trunk/src/m/enum/QmuVzMeshEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVzMeshEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuVzMeshEnum()
-%QMUVZMESHENUM - Enum of QmuVzMesh
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=QmuVzMeshEnum()
-
-macro=StringToEnum('QmuVzMesh');
Index: /issm/trunk/src/m/enum/RheologyBAbsGradientEnum.m
===================================================================
--- /issm/trunk/src/m/enum/RheologyBAbsGradientEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/RheologyBAbsGradientEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=RheologyBAbsGradientEnum()
+%RHEOLOGYBABSGRADIENTENUM - Enum of RheologyBAbsGradient
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=RheologyBAbsGradientEnum()
+
+macro=StringToEnum('RheologyBAbsGradient');
Index: /issm/trunk/src/m/enum/RootPathEnum.m
===================================================================
--- /issm/trunk/src/m/enum/RootPathEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/RootPathEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=RootPathEnum()
+%ROOTPATHENUM - Enum of RootPath
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=RootPathEnum()
+
+macro=StringToEnum('RootPath');
Index: /issm/trunk/src/m/enum/SmoothAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SmoothAnalysisEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/SmoothAnalysisEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=SmoothAnalysisEnum()
+%SMOOTHANALYSISENUM - Enum of SmoothAnalysis
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SmoothAnalysisEnum()
+
+macro=StringToEnum('SmoothAnalysis');
Index: /issm/trunk/src/m/enum/SmoothThicknessMultiplierEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SmoothThicknessMultiplierEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/SmoothThicknessMultiplierEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=SmoothThicknessMultiplierEnum()
+%SMOOTHTHICKNESSMULTIPLIERENUM - Enum of SmoothThicknessMultiplier
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SmoothThicknessMultiplierEnum()
+
+macro=StringToEnum('SmoothThicknessMultiplier');
Index: sm/trunk/src/m/enum/SmoothedSurfaceSlopeXAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SmoothedSurfaceSlopeXAnalysisEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=SmoothedSurfaceSlopeXAnalysisEnum()
-%SMOOTHEDSURFACESLOPEXANALYSISENUM - Enum of SmoothedSurfaceSlopeXAnalysis
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=SmoothedSurfaceSlopeXAnalysisEnum()
-
-macro=StringToEnum('SmoothedSurfaceSlopeXAnalysis');
Index: sm/trunk/src/m/enum/SmoothedSurfaceSlopeYAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SmoothedSurfaceSlopeYAnalysisEnum.m	(revision 19104)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=SmoothedSurfaceSlopeYAnalysisEnum()
-%SMOOTHEDSURFACESLOPEYANALYSISENUM - Enum of SmoothedSurfaceSlopeYAnalysis
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
-%            Please read src/c/shared/Enum/README for more information
-%
-%   Usage:
-%      macro=SmoothedSurfaceSlopeYAnalysisEnum()
-
-macro=StringToEnum('SmoothedSurfaceSlopeYAnalysis');
Index: /issm/trunk/src/m/enum/StrainRateeffectiveEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StrainRateeffectiveEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/StrainRateeffectiveEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=StrainRateeffectiveEnum()
+%STRAINRATEEFFECTIVEENUM - Enum of StrainRateeffective
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StrainRateeffectiveEnum()
+
+macro=StringToEnum('StrainRateeffective');
Index: /issm/trunk/src/m/enum/StrainRateparallelEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StrainRateparallelEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/StrainRateparallelEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=StrainRateparallelEnum()
+%STRAINRATEPARALLELENUM - Enum of StrainRateparallel
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StrainRateparallelEnum()
+
+macro=StringToEnum('StrainRateparallel');
Index: /issm/trunk/src/m/enum/StrainRateperpendicularEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StrainRateperpendicularEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/StrainRateperpendicularEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=StrainRateperpendicularEnum()
+%STRAINRATEPERPENDICULARENUM - Enum of StrainRateperpendicular
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StrainRateperpendicularEnum()
+
+macro=StringToEnum('StrainRateperpendicular');
Index: /issm/trunk/src/m/enum/StressIntensityFactorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressIntensityFactorEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/StressIntensityFactorEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=StressIntensityFactorEnum()
+%STRESSINTENSITYFACTORENUM - Enum of StressIntensityFactor
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressIntensityFactorEnum()
+
+macro=StringToEnum('StressIntensityFactor');
Index: /issm/trunk/src/m/enum/StressMaxPrincipalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressMaxPrincipalEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/StressMaxPrincipalEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=StressMaxPrincipalEnum()
+%STRESSMAXPRINCIPALENUM - Enum of StressMaxPrincipal
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=StressMaxPrincipalEnum()
+
+macro=StringToEnum('StressMaxPrincipal');
Index: /issm/trunk/src/m/enum/SurfaceAbsMisfitEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceAbsMisfitEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/SurfaceAbsMisfitEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=SurfaceAbsMisfitEnum()
+%SURFACEABSMISFITENUM - Enum of SurfaceAbsMisfit
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceAbsMisfitEnum()
+
+macro=StringToEnum('SurfaceAbsMisfit');
Index: /issm/trunk/src/m/enum/SurfaceforcingsIsmungsmEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsIsmungsmEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/SurfaceforcingsIsmungsmEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsIsmungsmEnum()
+%SURFACEFORCINGSISMUNGSMENUM - Enum of SurfaceforcingsIsmungsm
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsIsmungsmEnum()
+
+macro=StringToEnum('SurfaceforcingsIsmungsm');
Index: /issm/trunk/src/m/enum/SurfaceforcingsPfacEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsPfacEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/SurfaceforcingsPfacEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsPfacEnum()
+%SURFACEFORCINGSPFACENUM - Enum of SurfaceforcingsPfac
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsPfacEnum()
+
+macro=StringToEnum('SurfaceforcingsPfac');
Index: /issm/trunk/src/m/enum/SurfaceforcingsPrecipitationsLgmEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsPrecipitationsLgmEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/SurfaceforcingsPrecipitationsLgmEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsPrecipitationsLgmEnum()
+%SURFACEFORCINGSPRECIPITATIONSLGMENUM - Enum of SurfaceforcingsPrecipitationsLgm
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsPrecipitationsLgmEnum()
+
+macro=StringToEnum('SurfaceforcingsPrecipitationsLgm');
Index: /issm/trunk/src/m/enum/SurfaceforcingsRlapsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsRlapsEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/SurfaceforcingsRlapsEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsRlapsEnum()
+%SURFACEFORCINGSRLAPSENUM - Enum of SurfaceforcingsRlaps
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsRlapsEnum()
+
+macro=StringToEnum('SurfaceforcingsRlaps');
Index: /issm/trunk/src/m/enum/SurfaceforcingsRlapslgmEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsRlapslgmEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/SurfaceforcingsRlapslgmEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsRlapslgmEnum()
+%SURFACEFORCINGSRLAPSLGMENUM - Enum of SurfaceforcingsRlapslgm
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsRlapslgmEnum()
+
+macro=StringToEnum('SurfaceforcingsRlapslgm');
Index: /issm/trunk/src/m/enum/SurfaceforcingsS0tEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsS0tEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/SurfaceforcingsS0tEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsS0tEnum()
+%SURFACEFORCINGSS0TENUM - Enum of SurfaceforcingsS0t
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsS0tEnum()
+
+macro=StringToEnum('SurfaceforcingsS0t');
Index: /issm/trunk/src/m/enum/SurfaceforcingsSealevEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsSealevEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/SurfaceforcingsSealevEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsSealevEnum()
+%SURFACEFORCINGSSEALEVENUM - Enum of SurfaceforcingsSealev
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsSealevEnum()
+
+macro=StringToEnum('SurfaceforcingsSealev');
Index: /issm/trunk/src/m/enum/SurfaceforcingsTdiffEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsTdiffEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/SurfaceforcingsTdiffEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsTdiffEnum()
+%SURFACEFORCINGSTDIFFENUM - Enum of SurfaceforcingsTdiff
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=SurfaceforcingsTdiffEnum()
+
+macro=StringToEnum('SurfaceforcingsTdiff');
Index: /issm/trunk/src/m/enum/ThermalReltolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalReltolEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/ThermalReltolEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=ThermalReltolEnum()
+%THERMALRELTOLENUM - Enum of ThermalReltol
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ThermalReltolEnum()
+
+macro=StringToEnum('ThermalReltol');
Index: /issm/trunk/src/m/enum/ToolkitsFileNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ToolkitsFileNameEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/ToolkitsFileNameEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=ToolkitsFileNameEnum()
+%TOOLKITSFILENAMEENUM - Enum of ToolkitsFileName
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=ToolkitsFileNameEnum()
+
+macro=StringToEnum('ToolkitsFileName');
Index: /issm/trunk/src/m/enum/TransientIscalvingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientIscalvingEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/TransientIscalvingEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=TransientIscalvingEnum()
+%TRANSIENTISCALVINGENUM - Enum of TransientIscalving
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=TransientIscalvingEnum()
+
+macro=StringToEnum('TransientIscalving');
Index: /issm/trunk/src/m/enum/VxObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VxObsEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/VxObsEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=VxObsEnum()
+%VXOBSENUM - Enum of VxObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VxObsEnum()
+
+macro=StringToEnum('VxObs');
Index: /issm/trunk/src/m/enum/VyObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VyObsEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/VyObsEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=VyObsEnum()
+%VYOBSENUM - Enum of VyObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=VyObsEnum()
+
+macro=StringToEnum('VyObs');
Index: /issm/trunk/src/m/enum/WeightsVxObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/WeightsVxObsEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/WeightsVxObsEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=WeightsVxObsEnum()
+%WEIGHTSVXOBSENUM - Enum of WeightsVxObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=WeightsVxObsEnum()
+
+macro=StringToEnum('WeightsVxObs');
Index: /issm/trunk/src/m/enum/WeightsVyObsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/WeightsVyObsEnum.m	(revision 19105)
+++ /issm/trunk/src/m/enum/WeightsVyObsEnum.m	(revision 19105)
@@ -0,0 +1,11 @@
+function macro=WeightsVyObsEnum()
+%WEIGHTSVYOBSENUM - Enum of WeightsVyObs
+%
+%   WARNING: DO NOT MODIFY THIS FILE
+%            this file has been automatically generated by src/c/shared/Enum/Synchronize.sh
+%            Please read src/c/shared/Enum/README for more information
+%
+%   Usage:
+%      macro=WeightsVyObsEnum()
+
+macro=StringToEnum('WeightsVyObs');
Index: /issm/trunk/src/m/exp/exp_to_levelset.m
===================================================================
--- /issm/trunk/src/m/exp/exp_to_levelset.m	(revision 19105)
+++ /issm/trunk/src/m/exp/exp_to_levelset.m	(revision 19105)
@@ -0,0 +1,143 @@
+function  levelset=exp_to_levelset(md,contourname)
+%EXP_TO_LEVELSET - from an exp contour file, build a levelset which has positive sign inside the contour, and negative outside.
+%
+%   Usage:
+%      levelset=exp_to_levelset(md,contourname)
+%
+%   Where: 
+%      - 'md'     : model specifying the mesh
+%      - 'contourname'  : exp file which defines the closed contour
+%      - 'levelset'  : levelset vector on each vertex of the mesh, size md.mesh.numberofvertices
+%
+%   Example:
+%      level=exp_to_levelset(md,'DomainOutline.exp');
+%
+%   See also MESHPROFILEINTERSECTION, SHPREAD, EXPREAD
+	
+	tolerance=1e-5; %tolerance level used for detection of edges, points coinciding, etc ...
+		
+	%from exp contour, build list of segments throughout our mesh:
+	segments=MeshProfileIntersection(md.mesh.elements,md.mesh.x,md.mesh.y,contourname);
+
+	%cleanup: remove 0 length segments: 
+	cleanup=1;
+	if cleanup,
+		flags=zeros(size(segments,1),1);
+		for j=1:size(segments,1),
+			segment=segments(j,:);
+			x1=segment(1); x2=segment(3); 
+			y1=segment(2); y2=segment(4); 
+			Q1=[x1;y1];Q2=[x2;y2];
+			if norm(Q2-Q1)==0, 
+				flags(j)=1;
+			end
+		end
+		pos=find(flags);
+		segments(pos,:)=[];
+	end
+
+	%simplify segments. levelsets are P1 through our triangular elements, which means we can only have one segment per element. 
+	%We simplify by merging all segments into one for each element.
+	simplify=1;
+	if simplify,
+		ids=unique(segments(:,5));
+		newsegs=zeros(length(ids),5);
+		newsegs(:,5)=ids;
+		for j=1:length(ids),
+			pos=find(segments(:,5)==ids(j));
+			segs=segments(pos,1:4);
+			count=0;
+			while(size(segs,1)>1),
+				count=count+1;
+				if count>10,
+					%keep first segment cause something funky in the configuration is happening.
+					segs=segs(1,:);
+					break;
+				end
+				if (abs(segs(1,3)-segs(2,1))<tolerance & abs(segs(1,4)-segs(2,2))<tolerance),
+					%the second segment disappears, extending the first segment:
+					if size(segs,1)==2,
+						segs=[segs(1,1) segs(1,2) segs(2,3) segs(2,4)];
+					else
+						segs=[segs(1,1), segs(1,2), segs(2,3), segs(2,4); segs(3:end,:)];
+					end
+				else
+					%put the first segment at the end
+					segs=[segs(2:end,:); segs(1,:)];
+				end
+			end
+			newsegs(j,1:4)=segs;
+		end
+		segments=newsegs;
+	end
+
+	%cleanup: remove 0 length segments: 
+	if cleanup,
+		flags=zeros(size(segments,1),1);
+		for j=1:size(segments,1),
+			segment=segments(j,:);
+			x1=segment(1); x2=segment(3); 
+			y1=segment(2); y2=segment(4); 
+			Q1=[x1;y1];Q2=[x2;y2];
+			if norm(Q2-Q1)<tolerance,
+				flags(j)=1;
+			end
+		end
+		pos=find(flags);
+		segments(pos,:)=[];
+	end
+
+	%now, using the segments, create level set flags on each element that touches the segment.
+	distance=zeros(md.mesh.numberofvertices,1);
+	flags=zeros(md.mesh.numberofvertices,1);
+	for j=1:size(segments,1),
+		segment=segments(j,:);
+		id=segment(5);
+		x1=segment(1); x2=segment(3); 
+		y1=segment(2); y2=segment(4); 
+		for k=1:3,
+			node=md.mesh.elements(id,k);
+			xk=md.mesh.x(node); yk=md.mesh.y(node);
+			
+			%on which side of the segment is this node k? 
+			P=[xk;yk]; Q1=[x1;y1];Q2=[x2;y2];
+			d=(det([Q2-Q1,P-Q1]))/norm(Q2-Q1);
+			if(~flags(node)),
+				distance(node)=d;
+				flags(node)=1;
+			end
+		end
+	end
+		
+	%now go through all the other nodes and complete (similar to phase unwrapping: we march through the domain, and each time we 
+	%are connected to a node which has a levelset value, we adopt the same one.
+	complete=1;
+	if complete,
+		while(length(find(flags==0))),
+			sumf=sum(flags(md.mesh.elements),2);
+			pos=find(sumf==2);
+			if ~isempty(pos),
+				for j=1:length(pos),
+					el=pos(j);
+					f=flags(md.mesh.elements(el,:));
+					ids=find(f==1); 
+					d=distance(md.mesh.elements(el,ids));
+					if d(1)*d(2)<0,
+						%we have hit a snag here, can't decide!
+						continue;
+					else
+						d=d(1);
+					end
+					if abs(d)<tolerance,
+						continue;
+					end
+					ids=find(f==0);
+					if ~isempty(ids),
+						flags(md.mesh.elements(el,ids))=1;
+						distance(md.mesh.elements(el,ids))=d;
+					end
+				end
+			end
+		end
+	end
+	levelset=distance;
Index: /issm/trunk/src/m/exp/expdisp.m
===================================================================
--- /issm/trunk/src/m/exp/expdisp.m	(revision 19104)
+++ /issm/trunk/src/m/exp/expdisp.m	(revision 19105)
@@ -5,53 +5,54 @@
 %
 %   Usage:
-%      expdisp(domainoutline,varargin)
-%      expdisp(domainoutline,figurenumber,linestyle,linewidth,unitmultiplier)
+%      expdisp(domainoutline,options)
+%
+%   Available options:
+%      - 'figure'     : figure number or handle
+%      - 'linestyle'  : line style ('r--','-y',...)
+%      - 'linewidth'  : line width (1,2,...)
+%      - 'multiplier' : coordinate multiplier (10^3 if the plot is in km)
+%      - 'title'      : do we add contour names to each contour
+%      - 'patch'      : do we want the contour to be filled
 %
 %   Example:
-%      expdisp('Domain.exp',1,'--r',2,10^3);
+%      expdisp('Domain.exp','figure',1,'linestyle','--r','linewidth',2,'multiplier',10^3);
 %
 %   See also EXPMASTER, EXPDOC
 
-%check nargin
-if ~nargin | nargin>5
-	help expdisp
-	error('expdisp error message: bad usage');
-end
+%Get and process options
+options = pairoptions(varargin{:});
+unitmultiplier = getfieldvalue(options,'multiplier',1);
+linewidth      = getfieldvalue(options,'linewidth',1);
+linestyle      = getfieldvalue(options,'linestyle','-r');
+ispatch        = getfieldvalue(options,'patch',0);
 
-%parse input
-if nargin<=1,
-	figurenumber=1;
-else
-	figurenumber=varargin{1};
-end
-if nargin<=2
-	linestyle='r-';
-else
-	linestyle=varargin{2};
-end
-if nargin<=3
-	linewidth=1;
-else
-	linewidth=varargin{3};
-end
-if nargin<=4
-	unitmultiplier=1;
-else
-	unitmultiplier=varargin{4}; if isnan(unitmultiplier), unitmultiplier=1; end
-end
-
+%read file
 domain=expread(domainoutline);
 
-figure(figurenumber),hold on
+%Create figure if needed and hold
+if exist(options,'figure'),
+	figure(getfieldvalue(options,'figure'));
+end
+hold on
+
 for i=1:length(domain),		
 	if domain(i).nods==1
 		plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,'o','MarkerEdgeColor','k','MarkerFaceColor','r','MarkerSize',10);
+		if exist(options,'title')
+			text(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,domain(i).name,'BackgroundColor',[1. .0 .0]);
+		end
 	else
-		if (isnumeric(linestyle))
-			plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,'Color',linestyle,'linewidth',linewidth);
+		if ispatch,
+			patch(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,linestyle);
 		else
-			plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,linestyle,'linewidth',linewidth);
-	  end
-  end
+			if (isnumeric(linestyle))
+				plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,'Color',linestyle,'linewidth',linewidth);
+			else
+				plot(domain(i).x*unitmultiplier,domain(i).y*unitmultiplier,linestyle,'linewidth',linewidth);
+			end
+		end
+		if exist(options,'title')
+			text(domain(i).x(1)*unitmultiplier,domain(i).y(1)*unitmultiplier,domain(i).name,'BackgroundColor',[.7 .9 .7]);
+		end
+	end
 end
-
Index: /issm/trunk/src/m/exp/masktoexp.m
===================================================================
--- /issm/trunk/src/m/exp/masktoexp.m	(revision 19104)
+++ /issm/trunk/src/m/exp/masktoexp.m	(revision 19105)
@@ -24,4 +24,5 @@
 %Create exp structure
 A=struct();
+if(j-1<1), error('no contour found'); end
 for i=1:j-1,
 	A(i).x=s(i).x;
Index: /issm/trunk/src/m/inversions/marshallcostfunctions.m
===================================================================
--- /issm/trunk/src/m/inversions/marshallcostfunctions.m	(revision 19105)
+++ /issm/trunk/src/m/inversions/marshallcostfunctions.m	(revision 19105)
@@ -0,0 +1,15 @@
+function data = marshallcostfunctions(cost_functions)
+	pos=find(cost_functions==101); data(pos)=SurfaceAbsVelMisfitEnum();
+	pos=find(cost_functions==102); data(pos)=SurfaceRelVelMisfitEnum();
+	pos=find(cost_functions==103); data(pos)=SurfaceLogVelMisfitEnum();
+	pos=find(cost_functions==104); data(pos)=SurfaceLogVxVyMisfitEnum();
+	pos=find(cost_functions==105); data(pos)=SurfaceAverageVelMisfitEnum();
+	pos=find(cost_functions==201); data(pos)=ThicknessAbsMisfitEnum();
+	pos=find(cost_functions==501); data(pos)=DragCoefficientAbsGradientEnum();
+	pos=find(cost_functions==502); data(pos)=RheologyBbarAbsGradientEnum();
+	pos=find(cost_functions==503); data(pos)=ThicknessAbsGradientEnum();
+	pos=find(cost_functions==504); data(pos)=ThicknessAlongGradientEnum();
+	pos=find(cost_functions==505); data(pos)=ThicknessAcrossGradientEnum();
+	pos=find(cost_functions==506); data(pos)=BalancethicknessMisfitEnum();
+	pos=find(cost_functions==507); data(pos)=RheologyBAbsGradientEnum();
+	pos=find(cost_functions==601); data(pos)=SurfaceAbsMisfitEnum();
Index: /issm/trunk/src/m/inversions/marshallcostfunctions.py
===================================================================
--- /issm/trunk/src/m/inversions/marshallcostfunctions.py	(revision 19105)
+++ /issm/trunk/src/m/inversions/marshallcostfunctions.py	(revision 19105)
@@ -0,0 +1,33 @@
+import copy
+from EnumDefinitions import *
+
+def marshallcostfunctions(cost_functions):
+
+	#copy list first
+	data=copy.deepcopy(cost_functions)
+
+	#convert to  Enums
+	pos=[i for i,x in enumerate(cost_functions) if x==101];
+	for i in pos: data[i]=SurfaceAbsVelMisfitEnum()        
+	pos=[i for i,x in enumerate(cost_functions) if x==102];
+	for i in pos: data[i]=SurfaceRelVelMisfitEnum()        
+	pos=[i for i,x in enumerate(cost_functions) if x==103];
+	for i in pos: data[i]=SurfaceLogVelMisfitEnum()        
+	pos=[i for i,x in enumerate(cost_functions) if x==104];
+	for i in pos: data[i]=SurfaceLogVxVyMisfitEnum()       
+	pos=[i for i,x in enumerate(cost_functions) if x==105];
+	for i in pos: data[i]=SurfaceAverageVelMisfitEnum()    
+	pos=[i for i,x in enumerate(cost_functions) if x==201];
+	for i in pos: data[i]=ThicknessAbsMisfitEnum()         
+	pos=[i for i,x in enumerate(cost_functions) if x==501];
+	for i in pos: data[i]=DragCoefficientAbsGradientEnum() 
+	pos=[i for i,x in enumerate(cost_functions) if x==502];
+	for i in pos: data[i]=RheologyBbarAbsGradientEnum()    
+	pos=[i for i,x in enumerate(cost_functions) if x==503];
+	for i in pos: data[i]=ThicknessAbsGradientEnum()       
+	pos=[i for i,x in enumerate(cost_functions) if x==504];
+	for i in pos: data[i]=ThicknessAlongGradientEnum()     
+	pos=[i for i,x in enumerate(cost_functions) if x==505];
+	for i in pos: data[i]=ThicknessAcrossGradientEnum()    
+
+	return data
Index: /issm/trunk/src/m/inversions/supportedcontrols.m
===================================================================
--- /issm/trunk/src/m/inversions/supportedcontrols.m	(revision 19105)
+++ /issm/trunk/src/m/inversions/supportedcontrols.m	(revision 19105)
@@ -0,0 +1,14 @@
+function list = supportedcontrols(),
+
+	list = {...
+		'BalancethicknessThickeningRate',...
+		'FrictionCoefficient',...
+		'FrictionAs',...
+		'MaterialsRheologyBbar',...
+		'DamageDbar',...
+		'Vx',...
+		'Vy',...
+		'Thickness',...
+		'BalancethicknessOmega',...
+		'BalancethicknessApparentMassbalance',...
+		'MaterialsRheologyB'};
Index: /issm/trunk/src/m/inversions/supportedcontrols.py
===================================================================
--- /issm/trunk/src/m/inversions/supportedcontrols.py	(revision 19105)
+++ /issm/trunk/src/m/inversions/supportedcontrols.py	(revision 19105)
@@ -0,0 +1,2 @@
+def supportedcontrols():
+	return ['BalancethicknessThickeningRate','FrictionCoefficient','FrictionAs','MaterialsRheologyBbar','DamageDbar','Vx','Vy']
Index: /issm/trunk/src/m/inversions/supportedcostfunctions.m
===================================================================
--- /issm/trunk/src/m/inversions/supportedcostfunctions.m	(revision 19105)
+++ /issm/trunk/src/m/inversions/supportedcostfunctions.m	(revision 19105)
@@ -0,0 +1,3 @@
+function list = supportedcostfunctions(),
+
+	list = [101:105 201 501:507 601:604];
Index: /issm/trunk/src/m/inversions/supportedcostfunctions.py
===================================================================
--- /issm/trunk/src/m/inversions/supportedcostfunctions.py	(revision 19105)
+++ /issm/trunk/src/m/inversions/supportedcostfunctions.py	(revision 19105)
@@ -0,0 +1,2 @@
+def supportedcostfunctions():
+	return [101,102,103,104,105,201,501,502,503,504,505]
Index: /issm/trunk/src/m/mesh/MeshToShp.m
===================================================================
--- /issm/trunk/src/m/mesh/MeshToShp.m	(revision 19105)
+++ /issm/trunk/src/m/mesh/MeshToShp.m	(revision 19105)
@@ -0,0 +1,14 @@
+function MeshToShp(md,shapefilename)
+%MESHTOSHP - export mesh to shp file
+%
+%   Usage:
+%      MeshToShp(md,'Greenland.shp');
+
+	contours= struct([]);
+	for i=1:md.mesh.numberofvertices,
+		contours(i).x = md.mesh.x(i);
+		contours(i).y = md.mesh.y(i);
+		contours(i).id = i;
+		contours(i).Geometry = 'Point';
+	end
+	shpwrite(contours,shapefilename);
Index: /issm/trunk/src/m/mesh/bamg.m
===================================================================
--- /issm/trunk/src/m/mesh/bamg.m	(revision 19104)
+++ /issm/trunk/src/m/mesh/bamg.m	(revision 19105)
@@ -349,5 +349,23 @@
 	%Now, build the connectivity tables for this mesh.
 	md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
-else
+
+elseif getfieldvalue(options,'3dsurface',0),
+	
+	md.mesh=mesh3dsurface();
+	md.mesh.x=bamgmesh_out.Vertices(:,1);
+	md.mesh.y=bamgmesh_out.Vertices(:,2);
+	md.mesh.z=md.mesh.x; md.mesh.z(:)=0;
+	md.mesh.elements=bamgmesh_out.Triangles(:,1:3);
+	md.mesh.edges=bamgmesh_out.IssmEdges;
+	md.mesh.segments=bamgmesh_out.IssmSegments(:,1:3);
+	md.mesh.segmentmarkers=bamgmesh_out.IssmSegments(:,4);
+
+	%Fill in rest of fields:
+	md.mesh.numberofelements=size(md.mesh.elements,1);
+	md.mesh.numberofvertices=length(md.mesh.x);
+	md.mesh.numberofedges=size(md.mesh.edges,1);
+	md.mesh.vertexonboundary=zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
+
+else 
 	md.mesh=mesh2d();
 	md.mesh.x=bamgmesh_out.Vertices(:,1);
Index: /issm/trunk/src/m/miscellaneous/colinearity.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/colinearity.m	(revision 19105)
+++ /issm/trunk/src/m/miscellaneous/colinearity.m	(revision 19105)
@@ -0,0 +1,32 @@
+function theta = colinearity(md)
+
+%load some variables (it is much faster if the variab;es are loaded from md once for all) 
+if ~strcmpi(meshtype(md.mesh),'3D'),
+	numberofelements=md.mesh.numberofelements;
+	numberofnodes=md.mesh.numberofvertices;
+	index=md.mesh.elements;
+	x=md.mesh.x; y=md.mesh.y;
+else
+	numberofelements=md.mesh.numberofelements2d;
+	numberofnodes=md.mesh.numberofvertices2d;
+	index=md.mesh.elements2d;
+	x=md.mesh.x2d; y=md.mesh.y2d;
+end
+
+%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
+
+s = averaging(md,md.geometry.surface,2);
+
+summation=[1;1;1];
+dsdx=(s(index).*alpha)*summation;
+dsdy=(s(index).*beta)*summation;
+dsdx = -averaging(md,dsdx,0);
+dsdy = -averaging(md,dsdy,0);
+
+vx = md.inversion.vx_obs;
+vy = md.inversion.vy_obs;
+v  = md.inversion.vel_obs;
+v2 = sqrt(dsdx.^2 + dsdy.^2);
+
+theta = acos((vx.*dsdx + vy.*dsdy)./(v.*v2+eps));
Index: /issm/trunk/src/m/miscellaneous/vorticity.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/vorticity.m	(revision 19104)
+++ /issm/trunk/src/m/miscellaneous/vorticity.m	(revision 19105)
@@ -29,5 +29,5 @@
 rot=dvxdy - dvydx;
 
-if strcmpi(meshtype(md.mesh),'3D'),
+if strcmpi(domaintype(md.mesh),'3D'),
 	rot=project3d(md,'vector',rot,'type','element');
 end
Index: /issm/trunk/src/m/plot/applyoptions.m
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.m	(revision 19104)
+++ /issm/trunk/src/m/plot/applyoptions.m	(revision 19105)
@@ -6,11 +6,4 @@
 %
 %   See also: PLOTMODEL, PARSE_OPTIONS
-
-%some defaults
-if isfield(md.mesh,'hemisphere'),
-	if strcmpi(md.mesh.hemisphere,'n'), options=addfielddefault(options,'hemisphere','n'); 
-	elseif strcmpi(md.mesh.hemisphere,'s'), options=addfielddefault(options,'hemisphere','s'); 
-	end
-end
 
 %fontsize
@@ -68,4 +61,7 @@
 	elseif strcmp(domaintype(md.mesh),'2Dvertical'),
 		axis auto tight
+	elseif strcmp(domaintype(md.mesh),'3Dsurface'),
+		axis auto tight
+
 	elseif strcmp(domaintype(md.mesh),'2Dhorizontal'),
 		axis tight equal;
@@ -261,5 +257,5 @@
 			linewidthi=linewidth{i};
 		end
-		expdisp(filenamei,gcf,stylei,linewidthi,getfieldvalue(options,'unit',1));
+		expdisp(filenamei,'linestyle',stylei,'linewidthi',linewidthi,'multiplier',getfieldvalue(options,'unit',1));
 	end
 end
@@ -365,13 +361,13 @@
 	axis equal off
 	%box off
-	if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
+	if md.mesh.epsg==3413,
 		A=expread('/u/astrid-r1b/ModelData/Exp/GreenlandBoxFront.exp');
 		[A.x A.y]=ll2xy(A.x,A.y,+1,45,70);
 		A.x = A.x(1:30:end);
 		A.y = A.y(1:30:end);
-	elseif strcmpi(md.mesh.hemisphere,'s') | strcmpi(md.mesh.hemisphere,'south'),
+	elseif md.mesh.epsg==3031,
 		A=expread('/u/astrid-r1b/ModelData/Exp/Antarctica.exp');
 	else
-		error('applyoptions error message: hemisphere not defined');
+		error('applyoptions error message: md.mesh.epsg not defined');
 	end
 	offset=3*10^4;
@@ -434,5 +430,5 @@
 	end
 	hold on,p=plot(x,y,'k.');
-	markersize=getfieldvalue(options,'markersize',5);
+	markersize=getfieldvalue(options,'markersize',12);
 	color=getfieldvalue(options,'cloudcolor','k');
 	set(p,'Color',color);
Index: /issm/trunk/src/m/plot/applyoptions.py
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.py	(revision 19104)
+++ /issm/trunk/src/m/plot/applyoptions.py	(revision 19105)
@@ -24,8 +24,4 @@
 		See also: PLOTMODEL, PARSE_OPTIONS
 	'''
-
-	#some defaults (this seems to be adding a field that already exists...)
-	#if not isnan(md.mesh.hemisphere):
-	#	options.addfielddefault('hemisphere',md.mesh.hemisphere)
 
 	# get handle to current figure and axes instance
Index: /issm/trunk/src/m/plot/checkplotoptions.py
===================================================================
--- /issm/trunk/src/m/plot/checkplotoptions.py	(revision 19104)
+++ /issm/trunk/src/m/plot/checkplotoptions.py	(revision 19105)
@@ -115,14 +115,18 @@
 
 	#expdisp
-	expdispvaluesarray=[0,0]
-	expstylevaluesarray=[0,0]
-	expstylevalues=[0,0]
+	expdispvaluesarray=[]
+	expstylevaluesarray=[]
+	expstylevalues=[]
 	if options.exist('expstyle'):
-		expstylevalues=options.getfieldvalue('expstyle')
+	        expstylevalues=options.getfieldvalue('expstyle')
+                if type(expstylevalues)==str:
+                    expstylevalues=[expstylevalues]
 	if options.exist('expdisp'):
 		expdispvalues=options.getfieldvalue('expdisp')
+                if type(expdispvalues)==str:
+                    expdispvalues=[expdispvalues]
 		for i in npy.arange(len(expdispvalues)):
 			expdispvaluesarray.append(expdispvalues[i])
-			if len(expstylevalues)>i+1:
+			if len(expstylevalues)>i:
 				expstylevaluesarray.append(expstylevalues[i])
 			else:
@@ -154,6 +158,6 @@
 	#log scale
 	if options.exist('log'):
-		if options.exist('caxis'):
-			options.changefieldvalue('caxis',log(options.getfieldvalue('caxis'))/log(options.getfieldvalue('log')))
+		if options.exist('clim'):
+			options.changefieldvalue('clim',log(options.getfieldvalue('clim'))/log(options.getfieldvalue('log')))
 		options.changefieldvalue('cutoff',log(options.getfieldvalue('cutoff',1.5))/log(options.getfieldvalue('log')))
 
Index: /issm/trunk/src/m/plot/colormaps/bluewhitered.m
===================================================================
--- /issm/trunk/src/m/plot/colormaps/bluewhitered.m	(revision 19105)
+++ /issm/trunk/src/m/plot/colormaps/bluewhitered.m	(revision 19105)
@@ -0,0 +1,122 @@
+function newmap = bluewhitered(m)
+%BLUEWHITERED   Blue, white, and red color map.
+%   BLUEWHITERED(M) returns an M-by-3 matrix containing a blue to white
+%   to red colormap, with white corresponding to the CAXIS value closest
+%   to zero.  This colormap is most useful for images and surface plots
+%   with positive and negative values.  BLUEWHITERED, by itself, is the
+%   same length as the current colormap.
+%
+%   Examples:
+%   ------------------------------
+%   figure
+%   imagesc(peaks(250));
+%   colormap(bluewhitered(256)), colorbar
+%
+%   figure
+%   imagesc(peaks(250), [0 8])
+%   colormap(bluewhitered), colorbar
+%
+%   figure
+%   imagesc(peaks(250), [-6 0])
+%   colormap(bluewhitered), colorbar
+%
+%   figure
+%   surf(peaks)
+%   colormap(bluewhitered)
+%   axis tight
+%
+%   See also HSV, HOT, COOL, BONE, COPPER, PINK, FLAG, 
+%   COLORMAP, RGBPLOT.
+
+
+if nargin < 1
+   m = size(get(gcf,'colormap'),1);
+end
+
+
+bottom = [0 0 0.5];
+botmiddle = [0 0.5 1];
+middle = [1 1 1];
+topmiddle = [1 0 0];
+top = [0.5 0 0];
+
+% Find middle
+lims = get(gca, 'CLim');
+
+% Find ratio of negative to positive
+if (lims(1) < 0) & (lims(2) > 0)
+    % It has both negative and positive
+    % Find ratio of negative to positive
+    ratio = abs(lims(1)) / (abs(lims(1)) + lims(2));
+    neglen = round(m*ratio);
+    poslen = m - neglen;
+    
+    % Just negative
+    new = [bottom; botmiddle; middle];
+    len = length(new);
+    oldsteps = linspace(0, 1, len);
+    newsteps = linspace(0, 1, neglen);
+    newmap1 = zeros(neglen, 3);
+    
+    for i=1:3
+        % Interpolate over RGB spaces of colormap
+        newmap1(:,i) = min(max(interp1(oldsteps, new(:,i), newsteps)', 0), 1);
+    end
+    
+    % Just positive
+    new = [middle; topmiddle; top];
+    len = length(new);
+    oldsteps = linspace(0, 1, len);
+    newsteps = linspace(0, 1, poslen);
+    newmap = zeros(poslen, 3);
+    
+    for i=1:3
+        % Interpolate over RGB spaces of colormap
+        newmap(:,i) = min(max(interp1(oldsteps, new(:,i), newsteps)', 0), 1);
+    end
+    
+    % And put 'em together
+    newmap = [newmap1; newmap];
+    
+elseif lims(1) >= 0
+    % Just positive
+    new = [middle; topmiddle; top];
+    len = length(new);
+    oldsteps = linspace(0, 1, len);
+    newsteps = linspace(0, 1, m);
+    newmap = zeros(m, 3);
+    
+    for i=1:3
+        % Interpolate over RGB spaces of colormap
+        newmap(:,i) = min(max(interp1(oldsteps, new(:,i), newsteps)', 0), 1);
+    end
+    
+else
+    % Just negative
+    new = [bottom; botmiddle; middle];
+    len = length(new);
+    oldsteps = linspace(0, 1, len);
+    newsteps = linspace(0, 1, m);
+    newmap = zeros(m, 3);
+    
+    for i=1:3
+        % Interpolate over RGB spaces of colormap
+        newmap(:,i) = min(max(interp1(oldsteps, new(:,i), newsteps)', 0), 1);
+    end
+    
+end
+% 
+% m = 64;
+% new = [bottom; botmiddle; middle; topmiddle; top];
+% % x = 1:m;
+% 
+% oldsteps = linspace(0, 1, 5);
+% newsteps = linspace(0, 1, m);
+% newmap = zeros(m, 3);
+% 
+% for i=1:3
+%     % Interpolate over RGB spaces of colormap
+%     newmap(:,i) = min(max(interp1(oldsteps, new(:,i), newsteps)', 0), 1);
+% end
+% 
+% % set(gcf, 'colormap', newmap), colorbar
Index: /issm/trunk/src/m/plot/export_gl.m
===================================================================
--- /issm/trunk/src/m/plot/export_gl.m	(revision 19105)
+++ /issm/trunk/src/m/plot/export_gl.m	(revision 19105)
@@ -0,0 +1,117 @@
+function export_gl(md,varargin)
+
+	templist=plotoptions(varargin{:}); 
+	optionslist=templist.list;
+	options=optionslist{1};
+	options=checkplotoptions(md,options);
+
+	%Setup unique directory in present dir: 
+	directory=getfieldvalue(options,'directory','./');
+	databasename=getfieldvalue(options,'database','webgl');
+
+	%scaling factor: 
+	scaling_factor=getfieldvalue(options,'scaling_factor',50);
+
+	%Deal with title: 
+	if exist(options,'title')
+		title=getfieldvalue(options,'title');
+	else
+		title='';
+	end
+
+	%initialize model: 
+	model.title=title;
+	model.initialZoomFactor=getfieldvalue(options,'zoom',-.25);
+
+	%Deal with contour {{{
+
+	contour_lat1=md.mesh.lat(md.mesh.segments(:,1));
+	contour_lat2=md.mesh.lat(md.mesh.segments(:,2));
+	contour_long1=md.mesh.long(md.mesh.segments(:,1));
+	contour_long2=md.mesh.long(md.mesh.segments(:,2));
+	contour_surface1=md.geometry.surface(md.mesh.segments(:,1));
+	contour_surface2=md.geometry.surface(md.mesh.segments(:,2));
+
+	R1=6371000*ones(length(contour_surface1),1)+scaling_factor*contour_surface1;
+	R2=6371000*ones(length(contour_surface2),1)+scaling_factor*contour_surface2;
+
+	contourx1 = R1 .* cosd(contour_lat1) .* cosd(contour_long1);
+	contoury1 = R1 .* cosd(contour_lat1) .* sind(contour_long1);
+	contourz1 = R1 .* sind(contour_lat1);
+	
+	contourx2 = R2 .* cosd(contour_lat2) .* cosd(contour_long2);
+	contoury2 = R2 .* cosd(contour_lat2) .* sind(contour_long2);
+	contourz2 = R2 .* sind(contour_lat2);
+
+
+	model.contourx1=contourx1;
+	model.contoury1=contoury1;
+	model.contourz1=contourz1;
+	model.contourx2=contourx2;
+	model.contoury2=contoury2;
+	model.contourz2=contourz2;
+
+
+	%}}}
+%Deal with mesh and results {{{
+	
+	
+	lat=md.mesh.lat;
+	long=md.mesh.long;
+	surface=md.geometry.surface;
+	numberofelements=md.mesh.numberofelements;
+	numberofvertices=md.mesh.numberofvertices;
+
+	R=6371000*ones(numberofvertices,1)+scaling_factor*surface;
+
+	x = R .* cosd(lat) .* cosd(long);
+	y = R .* cosd(lat) .* sind(long);
+	z = R .* sind(lat);
+
+
+	%Deal with triangulation: 
+	model.index=md.mesh.elements;
+	model.x=x;
+	model.y=y;
+	model.z=z;
+	model.surface=surface;
+	
+	%Deal with data: 
+	results=struct([]);
+	for i=1:length(optionslist),
+		options=optionslist{i}; options=checkplotoptions(md,options);
+		data=getfieldvalue(options,'data');
+		results(i).data=data;
+		results(i).caxis=getfieldvalue(options,'caxis',[min(data(:)) max(data(:))]);
+
+		label=getfieldvalue(options,'label','');
+		if strcmpi(label,''),
+			%create generic label: 
+			label=['data' num2str(i)];
+		end
+		results(i).label=label;
+
+		shortlabel=getfieldvalue(options,'shortlabel','');
+		if strcmpi(shortlabel,''),
+			%create generic short label: 
+			shortlabel=['data' num2str(i)];
+		end
+		results(i).shortlabel=shortlabel;
+		
+		if size(data,2)>1,
+			time_range=getfieldvalue(options,'time_range',[0 100]);
+			results(i).time_range=time_range;
+		end
+
+		unit=getfieldvalue(options,'unit','');
+		if strcmpi(unit,''),
+			%create generic unit: 
+			unit='SI';
+		end
+		results(i).unit=unit;
+	end
+	model.results=results;
+	
+	%Write model to javascript database file: 
+	writejsfile([directory databasename '.js'],model,databasename);
+%}}}
Index: /issm/trunk/src/m/plot/export_gl.py
===================================================================
--- /issm/trunk/src/m/plot/export_gl.py	(revision 19105)
+++ /issm/trunk/src/m/plot/export_gl.py	(revision 19105)
@@ -0,0 +1,124 @@
+from plotoptions import plotoptions
+from checkplotoptions import checkplotoptions
+from model import model
+import numpy as np
+import math
+from writejsfile import writejsfile
+
+def export_gl(md,*varargin):
+	class ResultObj(object):
+	    def __getattr__(self, attr):
+		return self.__dict__.get(attr)
+
+	print ('getting options')
+	templist=plotoptions(varargin); 
+	optionslist=templist.list;
+	options=optionslist[1];
+	options=checkplotoptions(md,options);
+	#print (templist,options)
+	#templist contains options 0-3. Use in the future to rework.
+	
+	#Setup unique directory in present dir: 
+	print ('setting directory')
+	directory=optionslist[0].getfieldvalue('directory');
+	databasename=optionslist[0].getfieldvalue('database');
+	
+	#scaling factor: 
+	print ('setting scaling factor')
+	scaling_factor=optionslist[0].getfieldvalue('scaling_factor');
+
+	#Deal with title: 
+	print ('setting title')
+	if optionslist[0].exist('title'):
+		title=optionslist[0].getfieldvalue('title');
+	else:
+		title='';
+
+	#initialize model: 
+	print ('initializing model')
+	model.title=title;
+	model.initialZoomFactor=options.getfieldvalue('zoom',-.25);
+
+	#Deal with contour {{{
+	print ('getting contour')
+	print (md.mesh.segments)
+	segmenets0 = map(lambda s: s - 1, md.mesh.segments[:,0]);
+	segmenets1 = map(lambda s: s - 1, md.mesh.segments[:,1]);
+	
+	contour_lat1=md.mesh.lat.take(segmenets0)
+	contour_lat2=md.mesh.lat.take(segmenets1);
+	contour_long1=md.mesh.long.take(segmenets0);
+	contour_long2=md.mesh.long.take(segmenets1);
+	contour_surface1=md.geometry.surface.take(segmenets0);
+	contour_surface2=md.geometry.surface.take(segmenets1);
+
+	R1=6371000*np.ones(len(contour_surface1))+scaling_factor*contour_surface1;
+	R2=6371000*np.ones(len(contour_surface2))+scaling_factor*contour_surface2;
+
+	model.contourx1 = map(lambda r, lat, long: r * math.cos(math.radians(lat)) * math.cos(math.radians(long)), R1, contour_lat1, contour_long1);
+	model.contoury1 = map(lambda r, lat, long: r * math.cos(math.radians(lat)) * math.sin(math.radians(long)), R1, contour_lat1, contour_long1);
+	model.contourz1 = map(lambda r, lat: r * math.sin(math.radians(lat)), R1, contour_lat1);
+	
+	model.contourx2 = map(lambda r, lat, long: r * math.cos(math.radians(lat)) * math.cos(math.radians(long)), R2, contour_lat2, contour_long2);
+	model.contoury2 = map(lambda r, lat, long: r * math.cos(math.radians(lat)) * math.sin(math.radians(long)), R2, contour_lat2, contour_long2);
+	model.contourz2 = map(lambda r, lat: r * math.sin(math.radians(lat)), R2, contour_lat2);
+
+	#}}}
+	#Deal with mesh and results {{{
+	print ('getting mesh')
+	surface=md.geometry.surface.flatten();
+	numberofelements=md.mesh.numberofelements;
+	numberofvertices=md.mesh.numberofvertices;
+	R=6371000*np.ones(len(md.mesh.lat))+scaling_factor*surface;
+	
+	x = map(lambda r, lat, long: r * math.cos(math.radians(lat)) * math.cos(math.radians(long)), R, md.mesh.lat,md.mesh.long);
+	y = map(lambda r, lat, long: r * math.cos(math.radians(lat)) * math.sin(math.radians(long)), R, md.mesh.lat,md.mesh.long);
+	z = map(lambda r, lat: r * math.sin(math.radians(lat)), R, md.mesh.lat);
+	
+	#Deal with triangulation: 
+	print('getting triangulation')
+	model.index=md.mesh.elements;
+	model.x=x;
+	model.y=y;
+	model.z=z;
+	model.surface=surface;
+	
+	results = []
+	print(optionslist)	
+	#Deal with data: 
+	print('getting data')
+	for i in xrange(0,len(optionslist)):
+		options=optionslist[i]; 
+		options=checkplotoptions(md,options);
+		data=options.getfieldvalue('data').flatten();
+		results.append(ResultObj())
+		results[i].data=data;
+		results[i].caxis=options.getfieldvalue('caxis',[min(data), max(data)]);
+
+		label=options.getfieldvalue('label','');
+		if label=='':
+			#create generic label: 
+			label=['data', str(i)];
+		results[i].label=label;
+
+		shortlabel=options.getfieldvalue('shortlabel','');
+		if shortlabel=='':
+			#create generic short label: 
+			shortlabel=['data', str(i)];
+		results[i].shortlabel=shortlabel;
+
+		if type(data[2])!=np.float64:
+			time_range=options.getfieldvalue('time_range',[0, 100]);
+			results[i].time_range=time_range;
+
+		unit=options.getfieldvalue('unit','');
+		if unit=='':
+			#create generic unit: 
+			unit='SI';
+		results[i].unit=unit;
+	model.results=results;
+	
+	#Write model to javascript database file: 
+	print('writing to file')
+	writejsfile(directory + databasename + '.js',model,databasename);
+#}}}
Index: /issm/trunk/src/m/plot/googlemaps.m
===================================================================
--- /issm/trunk/src/m/plot/googlemaps.m	(revision 19104)
+++ /issm/trunk/src/m/plot/googlemaps.m	(revision 19105)
@@ -22,14 +22,18 @@
 	end
 end
+
+if md.mesh.epsg==0,
+	error('md.mesh.epsg not defined');
+end
 if nargin==1,
 	%Get xlim and ylim (used to extract Google maps image)
 	xlim=getfieldvalue(options,'xlim',[min(md.mesh.x) max(md.mesh.x)]);
 	ylim=getfieldvalue(options,'ylim',[min(md.mesh.y) max(md.mesh.y)]);
-	if strcmpi(md.mesh.hemisphere,'n'),
+	if md.mesh.epsg==3413,
 		[latlist lonlist]= xy2ll(...
 			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
 			[linspace(ylim(1),ylim(1),100) linspace(ylim(1),ylim(2),100) linspace(ylim(2),ylim(2),100) linspace(ylim(2),ylim(1),100)],...
 			+1,45,70);
-	elseif strcmpi(md.mesh.hemisphere,'s'),
+	elseif md.mesh.epsg==3031,
 		[latlist lonlist]= xy2ll(...
 			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
@@ -37,5 +41,5 @@
 			-1,0,71);
 	else
-		error('field hemisphere should either be ''n'' or ''s''');
+		error('EPSG code not supported yet');
 	end
 
@@ -50,11 +54,5 @@
 %Get region specific projection parameters
 EPSGgoogle = 'EPSG:3785';   % Mercator       http://www.spatialreference.org/ref/epsg/3785/
-if strcmpi(md.mesh.hemisphere,'n'),
-	EPSGlocal = 'EPSG:3413'; % UPS Greenland  http://www.spatialreference.org/ref/epsg/3413/
-elseif strcmpi(md.mesh.hemisphere,'s'),
-	EPSGlocal = 'EPSG:3031'; % UPS Antarctica http://www.spatialreference.org/ref/epsg/3031/
-else
-	error('field hemisphere should either be ''n'' or ''s''');
-end
+EPSGlocal  = ['EPSG:' num2str(md.mesh.epsg)];
 
 %Find optimal zoom
@@ -130,10 +128,10 @@
 	[gX gY]=meshgrid(ulx:ulx+size(final,2)-1,uly:-1:uly-size(final,1)+1);
 	[LAT LON]=pixelstolatlon(gX,gY, zoom);
-	if strcmpi(md.mesh.hemisphere,'n'),
+	if md.mesh.epsg==3413,
 		[X Y]=ll2xy(LAT,LON,+1,45,70);
-	elseif strcmpi(md.mesh.hemisphere,'s'),
+	elseif md.mesh.epsg==3031,
 		[X Y]=ll2xy(LAT,LON,-1,0,71);
 	else
-		error('field hemisphere should either be ''n'' or ''s''');
+		error('EPSG code not supported yet');
 	end
 	md.radaroverlay.pwr=final;
@@ -153,10 +151,10 @@
 	[gX gY]=meshgrid(ulx:ulx+size(final,2)-1,uly:-1:uly-size(final,1)+1);
 	[LAT LON]=pixelstolatlon(gX,gY, zoom);
-	if strcmpi(md.mesh.hemisphere,'n'),
+	if md.mesh.epsg==3413,
 		[X Y]=ll2xy(LAT,LON,+1,45,70);
-	elseif strcmpi(md.mesh.hemisphere,'s'),
+	elseif md.mesh.epsg==3031,
 		[X Y]=ll2xy(LAT,LON,-1,0,71);
 	else
-		error('field hemisphere should either be ''n'' or ''s''');
+		error('EPSG code not supported yet');
 	end
 	md.radaroverlay.pwr=final;
Index: /issm/trunk/src/m/plot/latlonoverlay.m
===================================================================
--- /issm/trunk/src/m/plot/latlonoverlay.m	(revision 19104)
+++ /issm/trunk/src/m/plot/latlonoverlay.m	(revision 19105)
@@ -66,11 +66,11 @@
 	latitudes =lat*ones(size(longitudes));
 
-	if strcmpi(md.mesh.hemisphere,'n'),
+	if md.mesh.epsg==3413,
 		if lat<0, continue; end
 		[x,y]=ll2xy(latitudes,longitudes,+1,45,70);
-	elseif strcmpi(md.mesh.hemisphere,'s'),
+	elseif md.mesh.epsg==3031,
 		if lat>0, continue; end
 		[x,y]=ll2xy(latitudes,longitudes,-1, 0,71);
-	else error('field hemisphere should either be ''n'' or ''s'''); end
+	else error('field md.mesh.epsg not supported yet'); end
 
 	pos=find(x<=xlimits(2) & x>=xlimits(1) & y<=ylimits(2) & y>=ylimits(1));
@@ -105,14 +105,14 @@
 for lon=-180:lonstep:180
 
-	if strcmpi(md.mesh.hemisphere,'n'),
+	if md.mesh.epsg==3413,
 		latitudes =0:resolution:90;
 		longitudes=lon*ones(size(latitudes));
 		[x,y]=ll2xy(latitudes,longitudes,+1,45,70);
-	elseif strcmpi(md.mesh.hemisphere,'s'),
+	elseif md.mesh.epsg==3031,
 		latitudes =-90:resolution:0;
 		longitudes=lon*ones(size(latitudes));
 		[x,y]=ll2xy(latitudes,longitudes,-1, 0,71);
 	else
-		error('field hemisphere should either be ''n'' or ''s'''); 
+		error('field md.mesh.epsg not supported yet'); 
 	end
 
Index: /issm/trunk/src/m/plot/manualcb.m
===================================================================
--- /issm/trunk/src/m/plot/manualcb.m	(revision 19104)
+++ /issm/trunk/src/m/plot/manualcb.m	(revision 19105)
@@ -102,5 +102,5 @@
 
 if exist(options,'title'),
-	title(getfieldvalue(options,'title'),'FontSize',fontsize);
+	title(getfieldvalue(options,'title'),'FontSize',getfieldvalue(options,'titlefontsize',fontsize));
 end
 if exist(options,'ylabel'),
Index: /issm/trunk/src/m/plot/plot_googlemaps.m
===================================================================
--- /issm/trunk/src/m/plot/plot_googlemaps.m	(revision 19104)
+++ /issm/trunk/src/m/plot/plot_googlemaps.m	(revision 19105)
@@ -25,10 +25,10 @@
 	xlim=getfieldvalue(options,'xlim',[min(x) max(x)]);
 	ylim=getfieldvalue(options,'ylim',[min(y) max(y)]);
-	if strcmpi(md.mesh.hemisphere,'n'),
+	if md.mesh.epsg==3413,
 		[latlist lonlist]= xy2ll(...
 			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
 			[linspace(ylim(1),ylim(1),100) linspace(ylim(1),ylim(2),100) linspace(ylim(2),ylim(2),100) linspace(ylim(2),ylim(1),100)],...
 			+1,45,70);
-	elseif strcmpi(md.mesh.hemisphere,'s'),
+	elseif md.mesh.epsg==3031,
 		[latlist lonlist]= xy2ll(...
 			[linspace(xlim(1),xlim(2),100) linspace(xlim(2),xlim(2),100) linspace(xlim(2),xlim(1),100) linspace(xlim(1),xlim(1),100)],...
@@ -36,5 +36,7 @@
 			-1,0,71);
 	else
-		error('field hemisphere should either be ''n'' or ''s''');
+		latlist = md.mesh.lat; %That might work?
+		lonlist = md.mesh.long;
+		error('EPSG code not supported yet');
 	end
 
Index: /issm/trunk/src/m/plot/plot_gridded.m
===================================================================
--- /issm/trunk/src/m/plot/plot_gridded.m	(revision 19104)
+++ /issm/trunk/src/m/plot/plot_gridded.m	(revision 19105)
@@ -86,5 +86,5 @@
 
 %Apply options
-if ~isnan(data_min),
+if ~isnan(data_min) & ~isinf(data_min),
 	options=changefieldvalue(options,'caxis',[data_min data_max]); % force caxis so that the colorbar is ready
 end
Index: /issm/trunk/src/m/plot/plot_rifts.m
===================================================================
--- /issm/trunk/src/m/plot/plot_rifts.m	(revision 19104)
+++ /issm/trunk/src/m/plot/plot_rifts.m	(revision 19105)
@@ -63,4 +63,7 @@
 	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
 	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
+elseif isplanet,
+	A=elements(:,1); B=elements(:,2); C=elements(:,3); 
+	patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','none','EdgeColor','black');
 else
 	A=elements(:,1); B=elements(:,2); C=elements(:,3); D=elements(:,4); E=elements(:,5); F=elements(:,6);
Index: /issm/trunk/src/m/plot/plot_scatter.m
===================================================================
--- /issm/trunk/src/m/plot/plot_scatter.m	(revision 19104)
+++ /issm/trunk/src/m/plot/plot_scatter.m	(revision 19105)
@@ -37,5 +37,5 @@
 
 %OK, should we create a new colorbar for the occasion?
-if isempty(findobj(gcf,'tag','TMW_COLORBAR')),
+if isempty(findobj(gcf,'tag','TMW_COLORBAR')) && isempty(findobj(gcf,'Type','Colorbar')),
 	alreadyplot=false;
 else
@@ -46,6 +46,12 @@
 if (alreadyplot),
 	phch = get(findall(gcf,'type','image','tag','TMW_COLORBAR'),{'parent'});
-	h    = phch{1};
-	ylim=get(h,'YLim');
+	if ~isempty(phch),
+		h    = phch{1};
+		ylim=get(h,'YLim');
+	else
+		%R2014b +
+		h = findobj(gcf,'Type','Colorbar');
+		ylim = h.Limits;
+	end
 	palette=colormap;
 	numcolors=size(palette,1);
Index: /issm/trunk/src/m/plot/plot_section.m
===================================================================
--- /issm/trunk/src/m/plot/plot_section.m	(revision 19104)
+++ /issm/trunk/src/m/plot/plot_section.m	(revision 19105)
@@ -53,5 +53,9 @@
 			resolution=getfieldvalue(options,'resolution');
 		else %Default resolution
-			resolution=[1000 10*md.mesh.numberoflayers];
+			if is2d,
+				resolution=[1000 1];
+			else
+				resolution=[1000 10*md.mesh.numberoflayers];
+			end
 			disp(['plot_section warning: no resolution specified, use default resolution: [horizontal_resolution vertical_resolution]=[' num2str(resolution)  ']']);
 		end
Index: /issm/trunk/src/m/plot/plot_tensor_principalaxis.m
===================================================================
--- /issm/trunk/src/m/plot/plot_tensor_principalaxis.m	(revision 19104)
+++ /issm/trunk/src/m/plot/plot_tensor_principalaxis.m	(revision 19105)
@@ -29,5 +29,5 @@
 %take the center of each element if ~isonnode
 if datatype==1,
-	x=mean(md.mesh.x(md.mesh.elements'))'; y=mean(md.mesh.y(md.mesh.elements'))'; z=mean(md.mesh.z(md.mesh.elements'))';
+	x=mean(x(elements'))'; y=mean(y(elements'))'; z=mean(z(elements'))';
 end
 
Index: /issm/trunk/src/m/plot/plotdoc.m
===================================================================
--- /issm/trunk/src/m/plot/plotdoc.m	(revision 19104)
+++ /issm/trunk/src/m/plot/plotdoc.m	(revision 19105)
@@ -54,8 +54,6 @@
 disp('                  - ''quiver'': quiver plot');
 
-disp('       ''alloptions'': apply the options to all subplots if ''on''');
 disp('       ''axis'': same as standard matlab option (''equal'',''off'',''equal on'',...)');
 disp('       ''basin'': zoom on a given basin (''pineislandglacier'',''ronneiceshelf'', use isbasin to identify a basin');
-disp('                 ''hemisphere'': specify +1 or -1');
 disp('                 ''basindeltax'': in m');
 disp('                 ''showbasins'': write lables for every existing basin name around the center of the plot');
@@ -109,5 +107,4 @@
 disp('       ''contrast'': (default 1) coefficient to add contrast to the radar amplitude image used in overlays');
 disp('       ''highres'': resolution of overlayed radar amplitude image (default is 0, high resolution is 1).');
-disp('       ''hem'': specify hemisphere ''n'' or ''s'' (default is ''s'').');
 disp('       ''alpha'': transparency coefficient (the higher, the more transparent). Default is 1.5');
 disp('       ''scaling'': scaling factor used by quiver plots. Default is 0.4');
Index: /issm/trunk/src/m/plot/processdata.m
===================================================================
--- /issm/trunk/src/m/plot/processdata.m	(revision 19104)
+++ /issm/trunk/src/m/plot/processdata.m	(revision 19105)
@@ -25,5 +25,5 @@
 	end
 	choice=input(['please enter the field number? (between 1 and ' num2str(numel(F)) ')  ']);
-	[data datatype]=processdata(md,data.(F{choice}),options);
+	[data datatype]=processdata(md,data(1).(F{choice}),options);
 end
 
@@ -189,4 +189,18 @@
 	clear databak
 end
+if datatype==3,
+	%Mask?
+	if exist(options,'mask'),
+		flags=getfieldvalue(options,'mask');
+		pos=find(~flags);
+		if length(flags)==md.mesh.numberofvertices,
+			data(pos,:)=NaN;
+		elseif length(flags)==md.mesh.numberofelements
+			data(md.mesh.elements(pos,:),:)=NaN;
+		else
+			disp('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements');
+		end
+	end
+end
 
 %OK, if datatype=0 error out
Index: /issm/trunk/src/m/plot/processmesh.m
===================================================================
--- /issm/trunk/src/m/plot/processmesh.m	(revision 19104)
+++ /issm/trunk/src/m/plot/processmesh.m	(revision 19105)
@@ -21,5 +21,10 @@
 end
 
-%first load x,y, etc ... to speed up plot
+%special case for mesh 3dsurface
+if strcmp(domaintype(md.mesh),'3Dsurface'),
+	[x y z elements is2d isplanet] = processmesh(md.mesh,options);
+	return;
+end
+
 if ~strcmpi(getfieldvalue(options,'coord','xy'),'latlon'),
 	x=md.mesh.x;
Index: /issm/trunk/src/m/plot/radarpower.m
===================================================================
--- /issm/trunk/src/m/plot/radarpower.m	(revision 19104)
+++ /issm/trunk/src/m/plot/radarpower.m	(revision 19105)
@@ -36,5 +36,5 @@
 %figure out if we should go look for Greenland or Antarctica geotiff, or if user provided one.
 if ~exist(options,'overlay_image'),
-	if strcmpi(md.mesh.hemisphere,'n'),
+	if md.mesh.epsg==3413,
 		%if ~exist(['/u/astrid-r1b/ModelData/MOG/mog150_greenland_map.jpg']),
 		%	error(['radarpower error message: file ' '/u/astrid-r1b/ModelData/MOG/mog150_greenland_map.jpg not found.']);
@@ -106,5 +106,5 @@
 		system('rm -rf ./temp.tif');
 
-	elseif strcmpi(md.mesh.hemisphere,'s'),
+	elseif md.mesh.epsg==3031,
 		if ~exist(options,'geotiff_name'),
 			if highres,
@@ -138,5 +138,5 @@
 
 	else
-		error('field hemisphere should either be ''n'' or ''s''');
+		error('EPSG code not supported yet (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)');
 	end
 else
Index: /issm/trunk/src/m/plot/showregion.m
===================================================================
--- /issm/trunk/src/m/plot/showregion.m	(revision 19104)
+++ /issm/trunk/src/m/plot/showregion.m	(revision 19105)
@@ -15,10 +15,10 @@
 axis equal off
 %box off
-if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
+if md.mesh.epsg==3413,
 	A=expread(['/u/astrid-r1b/ModelData/Exp/Greenland.exp']);
-elseif strcmpi(md.mesh.hemisphere,'s') | strcmpi(md.mesh.hemisphere,'south'),
+elseif md.mesh.epsg==3031,
 	A=expread(['/u/astrid-r1b/ModelData/Exp/Antarctica.exp']);
 else
-	error('applyoptions error message: hemisphere not defined');
+	error('md.mesh.epsg not supported yet');
 end
 
Index: /issm/trunk/src/m/plot/writejsfield.m
===================================================================
--- /issm/trunk/src/m/plot/writejsfield.m	(revision 19105)
+++ /issm/trunk/src/m/plot/writejsfield.m	(revision 19105)
@@ -0,0 +1,29 @@
+function writejsfield(fid,name,variable,nods)
+%WRITEJSFIELD - write variable to javascript file 
+%
+%   Usage:
+%      writejsfield(fid,name,variable)
+%
+
+	%write array:
+	if size(variable,2)==1,
+		fprintf(fid,'<!-- %s{{{-->\n',name);
+		fprintf(fid,'%s=[',name);
+		for i=1:nods-1,
+			fprintf(fid,'%g,',variable(i));
+		end
+		fprintf(fid,'%g];\n',variable(end));
+		fprintf(fid,'<!--}}}-->\n');
+	else
+		%multi-sized array: 
+		fprintf(fid,'<!-- %s{{{-->\n',name);
+		fprintf(fid,'%s=[]\n',name);
+		for i=1:size(variable,2),
+			fprintf(fid,'%s["%i"]=[',name,i);
+			for j=1:nods-1,
+				fprintf(fid,'%g,',variable(j,i));
+			end
+			fprintf(fid,'%g];\n',variable(end,i));
+		end
+		fprintf(fid,'<!--}}}-->\n');
+	end
Index: /issm/trunk/src/m/plot/writejsfield.py
===================================================================
--- /issm/trunk/src/m/plot/writejsfield.py	(revision 19105)
+++ /issm/trunk/src/m/plot/writejsfield.py	(revision 19105)
@@ -0,0 +1,26 @@
+import numpy
+def writejsfield(fid,name,variable,nods):
+#WRITEJSFIELD - write variable to javascript file 
+#
+#   Usage:
+#      writejsfield(fid,name,variable)
+#
+	#write array:
+	#if not isinstance(variable, list):
+	if type(variable[0])==numpy.float64:
+		fid.write('<!-- {0}{{{{{{-->\n'.format(name))
+		fid.write('{0}=['.format(name))
+		for i in xrange(0, nods-1):
+			fid.write('{0},'.format(variable[i]))
+		fid.write('{0}];\n'.format(variable[-1]))
+		fid.write('<!--}}}}}}-->\n')
+	else:
+		#multi-sized array: 
+		fid.write('<!-- {0}{{{{{{-->\n'.format(name))
+		fid.write('{0}=[]\n'.format(name))
+		for i in xrange(0, len(variable[2])):
+			fid.write('{0}["{1}"]=['.format(name,i))
+			for j in xrange(1, nods-1):
+				fid.write('{0},'.format(variable[j][i]))
+			fid.write('{0}];\n'.format(variable[-1][i]))
+		fid.write('<!--}}}}}}-->\n')
Index: /issm/trunk/src/m/plot/writejsfile.m
===================================================================
--- /issm/trunk/src/m/plot/writejsfile.m	(revision 19105)
+++ /issm/trunk/src/m/plot/writejsfile.m	(revision 19105)
@@ -0,0 +1,59 @@
+function writejsfile(filename,model,keyname)
+%WRITEJSFILE - write model file to javascript database
+%
+%   Usage:
+%      writejsfile(filename,model,keyname)
+%
+
+	nods=length(model.x);
+	nel=size(model.index,1);
+	nx=length(model.contourx1);
+	
+	fid=fopen(filename,'w');
+
+	fprintf(fid,'model = {};\n');
+	fprintf(fid,'model["title"]="%s";\n',model.title);
+	fprintf(fid,'model["initialZoomFactor"]=%s;\n',model.initialZoomFactor);
+	
+	%write index:
+	fprintf(fid,'<!-- model["index"]{{{-->\n');
+	fprintf(fid,'model["index"]=[');
+	for i=1:nel-1,
+		fprintf(fid,'[%i, %i, %i],',model.index(i,1),model.index(i,2),model.index(i,3));
+	end
+	fprintf(fid,'[%i, %i, %i]];\n',model.index(end,1),model.index(end,2),model.index(end,3));
+	fprintf(fid,'<!--}}}-->\n');
+	
+	writejsfield(fid,'model["x"]',model.x,nods);
+	writejsfield(fid,'model["y"]',model.y,nods);
+	writejsfield(fid,'model["z"]',model.z,nods);
+	writejsfield(fid,'model["surface"]',model.surface,nods);
+	writejsfield(fid,'model["contourx1"]',model.contourx1,nx);
+	writejsfield(fid,'model["contoury1"]',model.contoury1,nx);
+	writejsfield(fid,'model["contourz1"]',model.contourz1,nx);
+	writejsfield(fid,'model["contourx2"]',model.contourx2,nx);
+	writejsfield(fid,'model["contoury2"]',model.contoury2,nx);
+	writejsfield(fid,'model["contourz2"]',model.contourz2,nx);
+
+
+	results=model.results;
+	fprintf(fid,'results={};\n');
+
+	for i=1:length(results),
+		fprintf(fid,'result={};\n');
+		writejsfield(fid,'result["data"]',results(i).data,nods);
+		fprintf(fid,'<!--{{{-->\n');
+		fprintf(fid,'result["caxis"]=[%g,%g];\n',results(i).caxis(1),results(i).caxis(2));
+		fprintf(fid,'result["label"]="%s";\n',results(i).label);
+		fprintf(fid,'result["shortlabel"]="%s";\n',results(i).shortlabel);
+		fprintf(fid,'result["unit"]="%s";\n',results(i).unit);
+		if size(results(i).data,2)>1,
+			fprintf(fid,'result["time_range"]=[%g,%g];\n',results(i).time_range(1),results(i).time_range(2));
+		end
+		fprintf(fid,'results["%i"]=result;\n',i);
+		fprintf(fid,'<!--}}}-->\n');
+	end
+	fprintf(fid,'model.results=results;\n');
+	fprintf(fid,'models["%s"]=model;\n',keyname);
+
+	fclose(fid);
Index: /issm/trunk/src/m/plot/writejsfile.py
===================================================================
--- /issm/trunk/src/m/plot/writejsfile.py	(revision 19105)
+++ /issm/trunk/src/m/plot/writejsfile.py	(revision 19105)
@@ -0,0 +1,57 @@
+import numpy
+from writejsfield import writejsfield
+def writejsfile(filename,model,keyname):
+#WRITEJSFILE - write model file to javascript database
+#
+#   Usage:
+#      writejsfile(filename,model,keyname)
+#
+
+	nods=len(model.x)
+	nel=len(model.index)
+	nx=len(model.contourx1)
+	print(filename)	
+	fid=open(filename,'w', 0)
+
+	fid.write('model = {};\n')
+	fid.write('model["title"]="{0}";\n'.format(model.title))
+	fid.write('model["initialZoomFactor"]={0};\n'.format(model.initialZoomFactor))
+	#write index:
+	fid.write('<!-- model["index"]{{{-->\n')
+	fid.write('model["index"]=[')
+	for i in xrange(0, nel-1):
+		fid.write('[{0}, {1}, {2}],'.format(model.index[i][0],model.index[i][1],model.index[i][2]))
+	fid.write('[{0}, {1}, {2}]];\n'.format(model.index[-1][0],model.index[-1][1],model.index[-1][2]))
+	fid.write('<!--}}}-->\n')
+	print('writing model coordinates')
+	writejsfield(fid,'model["x"]',model.x,nods)
+	writejsfield(fid,'model["y"]',model.y,nods)
+	writejsfield(fid,'model["z"]',model.z,nods)
+	writejsfield(fid,'model["surface"]',model.surface,nods)
+	writejsfield(fid,'model["contourx1"]',model.contourx1,nx)
+	writejsfield(fid,'model["contoury1"]',model.contoury1,nx)
+	writejsfield(fid,'model["contourz1"]',model.contourz1,nx)
+	writejsfield(fid,'model["contourx2"]',model.contourx2,nx)
+	writejsfield(fid,'model["contoury2"]',model.contoury2,nx)
+	writejsfield(fid,'model["contourz2"]',model.contourz2,nx)
+
+	print('writing results')
+	results=model.results
+	fid.write('results={};\n')
+
+	for i in xrange(0,len(results)):
+		fid.write('result={};\n')
+		writejsfield(fid,'result["data"]',results[i].data,nods)
+		fid.write('<!--{{{-->\n')
+		fid.write('result["caxis"]=[{0},{1}];\n'.format(results[i].caxis[0],results[i].caxis[1]))
+		fid.write('result["label"]="{0}";\n'.format(results[i].label))
+		fid.write('result["shortlabel"]="{0}";\n'.format(results[i].shortlabel))
+		fid.write('result["unit"]="{0}";\n'.format(results[i].unit))
+		if type(results[i].data)==numpy.float64:
+			fid.write('result["time_range"]=[{0},{1}];\n'.format(results[i].time_range[0],results[i].time_range[1]))
+		fid.write('results["{0}"]=result;\n'.format(i))
+		fid.write('<!--}}}-->\n')
+	fid.write('model.results=results;\n')
+	fid.write('models["{0}"]=model;\n'.format(keyname))
+
+	fid.close()
Index: /issm/trunk/src/m/qmu/dakota_out_parse.m
===================================================================
--- /issm/trunk/src/m/qmu/dakota_out_parse.m	(revision 19104)
+++ /issm/trunk/src/m/qmu/dakota_out_parse.m	(revision 19105)
@@ -219,4 +219,6 @@
 dquart3=prctile_issm(data,75,1);
 dmax   =max         (data,[],1);
+dmin95=prctile_issm(data,5,1);
+dmax95=prctile_issm(data,95,1);
 
 %  same as Dakota scm, Excel correl
@@ -237,4 +239,6 @@
     dresp(i).quart3    =dquart3(i);
     dresp(i).max       =dmax(i);
+	 dresp(i).dmin95    =dmin95(i);
+	 dresp(i).dmax95    =dmax95(i);
 end
 
Index: /issm/trunk/src/m/qmu/plot/plot_hist_norm.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_hist_norm.m	(revision 19104)
+++ /issm/trunk/src/m/qmu/plot/plot_hist_norm.m	(revision 19105)
@@ -44,5 +44,7 @@
 %    ymin2         (numeric, minimum of cdf y-axis)
 %    ymax2         (numeric, maximum of cdf y-axis)
-%    nrmplt        (char, 'line' or 'off' to change nrm plots from 'bar')
+%    nrmplt        (char, pass 'l' or 'off' to change nrm plots 
+%                   from default of 'bar' or 'b' to 'line' instead, 
+%                   pass 's' to change nrm plot to 'stairs')                                                  
 %    cdfplt        (char, 'off' to turn off cdf line plots)
 %    cdfleg        (char, 'off' to turn off cdf legends)
@@ -174,5 +176,5 @@
 
 %  parameters
-
+LineWidth=1;
 while (iarg <= nargin-1)
     if ischar(varargin{iarg})
@@ -180,5 +182,6 @@
                 {'hmin','hmax','hnint',...
                  'ymin1','ymax1','ymin2','ymax2',...
-                 'nrmplt','EdgeColor','FaceColor','cdfplt','cdfleg','nrmleg','cmap','titleplt','xlabelplt','ylabelplt','FontSize'},...
+                 'nrmplt','EdgeColor','FaceColor','LineWidth','cdfplt',...
+				     'cdfleg','nrmleg','cmap','titleplt','xlabelplt','ylabelplt','FontSize'},...
                 'exact'))
             eval([varargin{iarg} '=varargin{iarg+1};']);
@@ -251,5 +254,7 @@
     hl1(1*ncol+1:2*ncol)=...
         line(edges(1:end-1),dhistc(1:end-1,1*ncol+1:2*ncol),...
-             'LineWidth',2);
+             'LineWidth',LineWidth);
+elseif strncmpi(nrmplt,'s',1)
+	 hl1=stairs(edges(1:end-1)-(hmax-hmin)/hnint/2,dhistc(1:end-1,1:ncol));
 elseif strncmpi(nrmplt,'off',3)
     hl1=bar (edges(1:end-1),dhistc(1:end-1,1:1*ncol));
@@ -269,6 +274,8 @@
 
 %set face and edge color
-for i=1:length(hl1)
-	set(hl1(i),'EdgeColor',EdgeColor,'FaceColor',FaceColor);
+if ~strncmpi(nrmplt,'s',1)
+	for i=1:length(hl1)
+		set(hl1(i),'EdgeColor',EdgeColor,'FaceColor',FaceColor,'LineWidth',LineWidth);
+	end
 end
 
@@ -282,19 +289,21 @@
 cmap=colormap;
 for i=1:length(hl1)
-    if (length(hl1) > 1)
-        imap=round((i-1)/(length(hl1)-1)*(size(cmap,1)-1))+1;
-    else
-        imap=1;
-    end
-    if     strcmpi(get(hl1(i),'Type'),'hggroup')
-        if ischar(get(hl1(i),'FaceColor')) && ...
-           strcmpi(get(hl1(i),'FaceColor'),'flat')
-            set(hl1(i),'FaceColor',cmap(imap,:))
-        else
-            set(hl1(i),'FaceColor',get(hl1(i),'FaceColor'))
-        end
-    elseif strcmpi(get(hl1(i),'Type'),'line')
-        set(hl1(i),'Color',cmap(imap,:))
-    end
+	if (length(hl1) > 1)
+		imap=round((i-1)/(length(hl1)-1)*(size(cmap,1)-1))+1;
+	else
+		imap=1;
+	end
+	if ~strncmpi(nrmplt,'s',1) && strcmpi(get(hl1(i),'Type'),'hggroup')
+		if ischar(get(hl1(i),'FaceColor')) && ...
+				strcmpi(get(hl1(i),'FaceColor'),'flat')
+			set(hl1(i),'FaceColor',cmap(imap,:))
+		else
+			set(hl1(i),'FaceColor',get(hl1(i),'FaceColor'))
+		end
+	elseif strcmpi(get(hl1(i),'Type'),'line')
+		set(hl1(i),'Color',cmap(imap,:))
+	elseif strncmpi(nrmplt,'s',1)
+		set(hl1(i),'Color',EdgeColor,'LineWidth',2)
+	end
 end
 
Index: /issm/trunk/src/m/solve/WriteData.m
===================================================================
--- /issm/trunk/src/m/solve/WriteData.m	(revision 19104)
+++ /issm/trunk/src/m/solve/WriteData.m	(revision 19105)
@@ -27,5 +27,5 @@
 format  = getfieldvalue(options,'format');
 mattype = getfieldvalue(options,'mattype',0);    %only required for matrices
-forcinglength = getfieldvalue(options,'forcinglength',-1);
+timeserieslength = getfieldvalue(options,'timeserieslength',-1);
 
 %Process sparse matrices
@@ -37,5 +37,5 @@
 if exist(options,'scale'),
 	scale = getfieldvalue(options,'scale');
-	if size(data,1)==forcinglength,
+	if size(data,1)==timeserieslength,
 		data(1:end-1,:) = scale.*data(1:end-1,:);
 	else
@@ -43,5 +43,5 @@
 	end
 end
-if(size(data,1)==forcinglength),
+if(size(data,1)==timeserieslength),
 	yts=365.0*24.0*3600.0;
 	data(end,:) = data(end,:)*yts;
Index: /issm/trunk/src/m/solve/WriteData.py
===================================================================
--- /issm/trunk/src/m/solve/WriteData.py	(revision 19104)
+++ /issm/trunk/src/m/solve/WriteData.py	(revision 19105)
@@ -35,5 +35,5 @@
 	format  = options.getfieldvalue('format')
 	mattype = options.getfieldvalue('mattype',0)    #only required for matrices
-	forcinglength = options.getfieldvalue('forcinglength',-1)
+	timeserieslength = options.getfieldvalue('timeserieslength',-1)
 
 	#Process sparse matrices
@@ -46,5 +46,5 @@
 		scale = options.getfieldvalue('scale')
 		if numpy.size(data) > 1 :
-			if numpy.size(data,0)==forcinglength:
+			if numpy.size(data,0)==timeserieslength:
 				data=numpy.array(data)
 				data[0:-1,:] = scale*data[0:-1,:]
@@ -54,5 +54,5 @@
 			data  = scale*data
 	if numpy.size(data) > 1 :
-		if numpy.size(data,0)==forcinglength:
+		if numpy.size(data,0)==timeserieslength:
 			yts=365.0*24.0*3600.0
 			data[-1,:] = yts*data[-1,:]
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.m
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 19104)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 19105)
@@ -184,4 +184,6 @@
 	elseif strcmp(fieldname,'SurfaceforcingsMassBalance'),
 		field = field*yts;
+	elseif strcmp(fieldname,'CalvingCalvingrate'),
+		field = field*yts;
 	end
 
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.py
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 19104)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 19105)
@@ -184,4 +184,7 @@
 		elif m.strcmp(fieldname,'SurfaceforcingsMassBalance'):
 			field = field*yts
+		elif m.strcmp(fieldname,'CalvingCalvingrate'):
+			field = field*yts
+
 
 		result=OrderedDict()
Index: /issm/trunk/src/m/solve/waitonlock.m
===================================================================
--- /issm/trunk/src/m/solve/waitonlock.m	(revision 19104)
+++ /issm/trunk/src/m/solve/waitonlock.m	(revision 19105)
@@ -27,5 +27,5 @@
 
 %If we are using the generic cluster in interactive mode, job is already complete
-if isa(cluster,'generic') & cluster.interactive
+if (isa(cluster,'generic') & cluster.interactive) | isa(cluster,'generic_static'),
 	%We are in interactive mode, no need to check for job completion
 	ispresent=1;
Index: /issm/trunk/src/wrappers/ExpSimplify/ExpSimplify.cpp
===================================================================
--- /issm/trunk/src/wrappers/ExpSimplify/ExpSimplify.cpp	(revision 19104)
+++ /issm/trunk/src/wrappers/ExpSimplify/ExpSimplify.cpp	(revision 19105)
@@ -18,5 +18,5 @@
 	_printf_("   Example:\n");
 	_printf_("      ExpSimplify('file.exp',100);\n");
-	_printf_("      ExpSimplify('file.exp',100,'remove1',false);\n");
+	_printf_("      ExpSimplify('file.exp',100,'min',4);\n");
 }/*}}}*/
 void simplify(Contour<double>* contour,bool* flags,int ind0,int ind1,double tolerance){/*{{{*/
Index: /issm/trunk/src/wrappers/ExpToLevelSet/ExpToLevelSet.cpp
===================================================================
--- /issm/trunk/src/wrappers/ExpToLevelSet/ExpToLevelSet.cpp	(revision 19105)
+++ /issm/trunk/src/wrappers/ExpToLevelSet/ExpToLevelSet.cpp	(revision 19105)
@@ -0,0 +1,76 @@
+/*! \file  ContourtoMesh
+    \brief: takes a  contour file, a cloud of points, and figures out a levelset dependent on the distance between the contour and 
+	the cloud.
+*/
+
+#include "./ExpToLevelSet.h"
+
+void ExpToLevelSetUsage(void){/*{{{*/
+	_printf_("EXPTOLEVELSET - determien levelset distance between a contour and a cloud of points\n");
+	_printf_("\n");
+	_printf_("      Usage: \n");
+	_printf_("         distance=ExpToLevelSet(x,y,contourname)\n");
+	_printf_("\n");
+	_printf_("         x,y: cloud point.\n");
+	_printf_("         contourname: name of .exp file containing the contours.\n");
+	_printf_("         distance: distance vector representing a levelset where the 0 level is one the contour segments', \n");
+	_printf_("\n");
+	_printf_("      Example: \n");
+	_printf_("         distance=ExpToLevelSet(md.mesh.x,md.mesh.y,'Contour.exp')\n");
+	_printf_("\n");
+}/*}}}*/
+WRAPPER(ExpToLevelSet){
+
+	/*diverse: */
+	int i;
+
+	/* required input: */
+	int       nods;
+	double   *x           = NULL;
+	double   *y           = NULL;
+	char     *interptype  = NULL;
+	double *flags = NULL;
+	Contours *contours    = NULL;
+
+	/* output: */
+	double *distance  = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*check on input arguments: */
+	if(nrhs!=NRHS | nlhs!=NLHS){
+		ExpToLevelSetUsage();
+		_error_("usage. See above");
+	}
+
+	/*Fetch inputs: */
+	FetchData(&x,&nods,NULL,X);
+	FetchData(&y,NULL,NULL,Y);
+	FetchData(&contours,CONTOUR);
+
+	/*Run interpolation routine: */
+	ExpToLevelSetx( &distance,x,y,nods,contours);
+	ContourToNodesx(&flags,x,y,nods,contours,2);
+
+	/*Make flags into a sign, left or right, or nill: */
+	for(i=0;i<nods;i++){
+		if (flags[i]==0) flags[i]=-1;
+		else if (flags[i]==2) flags[i]=0;
+	}
+
+	/*Multiply flags and distance: */
+	for(i=0;i<nods;i++)distance[i]*=flags[i];
+
+	/* output: */
+	WriteData(PLHS0,distance,nods);
+
+	/*Clean up*/
+	xDelete<double>(x);
+	xDelete<double>(y);
+	delete contours;
+	delete distance;
+	
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/ExpToLevelSet/ExpToLevelSet.h
===================================================================
--- /issm/trunk/src/wrappers/ExpToLevelSet/ExpToLevelSet.h	(revision 19105)
+++ /issm/trunk/src/wrappers/ExpToLevelSet/ExpToLevelSet.h	(revision 19105)
@@ -0,0 +1,56 @@
+/*
+	ExpToLevelSet.h
+*/
+
+#ifndef _EXPTOLEVELSET_H
+#define _EXPTOLEVELSET_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
+#include "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+#include "../../c/shared/io/io.h"
+#include "../../c/shared/Enum/Enum.h"
+
+#undef __FUNCT__
+#define __FUNCT__ "ExpToLevelSet"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define X           prhs[0]
+#define Y           prhs[1]
+#define CONTOUR     prhs[2]
+
+/* serial output macros: */
+#define PLHS0 (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define X           PyTuple_GetItem(args,0)
+#define Y           PyTuple_GetItem(args,1)
+#define CONTOUR     PyTuple_GetItem(args,2)
+/* serial output macros: */
+#define PLHS0 output,0
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS 3
+
+#endif  /* _EXPTOLEVELSET_H */
Index: /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 19104)
+++ /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 19105)
@@ -76,4 +76,12 @@
 
 	/*end module: */
+	xDelete<int>(index);
+	xDelete<double>(x_data);
+	xDelete<double>(y_data);
+	xDelete<double>(data);
+	xDelete<double>(x_interp);
+	xDelete<double>(y_interp);
+	xDelete<double>(data_interp);
+	delete options;
 	MODULEEND();
 }
Index: /issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp
===================================================================
--- /issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp	(revision 19104)
+++ /issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp	(revision 19105)
@@ -76,4 +76,11 @@
 		#endif
 	}
+	else if(strcmp(name,"_PETSC_MINOR_")==0){
+		#ifdef _PETSC_MINOR_
+		value = IssmDouble(_PETSC_MINOR_);
+		#else
+		_error_("_PETSC_MINOR_ not found in config.h");
+		#endif
+	}
 	else if(strcmp(name,"_DAKOTA_VERSION_")==0){
 		#ifdef _DAKOTA_VERSION_
@@ -115,4 +122,29 @@
 		xMemCpy<char>(svalue,PACKAGE_BUILD_DATE,(strlen(PACKAGE_BUILD_DATE)+1));
 	}
+	else if(strcmp(name,"HOST_OS")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(HOST_OS)+1);
+		xMemCpy<char>(svalue,HOST_OS,(strlen(HOST_OS)+1));
+	}
+	else if(strcmp(name,"USER_NAME")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(USER_NAME)+1);
+		xMemCpy<char>(svalue,USER_NAME,(strlen(USER_NAME)+1));
+	}
+	else if(strcmp(name,"HOST_VENDOR")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(HOST_VENDOR)+1);
+		xMemCpy<char>(svalue,HOST_VENDOR,(strlen(HOST_VENDOR)+1));
+	}
+	else if(strcmp(name,"HOST_OS")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(HOST_OS)+1);
+		xMemCpy<char>(svalue,HOST_OS,(strlen(HOST_OS)+1));
+	}
+	else if(strcmp(name,"HOST_ARCH")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(HOST_ARCH)+1);
+		xMemCpy<char>(svalue,HOST_ARCH,(strlen(HOST_ARCH)+1));
+	}
 	else{
 		_error_("variable " << name << " not supported yet");
Index: /issm/trunk/src/wrappers/M1qn3/M1qn3.cpp
===================================================================
--- /issm/trunk/src/wrappers/M1qn3/M1qn3.cpp	(revision 19105)
+++ /issm/trunk/src/wrappers/M1qn3/M1qn3.cpp	(revision 19105)
@@ -0,0 +1,185 @@
+/*!\file M1qn3.c
+ * \brief: data interpolation from a list of (x,y,values) into mesh vertices
+*/
+
+#include "./M1qn3.h"
+
+#ifdef _HAVE_M1QN3_
+/*m1qn3 prototypes {{{*/
+extern "C" void *ctonbe_; // DIS mode : Conversion
+extern "C" void *ctcabe_; // DIS mode : Conversion
+extern "C" void *euclid_; // Scalar product
+typedef void (*SimulFunc) (long* indic,long* n, double* x, double* pf,double* g,long [],float [],void* dzs);
+extern "C" void m1qn3_ (void f(long* indic,long* n, double* x, double* pf,double* g,long [],float [],void* dzs),
+			void **, void **, void **,
+			long *, double [], double *, double [], double*, double *,
+			double *, char [], long *, long *, long *, long *, long *, long *, long [], double [], long *,
+			long *, long *, long [], float [],void* );
+/*Cost function prototype*/
+void fakesimul(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs);
+typedef struct {
+	int priorn; 
+	int counter; 
+	double* Gs; 
+	double* Xs;
+	double* Js;
+} Data; 
+/*}}}*/
+void M1qn3Usage(void){/*{{{*/
+	_printf0_("   usage:\n");
+	_printf0_("         X=M1qn3(Xs,Gs);\n");
+	_printf0_("   where:\n");
+	_printf0_("      Xs are the X values (m x n, where m is the number of independents, n the number of evaluations previously carried out on X)\n");
+	_printf0_("      Gs are the G (gradient) values (m x n, where m is the number of independents, n the number of evaluations previously carried out on X,G)\n");
+	_printf0_("      X - the new direction.\n");
+	_printf0_("\n");
+}/*}}}*/
+#endif
+WRAPPER(M1qn3){
+
+#ifdef _HAVE_M1QN3_
+	/*input: */
+	double* Xs=NULL;
+	double* Gs=NULL;
+	double* Js=NULL;
+	int     intn;
+	int     priorn;
+	int     maxsteps,maxiter;
+	Data    data_struct;
+
+	/* output: */
+	double* X_out = NULL;
+
+	/*intermediary: */
+	double* G=NULL;
+	double* X=NULL;
+	double f;
+	double dxmin=.01;
+	double gttol=.0001;
+	long   omode;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if(nlhs!=NLHS){
+		M1qn3Usage();
+		_error_("M1qn3 usage error");
+	}
+	if(nrhs!=5){
+		M1qn3Usage();
+		_error_("M1qn3 usage error");
+	}
+
+	/*Input datasets: */
+	FetchData(&Xs,&intn,&priorn,XHANDLE);
+	FetchData(&Gs,&intn,&priorn,GHANDLE);
+	FetchData(&Js,&priorn,JHANDLE);
+	FetchData(&maxsteps,MAXSTEPSHANDLE);
+	FetchData(&maxiter,MAXITERHANDLE);
+
+	/*_printf_("Xs: " << Xs[0] << "\n");
+	_printf_("Gs: " << Gs[0] << "\n");
+	_printf_("Js: " << Js[0] << "\n");
+	_printf_("maxiter: " << maxiter << "\n");
+	_printf_("maxsteps: " << maxsteps << "\n");*/
+
+	/*Initialize M1QN3 parameters*/
+	SimulFunc costfuncion  = &fakesimul;  /*Cost function address*/
+	void**    prosca       = &euclid_;  /*Dot product function (euclid is the default)*/
+	char      normtype[]   = "dfn";     /*Norm type: dfn = scalar product defined by prosca*/
+	long      izs[5];                   /*Arrays used by m1qn3 subroutines*/
+	long      iz[5];                    /*Integer m1qn3 working array of size 5*/
+	float     rzs[1];                   /*Arrays used by m1qn3 subroutines*/
+	long      impres       = 0;         /*verbosity level*/
+	long      imode[3]     = {0};       /*scaling and starting mode, 0 by default*/
+	long      indic        = 4;         /*compute f and g*/
+	long      reverse      = 0;         /*reverse or direct mode*/
+	long      io           = 6;         /*Channel number for the output*/
+
+	/*Optimization criterions*/
+	long niter = long(maxsteps); /*Maximum number of iterations*/
+	long nsim  = long(maxiter);/*Maximum number of function calls*/
+
+	/*Get problem dimension and initialize X, G and f: */
+	/*_printf_("intn: " << intn << "\n");
+	_printf_("priorn: " << priorn << "\n");*/
+	long n = long(intn);
+	IssmPDouble* G = xNew<IssmPDouble>(n); for (int i=0;i<n;i++)G[i]=Gs[i*priorn];
+	IssmPDouble* X = xNew<IssmPDouble>(n); for (int i=0;i<n;i++)X[i]=Xs[i*priorn];
+	f = Js[0];
+	
+	/*_printf_("X: " << X[0] << "\n");
+	_printf_("G: " << G[0] << "\n");
+	_printf_("J: " << f << "\n");
+	_printf_("n: " << n << "\n");*/
+
+
+	/*Allocate m1qn3 working arrays (see doc)*/
+	long      m   = 100;
+	long      ndz = 4*n+m*(2*n+1);
+	double*   dz  = xNew<double>(ndz);
+	double f1=f;
+
+	/*Initialize: */
+	data_struct.priorn=priorn;
+	data_struct.counter=0;
+	data_struct.Gs=Gs;
+	data_struct.Js=Js;
+	data_struct.Xs=Xs;
+
+	m1qn3_(costfuncion,prosca,&ctonbe_,&ctcabe_,
+				&n,X,&f,G,&dxmin,&f1,
+				&gttol,normtype,&impres,&io,imode,&omode,&niter,&nsim,iz,dz,&ndz,
+				&reverse,&indic,izs,rzs,(void*)&data_struct);
+
+	switch(int(omode)){
+		case 0: /*_printf0_("   Stop requested (indic = 0)\n"); */ break;
+		case 1:  _printf0_("   Convergence reached (gradient satisfies stopping criterion)\n"); break;
+		case 2:  _printf0_("   Bad initialization\n"); break;
+		case 3:  _printf0_("   Line search failure\n"); break;
+		case 4:  _printf0_("   Maximum number of iterations exceeded\n");break;
+		case 5:  _printf0_("   Maximum number of function calls exceeded\n"); break;
+		case 6:  _printf0_("   stopped on dxmin during line search\n"); break;
+		case 7:  _printf0_("   <g,d> > 0  or  <y,s> <0\n"); break;
+		default: _printf0_("   Unknown end condition\n");
+	}
+
+	/*build output: */
+	X_out=xNew<IssmPDouble>(n);
+	for(int i=0;i<n;i++)X_out[i]=X[i];
+
+	/*Write data: */
+	WriteData(XOUT,X_out,n);
+
+	/*end module: */
+	MODULEEND();
+	#else
+	_error_("m1qn3 is not installed");
+	#endif
+}
+
+
+#ifdef _HAVE_M1QN3_
+void fakesimul(long* indic,long* n,double* X,double* pf,double* G,long izs[1],float rzs[1],void* dzs){
+
+	Data* ds=(Data*)dzs;
+	double* Xs=ds->Xs;
+	double* Gs=ds->Gs;
+	double* Js=ds->Js;
+	
+	/*Are we done? : */
+	if(ds->counter+1==ds->priorn){
+		*indic=0;
+		return;
+	}
+	else{
+		//_printf0_("counter: " << ds->counter << "\n");
+		ds->counter++;
+		*pf=Js[ds->counter];
+		for(int i=0;i<*n;i++)X[i]=Xs[ds->priorn*i+ds->counter];
+		for(int i=0;i<*n;i++)G[i]=Gs[ds->priorn*i+ds->counter];
+	}
+
+}
+#endif
Index: /issm/trunk/src/wrappers/M1qn3/M1qn3.h
===================================================================
--- /issm/trunk/src/wrappers/M1qn3/M1qn3.h	(revision 19105)
+++ /issm/trunk/src/wrappers/M1qn3/M1qn3.h	(revision 19105)
@@ -0,0 +1,53 @@
+/*!\file M1qn3.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _M1QN3_WRAPPER_H
+#define _M1QN3_WRAPPER_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../bindings.h"
+#include "../../c/main/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "M1qn3"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define XHANDLE       prhs[0]
+#define GHANDLE       prhs[1]
+#define JHANDLE       prhs[2]
+#define MAXSTEPSHANDLE prhs[3]
+#define MAXITERHANDLE prhs[4]
+/* serial output macros: */
+#define XOUT (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define XHANDLE   PyTuple_GetItem(args,0)
+#define GHANDLE       PyTuple_GetItem(args,1)
+#define JHANDLE       PyTuple_GetItem(args,2)
+#define MAXSTEPSHANDLE PyTuple_GetItem(args,3)
+#define MAXITERHANDLE PyTuple_GetItem(args,4)
+/* serial output macros: */
+#define XOUT output,0
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+
+#endif  /* _M1QN3_WRAPPER_H */
Index: /issm/trunk/src/wrappers/matlab/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 19104)
+++ /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 19105)
@@ -8,40 +8,22 @@
 
 #matlab io{{{
-lib_LIBRARIES = libISSMMatlab.a 
-if SHAREDLIBS
 lib_LTLIBRARIES = libISSMMatlab.la
-else
-lib_LTLIBRARIES =
-endif
-
-io_sources= ./include/matlabincludes.h\
-				./io/matlabio.h\
-				./io/CheckNumMatlabArguments.cpp\
+
+io_sources= ./io/CheckNumMatlabArguments.cpp\
 				./io/WriteMatlabData.cpp\
 				./io/FetchMatlabData.cpp
 
-ALLCXXFLAGS= -fPIC -D_GNU_SOURCE -fno-omit-frame-pointer -pthread -D_CPP_ -D_WRAPPERS_ $(CXXFLAGS) $(CXXOPTFLAGS) 
-
-libISSMMatlab_a_SOURCES = $(io_sources)
-libISSMMatlab_a_CXXFLAGS= $(ALLCXXFLAGS)
-if SHAREDLIBS
+ALLCXXFLAGS= -fPIC -D_WRAPPERS_ $(CXXFLAGS) $(CXXOPTFLAGS) 
+
 libISSMMatlab_la_SOURCES = $(io_sources)
-endif
+libISSMMatlab_la_CXXFLAGS= $(ALLCXXFLAGS)
 #}}}
 #api io{{{
-lib_LIBRARIES += libISSMApi.a 
-if SHAREDLIBS
 lib_LTLIBRARIES += libISSMApi.la
-else
-lib_LTLIBRARIES +=
-endif
 
 api_sources= ./io/ApiPrintf.cpp
 
-libISSMApi_a_SOURCES = $(api_sources)
-libISSMApi_a_CXXFLAGS= $(ALLCXXFLAGS)
-if SHAREDLIBS
 libISSMApi_la_SOURCES = $(api_sources)
-endif
+libISSMApi_la_CXXFLAGS= $(ALLCXXFLAGS)
 #}}}
 #Wrappers {{{
@@ -54,4 +36,5 @@
 						 EnumToString.la\
 						 ExpSimplify.la\
+						 ExpToLevelSet.la\
 						 InterpFromGridToMesh.la\
 						 InterpFromMeshToMesh2d.la\
@@ -62,4 +45,5 @@
 						 Ll2xy.la\
 						 NodeConnectivity.la\
+						 M1qn3.la\
 						 MeshPartition.la\
 						 MeshProfileIntersection.la\
@@ -95,5 +79,5 @@
 
 #Matlab part
-AM_LDFLAGS = -module $(MEXLINK) -shrext ${EXEEXT}  -L/usr/lib
+AM_LDFLAGS = -module $(MEXLINK) -shrext ${EXEEXT} --export-dynamic -rdynamic
 if VERSION
 AM_LDFLAGS +=
@@ -102,14 +86,18 @@
 endif
 
-AM_CXXFLAGS +=  -D_HAVE_MATLAB_MODULES_  -D_GNU_SOURCE -fPIC -fno-omit-frame-pointer -pthread 
-
-if SHAREDLIBS
+if STANDALONE_MODULES
+AM_LDFLAGS += -Wl,-static
+endif
+
+AM_CXXFLAGS +=  -D_HAVE_MATLAB_MODULES_ -fPIC
+
 deps += ./libISSMMatlab.la ../../c/libISSMModules.la ../../c/libISSMCore.la ./libISSMApi.la
 
-else
-deps += ./libISSMMatlab.a ../../c/libISSMModules.a ../../c/libISSMCore.a ./libISSMApi.a
 if ADOLC
 deps += $(ADOLCLIB)
 endif
+
+if FORTRAN
+deps += $(FLIBS) $(FORTRANLIB)
 endif
 
@@ -121,148 +109,126 @@
 #}}}
 # Module sources and dependencies {{{
-libISSMMatlab_la_LIBADD = ./../../c/libISSMCore.la ./../../c/libISSMModules.la $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MATHLIB) $(MEXLIB) 
-libISSMMatlab_la_LDFLAGS = -module -export-dynamic
-
-libISSMApi_la_LIBADD = $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MATHLIB) $(MEXLIB)
-libISSMApi_la_LDFLAGS = -module -export-dynamic
-
-BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp\
-								../BamgMesher/BamgMesher.h
-BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
-									  ../BamgConvertMesh/BamgConvertMesh.h
-BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-BamgTriangulate_la_SOURCES = ../BamgTriangulate/BamgTriangulate.cpp\
-									  ../BamgTriangulate/BamgTriangulate.h
-BamgTriangulate_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-Chaco_la_SOURCES = ../Chaco/Chaco.cpp\
-						 ../Chaco/Chaco.h
-Chaco_la_LIBADD = ${deps} $(MPILIB) $(CHACOLIB) $(GSLLIB) $(PETSCLIB)
-
-ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
-									../ContourToMesh/ContourToMesh.h
-ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
-
-ContourToNodes_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
-									 ../ContourToNodes/ContourToNodes.h
-ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-ElementConnectivity_la_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
-											../ElementConnectivity/ElementConnectivity.h
-ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-EnumToString_la_SOURCES = ../EnumToString/EnumToString.cpp\
-								  ../EnumToString/EnumToString.h
-EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-StringToEnum_la_SOURCES = ../StringToEnum/StringToEnum.cpp\
-								  ../StringToEnum/StringToEnum.h
-StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
-											 ../InterpFromGridToMesh/InterpFromGridToMesh.h
-InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
-
-InterpFromMeshToMesh2d_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
-												../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
-InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
-
-InterpFromMeshToMesh3d_la_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
-												../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
-InterpFromMeshToMesh3d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-InterpFromMeshToGrid_la_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
-											 ../InterpFromMeshToGrid/InterpFromMeshToGrid.h
-InterpFromMeshToGrid_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-InterpFromMesh2d_la_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp\
-										../InterpFromMesh2d/InterpFromMesh2d.h
-InterpFromMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
-
-IssmConfig_la_SOURCES = ../IssmConfig/IssmConfig.cpp\
-										../IssmConfig/IssmConfig.h
+libISSMMatlab_la_LIBADD = ./../../c/libISSMCore.la ./../../c/libISSMModules.la $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB) $(MATHLIB) $(MEXLIB) 
+
+if STANDALONE_LIBRARIES
+libISSMMatlab_la_LDFLAGS = -static 
+endif
+
+libISSMApi_la_LIBADD = $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB) $(MATHLIB) $(MEXLIB)
+
+if STANDALONE_LIBRARIES
+libISSMApi_la_LDFLAGS = -static 
+endif
+
+BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp
+BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp
+BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+BamgTriangulate_la_SOURCES = ../BamgTriangulate/BamgTriangulate.cpp
+BamgTriangulate_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+Chaco_la_SOURCES = ../Chaco/Chaco.cpp
+Chaco_la_LIBADD = ${deps} $(MPILIB) $(CHACOLIB) $(GSLLIB) $(PROJ4LIB) $(PETSCLIB)
+
+ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp
+ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+
+ExpToLevelSet_la_SOURCES = ../ExpToLevelSet/ExpToLevelSet.cpp
+ExpToLevelSet_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+
+
+ContourToNodes_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp
+ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+ElementConnectivity_la_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp
+ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+EnumToString_la_SOURCES = ../EnumToString/EnumToString.cpp
+EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+StringToEnum_la_SOURCES = ../StringToEnum/StringToEnum.cpp
+StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp
+InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+
+InterpFromMeshToMesh2d_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
+InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+
+InterpFromMeshToMesh3d_la_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp
+InterpFromMeshToMesh3d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+InterpFromMeshToGrid_la_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp
+InterpFromMeshToGrid_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+InterpFromMesh2d_la_SOURCES = ../InterpFromMesh2d/InterpFromMesh2d.cpp
+InterpFromMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+
+IssmConfig_la_SOURCES = ../IssmConfig/IssmConfig.cpp
 IssmConfig_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
 
-KMLFileRead_la_SOURCES = ../KMLFileRead/KMLFileRead.cpp\
-								 ../KMLFileRead/KMLFileRead.h
-KMLFileRead_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-KMLMeshWrite_la_SOURCES = ../KMLMeshWrite/KMLMeshWrite.cpp\
-								  ../KMLMeshWrite/KMLMeshWrite.h
-KMLMeshWrite_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-KMLOverlay_la_SOURCES = ../KMLOverlay/KMLOverlay.cpp\
-								../KMLOverlay/KMLOverlay.h
-KMLOverlay_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-Xy2ll_la_SOURCES = ../Xy2ll/Xy2ll.cpp\
-						 ../Xy2ll/Xy2ll.h
-Xy2ll_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-Ll2xy_la_SOURCES = ../Ll2xy/Ll2xy.cpp\
-						 ../Ll2xy/Ll2xy.h
-Ll2xy_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-ExpSimplify_la_SOURCES = ../ExpSimplify/ExpSimplify.cpp\
-							../ExpSimplify/ExpSimplify.h
-ExpSimplify_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-Exp2Kml_la_SOURCES = ../Exp2Kml/Exp2Kml.cpp\
-							../Exp2Kml/Exp2Kml.h
-Exp2Kml_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-Kml2Exp_la_SOURCES = ../Kml2Exp/Kml2Exp.cpp\
-							../Kml2Exp/Kml2Exp.h
-Kml2Exp_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-Kriging_la_SOURCES = ../Kriging/Kriging.cpp\
-							../Kriging/Kriging.h
-Kriging_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MULTITHREADINGLIB) $(GSLLIB)
-
-MeshPartition_la_SOURCES = ../MeshPartition/MeshPartition.cpp\
-									../MeshPartition/MeshPartition.h
-MeshPartition_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(METISLIB) $(GSLLIB)
-
-MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
-												 ../MeshProfileIntersection/MeshProfileIntersection.h
-MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
-										../NodeConnectivity/NodeConnectivity.h
-NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-PointCloudFindNeighbors_la_SOURCES = ../PointCloudFindNeighbors/PointCloudFindNeighbors.cpp\
-												 ../PointCloudFindNeighbors/PointCloudFindNeighbors.h
-PointCloudFindNeighbors_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
-
-PropagateFlagsFromConnectivity_la_SOURCES = ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp\
-														  ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
-PropagateFlagsFromConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-Scotch_la_SOURCES = ../Scotch/Scotch.cpp\
-						  ../Scotch/Scotch.h
+KMLFileRead_la_SOURCES = ../KMLFileRead/KMLFileRead.cpp
+KMLFileRead_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+KMLMeshWrite_la_SOURCES = ../KMLMeshWrite/KMLMeshWrite.cpp
+KMLMeshWrite_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+KMLOverlay_la_SOURCES = ../KMLOverlay/KMLOverlay.cpp
+KMLOverlay_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+Xy2ll_la_SOURCES = ../Xy2ll/Xy2ll.cpp
+Xy2ll_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+Ll2xy_la_SOURCES = ../Ll2xy/Ll2xy.cpp
+Ll2xy_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+ExpSimplify_la_SOURCES = ../ExpSimplify/ExpSimplify.cpp
+ExpSimplify_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+Exp2Kml_la_SOURCES = ../Exp2Kml/Exp2Kml.cpp
+Exp2Kml_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+Kml2Exp_la_SOURCES = ../Kml2Exp/Kml2Exp.cpp
+Kml2Exp_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+Kriging_la_SOURCES = ../Kriging/Kriging.cpp
+Kriging_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+
+MeshPartition_la_SOURCES = ../MeshPartition/MeshPartition.cpp
+MeshPartition_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(METISLIB) $(GSLLIB) $(PROJ4LIB)
+
+M1qn3_la_SOURCES = ../M1qn3/M1qn3.cpp
+M1qn3_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(METISLIB) $(M1QN3LIB) $(GSLLIB) $(PROJ4LIB)
+
+MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp
+MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp
+NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+PointCloudFindNeighbors_la_SOURCES = ../PointCloudFindNeighbors/PointCloudFindNeighbors.cpp
+PointCloudFindNeighbors_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
+
+PropagateFlagsFromConnectivity_la_SOURCES = ../PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp
+PropagateFlagsFromConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+Scotch_la_SOURCES = ../Scotch/Scotch.cpp
 Scotch_la_LIBADD = ${deps} $(SCOTCHLIB) $(MPILIB) $(BLASLAPACKLIB)
 
-ShpRead_la_SOURCES = ../ShpRead/ShpRead.cpp\
-							../ShpRead/ShpRead.h
-ShpRead_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-Shp2Kml_la_SOURCES = ../Shp2Kml/Shp2Kml.cpp\
-							../Shp2Kml/Shp2Kml.h
-Shp2Kml_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-TriaSearch_la_SOURCES = ../TriaSearch/TriaSearch.cpp\
-								../TriaSearch/TriaSearch.h
-TriaSearch_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-
-TriMesh_la_SOURCES = ../TriMesh/TriMesh.cpp\
-							../TriMesh/TriMesh.h
-TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB)
-
-TriMeshProcessRifts_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
-											../TriMeshProcessRifts/TriMeshProcessRifts.h
-TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
-#}}}
+ShpRead_la_SOURCES = ../ShpRead/ShpRead.cpp
+ShpRead_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+Shp2Kml_la_SOURCES = ../Shp2Kml/Shp2Kml.cpp
+Shp2Kml_la_LIBADD = ${deps} $(SHAPELIBLIB) $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+TriaSearch_la_SOURCES = ../TriaSearch/TriaSearch.cpp
+TriaSearch_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+
+TriMesh_la_SOURCES = ../TriMesh/TriMesh.cpp
+TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB) $(PROJ4LIB)
+
+TriMeshProcessRifts_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp
+TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
+#}}}
Index: /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp	(revision 19104)
+++ /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp	(revision 19105)
@@ -192,5 +192,5 @@
 	int         i;
 	mxArray    *dataref           = NULL;
-	const int   numfields         = 16;
+	const int   numfields         = 17;
 	const char *fnames[numfields];
 	mwSize      ndim              = 2;
@@ -215,4 +215,5 @@
 	fnames[i++] = "CrackedVertices";
 	fnames[i++] = "CrackedEdges";
+	fnames[i++] = "PreviousNumbering";
 	_assert_(i==numfields);
 
@@ -238,4 +239,5 @@
 	i++; SetStructureField(dataref,"CrackedVertices", bamgmesh->CrackedVerticesSize[0],bamgmesh->CrackedVerticesSize[1], bamgmesh->CrackedVertices);
 	i++; SetStructureField(dataref,"CrackedEdges",bamgmesh->CrackedEdgesSize[0], bamgmesh->CrackedEdgesSize[1],bamgmesh->CrackedEdges);
+	i++; SetStructureField(dataref,"PreviousNumbering",bamgmesh->VerticesSize[0],1,bamgmesh->PreviousNumbering);
 	_assert_(i==numfields);
 
Index: /issm/trunk/src/wrappers/python/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/python/Makefile.am	(revision 19104)
+++ /issm/trunk/src/wrappers/python/Makefile.am	(revision 19105)
@@ -8,65 +8,43 @@
 
 #python io{{{
-lib_LIBRARIES = libISSMPython.a 
-if SHAREDLIBS
 lib_LTLIBRARIES = libISSMPython.la
-else
-lib_LTLIBRARIES =
-endif
 
-io_sources= ./include/pythonincludes.h\
-				./io/pythonio.h\
-				./io/WritePythonData.cpp\
+io_sources= ./io/WritePythonData.cpp\
 				./io/CheckNumPythonArguments.cpp\
 				./io/FetchPythonData.cpp
 
-ALLCXXFLAGS= -fPIC -D_GNU_SOURCE -fno-omit-frame-pointer -pthread -D_CPP_  -D_WRAPPERS_ $(CXXFLAGS) $(CXXOPTFLAGS) 
-libISSMPython_a_SOURCES = $(io_sources)
-libISSMPython_a_CXXFLAGS= $(ALLCXXFLAGS)
-if SHAREDLIBS
+ALLCXXFLAGS= -fPIC -D_WRAPPERS_ $(CXXFLAGS) $(CXXOPTFLAGS) 
 libISSMPython_la_SOURCES = $(io_sources)
-endif
+libISSMPython_la_CXXFLAGS= $(ALLCXXFLAGS)
 #}}}
 #api io{{{
-lib_LIBRARIES += libISSMApi.a 
-if SHAREDLIBS
 lib_LTLIBRARIES += libISSMApi.la
-else
-lib_LTLIBRARIES +=
-endif
 
 api_sources= ./io/ApiPrintf.cpp
 
-libISSMApi_a_SOURCES = $(api_sources)
-libISSMApi_a_CXXFLAGS= $(ALLCXXFLAGS)
-if SHAREDLIBS
 libISSMApi_la_SOURCES = $(api_sources)
-endif
+libISSMApi_la_CXXFLAGS= $(ALLCXXFLAGS)
 #}}}
 #Wrappers {{{
+if WRAPPERS
 lib_LTLIBRARIES += BamgConvertMesh.la\
-						 BamgMesher.la\
-						 ContourToMesh.la\
-						 ContourToNodes.la\
-						 ElementConnectivity.la\
-						 EnumToString.la\
-						 InterpFromMeshToMesh2d.la\
-						 InterpFromMeshToMesh3d.la\
-						 InterpFromGridToMesh.la\
-						 InterpFromMeshToGrid.la\
-						 IssmConfig.la\
-						 MeshProfileIntersection.la\
-						 NodeConnectivity.la\
-						 StringToEnum.la\
-						 TriMesh.la\
-						 TriMeshProcessRifts.la
+						BamgMesher.la\
+						ContourToMesh.la\
+						ContourToNodes.la\
+						ElementConnectivity.la\
+						EnumToString.la\
+						InterpFromMeshToMesh2d.la\
+						InterpFromMeshToMesh3d.la\
+						InterpFromGridToMesh.la\
+						InterpFromMeshToGrid.la\
+						IssmConfig.la\
+						MeshProfileIntersection.la\
+						NodeConnectivity.la\
+						StringToEnum.la\
+						TriMesh.la\
+						TriMeshProcessRifts.la
+endif 
 #}}}
 #Flags and libraries {{{
-#if SHAREDLIBS
-#deps = ../../c/libISSMCore.la ../../c/libISSMModules.la
-#else
-#deps = ../../c/libISSMCore.a ../../c/libISSMModules.a
-#endif
-#deps +=  $(MATHLIB) ${PYTHONLIB}
 deps =  $(MATHLIB) ${PYTHONLIB}
 
@@ -81,10 +59,11 @@
 AM_LDFLAGS += -avoid-version
 endif
-if SHAREDLIBS
+
+if STANDALONE_MODULES
+AM_LDFLAGS += -Wl,-static
+endif
+
 deps += ./libISSMPython.la 
-else
-deps += ./libISSMPython.a
 AM_LDFLAGS += --no-warnings 
-endif
 
 AM_CXXFLAGS +=  -D_HAVE_PYTHON_MODULES_   -fPIC
@@ -93,21 +72,17 @@
 endif
 
-if SHAREDLIBS 	 	 
-deps += 	 	 
-else 	 	 
-deps += ../../c/libISSMModules.a ../../c/libISSMCore.a 	 	 
+deps += ../../c/libISSMModules.la ../../c/libISSMCore.la
 if ADOLC
 deps += $(ADOLCLIB)
 endif
 
-if SHAREDLIBS
 deps += ./libISSMApi.la 
-else
-deps += ./libISSMApi.a
+
+if STANDALONE_LIBRARIES
+libISSMPython_la_LDFLAGS = -static 
 endif
-
-
-
-endif 
+if STANDALONE_LIBRARIES
+libISSMApi_la_LDFLAGS = -static 
+endif
 
 #Optimization flags:
@@ -115,66 +90,50 @@
 #}}}
 #Bin sources {{{
-BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
-									  ../BamgConvertMesh/BamgConvertMesh.h
-BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp
+BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 
-BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp\
-								../BamgMesher/BamgMesher.h
-BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp
+BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 
-ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
-									 ../ContourToMesh/ContourToMesh.h
-ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp
+ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 
-ContourToNodes_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp\
-									 ../ContourToNodes/ContourToNodes.h
-ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+ContourToNodes_la_SOURCES = ../ContourToNodes/ContourToNodes.cpp
+ContourToNodes_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 
-ElementConnectivity_la_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp\
-											../ElementConnectivity/ElementConnectivity.h
-ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+ElementConnectivity_la_SOURCES = ../ElementConnectivity/ElementConnectivity.cpp
+ElementConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 
-EnumToString_la_SOURCES = ../EnumToString/EnumToString.cpp\
-								  ../EnumToString/EnumToString.h
-EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+EnumToString_la_SOURCES = ../EnumToString/EnumToString.cpp
+EnumToString_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 
-InterpFromMeshToMesh2d_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp\
-												../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
-InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+InterpFromMeshToMesh2d_la_SOURCES = ../InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
+InterpFromMeshToMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
 
-InterpFromMeshToMesh3d_la_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp\
-												../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
-InterpFromMeshToMesh3d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+InterpFromMeshToMesh3d_la_SOURCES = ../InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp
+InterpFromMeshToMesh3d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
 
-InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
-												../InterpFromGridToMesh/InterpFromGridToMesh.h
-InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp
+InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
 
-InterpFromMeshToGrid_la_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp\
-												../InterpFromMeshToGrid/InterpFromMeshToGrid.h
-InterpFromMeshToGrid_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
+InterpFromMeshToGrid_la_SOURCES = ../InterpFromMeshToGrid/InterpFromMeshToGrid.cpp
+InterpFromMeshToGrid_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(PROJ4LIB)
 
-IssmConfig_la_SOURCES = ../IssmConfig/IssmConfig.cpp\
-											 ../IssmConfig/IssmConfig.h
+IssmConfig_la_SOURCES = ../IssmConfig/IssmConfig.cpp
 IssmConfig_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
 
-MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
-										../MeshProfileIntersection/MeshProfileIntersection.h
-MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp
+MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 
-NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
-										../NodeConnectivity/NodeConnectivity.h
-NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp
+NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 
-StringToEnum_la_SOURCES = ../StringToEnum/StringToEnum.cpp\
-								  ../StringToEnum/StringToEnum.h
-StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+StringToEnum_la_SOURCES = ../StringToEnum/StringToEnum.cpp
+StringToEnum_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 
-TriMesh_la_SOURCES = ../TriMesh/TriMesh.cpp\
-							../TriMesh/TriMesh.h
-TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB)
+TriMesh_la_SOURCES = ../TriMesh/TriMesh.cpp
+TriMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(TRIANGLELIB) $(GSLLIB) $(PROJ4LIB)
 
-TriMeshProcessRifts_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
-											../TriMeshProcessRifts/TriMeshProcessRifts.h
-TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB)
+TriMeshProcessRifts_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp
+TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(GSLLIB) $(PROJ4LIB)
 #}}}
Index: /issm/trunk/src/wrappers/python/include/wrapper_macros.h
===================================================================
--- /issm/trunk/src/wrappers/python/include/wrapper_macros.h	(revision 19104)
+++ /issm/trunk/src/wrappers/python/include/wrapper_macros.h	(revision 19105)
@@ -15,5 +15,5 @@
 /* MODULEBOOT/MODULEEND {{{*/
 
-/*The following macros hide the error exception handling in a matlab module. Just put 
+/*The following macros hide the error exception handling in a python module. Just put 
  * MODULEBOOT(); and MODULEEND(); at the beginning and end of a module, and c++ exceptions 
  * will be trapped*/
Index: /issm/trunk/src/wrappers/python/io/WritePythonData.cpp
===================================================================
--- /issm/trunk/src/wrappers/python/io/WritePythonData.cpp	(revision 19104)
+++ /issm/trunk/src/wrappers/python/io/WritePythonData.cpp	(revision 19105)
@@ -35,7 +35,11 @@
 	PyObject* array=NULL;
 
-	dims[0]=(npy_intp)M;
-	dims[1]=(npy_intp)N;
-	array=PyArray_SimpleNewFromData(2,dims,NPY_DOUBLE,matrix);
+	/*copy matrix: */
+	double* matrix_python=xNew<double>(M*N);
+	memcpy(matrix_python,matrix,M*N*sizeof(double));
+
+	dims[0]=(npy_intp)M;
+	dims[1]=(npy_intp)N;
+	array=PyArray_SimpleNewFromData(2,dims,NPY_DOUBLE,matrix_python);
 
 	PyTuple_SetItem(tuple, index, array);
@@ -47,11 +51,7 @@
 	PyObject* array=NULL;
 
-	/*intermediary:*/
-	long* lmatrix=NULL;
-	int i;
-
 	/*transform into long matrix: */
-	lmatrix=xNew<long>(M*N);
-	for(i=0;i<M*N;i++)lmatrix[i]=(long)matrix[i];
+	long* lmatrix=xNew<long>(M*N);
+	for(int i=0;i<M*N;i++)lmatrix[i]=(long)matrix[i];
 
 	dims[0]=(npy_intp)M;
@@ -67,7 +67,11 @@
 	PyObject* array=NULL;
 
-	dims[0]=(npy_intp)M;
-	dims[1]=(npy_intp)N;
-	array=PyArray_SimpleNewFromData(2,dims,NPY_BOOL,matrix);
+	/*copy matrix: */
+	bool* matrix_python=xNew<bool>(M*N);
+	memcpy(matrix_python,matrix,M*N*sizeof(bool));
+
+	dims[0]=(npy_intp)M;
+	dims[1]=(npy_intp)N;
+	array=PyArray_SimpleNewFromData(2,dims,NPY_BOOL,matrix_python);
 
 	PyTuple_SetItem(tuple, index, array);
@@ -76,14 +80,14 @@
 void WriteData(PyObject* py_tuple, int index, double* vector, int M){
 
-	double   *buffer = NULL;
 	npy_intp  dim   = 10;
 	PyObject *array = NULL;
 
-	/*Copy vector*/
-	buffer=xNew<double>(M);
-	for(int i=0;i<M;i++)buffer[i]=vector[i];
+
+	/*copy vector: */
+	double* vector_python=xNew<double>(M);
+	memcpy(vector_python,vector,M*sizeof(double));
 
 	dim=(npy_intp)M;
-	array=PyArray_SimpleNewFromData(1,&dim,NPY_DOUBLE,buffer);
+	array=PyArray_SimpleNewFromData(1,&dim,NPY_DOUBLE,vector_python);
 
 	PyTuple_SetItem(py_tuple, index, array);
Index: /issm/trunk/test/Exp/SquareOne.exp
===================================================================
--- /issm/trunk/test/Exp/SquareOne.exp	(revision 19105)
+++ /issm/trunk/test/Exp/SquareOne.exp	(revision 19105)
@@ -0,0 +1,10 @@
+## Name:domainoutline
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+1 0
+1 1
+0 1
+0 0
Index: /issm/trunk/test/MITgcm/build.sh
===================================================================
--- /issm/trunk/test/MITgcm/build.sh	(revision 19105)
+++ /issm/trunk/test/MITgcm/build.sh	(revision 19105)
@@ -0,0 +1,35 @@
+#!/bin/bash
+#This script compiles and links MITgcm
+
+#recover hostname and model path:
+hostname="$1"
+modelpath="$2"
+
+if [ -e ~/.bashrc ]; then
+	source ~/.bashrc
+fi
+
+# Clean up build directory
+cd $modelpath
+if [ ! -d "build" ]; then mkdir build; fi
+\rm -f build/*
+
+# Get MITgcm code, if needed
+if [ ! -d "$SLR_DIR/components/mitgcm/install" ]; then
+   cd $modelpath/../MITgcm
+   source install.sh
+   cd $modelpath
+fi
+
+#create MITgcm makefile and code links for this run
+cd build
+if [ ! -f Makefile ]; then
+
+	if [ $hostname == "pleiades" ]; then 
+		$SLR_DIR/components/mitgcm/install/tools/genmake2 -of $SLR_DIR/models/ice-ocean/configs/linux_amd64_gfortran+mpi_ice_nas -mo ../code -rd $SLR_DIR/components/mitgcm/install
+	else
+		$modelpath/../MITgcm/install/tools/genmake2 -mpi -mo $modelpath/../MITgcm/code -rd $modelpath/../MITgcm/install
+	fi
+    make depend
+fi
+make -j 8
Index: /issm/trunk/test/MITgcm/code/SIZE.h
===================================================================
--- /issm/trunk/test/MITgcm/code/SIZE.h	(revision 19105)
+++ /issm/trunk/test/MITgcm/code/SIZE.h	(revision 19105)
@@ -0,0 +1,64 @@
+C $Header: /u/gcmpack/MITgcm/model/inc/SIZE.h,v 1.28 2009/05/17 21:15:07 jmc Exp $
+C $Name:  $
+C
+CBOP
+C    !ROUTINE: SIZE.h
+C    !INTERFACE:
+C    include SIZE.h
+C    !DESCRIPTION: \bv
+C     *==========================================================*
+C     | SIZE.h Declare size of underlying computational grid.     
+C     *==========================================================*
+C     | The design here support a three-dimensional model grid    
+C     | with indices I,J and K. The three-dimensional domain      
+C     | is comprised of nPx*nSx blocks of size sNx along one axis 
+C     | nPy*nSy blocks of size sNy along another axis and one     
+C     | block of size Nz along the final axis.                    
+C     | Blocks have overlap regions of size OLx and OLy along the 
+C     | dimensions that are subdivided.                           
+C     *==========================================================*
+C     \ev
+CEOP
+C     Voodoo numbers controlling data layout.
+C     sNx :: No. X points in sub-grid.
+C     sNy :: No. Y points in sub-grid.
+C     OLx :: Overlap extent in X.
+C     OLy :: Overlat extent in Y.
+C     nSx :: No. sub-grids in X.
+C     nSy :: No. sub-grids in Y.
+C     nPx :: No. of processes to use in X.
+C     nPy :: No. of processes to use in Y.
+C     Nx  :: No. points in X for the total domain.
+C     Ny  :: No. points in Y for the total domain.
+C     Nr  :: No. points in Z for full process domain.
+      INTEGER sNx
+      INTEGER sNy
+      INTEGER OLx
+      INTEGER OLy
+      INTEGER nSx
+      INTEGER nSy
+      INTEGER nPx
+      INTEGER nPy
+      INTEGER Nx
+      INTEGER Ny
+      INTEGER Nr
+      PARAMETER (
+     &           sNx =  10,
+     &           sNy =  10,
+     &           OLx =   3,
+     &           OLy =   3,
+     &           nSx =   1,
+     &           nSy =   1,
+     &           nPx = 2,
+     &           nPy = 4,
+     &           Nx  = sNx*nSx*nPx,
+     &           Ny  = sNy*nSy*nPy,
+     &           Nr  =  30)
+
+C     MAX_OLX :: Set to the maximum overlap region size of any array
+C     MAX_OLY    that will be exchanged. Controls the sizing of exch
+C                routine buffers.
+      INTEGER MAX_OLX
+      INTEGER MAX_OLY
+      PARAMETER ( MAX_OLX = OLx,
+     &            MAX_OLY = OLy )
Index: /issm/trunk/test/MITgcm/code/SIZE.h.bak
===================================================================
--- /issm/trunk/test/MITgcm/code/SIZE.h.bak	(revision 19105)
+++ /issm/trunk/test/MITgcm/code/SIZE.h.bak	(revision 19105)
@@ -0,0 +1,64 @@
+C $Header: /u/gcmpack/MITgcm/model/inc/SIZE.h,v 1.28 2009/05/17 21:15:07 jmc Exp $
+C $Name:  $
+C
+CBOP
+C    !ROUTINE: SIZE.h
+C    !INTERFACE:
+C    include SIZE.h
+C    !DESCRIPTION: \bv
+C     *==========================================================*
+C     | SIZE.h Declare size of underlying computational grid.     
+C     *==========================================================*
+C     | The design here support a three-dimensional model grid    
+C     | with indices I,J and K. The three-dimensional domain      
+C     | is comprised of nPx*nSx blocks of size sNx along one axis 
+C     | nPy*nSy blocks of size sNy along another axis and one     
+C     | block of size Nz along the final axis.                    
+C     | Blocks have overlap regions of size OLx and OLy along the 
+C     | dimensions that are subdivided.                           
+C     *==========================================================*
+C     \ev
+CEOP
+C     Voodoo numbers controlling data layout.
+C     sNx :: No. X points in sub-grid.
+C     sNy :: No. Y points in sub-grid.
+C     OLx :: Overlap extent in X.
+C     OLy :: Overlat extent in Y.
+C     nSx :: No. sub-grids in X.
+C     nSy :: No. sub-grids in Y.
+C     nPx :: No. of processes to use in X.
+C     nPy :: No. of processes to use in Y.
+C     Nx  :: No. points in X for the total domain.
+C     Ny  :: No. points in Y for the total domain.
+C     Nr  :: No. points in Z for full process domain.
+      INTEGER sNx
+      INTEGER sNy
+      INTEGER OLx
+      INTEGER OLy
+      INTEGER nSx
+      INTEGER nSy
+      INTEGER nPx
+      INTEGER nPy
+      INTEGER Nx
+      INTEGER Ny
+      INTEGER Nr
+      PARAMETER (
+     &           sNx =  20,
+     &           sNy =  20,
+     &           OLx =   3,
+     &           OLy =   3,
+     &           nSx =   1,
+     &           nSy =   1,
+     &           nPx =   1,
+     &           nPy =   2,
+     &           Nx  = sNx*nSx*nPx,
+     &           Ny  = sNy*nSy*nPy,
+     &           Nr  =  30)
+
+C     MAX_OLX :: Set to the maximum overlap region size of any array
+C     MAX_OLY    that will be exchanged. Controls the sizing of exch
+C                routine buffers.
+      INTEGER MAX_OLX
+      INTEGER MAX_OLY
+      PARAMETER ( MAX_OLX = OLx,
+     &            MAX_OLY = OLy )
Index: /issm/trunk/test/MITgcm/get_mitgcm.sh
===================================================================
--- /issm/trunk/test/MITgcm/get_mitgcm.sh	(revision 19105)
+++ /issm/trunk/test/MITgcm/get_mitgcm.sh	(revision 19105)
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+if [ -e ~/.bashrc ]; then 
+	source ~/.bashrc
+fi
+
+# Download fresh copy of MITgcm
+cd ../MITgcm/
+source install.sh
Index: /issm/trunk/test/MITgcm/input/data
===================================================================
--- /issm/trunk/test/MITgcm/input/data	(revision 19105)
+++ /issm/trunk/test/MITgcm/input/data	(revision 19105)
@@ -0,0 +1,74 @@
+# ====================
+# | Model parameters |
+# ====================
+#
+# Continuous equation parameters
+ &PARM01
+ Tref = 30*-1.9,
+ Sref = 30*34.4,
+ viscAz=1.E-3,
+ viscAh=600.0,
+ no_slip_sides=.FALSE.,
+ no_slip_bottom=.FALSE.,
+ diffKhT=100.0,
+ diffKzT=5.E-5,
+ diffKhS=100.0,
+ diffKzS=5.E-5,
+ bottomDragQuadratic=2.5E-3,
+ eosType='JMD95Z', 
+ HeatCapacity_cp = 3974.0,
+ rhoConst=1030.,
+ rhoNil=1030.,
+ gravity=9.81,
+ convertFW2Salt = 33.4,
+ rigidLid=.FALSE.,
+ implicitFreeSurface=.TRUE.,
+ exactConserv=.TRUE.,
+ hFacMin=0.05,
+ nonHydrostatic=.FALSE.,
+ globalfiles = .TRUE.,
+ useSingleCpuIO = .TRUE.,
+ &
+
+# Elliptic solver parameters
+ &PARM02
+ cg2dMaxIters=1000,
+ cg2dTargetResidual=1.E-13,
+ cg3dMaxIters=400,
+ cg3dTargetResidual=1.E-13,
+ &
+
+# Time stepping parameters
+ &PARM03
+ startTime=0.,
+ endTime=2592000.,
+ deltaT=1200.0,
+ abEps=0.1,
+ cAdjFreq = 1.,
+ pChkptFreq=2592000.,
+ chkptFreq=0.,
+ dumpFreq=0.,
+ taveFreq=2592000.,
+ monitorFreq=86400.,
+ monitorSelect=2,
+ &
+
+# Gridding parameters
+ &PARM04
+ usingSphericalPolarGrid=.TRUE.,
+ xgOrigin = 0.0,
+ ygOrigin = -80.0,
+ delX = 20*0.25,
+ delY = 40*0.05,
+ delZ = 30*30.0,
+ &
+
+# Input datasets
+ &PARM05
+ bathyFile       = 'bathymetry.bin',
+ hydrogSaltFile  = 'Salt.bin',
+ hydrogThetaFile = 'Theta.bin',
+ uVelInitFile    = 'Uvel.bin',
+ vVelInitFile    = 'Vvel.bin',
+ pSurfInitFile   = 'Etan.bin',
+ &
Index: /issm/trunk/test/MITgcm/input/data.obcs
===================================================================
--- /issm/trunk/test/MITgcm/input/data.obcs	(revision 19105)
+++ /issm/trunk/test/MITgcm/input/data.obcs	(revision 19105)
@@ -0,0 +1,18 @@
+# ***************
+# Open boundaries
+# ***************
+ &OBCS_PARM01
+ OB_Iwest = 40*1,
+ OB_Ieast = 40*-1,
+#
+ useOBCSprescribe = .TRUE.,
+#
+ OBWsFile = 'OBs.bin',
+ OBWtFile = 'OBt.bin',
+ OBWuFile = 'OBu.bin',
+ OBWvFile = 'zeros.bin',
+ OBEsFile = 'OBs.bin',
+ OBEtFile = 'OBt.bin',
+ OBEuFile = 'OBu.bin',
+ OBEvFile = 'zeros.bin',
+ &
Index: /issm/trunk/test/MITgcm/input/data.pkg
===================================================================
--- /issm/trunk/test/MITgcm/input/data.pkg	(revision 19105)
+++ /issm/trunk/test/MITgcm/input/data.pkg	(revision 19105)
@@ -0,0 +1,5 @@
+# Packages
+ &PACKAGES
+ useShelfIce = .TRUE.,
+ useOBCS     = .TRUE.,
+ &
Index: /issm/trunk/test/MITgcm/input/data.shelfice
===================================================================
--- /issm/trunk/test/MITgcm/input/data.shelfice	(revision 19105)
+++ /issm/trunk/test/MITgcm/input/data.shelfice	(revision 19105)
@@ -0,0 +1,9 @@
+# ===================================
+# | Parameters for SHELFICE package |
+# ===================================
+ &SHELFICE_PARM01
+ SHELFICEconserve = .TRUE.,
+ SHELFICEboundaryLayer = .TRUE.,
+ SHELFICEtopoFile='icetopo.bin',
+ SHELFICEwriteState = .TRUE.,
+ &
Index: /issm/trunk/test/MITgcm/input/eedata
===================================================================
--- /issm/trunk/test/MITgcm/input/eedata	(revision 19105)
+++ /issm/trunk/test/MITgcm/input/eedata	(revision 19105)
@@ -0,0 +1,9 @@
+# Example "eedata" file
+# Lines beginning "#" are comments
+# nTx - No. threads per process in X
+# nTy - No. threads per process in Y
+ &EEPARMS
+ &
+# Note: Some systems use & as the
+# namelist terminator. Other systems
+# use a / character (as shown here).
Index: /issm/trunk/test/MITgcm/install.sh
===================================================================
--- /issm/trunk/test/MITgcm/install.sh	(revision 19105)
+++ /issm/trunk/test/MITgcm/install.sh	(revision 19105)
@@ -0,0 +1,17 @@
+#!/bin/bash
+
+#Some cleanup
+\rm -rf install
+
+#Add cvs repository
+export CVSROOT=':pserver:cvsanon@mitgcm.org:/u/gcmpack'
+
+#Download code from server
+echo loging into MITgcm CVS server
+echo enter MITgcm CVS password: cvsanon
+#Login only the first time
+#cvs login
+cvs co -P MITgcm_code
+
+#Move
+mv MITgcm install
Index: /issm/trunk/test/MITgcm/tools/myint2str.m
===================================================================
--- /issm/trunk/test/MITgcm/tools/myint2str.m	(revision 19105)
+++ /issm/trunk/test/MITgcm/tools/myint2str.m	(revision 19105)
@@ -0,0 +1,12 @@
+function s=myint2str(x,n);
+%MYIN2STR(X,N)   convert integer to string with leading zeros
+%                padds integer X with zeros to N locations
+
+if nargin < 2, n=2;  end
+if nargin < 1, help myint2str, return, end
+
+s=int2str(x);
+n=n-length(s);
+for i=1:n
+  s=['0' s];
+end
Index: /issm/trunk/test/MITgcm/tools/readbin.m
===================================================================
--- /issm/trunk/test/MITgcm/tools/readbin.m	(revision 19105)
+++ /issm/trunk/test/MITgcm/tools/readbin.m	(revision 19105)
@@ -0,0 +1,68 @@
+function fld=readbin(fnam,siz,typ,prec,skip,mform)
+
+% Function fld=readbin(fnam,siz,typ,prec,skip,mform)
+% read in N-D binary field
+%
+% INPUTS
+% fnam  input path and file name
+% siz   grid dimension (default [360 224 46])
+% typ   0: sequential FORTRAN;  1: plain binary (the default)
+% prec  numeric precision (see fread; default: 'real*4')
+% skip  records to skip before reading (default 0)
+% mform machine format (see fopen; default: 'ieee-be')
+%
+% OUTPUTS
+% fld    output array of dimension siz
+%
+% SEE ALSO
+% read_ijk read_ijkt writebin
+
+if nargin < 6, mform='ieee-be'; end
+if nargin < 5, skip=0; end
+if nargin < 4, prec='real*4'; end
+if nargin < 3, typ=1; end
+if nargin < 2, siz=[360 224 46]; end
+if nargin < 1, error('please specify input file name'); end
+
+fid=fopen(fnam,'r',mform);
+
+if skip>0
+  if typ==0
+    for n=1:skip
+      tmp=read_record(fid,prec);
+    end
+  else
+    switch prec
+      case {'int8','integer*1'}
+        reclength=prod(siz);
+      case {'int16','integer*2','uint16','integer*2'}
+        reclength=2*prod(siz);
+      case {'int32','integer*4','uint32','single','real*4','float32'}
+        reclength=4*prod(siz);
+      case {'int64','integer*8','uint64','double','real*8','float64'}
+        reclength=8*prod(siz);
+    end
+    if(fseek(fid,skip*reclength,'bof')<0), error('past end of file'); end
+  end
+end
+
+switch typ
+  case 0
+    tmp=read_record(fid,prec);
+  case 1
+    tmp=fread(fid,[siz(1),prod(siz(2:length(siz)))],prec);
+end
+fid=fclose(fid);
+
+switch length(siz)
+  case 2
+    fld=reshape(tmp,siz(1),siz(2));
+  case 3
+    fld=reshape(tmp,siz(1),siz(2),siz(3));
+  case 4
+    fld=reshape(tmp,siz(1),siz(2),siz(3),siz(4));
+  case 5
+    fld=reshape(tmp,siz(1),siz(2),siz(3),siz(4),siz(5));
+  otherwise
+    fld=tmp;
+end
Index: /issm/trunk/test/NightlyRun/IdFromString.m
===================================================================
--- /issm/trunk/test/NightlyRun/IdFromString.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/IdFromString.m	(revision 19105)
@@ -18,5 +18,5 @@
 
 %Grep string
-[dummy ids_raw]=system(['cat IdToName.m | grep ' string ' | awk ''{print $2 }'' | sed -e "s/(id==//g" | sed -e "s/),//g"']);
+[dummy ids_raw]=system(['find ./ -name "test[0-9]*.m" | xargs grep "%Test Name:" | grep ' string ' | sed -e "s/test/ /g" -e "s/\.m:/ /g" | awk {''print $2''}']);
 
 %return if no test found
Index: /issm/trunk/test/NightlyRun/IdToName.m
===================================================================
--- /issm/trunk/test/NightlyRun/IdToName.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/IdToName.m	(revision 19105)
@@ -1,263 +1,46 @@
 function name=IdToName(id);
 %IDTONAME- return name of test
+%  
+%   if id=0, the full list of test is returned
 %
 %   Usage:
+%      name=IdToName();
 %      name=IdToName(id);
 
-switch id,
-	case 101, name='SquareShelfConstrainedStressSSA2d';
-	case 102, name='SquareShelfConstrainedStressSSA3d';
-	case 103, name='SquareShelfConstrainedStressHO';
-	case 104, name='SquareShelfConstrainedStressFS';
-	case 105, name='SquareShelfConstrainedMasstransp2d';
-	case 106, name='SquareShelfConstrainedMasstransp2dDG';
-	case 107, name='SquareShelfConstrainedMasstransp3d';
-	case 108, name='SquareShelfConstrainedTherStea';
-	case 109, name='SquareShelfConstrainedTherTran';
-	case 110, name='SquareShelfConstrainedTranSSA2d';
-	case 111, name='SquareShelfConstrainedTranHO';
-	case 112, name='SquareShelfConstrainedSurfSlop2d';
-	case 113, name='SquareShelfConstrainedSurfSlope3d';
-	case 114, name='SquareShelfConstrainedBedSlop2d';
-	case 115, name='SquareShelfConstrainedBedSlop3d';
-	case 116, name='SquareShelfConstrainedBalThic2d';
-	case 117, name='SquareShelfConstrainedBalThic3d';
-	case 118, name='SquareShelfConstrainedBalThic2dDG';
-	case 119, name='SquareBamgMesh';
-	case 120, name='SquareShelfConstrainedEnthalpyStea';
-	case 121, name='SquareShelfConstrainedEnthalpyTran';
-	case 122, name='SquareShelfConstrainedTransHOEnth';
-	case 123, name='SquareShelfConstrainedTranMisfitSurface';
-	case 124, name='SquareShelfConstrainedTranFSFreeSurface';
-	case 201, name='SquareShelfStressSSA2d';
-	case 202, name='SquareShelfStressSSA3d';
-	case 203, name='SquareShelfStressHO';
-	case 204, name='SquareShelfStressFS';
-	case 205, name='SquareShelfStressMHOPenalties';
-	case 206, name='SquareShelfTherStea';
-	case 207, name='SquareShelfTherTran';
-	case 208, name='SquareShelfTranSSA2d';
-	case 209, name='SquareShelfTranSSA3d';
-	case 210, name='SquareShelfTranHO';
-	case 211, name='SquareShelfTranFS';
-	case 212, name='SquareShelfCMBSSA2d';
-	case 213, name='SquareShelfCMBSSA3d';
-	case 214, name='SquareShelfCMBHO';
-	case 215, name='SquareShelfCMBFS';
-	case 216, name='SquareShelfStressSSA2dRift';
-	case 217, name='SquareShelfConstrained';
-	case 218, name='SquareShelfConstrainedDakotaB';
-	case 219, name='SquareShelfStressSSAHOTiling';
-	case 220, name='SquareShelfStressHOFS3dTiling';
-	case 221, name='SquareShelfStressSSAFS3dTiling';
-	case 222, name='SquareShelfStressSSA2dTransientIncrHydro';
-	case 223, name='SquareShelfStressSSA2dTransientIncrNonHydro';
-	case 224, name='SquareShelfStressHOTransientIncrHydro';
-	case 225, name='SquareShelfStressHOTransientIncrNonHydro';
-	case 226, name='SquareShelfTranCflSSA2d';
-	case 227, name='SquareShelfTranCflHO';
-	case 228, name='SquareShelfTranForceNeg2d';
-	case 229, name='SquareShelfTranForcePos2d';
-	case 230, name='SquareShelfTranForceNeg3d';
-	case 231, name='SquareShelfTranForcePos3d';
-	case 232, name='SquareShelfTherTranForcTemp';
-	case 233, name='SquareShelfTranHOForcTemp';
-	case 234, name='SquareShelfTranForceNeg2dDakotaSamp';
-	case 235, name='SquareShelfTranForceNeg2dDakotaLocal';
-	case 236, name='SquareShelfTranIspddIsdeltaSSA2d';
-	case 237, name='SquareShelfTranIspddIsdeltaSSA3d';
-	case 238, name='SquareShelfTranForceNoInterp2d';
-	case 239, name='SquareShelfTranForceNoInterp3d';
-	case 270, name='SquareShelfStressSSA2dDamage';
-	case 271, name='SquareShelfStressSSA2dDamageTran';
-	case 272, name='SquareShelfCMZSSA2dDamage';
-	case 274, name='SquareShelfStressSSA2dDamageRift';
-	case 275, name='SquareShelfDamageEvolutionSSA2d';
-	case 276, name='SquareShelfDamageEvolutionSSA2dP2';
-	case 280, name='SquareShelfStressSSA2dHigherOrder';
-	case 285, name='SquareShelfStressHOHigherOrder';
-	case 290, name='SquareShelfStressFSP2P1';
-	case 291, name='SquareShelfStressFSP4z';
-	case 292, name='SquareShelfTranSSA2dFloatingMeltParam';
-	case 301, name='SquareSheetConstrainedStressSSA2d';
-	case 302, name='SquareSheetConstrainedStressSIA2d';
-	case 303, name='SquareSheetConstrainedStressSIASSA2d';
-	case 304, name='SquareSheetConstrainedStressSSA3d';
-	case 305, name='SquareSheetConstrainedStressSIA3d';
-	case 306, name='SquareSheetConstrainedStressSIASSA3d';
-	case 307, name='SquareSheetConstrainedStressHO';
-	case 308, name='SquareSheetConstrainedStressFS';
-	case 309, name='SquareSheetConstrainedMasstransp2d';
-	case 320, name='SquareSheetConstrainedMasstransp2dDG';
-	case 311, name='SquareSheetConstrainedMasstransp3d';
-	case 312, name='SquareSheetConstrainedTherStea';
-	case 313, name='SquareSheetConstrainedTherTran';
-	case 314, name='SquareSheetConstrainedTranSIA2d';
-	case 315, name='SquareSheetConstrainedTranSIA3d';
-	case 316, name='SquareSheetConstrainedTranSSA2d';
-	case 317, name='SquareSheetConstrainedTranHO';
-	case 318, name='SquareSheetConstrainedSteaSIA3d';
-	case 319, name='SquareSheetConstrainedCMDragSSA2d';
-	case 320, name='SquareSheetConstrainedCMDragSSA3d';
-	case 321, name='SquareSheetConstrainedCMDragHO';
-	case 322, name='SquareSheetConstrainedCMDragFS';
-	case 323, name='SquareSheetConstrainedTranCflSSA2d';
-	case 324, name='SquareSheetConstrainedTranCflSIA3d';
-	case 325, name='SquareSheetConstrainedEnthalpyStea';
-	case 326, name='SquareSheetConstrainedEnthalpyTran';
-	case 327, name='SquareSheetConstrainedTransHOEnth';
-	case 328, name='SquareSheetConstrainedSmbGradients2d';
-	case 329, name='SquareSheetConstrainedSmbGradients3d';
-	case 332, name='SquareSheetConstrainedHydrologyDC';
-	case 333, name='SquareSheetHydrologyDCTwoLayers';
-	case 334, name='SquareSheetConstrainedExtrudedHydrologyDC';
-	case 335, name='SquareSheetExtrudedHydrologyDCTwoLayers';
-	case 336, name='SquareSheetConstrainedSmbComponents2d';
-	case 337, name='SquareSheetConstrainedSmbComponents3d';
-	case 338, name='SquareSheetConstrainedSmbMeltComponents2d';
-	case 339, name='SquareSheetConstrainedSmbMeltComponents3d';
-	case 401, name='SquareSheetShelfStressSSA2d';
-	case 402, name='SquareSheetShelfStressSSA3d';
-	case 403, name='SquareSheetShelfStressHO';
-	case 404, name='SquareSheetShelfStressFS';
-	case 405, name='SquareSheetShelfStressMHOPenalties';
-	case 406, name='SquareSheetShelfTherStea';
-	case 407, name='SquareSheetShelfTherTran';
-	case 408, name='SquareSheetShelfTranSSA2d';
-	case 409, name='SquareSheetShelfTranMHOPenalties';
-	case 410, name='SquareSheetShelfSteaSSA3d';
-	case 411, name='SquareSheetShelfSteaHO';
-	case 412, name='SquareSheetShelfDiadSSA3dDakota';
-	case 413, name='SquareSheetShelfDiadSSA3dDakotaPart';
-	case 414, name='SquareSheetShelfDiadSSA3dDakotaMassFlux';
-	case 415, name='SquareSheetShelfCMDragSteaSSA3d';
-	case 416, name='SquareSheetShelfCMDragSteaHO';
-	case 417, name='SquareSheetShelfDiadSSA3dDakotaSamp';
-	case 418, name='SquareSheetShelfDiadSSA3dDakotaAreaAverage';
-	case 419, name='SquareSheetShelfStressSSAHOTiling';
-	case 420, name='SquareSheetShelfDakotaScaledResponse';
-	case 421, name='SquareSheetShelfStressHOFS3dTiling';
-	case 422, name='SquareSheetShelfStressSSAFS3dTiling';
-	case 423, name='RoundSheetShelfGLMigrationSSA2d';
-	case 424, name='SquareSheetShelfGroundingLine2dAggressive';
-	case 425, name='SquareSheetShelfGroundingLine2dSoft';
-	case 426, name='SquareSheetShelfGroundingLine3dAggressive';
-	case 427, name='SquareSheetShelfGroundingLine3dSoft';
-	case 428, name='SquareSheetShelfStressSSA2dNewton';
-	case 429, name='SquareSheetShelfStressHONewton';
-	case 431, name='SquareSheetShelfSteaEnthalpySSA3d';
-	case 432, name='SquareSheetShelfSteaEnthalpyHO';
-	case 433, name='RoundSheetShelfGLMigrationSSA3d';
-	case 434, name='SquareSheetShelfL1L2';
-	case 435, name='MISMIP3DHO';
-	case 450, name='SquareSheetShelfStressSSAHigherOrder';
-	case 455, name='SquareSheetShelfStressHOHigherOrder';
-	case 501, name='PigStressSSA2d';
-	case 502, name='PigStressHO';
-	case 503, name='PigStressFS';
-	case 504, name='PigTranSSA2d';
-	case 505, name='PigTranSSA3d';
-	case 506, name='PigTranHO';
-	case 507, name='PigTranFS';
-	case 508, name='PigSteaSSA3d';
-	case 509, name='PigSteaHO';
-	case 510, name='PigSteaFS';
-	case 530, name='PigBalVel1';
-	case 531, name='PigBalVel2';
-	case 511, name='PigCMBFS';
-	case 512, name='PigCMDragHO';
-	case 513, name='PigCMDragSteaSSA3d';
-	case 514, name='PigBamgMesh';
-	case 515, name='PigTherTranSUPG';
-	case 516, name='PigTherSteaSUPG';
-	case 601, name='79NorthMasstransp2d';
-	case 602, name='79NorthMasstransp2dDG';
-	case 603, name='79NorthMasstransp3d';
-	case 604, name='79NorthSurfSlop2d';
-	case 605, name='79NorthSurfSlop3d';
-	case 606, name='79NorthBedSlop2d';
-	case 607, name='79NorthBedSlop3d';
-	case 608, name='79NorthBalThic2d';
-	case 609, name='79NorthBalThic2dDG';
-	case 610, name='79NorthBalThic3d';
-	case 611, name='79NorthCMBalThic2dCG';
-	case 613, name='79NorthCMBalThicVxVy';
-	case 701, name='FlowbandFSshelf';
-	case 702, name='FlowbandFSsheetshelf';
-	case 703, name='FlowbandFSsheetshelfTrans';
-	case 801, name='ValleyGlacierLevelsetSSA2d';
-	case 802, name='ValleyGlacierLevelsetThermalSSA3d';
-	case 803, name='ValleyGlacierLevelsetEnthalpyHO3d';
-	case 804, name='ValleyGlacierLevelsetCalvingSIA2d';
-	case 805, name='ValleyGlacierLevelsetEnthCalvingHO3d';
-	case 1101, name='ISMIPAHO';
-	case 1102, name='ISMIPAFS';
-	case 1103, name='ISMIPBHO';
-	case 1104, name='ISMIPBFS';
-	case 1105, name='ISMIPCHO';
-	case 1106, name='ISMIPCFS';
-	case 1107, name='ISMIPDHO';
-	case 1108, name='ISMIPDFS';
-	case 1109, name='ISMIPE';
-	case 1110, name='ISMIPF';
-	case 1201, name='EISMINTMassConservation';
-	case 1202, name='EISMINTStress1';
-	case 1203, name='EISMINTStress2';
-	case 1204, name='EISMINTTran2';
-	case 1205, name='EISMINTRoundIceSheetStaticSIA';
-	case 1206, name='EISMINTRoundIceSheetStaticHO';
-	case 1207, name='EISMINTRoundIceSheetStaticFS';
-	case 1208, name='EISMINTA';
-	case 1301, name='ThermalMelting';
-	case 1302, name='ThermalAdvection';
-	case 1303, name='ThermalConduction';
-	case 1304, name='ThermalGeothermalFlux';
-	case 1401, name='AdaptiveMeshRefinement1';
-	case 1402, name='AdaptiveMeshRefinement2';
-	case 1501, name='SquareShelfTranSawTooth2d';
-	case 1502, name='SquareShelfTranSawTooth3d';
-	case 1601, name='SquareShelfSSA2dRotation';
-	case 1602, name='SquareSheetShelfHORotation';
-	case 2001, name='SquareSheetConstrainedGia2d';
-	case 2051, name='GiaBenchmarksAB2dA1';
-	case 2052, name='GiaBenchmarksAB2dA2';
-	case 2053, name='GiaBenchmarksAB2dA3';
-	case 2061, name='GiaBenchmarksAB2dB1';
-	case 2062, name='GiaBenchmarksAB2dB2';
-	case 2063, name='GiaBenchmarksAB2dB3';
-	case 2071, name='GiaBenchmarksAB2dC1';
-	case 2072, name='GiaBenchmarksAB2dC2';
-	case 2073, name='GiaBenchmarksAB2dC3';
-	case 2081, name='GiaBenchmarksAB2dD1';
-	case 2082, name='GiaBenchmarksAB2dD2';
-	case 2083, name='GiaBenchmarksAB2dD3';
-	case 3001, name='SquareShelfConstrainedStressSSA2dAdolc';
-	case 3002, name='SquareShelfConstrainedStressSSA3dAdolc';
-	case 3003, name='SquareShelfConstrainedStressHOAdolc';
-	case 3004, name='SquareShelfConstrainedStressFSAdolc';
-	case 3005, name='SquareShelfConstrainedMasstransp2dAdolc';
-	case 3006, name='SquareShelfConstrainedMasstransp2dDGAdolc';
-	case 3007, name='SquareShelfConstrainedMasstransp3dAdolc';
-	case 3008, name='SquareShelfConstrainedTherSteaAdolc';
-	case 3009, name='SquareShelfConstrainedTherTranAdolc';
-	case 3010, name='SquareShelfConstrainedTranSSA2dAdolc';
-	case 3015, name='SquareShelfConstrainedMasstransp2dAdolcForwardDifference';
-	case 3019, name='SquareShelfConstrainedTherTranAdolcReverseVsForward';
-	case 3020, name='SquareShelfConstrainedTranAdolcReverseVsForward';
-	case 3101, name='SquareShelfConstrainedStressSSA2dAdolcMumps';
-	case 3102, name='SquareShelfConstrainedStressSSA3dAdolcMumps';
-	case 3103, name='SquareShelfConstrainedStressHOAdolcMumps';
-	case 3104, name='SquareShelfConstrainedStressFSAdolcMumps';
-	case 3105, name='SquareShelfConstrainedMasstransp2dAdolcMumps';
-	case 3106, name='SquareShelfConstrainedMasstransp2dDGAdolcMumps';
-	case 3107, name='SquareShelfConstrainedMasstransp3dAdolcMumps';
-	case 3108, name='SquareShelfConstrainedTherSteaAdolcMumps';
-	case 3109, name='SquareShelfConstrainedTherTranAdolcMumps';
-	case 3110, name='SquareShelfConstrainedTranSSA2dAdolcMumps';
-	case 3115, name='SquareShelfConstrainedMasstransp2dAdolcForwardDifferenceMumps';
-	case 3019, name='SquareShelfConstrainedTherTranAdolcReverseVsForward';
-	case 3120, name='SquareShelfConstrainedTranAdolcReverseVsForwardMumps';
+if nargin==0 | id==0,
+	flist=dir;%use dir, as it seems to act OS independent
+	list_ids=[];
+	for i=1:numel(flist),
+		if ( strncmp(flist(i).name,'test',4) &...                         %File name must start with 'test'
+				strncmp(fliplr(flist(i).name),fliplr('.m'),2)&...           %File name must end by '.m'
+				~strcmp(flist(i).name,'test.m'))                            %File name must be different than 'test.m'
+			id=str2num(flist(i).name(5:end-2));
+			if isempty(id),
+				disp(['WARNING: ignore file ' flist(i).name ]);
+			else
+				list_ids(end+1)=eval(flist(i).name(5:end-2));                  %Keep test id only (skip 'test' and '.m')
+			end
+		end
+	end
+	list_ids=sort(list_ids);
+	for i=list_ids,
+		name=IdToName(i);
+		disp(['test ' num2str(i,'%5i\n') ' : ' name]);
+	end
+	return;
+end
 
+filename = ['test' num2str(id) '.m'];
 
-	otherwise, name='N/A';
+if ~exist(filename,'file')
+	error(['file ' filename ' does not exist']);
 end
+
+string='%TestName:';
+fid=fopen(filename,'r');
+A=fscanf(fid,'%s',3);
+if ~strncmp(A,string,numel(string)) | numel(A)<numel(string)+2,
+	error(['Test file ' filename ' does to start with a test name']);
+end
+name = A(numel(string)+1:end);
+fclose(fid);
Index: /issm/trunk/test/NightlyRun/IdToName.py
===================================================================
--- /issm/trunk/test/NightlyRun/IdToName.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/IdToName.py	(revision 19105)
@@ -9,247 +9,9 @@
 	"""
 
-	idname={
-	101 : 'SquareShelfConstrainedStressSSA2d',
-	102 : 'SquareShelfConstrainedStressSSA3d',
-	103 : 'SquareShelfConstrainedStressHO',
-	104 : 'SquareShelfConstrainedStressFS',
-	105 : 'SquareShelfConstrainedMasstransp2d',
-	106 : 'SquareShelfConstrainedMasstransp2dDG',
-	107 : 'SquareShelfConstrainedMasstransp3d',
-	108 : 'SquareShelfConstrainedTherStea',
-	109 : 'SquareShelfConstrainedTherTran',
-	110 : 'SquareShelfConstrainedTranSSA2d',
-	111 : 'SquareShelfConstrainedTranHO',
-	112 : 'SquareShelfConstrainedSurfSlop2d',
-	113 : 'SquareShelfConstrainedSurfSlope3d',
-	114 : 'SquareShelfConstrainedBedSlop2d',
-	115 : 'SquareShelfConstrainedBedSlop3d',
-	116 : 'SquareShelfConstrainedBalThic2d',
-	117 : 'SquareShelfConstrainedBalThic3d',
-	118 : 'SquareShelfConstrainedBalThic2dDG',
-	119 : 'SquareBamgMesh',
-	120 : 'SquareShelfConstrainedEnthalpyStea',
-	121 : 'SquareShelfConstrainedEnthalpyTran',
-	122 : 'SquareShelfConstrainedTransHOEnth',
-	201 : 'SquareShelfStressSSA2d',
-	202 : 'SquareShelfStressSSA3d',
-	203 : 'SquareShelfStressHO',
-	204 : 'SquareShelfStressFS',
-	205 : 'SquareShelfStressMHOPenalties',
-	206 : 'SquareShelfTherStea',
-	207 : 'SquareShelfTherTran',
-	208 : 'SquareShelfTranSSA2d',
-	209 : 'SquareShelfTranSSA3d',
-	210 : 'SquareShelfTranHO',
-	211 : 'SquareShelfTranFS',
-	212 : 'SquareShelfCMBSSA2d',
-	213 : 'SquareShelfCMBSSA3d',
-	214 : 'SquareShelfCMBHO',
-	215 : 'SquareShelfCMBFS',
-	216 : 'SquareShelfStressSSA2dRift',
-	217 : 'SquareShelfConstrained',
-	218 : 'SquareShelfConstrainedDakotaB',
-	219 : 'SquareShelfStressSSAHOTiling',
-	220 : 'SquareShelfStressHOFS3dTiling',
-	221 : 'SquareShelfStressSSAFS3dTiling',
-	222 : 'SquareShelfStressSSA2dTransientIncrHydro',
-	223 : 'SquareShelfStressSSA2dTransientIncrNonHydro',
-	224 : 'SquareShelfStressHOTransientIncrHydro',
-	225 : 'SquareShelfStressHOTransientIncrNonHydro',
-	226 : 'SquareShelfTranCflSSA2d',
-	227 : 'SquareShelfTranCflHO',
-	228 : 'SquareShelfTranForceNeg2d',
-	229  : 'SquareShelfTranForcePos2d',
-	230  : 'SquareShelfTranForceNeg3d',
-	231  : 'SquareShelfTranForcePos3d',
-	232  : 'SquareShelfTherTranForcTemp',
-	233  : 'SquareShelfTranHOForcTemp',
-	234  : 'SquareShelfTranForceNeg2dDakotaSamp',
-	235  : 'SquareShelfTranForceNeg2dDakotaLocal',
-	236  : 'SquareShelfTranIspddIsdeltaSSA2d',
-	237  : 'SquareShelfTranIspddIsdeltaSSA3d',
-	270  : 'SquareShelfStressSSA2dDamage',
-	272  : 'SquareShelfCMZSSA2dDamage',
-	274  : 'SquareShelfStressSSA2dDamageRift',
-	275  : 'SquareShelfDamageEvolutionSSA2d',
-	276  : 'SquareShelfDamageEvolutionSSA2dP2',
-	280  : 'SquareShelfStressSSA2dHigherOrder',
-	285  : 'SquareShelfStressHOHigherOrder',
-	290  : 'SquareShelfStressFSP2P1',
-	291  : 'SquareShelfStressFSP4z',
-	292  : 'SquareShelfTranSSA2dFloatingMeltParam',
-	301  : 'SquareSheetConstrainedStressSSA2d',
-	302  : 'SquareSheetConstrainedStressSIA2d',
-	303  : 'SquareSheetConstrainedStressSIASSA2d',
-	304  : 'SquareSheetConstrainedStressSSA3d',
-	305  : 'SquareSheetConstrainedStressSIA3d',
-	306  : 'SquareSheetConstrainedStressSIASSA3d',
-	307  : 'SquareSheetConstrainedStressHO',
-	308  : 'SquareSheetConstrainedStressFS',
-	309  : 'SquareSheetConstrainedMasstransp2d',
-	320  : 'SquareSheetConstrainedMasstransp2dDG',
-	311  : 'SquareSheetConstrainedMasstransp3d',
-	312  : 'SquareSheetConstrainedTherStea',
-	313  : 'SquareSheetConstrainedTherTran',
-	314  : 'SquareSheetConstrainedTranSIA2d',
-	315  : 'SquareSheetConstrainedTranSIA3d',
-	316  : 'SquareSheetConstrainedTranSSA2d',
-	317  : 'SquareSheetConstrainedTranHO',
-	318  : 'SquareSheetConstrainedSteaSIA3d',
-	319  : 'SquareSheetConstrainedCMDragSSA2d',
-	320  : 'SquareSheetConstrainedCMDragSSA3d',
-	321  : 'SquareSheetConstrainedCMDragHO',
-	322  : 'SquareSheetConstrainedCMDragFS',
-	323  : 'SquareSheetConstrainedTranCflSSA2d',
-	324  : 'SquareSheetConstrainedTranCflSIA3d',
-	325  : 'SquareSheetConstrainedEnthalpyStea',
-	326  : 'SquareSheetConstrainedEnthalpyTran',
-	327  : 'SquareSheetConstrainedTransHOEnth',
-	328  : 'SquareSheetConstrainedSmbGradients2d',
-	329  : 'SquareSheetConstrainedSmbGradients3d',
-	332  : 'SquareSheetConstrainedHydrologyDC',
-	333  : 'SquareSheetHydrologyDCTwoLayers',
-	401  : 'SquareSheetShelfStressSSA2d',
-	402  : 'SquareSheetShelfStressSSA3d',
-	403  : 'SquareSheetShelfStressHO',
-	404  : 'SquareSheetShelfStressFS',
-	405  : 'SquareSheetShelfStressMHOPenalties',
-	406  : 'SquareSheetShelfTherStea',
-	407  : 'SquareSheetShelfTherTran',
-	408  : 'SquareSheetShelfTranSSA2d',
-	409  : 'SquareSheetShelfTranMHOPenalties',
-	410  : 'SquareSheetShelfSteaSSA3d',
-	411  : 'SquareSheetShelfSteaHO',
-	412  : 'SquareSheetShelfDiadSSA3dDakota',
-	413  : 'SquareSheetShelfDiadSSA3dDakotaPart',
-	414  : 'SquareSheetShelfDiadSSA3dDakotaMassFlux',
-	415  : 'SquareSheetShelfCMDragSteaSSA3d',
-	416  : 'SquareSheetShelfCMDragSteaHO',
-	417  : 'SquareSheetShelfDiadSSA3dDakotaSamp',
-	418  : 'SquareSheetShelfDiadSSA3dDakotaAreaAverage',
-	419  : 'SquareSheetShelfStressSSAHOTiling',
-	420  : 'SquareSheetShelfDakotaScaledResponse',
-	421  : 'SquareSheetShelfStressHOFS3dTiling',
-	422  : 'SquareSheetShelfStressSSAFS3dTiling',
-	423  : 'RoundSheetShelfGLMigrationSSA2d',
-	424  : 'SquareSheetShelfGroundingLine2dAggressive',
-	425  : 'SquareSheetShelfGroundingLine2dSoft',
-	426  : 'SquareSheetShelfGroundingLine3dAggressive',
-	427  : 'SquareSheetShelfGroundingLine3dSoft',
-	428  : 'SquareSheetShelfStressSSA2dNewton',
-	429  : 'SquareSheetShelfStressHONewton',
-	431  : 'SquareSheetShelfSteaEnthalpySSA3d',
-	432  : 'SquareSheetShelfSteaEnthalpyHO',
-	433  : 'RoundSheetShelfGLMigrationSSA3d',
-	434  : 'SquareSheetShelfL1L2',
-	450  : 'SquareSheetShelfStressSSAHigherOrder',
-	455  : 'SquareSheetShelfStressHOHigherOrder',
-	501  : 'PigStressSSA2d',
-	502  : 'PigStressHO',
-	503  : 'PigStressFS',
-	504  : 'PigTranSSA2d',
-	505  : 'PigTranSSA3d',
-	506  : 'PigTranHO',
-	507  : 'PigTranFS',
-	508  : 'PigSteaSSA3d',
-	509  : 'PigSteaHO',
-	510  : 'PigSteaFS',
-	511  : 'PigCMBFS',
-	512  : 'PigCMDragHO',
-	513  : 'PigCMDragSteaSSA3d',
-	514  : 'PigBamgMesh',
-	515  : 'PigTherTranSUPG',
-	516  : 'PigTherSteaSUPG',
-	530  : 'PigBalVel1',
-	531  : 'PigBalVel2',
-	601  : '79NorthMasstransp2d',
-	602  : '79NorthMasstransp2dDG',
-	603  : '79NorthMasstransp3d',
-	604  : '79NorthSurfSlop2d',
-	605  : '79NorthSurfSlop3d',
-	606  : '79NorthBedSlop2d',
-	607  : '79NorthBedSlop3d',
-	608  : '79NorthBalThic2d',
-	609  : '79NorthBalThic2dDG',
-	610  : '79NorthBalThic3d',
-	611  : '79NorthCMBalThic2dCG',
-	613  : '79NorthCMBalThicVxVy',
-	801  : 'ValleyGlacierLevelsetSSA2d',	
-	802  : 'ValleyGlacierLevelsetThermalSSA3d',	
-	803  : 'ValleyGlacierLevelsetEnthalpyHO3d',	
-	804  : 'ValleyGlacierLevelsetCalvingSIA2d',	
-	805  : 'ValleyGlacierLevelsetEnthCalvingHO3d',	
-	1101 : 'ISMIPAHO',
-	1102 : 'ISMIPAFS',
-	1103 : 'ISMIPBHO',
-	1104 : 'ISMIPBFS',
-	1105 : 'ISMIPCHO',
-	1106 : 'ISMIPCFS',
-	1107 : 'ISMIPDHO',
-	1108 : 'ISMIPDFS',
-	1109 : 'ISMIPE',
-	1110 : 'ISMIPF',
-	1201 : 'EISMINTMassConservation',
-	1202 : 'EISMINTStress1',
-	1203 : 'EISMINTStress2',
-	1204 : 'EISMINTTran2',
-	1205 : 'EISMINTRoundIceSheetStaticSIA',
-	1206 : 'EISMINTRoundIceSheetStaticHO',
-	1207 : 'EISMINTRoundIceSheetStaticFS',
-	1208 : 'EISMINTA',
-	1301 : 'ThermalMelting',
-	1302 : 'ThermalAdvection',
-	1303 : 'ThermalConduction',
-	1304 : 'ThermalGeothermalFlux',
-	1401 : 'AdaptiveMeshRefinement1',
-	1402 : 'AdaptiveMeshRefinement2',
-	1501 : 'SquareShelfTranSawTooth2d',
-	1502 : 'SquareShelfTranSawTooth3d',
-	1601 : 'SquareShelfSSA2dRotation',
-	1602 : 'SquareSheetShelfHORotation',
-	2001 : 'SquareSheetConstrainedGia2d',
-	2051 : 'GiaBenchmarksAB2dA1',
-	2052 : 'GiaBenchmarksAB2dA2',
-	2053 : 'GiaBenchmarksAB2dA3',
-	2061 : 'GiaBenchmarksAB2dB1',
-	2062 : 'GiaBenchmarksAB2dB2',
-	2063 : 'GiaBenchmarksAB2dB3',
-	2071 : 'GiaBenchmarksAB2dC1',
-	2072 : 'GiaBenchmarksAB2dC2',
-	2073 : 'GiaBenchmarksAB2dC3',
-	2081 : 'GiaBenchmarksAB2dD1',
-	2082 : 'GiaBenchmarksAB2dD2',
-	2083 : 'GiaBenchmarksAB2dD3',
-	3001 : 'SquareShelfConstrainedStressSSA2dAdolc',
-	3002 : 'SquareShelfConstrainedStressSSA3dAdolc',
-	3003 : 'SquareShelfConstrainedStressHOAdolc',
-	3004 : 'SquareShelfConstrainedStressFSAdolc',
-	3005 : 'SquareShelfConstrainedMasstransp2dAdolc',
-	3006 : 'SquareShelfConstrainedMasstransp2dDGAdolc',
-	3007 : 'SquareShelfConstrainedMasstransp3dAdolc',
-	3008 : 'SquareShelfConstrainedTherSteaAdolc',
-	3009 : 'SquareShelfConstrainedTherTranAdolc',
-	3010 : 'SquareShelfConstrainedTranSSA2dAdolc',
-	3015 : 'SquareShelfConstrainedMasstransp2dAdolcForwardDifference',
-	3019 : 'SquareShelfConstrainedTherTranAdolcReverseVsForward',
-	3020 : 'SquareShelfConstrainedTranAdolcReverseVsForward',
-	3101 : 'SquareShelfConstrainedStressSSA2dAdolcMumps',
-	3102 : 'SquareShelfConstrainedStressSSA3dAdolcMumps',
-	3103 : 'SquareShelfConstrainedStressHOAdolcMumps',
-	3104 : 'SquareShelfConstrainedStressFSAdolcMumps',
-	3105 : 'SquareShelfConstrainedMasstransp2dAdolcMumps',
-	3106 : 'SquareShelfConstrainedMasstransp2dDGAdolcMumps',
-	3107 : 'SquareShelfConstrainedMasstransp3dAdolcMumps',
-	3108 : 'SquareShelfConstrainedTherSteaAdolcMumps',
-	3109 : 'SquareShelfConstrainedTherTranAdolcMumps',
-	3110 : 'SquareShelfConstrainedTranSSA2dAdolcMumps',
-	3115 : 'SquareShelfConstrainedMasstransp2dAdolcForwardDifferenceMumps',
-	3119 : 'SquareShelfConstrainedTherTranAdolcReverseVsForwardMumps',
-	3120 : 'SquareShelfConstrainedTranAdolcReverseVsForwardMumps',
-	3300 : 'SquareSheetHydrologyDCTwoLayersVolumeControl',
-	}
+	infile  = open('test' + str(id) + '.py','r')
+	file_text  = infile.readlines()
 
-	if not id == 0:
-		return idname.get(id,'N/A')
-	else:
-		return idname
+	string='#Test Name:';
+	name=file_text[0]
+	name=name[len(string)+1:-1]
+	return name
Index: /issm/trunk/test/NightlyRun/runme.m
===================================================================
--- /issm/trunk/test/NightlyRun/runme.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/runme.m	(revision 19105)
@@ -34,7 +34,4 @@
 %      runme('exclude',101);
 %      runme('id',102,'procedure','update');
-
-%Get ISSM_DIR variable
-ISSM_DIR=issmdir();
 
 %Check inputs
@@ -132,10 +129,10 @@
 root=pwd;
 for id=test_ids,
+	disp(sprintf('%s%i%s','----------------starting:',id,'-----------------------'));
 	try,
-
 		%Execute test
 		eval(['cd ' root ]);
+		id_string='N/A';
 		id_string=IdToName(id);
-		disp(sprintf('%s%i%s','----------------starting:',id,'-----------------------'));
 		eval(['test' num2str(id)]);
 
@@ -238,5 +235,5 @@
 					fprintf('%s',message);
 					if strcmpi(output,'nightly')
-						fid=fopen([ISSM_DIR '/nightlylog/matlaberror.log'], 'at');
+						fid=fopen([issmdir() '/nightlylog/matlaberror.log'], 'at');
 						fprintf(fid,'%s',message);
 						fprintf(fid,'\n------------------------------------------------------------------\n');
@@ -252,7 +249,4 @@
 			end
 		end
-		
-		disp(sprintf('%s%i%s','----------------finished:',id,'-----------------------'));
-
 	catch me,
 
@@ -261,5 +255,5 @@
 		fprintf('%s',message);
 		if strcmpi(output,'nightly')
-			fid=fopen([ISSM_DIR '/nightlylog/matlaberror.log'], 'at');
+			fid=fopen([issmdir() '/nightlylog/matlaberror.log'], 'at');
 			fprintf(fid,'%s',message);
 			fprintf(fid,'\n------------------------------------------------------------------\n');
@@ -271,5 +265,5 @@
 			if(getfieldvalue(options,'stoponerror',0)), disp('STOP'); return; end
 		end
-		disp(sprintf('%s%i%s','----------------finished:',id,'-----------------------'));
 	end
-end
+	disp(sprintf('%s%i%s','----------------finished:',id,'-----------------------'));
+end
Index: /issm/trunk/test/NightlyRun/runme.py
===================================================================
--- /issm/trunk/test/NightlyRun/runme.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/runme.py	(revision 19105)
@@ -129,4 +129,5 @@
 	root=os.getcwd()
 	for id in test_ids:
+		print "----------------starting:%i-----------------------" % id
 		try:
 
@@ -134,5 +135,4 @@
 			os.chdir(root)
 			id_string=IdToName(id)
-			print "----------------starting:%i-----------------------" % id
 			execfile('test'+str(id)+'.py',globals())
 
@@ -221,5 +221,4 @@
 
 				f.close()
-				print "----------------finished:%i-----------------------" % id
 
 		except Exception as me:
@@ -243,6 +242,6 @@
 				print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,'N/A')
 				raise RuntimeError(me)
-			print "----------------finished:%i-----------------------" % id
-
+
+		print "----------------finished:%i-----------------------" % id
 	return
 
Index: /issm/trunk/test/NightlyRun/test101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test101.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test101.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressSSA2d
 md=triangle(model(),'../Exp/Square.exp',50000.);
 md=setmask(md,'all','');
@@ -8,10 +9,10 @@
 md.stressbalance.requested_outputs={'default','DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy','MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6'};
 md.outputdefinition.definitions={...
-	massfluxatgate('MassFlux1',['../Exp/MassFlux1.exp']),...
-	massfluxatgate('MassFlux2',['../Exp/MassFlux2.exp']),...
-	massfluxatgate('MassFlux3',['../Exp/MassFlux3.exp']),...
-	massfluxatgate('MassFlux4',['../Exp/MassFlux4.exp']),...
-	massfluxatgate('MassFlux5',['../Exp/MassFlux5.exp']),...
-	massfluxatgate('MassFlux6',['../Exp/MassFlux6.exp'])...
+	massfluxatgate('name','MassFlux1','profilename',['../Exp/MassFlux1.exp'],'definitionenum',Outputdefinition1Enum()),...
+	massfluxatgate('name','MassFlux2','profilename',['../Exp/MassFlux2.exp'],'definitionenum',Outputdefinition2Enum()),...
+	massfluxatgate('name','MassFlux3','profilename',['../Exp/MassFlux3.exp'],'definitionenum',Outputdefinition3Enum()),...
+	massfluxatgate('name','MassFlux4','profilename',['../Exp/MassFlux4.exp'],'definitionenum',Outputdefinition4Enum()),...
+	massfluxatgate('name','MassFlux5','profilename',['../Exp/MassFlux5.exp'],'definitionenum',Outputdefinition5Enum()),...
+	massfluxatgate('name','MassFlux6','profilename',['../Exp/MassFlux6.exp'],'definitionenum',Outputdefinition6Enum())...
 	};
 
Index: /issm/trunk/test/NightlyRun/test101.py
===================================================================
--- /issm/trunk/test/NightlyRun/test101.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test101.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressSSA2d
 from model import *
 from triangle import *
@@ -19,10 +20,10 @@
 md.stressbalance.requested_outputs=['default','DeviatoricStressxx','DeviatoricStressyy','DeviatoricStressxy','MassFlux1','MassFlux2','MassFlux3','MassFlux4','MassFlux5','MassFlux6']
 md.outputdefinition.definitions=[
-		massfluxatgate('MassFlux1','../Exp/MassFlux1.exp'),
-		massfluxatgate('MassFlux2','../Exp/MassFlux2.exp'),
-		massfluxatgate('MassFlux3','../Exp/MassFlux3.exp'),
-		massfluxatgate('MassFlux4','../Exp/MassFlux4.exp'),
-		massfluxatgate('MassFlux5','../Exp/MassFlux5.exp'),
-		massfluxatgate('MassFlux6','../Exp/MassFlux6.exp')
+		massfluxatgate('name','MassFlux1','profilename','../Exp/MassFlux1.exp','definitionenum',Outputdefinition1Enum()),
+		massfluxatgate('name','MassFlux2','profilename','../Exp/MassFlux2.exp','definitionenum',Outputdefinition2Enum()),
+		massfluxatgate('name','MassFlux3','profilename','../Exp/MassFlux3.exp','definitionenum',Outputdefinition3Enum()),
+		massfluxatgate('name','MassFlux4','profilename','../Exp/MassFlux4.exp','definitionenum',Outputdefinition4Enum()),
+		massfluxatgate('name','MassFlux5','profilename','../Exp/MassFlux5.exp','definitionenum',Outputdefinition5Enum()),
+		massfluxatgate('name','MassFlux6','profilename','../Exp/MassFlux6.exp','definitionenum',Outputdefinition6Enum())
 		]
 
Index: /issm/trunk/test/NightlyRun/test102.m
===================================================================
--- /issm/trunk/test/NightlyRun/test102.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test102.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressSSA3d
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test102.py
===================================================================
--- /issm/trunk/test/NightlyRun/test102.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test102.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressSSA3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test103.m
===================================================================
--- /issm/trunk/test/NightlyRun/test103.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test103.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressHO
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test103.py
===================================================================
--- /issm/trunk/test/NightlyRun/test103.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test103.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressHO
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test104.m
===================================================================
--- /issm/trunk/test/NightlyRun/test104.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test104.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressFS
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test104.py
===================================================================
--- /issm/trunk/test/NightlyRun/test104.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test104.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressFS
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test105.m
===================================================================
--- /issm/trunk/test/NightlyRun/test105.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test105.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedMasstransp2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test105.py
===================================================================
--- /issm/trunk/test/NightlyRun/test105.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test105.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedMasstransp2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test106.m
===================================================================
--- /issm/trunk/test/NightlyRun/test106.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test106.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedMasstransp2dDG
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=meshconvert(md);
Index: /issm/trunk/test/NightlyRun/test106.py
===================================================================
--- /issm/trunk/test/NightlyRun/test106.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test106.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedMasstransp2dDG
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test107.m
===================================================================
--- /issm/trunk/test/NightlyRun/test107.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test107.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedMasstransp3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test107.py
===================================================================
--- /issm/trunk/test/NightlyRun/test107.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test107.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedMasstransp3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test108.m
===================================================================
--- /issm/trunk/test/NightlyRun/test108.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test108.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTherStea
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test108.py
===================================================================
--- /issm/trunk/test/NightlyRun/test108.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test108.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTherStea
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test109.m
===================================================================
--- /issm/trunk/test/NightlyRun/test109.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test109.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTherTran
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test109.py
===================================================================
--- /issm/trunk/test/NightlyRun/test109.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test109.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTherTran
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test110.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test110.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTranSSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test110.py
===================================================================
--- /issm/trunk/test/NightlyRun/test110.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test110.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTranSSA2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test1101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1101.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1101.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ISMIPAHO
 %This test is a test from the ISMP-HOM Intercomparison project.
 %Pattyn and Payne 2006
Index: /issm/trunk/test/NightlyRun/test1101.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1101.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1101.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ISMIPAHO
 import numpy
 import shutil
Index: /issm/trunk/test/NightlyRun/test1102.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1102.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1102.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ISMIPAFS
 %This test is a test from the ISMP-HOM Intercomparison project.
 %Pattyn and Payne 2006
Index: /issm/trunk/test/NightlyRun/test1102.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1102.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1102.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ISMIPAFS
 import numpy
 import shutil
Index: /issm/trunk/test/NightlyRun/test1103.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1103.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1103.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ISMIPBHO
 %This test is a test from the ISMP-HOM Intercomparison project.
 %Pattyn and Payne 2006
Index: /issm/trunk/test/NightlyRun/test1103.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1103.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1103.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ISMIPBHO
 import numpy
 import shutil
Index: /issm/trunk/test/NightlyRun/test1104.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1104.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1104.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ISMIPBFS
 %This test is a test from the ISMP-HOM Intercomparison project.
 %Pattyn and Payne 2006
Index: /issm/trunk/test/NightlyRun/test1104.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1104.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1104.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ISMIPBFS
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test1105.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1105.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1105.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ISMIPCHO
 %This test is a test from the ISMP-HOM Intercomparison project.
 %Pattyn and Payne 2006
Index: /issm/trunk/test/NightlyRun/test1105.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1105.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1105.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ISMIPCHO
 import numpy
 import shutil
Index: /issm/trunk/test/NightlyRun/test1106.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1106.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1106.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ISMIPCFS
 %This test is a test from the ISMP-HOM Intercomparison project.
 %Pattyn and Payne 2006
Index: /issm/trunk/test/NightlyRun/test1106.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1106.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1106.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ISMIPCFS
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test1107.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1107.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1107.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ISMIPDHO
 %This test is a test from the ISMP-HOM Intercomparison project.
 %Pattyn and Payne 2006
Index: /issm/trunk/test/NightlyRun/test1107.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1107.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1107.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ISMIPDHO
 import numpy
 import shutil
Index: /issm/trunk/test/NightlyRun/test1108.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1108.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1108.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ISMIPDFS
 %This test is a test from the ISMP-HOM Intercomparison project.
 %Pattyn and Payne 2006
Index: /issm/trunk/test/NightlyRun/test1108.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1108.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1108.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ISMIPDFS
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test1109.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1109.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1109.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ISMIPE
 %This test is a test from the ISMP-HOM Intercomparison project.
 %TestE 
Index: /issm/trunk/test/NightlyRun/test111.m
===================================================================
--- /issm/trunk/test/NightlyRun/test111.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test111.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTranHO
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test111.py
===================================================================
--- /issm/trunk/test/NightlyRun/test111.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test111.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTranHO
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test1110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1110.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1110.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ISMIPF
 %This test is a test from the ISMP-HOM Intercomparison project.
 %TestF 
Index: /issm/trunk/test/NightlyRun/test112.m
===================================================================
--- /issm/trunk/test/NightlyRun/test112.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test112.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedSurfSlop2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test112.py
===================================================================
--- /issm/trunk/test/NightlyRun/test112.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test112.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedSurfSlop2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test113.m
===================================================================
--- /issm/trunk/test/NightlyRun/test113.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test113.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedSurfSlope3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test113.py
===================================================================
--- /issm/trunk/test/NightlyRun/test113.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test113.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedSurfSlope3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test114.m
===================================================================
--- /issm/trunk/test/NightlyRun/test114.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test114.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedBedSlop2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test114.py
===================================================================
--- /issm/trunk/test/NightlyRun/test114.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test114.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedBedSlop2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test115.m
===================================================================
--- /issm/trunk/test/NightlyRun/test115.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test115.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedBedSlop3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test115.py
===================================================================
--- /issm/trunk/test/NightlyRun/test115.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test115.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedBedSlop3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test116.m
===================================================================
--- /issm/trunk/test/NightlyRun/test116.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test116.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedBalThic2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test116.py
===================================================================
--- /issm/trunk/test/NightlyRun/test116.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test116.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedBalThic2d
 import numpy
 from model import *
Index: sm/trunk/test/NightlyRun/test117.m
===================================================================
--- /issm/trunk/test/NightlyRun/test117.m	(revision 19104)
+++ 	(revision )
@@ -1,17 +1,0 @@
-md=triangle(model(),'../Exp/Square.exp',150000.);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,5,1.);
-%Add boundary conditions on thickness on the border
-pos=find(md.mesh.vertexonboundary);
-md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
-md=setflowequation(md,'SSA','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum());
-
-%Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
-field_values={...
-	(md.results.BalancethicknessSolution.Thickness),...
-	};
Index: sm/trunk/test/NightlyRun/test117.py
===================================================================
--- /issm/trunk/test/NightlyRun/test117.py	(revision 19104)
+++ 	(revision )
@@ -1,27 +1,0 @@
-import numpy
-from model import *
-from triangle import *
-from setmask import *
-from parameterize import *
-from setflowequation import *
-from EnumDefinitions import *
-from solve import *
-from MatlabFuncs import *
-
-md=triangle(model(),'../Exp/Square.exp',150000)
-md=setmask(md,'all','')
-md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(5,1.)
-#Add boundary conditions on thickness on the border
-pos=numpy.nonzero(md.mesh.vertexonboundary)
-md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
-md=setflowequation(md,'SSA','all')
-md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,BalancethicknessSolutionEnum())
-
-#Fields and tolerances to track changes
-field_names     =['Thickness']
-field_tolerances=[1e-13]
-field_values=[\
-	md.results.BalancethicknessSolution.Thickness,\
-	]
Index: sm/trunk/test/NightlyRun/test118.m
===================================================================
--- /issm/trunk/test/NightlyRun/test118.m	(revision 19104)
+++ 	(revision )
@@ -1,16 +1,0 @@
-md=triangle(model(),'../Exp/Square.exp',150000.);
-md=meshconvert(md);
-md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md.balancethickness.stabilization=3;
-md.initialization.vy=md.initialization.vy+400;
-md=setflowequation(md,'SSA','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum());
-
-%Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
-field_values={...
-	(md.results.BalancethicknessSolution.Thickness),...
-	};
Index: sm/trunk/test/NightlyRun/test118.py
===================================================================
--- /issm/trunk/test/NightlyRun/test118.py	(revision 19104)
+++ 	(revision )
@@ -1,26 +1,0 @@
-from model import *
-from triangle import *
-from meshconvert import *
-from setmask import *
-from parameterize import *
-from setflowequation import *
-from EnumDefinitions import *
-from solve import *
-from MatlabFuncs import *
-
-md=triangle(model(),'../Exp/Square.exp',150000)
-md=meshconvert(md)
-md=setmask(md,'all','')
-md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.balancethickness.stabilization=3
-md.initialization.vy=md.initialization.vy+400.
-md=setflowequation(md,'SSA','all')
-md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,BalancethicknessSolutionEnum())
-
-#Fields and tolerances to track changes
-field_names     =['Thickness']
-field_tolerances=[1e-13]
-field_values=[\
-	md.results.BalancethicknessSolution.Thickness,\
-	]
Index: /issm/trunk/test/NightlyRun/test119.m
===================================================================
--- /issm/trunk/test/NightlyRun/test119.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test119.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareBamgMesh
 
 %Simple mesh
Index: /issm/trunk/test/NightlyRun/test119.py
===================================================================
--- /issm/trunk/test/NightlyRun/test119.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test119.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareBamgMesh
 import numpy
 import time
Index: /issm/trunk/test/NightlyRun/test120.m
===================================================================
--- /issm/trunk/test/NightlyRun/test120.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test120.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedEnthalpyStea
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test120.py
===================================================================
--- /issm/trunk/test/NightlyRun/test120.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test120.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedEnthalpyStea
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test1201.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1201.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1201.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: EISMINTMassConservation
 %This test is a test from the EISMINT for Ice shelves Vincent Rommelaere 1996.
 printingflag=false;
Index: /issm/trunk/test/NightlyRun/test1201.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1201.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1201.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: EISMINTMassConservation
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test1202.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1202.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1202.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: EISMINTStress1
 %Test on the stressbalance model and the masstransport in 2d.
 printingflag=false;
Index: /issm/trunk/test/NightlyRun/test1202.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1202.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1202.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: EISMINTStress1
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test1203.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1203.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1203.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: EISMINTStress2
 %Test on the stressbalance model and the masstransport in 2d
 printingflag=false;
Index: /issm/trunk/test/NightlyRun/test1203.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1203.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1203.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: EISMINTStress2
 import numpy
 import sys
Index: /issm/trunk/test/NightlyRun/test1204.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1204.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1204.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: EISMINTTran2
 %Test on the stressbalance model and the masstransport in 2d
 printingflag=false;
Index: /issm/trunk/test/NightlyRun/test1204.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1204.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1204.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: EISMINTTran2
 import numpy
 import sys
Index: /issm/trunk/test/NightlyRun/test1205.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1205.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1205.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: EISMINTRoundIceSheetStaticSIA
 %The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
 printingflag=false;
Index: /issm/trunk/test/NightlyRun/test1205.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1205.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1205.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: EISMINTRoundIceSheetStaticSIA
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test1206.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1206.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1206.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: EISMINTRoundIceSheetStaticHO
 %The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
 printingflag=false;
Index: /issm/trunk/test/NightlyRun/test1206.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1206.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1206.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: EISMINTRoundIceSheetStaticHO
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test1207.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1207.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1207.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: EISMINTRoundIceSheetStaticFS
 %The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
 printingflag=false;
Index: /issm/trunk/test/NightlyRun/test1207.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1207.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1207.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: EISMINTRoundIceSheetStaticFS
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test1208.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1208.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1208.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: EISMINTA
 %EISMINT benchmark experiment A
 numlayers=8;
Index: /issm/trunk/test/NightlyRun/test1208.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1208.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1208.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: EISMINTA
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test121.m
===================================================================
--- /issm/trunk/test/NightlyRun/test121.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test121.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedEnthalpyTran
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test121.py
===================================================================
--- /issm/trunk/test/NightlyRun/test121.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test121.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedEnthalpyTran
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test122.m
===================================================================
--- /issm/trunk/test/NightlyRun/test122.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test122.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTransHOEnth
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test122.py
===================================================================
--- /issm/trunk/test/NightlyRun/test122.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test122.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTransHOEnth
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test123.m
===================================================================
--- /issm/trunk/test/NightlyRun/test123.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test123.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTranMisfitSurface
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
@@ -10,5 +11,5 @@
 
 md.transient.requested_outputs={'default','SurfaceMisfit'};
-md.outputdefinition.definitions={misfit('name','SurfaceMisfit', 'model_enum',SurfaceEnum,'observation_enum',SurfaceObservationEnum,'observation',fake_surface,'timeinterpolation','nearestneighbor','weights',ones(md.mesh.numberofvertices,1),'weights_enum',WeightsSurfaceObservationEnum)};
+md.outputdefinition.definitions={misfit('name','SurfaceMisfit', 'definitionenum',Outputdefinition1Enum,'model_enum',SurfaceEnum,'observation_enum',SurfaceObservationEnum,'observation',fake_surface,'timeinterpolation','nearestneighbor','weights',ones(md.mesh.numberofvertices,1),'weights_enum',WeightsSurfaceObservationEnum)};
 
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test124.m
===================================================================
--- /issm/trunk/test/NightlyRun/test124.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test124.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTranFSFreeSurface
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test1301.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1301.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1301.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ThermalMelting
 % This file can be run to check that the melting in simple conduction is correctly modeled.
 % There is no velocity (no advection) the only thermal boundary conditions are an imposed temperature
Index: /issm/trunk/test/NightlyRun/test1301.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1301.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1301.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ThermalMelting
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test1302.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1302.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1302.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ThermalAdvection
 % This file can be run to check that the advection-diffusion  is correctly modeled.
 % There is u=v=0 and w=cst everywhere the only thermal boundary conditions are an imposed temperature
Index: /issm/trunk/test/NightlyRun/test1302.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1302.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1302.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ThermalAdvection
 import numpy
 import sys
Index: /issm/trunk/test/NightlyRun/test1303.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1303.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1303.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ThermalConduction
 % This file can be run to check that the conduction is correctly modeled.
 % There is no velocity (no advection) the only thermal boundary conditions are an imposed temperature
Index: /issm/trunk/test/NightlyRun/test1303.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1303.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1303.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ThermalConduction
 import numpy
 import sys
Index: /issm/trunk/test/NightlyRun/test1304.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1304.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1304.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ThermalGeothermalFlux
 % This file can be run to check that the geothermal flux in simple conduction is correctly modeled.
 % There is no velocity (no advection) the only thermal boundary conditions are an imposed temperature
Index: /issm/trunk/test/NightlyRun/test1304.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1304.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1304.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ThermalGeothermalFlux
 import numpy
 import sys
Index: /issm/trunk/test/NightlyRun/test1401.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1401.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1401.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: AdaptiveMeshRefinement1
 %test the anisotropic mesh adaptation
 %function to capture = exp(-(sqrt((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)-0.75).^2*10.^6)+((md.mesh.x+0.1).^2+(md.mesh.y+0.1).^2)/2.;
Index: /issm/trunk/test/NightlyRun/test1402.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1402.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1402.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: AdaptiveMeshRefinement2
 %test the anisotropic mesh adaptation
 printingflag=false;
Index: /issm/trunk/test/NightlyRun/test1501.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1501.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1501.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranSawTooth2d
 printingflag = false;
 
@@ -15,5 +16,5 @@
 smb= 2.*ones(md.mesh.numberofvertices,1);
 md.surfaceforcings.mass_balance= smb;
-md.basalforcings.melting_rate= smb;
+md.basalforcings.groundedice_melting_rate= smb;
 
 md=solve(md,MasstransportSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test1501.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1501.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1501.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranSawTooth2d
 import numpy
 import sys
@@ -26,5 +27,5 @@
 smb= 2.*numpy.ones((md.mesh.numberofvertices,1))
 md.surfaceforcings.mass_balance= smb
-md.basalforcings.melting_rate= smb
+md.basalforcings.groundedice_melting_rate= smb
 
 md=solve(md,MasstransportSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test1502.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1502.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1502.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranSawTooth3d
 printingflag = false;
 
@@ -16,5 +17,5 @@
 smb= 2.*ones(md.mesh.numberofvertices,1);
 md.surfaceforcings.mass_balance= smb;
-md.basalforcings.melting_rate= smb;
+md.basalforcings.groundedice_melting_rate= smb;
 
 md=solve(md,MasstransportSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test1502.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1502.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1502.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranSawTooth3d
 import numpy
 import sys
@@ -27,5 +28,5 @@
 smb= 2.*numpy.ones((md.mesh.numberofvertices,1))
 md.surfaceforcings.mass_balance= smb
-md.basalforcings.melting_rate= smb
+md.basalforcings.groundedice_melting_rate= smb
 
 md=solve(md,MasstransportSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test1601.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1601.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1601.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfSSA2dRotation
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test1601.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1601.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1601.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfSSA2dRotation
 import numpy
 import sys
Index: /issm/trunk/test/NightlyRun/test1602.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1602.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1602.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfHORotation
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test1602.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1602.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test1602.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfHORotation
 import numpy
 import sys
Index: /issm/trunk/test/NightlyRun/test2001.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2001.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test2001.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedGia2d
 %GIA test, inspired on test101
 md=triangle(model(),'../Exp/Square.exp',100000.);
Index: /issm/trunk/test/NightlyRun/test2001.py
===================================================================
--- /issm/trunk/test/NightlyRun/test2001.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test2001.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedGia2d
 import numpy
 import copy
Index: /issm/trunk/test/NightlyRun/test201.m
===================================================================
--- /issm/trunk/test/NightlyRun/test201.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test201.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressSSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test201.py
===================================================================
--- /issm/trunk/test/NightlyRun/test201.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test201.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressSSA2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test202.m
===================================================================
--- /issm/trunk/test/NightlyRun/test202.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test202.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressSSA3d
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test202.py
===================================================================
--- /issm/trunk/test/NightlyRun/test202.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test202.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressSSA3d
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test203.m
===================================================================
--- /issm/trunk/test/NightlyRun/test203.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test203.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressHO
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test203.py
===================================================================
--- /issm/trunk/test/NightlyRun/test203.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test203.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressHO
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test204.m
===================================================================
--- /issm/trunk/test/NightlyRun/test204.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test204.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressFS
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test204.py
===================================================================
--- /issm/trunk/test/NightlyRun/test204.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test204.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressFS
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test205.m
===================================================================
--- /issm/trunk/test/NightlyRun/test205.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test205.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressMHOPenalties
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test205.py
===================================================================
--- /issm/trunk/test/NightlyRun/test205.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test205.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressMHOPenalties
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test2051.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2051.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test2051.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: GiaBenchmarksAB2dA1
 % Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
 md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
Index: /issm/trunk/test/NightlyRun/test2052.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2052.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test2052.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: GiaBenchmarksAB2dA2
 % Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
 md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
Index: /issm/trunk/test/NightlyRun/test2053.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2053.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test2053.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: GiaBenchmarksAB2dA3
 % Benchmark experiments (Figure A2a Ivins and James, 1999, Geophys. J. Int.) 
 md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
Index: /issm/trunk/test/NightlyRun/test206.m
===================================================================
--- /issm/trunk/test/NightlyRun/test206.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test206.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTherStea
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test206.py
===================================================================
--- /issm/trunk/test/NightlyRun/test206.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test206.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTherStea
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test207.m
===================================================================
--- /issm/trunk/test/NightlyRun/test207.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test207.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTherTran
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test207.py
===================================================================
--- /issm/trunk/test/NightlyRun/test207.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test207.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTherTran
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test2071.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2071.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test2071.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: GiaBenchmarksAB2dC1
 % Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
 md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
Index: /issm/trunk/test/NightlyRun/test2072.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2072.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test2072.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: GiaBenchmarksAB2dC2
 % Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
 md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
Index: /issm/trunk/test/NightlyRun/test2073.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2073.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test2073.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: GiaBenchmarksAB2dC3
 % Benchmark experiments (Figure A2c Ivins and James, 1999, Geophys. J. Int.) 
 md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
Index: /issm/trunk/test/NightlyRun/test208.m
===================================================================
--- /issm/trunk/test/NightlyRun/test208.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test208.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranSSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test208.py
===================================================================
--- /issm/trunk/test/NightlyRun/test208.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test208.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranSSA2d
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test2081.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2081.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test2081.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: GiaBenchmarksAB2dD1
 % Benchmark experiments (Figure A2d Ivins and James, 1999, Geophys. J. Int.) 
 md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
Index: /issm/trunk/test/NightlyRun/test2082.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2082.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test2082.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: GiaBenchmarksAB2dD2
 % Benchmark experiments (Figure A2d Ivins and James, 1999, Geophys. J. Int.) 
 md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
Index: /issm/trunk/test/NightlyRun/test2083.m
===================================================================
--- /issm/trunk/test/NightlyRun/test2083.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test2083.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: GiaBenchmarksAB2dD3
 % Benchmark experiments (Figure A2d Ivins and James, 1999, Geophys. J. Int.) 
 md=triangle(model(),'../Exp/RoundFrontEISMINT.exp',200000.);
Index: /issm/trunk/test/NightlyRun/test209.m
===================================================================
--- /issm/trunk/test/NightlyRun/test209.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test209.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranSSA3d
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test209.py
===================================================================
--- /issm/trunk/test/NightlyRun/test209.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test209.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranSSA3d
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test210.m
===================================================================
--- /issm/trunk/test/NightlyRun/test210.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test210.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranHO
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test210.py
===================================================================
--- /issm/trunk/test/NightlyRun/test210.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test210.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranHO
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test211.m
===================================================================
--- /issm/trunk/test/NightlyRun/test211.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test211.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranFS
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
@@ -16,5 +17,5 @@
 	2e-08,2e-08,1e-06,2e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,...
 	5e-07,5e-07,5e-05,1e-07,1e-08,1e-08,1e-08,1e-08,5e-08,2e-06,...
-	5e-06,5e-06,5e-05,5e-06,5e-07,5e-07,5e-07,1e-07,1e-06,5e-05};
+	5e-06,5e-06,5e-05,5e-06,5e-07,5e-07,5e-07,5e-07,5e-06,5e-05};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test211.py
===================================================================
--- /issm/trunk/test/NightlyRun/test211.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test211.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranFS
 from MatlabFuncs import *
 from model import *
@@ -29,5 +30,5 @@
 	2e-08,2e-08,1e-06,2e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,\
 	5e-07,5e-07,5e-05,1e-07,1e-08,1e-08,1e-08,1e-08,5e-08,2e-06,\
-	5e-06,5e-06,5e-05,5e-06,1e-07,5e-07,5e-07,5e-07,1e-06,5e-05]
+	5e-06,5e-06,5e-05,5e-06,1e-07,5e-07,5e-07,5e-07,5e-06,5e-05]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test212.m
===================================================================
--- /issm/trunk/test/NightlyRun/test212.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test212.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfCMBSSA2d
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test212.py
===================================================================
--- /issm/trunk/test/NightlyRun/test212.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test212.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfCMBSSA2d
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test213.m
===================================================================
--- /issm/trunk/test/NightlyRun/test213.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test213.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfCMBSSA3d
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test213.py
===================================================================
--- /issm/trunk/test/NightlyRun/test213.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test213.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfCMBSSA3d
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test214.m
===================================================================
--- /issm/trunk/test/NightlyRun/test214.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test214.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfCMBHO
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test214.py
===================================================================
--- /issm/trunk/test/NightlyRun/test214.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test214.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfCMBHO
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test215.m
===================================================================
--- /issm/trunk/test/NightlyRun/test215.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test215.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfCMBFS
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test215.py
===================================================================
--- /issm/trunk/test/NightlyRun/test215.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test215.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfCMBFS
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test216.m
===================================================================
--- /issm/trunk/test/NightlyRun/test216.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test216.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressSSA2dRift
 md=triangle(model(),'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000.);
 md=meshprocessrifts(md,'../Exp/Square.exp');
Index: /issm/trunk/test/NightlyRun/test216.py
===================================================================
--- /issm/trunk/test/NightlyRun/test216.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test216.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressSSA2dRift
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test217.m
===================================================================
--- /issm/trunk/test/NightlyRun/test217.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test217.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrained
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test217.py
===================================================================
--- /issm/trunk/test/NightlyRun/test217.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test217.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrained
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test218.m
===================================================================
--- /issm/trunk/test/NightlyRun/test218.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test218.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedDakotaB
 md=squaremesh(model(),1000000,1000000,5,5);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test219.m
===================================================================
--- /issm/trunk/test/NightlyRun/test219.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test219.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressSSAHOTiling
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test219.py
===================================================================
--- /issm/trunk/test/NightlyRun/test219.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test219.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressSSAHOTiling
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test220.m
===================================================================
--- /issm/trunk/test/NightlyRun/test220.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test220.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressHOFS3dTiling
 md=triangle(model(),'../Exp/Square.exp',120000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test220.py
===================================================================
--- /issm/trunk/test/NightlyRun/test220.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test220.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressHOFS3dTiling
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test221.m
===================================================================
--- /issm/trunk/test/NightlyRun/test221.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test221.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressSSAFS3dTiling
 md=triangle(model(),'../Exp/Square.exp',120000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test221.py
===================================================================
--- /issm/trunk/test/NightlyRun/test221.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test221.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressSSAFS3dTiling
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test222.m
===================================================================
--- /issm/trunk/test/NightlyRun/test222.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test222.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressSSA2dTransientIncrHydro
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test222.py
===================================================================
--- /issm/trunk/test/NightlyRun/test222.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test222.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressSSA2dTransientIncrHydro
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test223.m
===================================================================
--- /issm/trunk/test/NightlyRun/test223.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test223.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressSSA2dTransientIncrNonHydro
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test223.py
===================================================================
--- /issm/trunk/test/NightlyRun/test223.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test223.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressSSA2dTransientIncrNonHydro
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test224.m
===================================================================
--- /issm/trunk/test/NightlyRun/test224.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test224.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressHOTransientIncrHydro
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test224.py
===================================================================
--- /issm/trunk/test/NightlyRun/test224.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test224.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressHOTransientIncrHydro
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test225.m
===================================================================
--- /issm/trunk/test/NightlyRun/test225.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test225.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressHOTransientIncrNonHydro
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test225.py
===================================================================
--- /issm/trunk/test/NightlyRun/test225.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test225.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressHOTransientIncrNonHydro
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test226.m
===================================================================
--- /issm/trunk/test/NightlyRun/test226.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test226.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranCflSSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test226.py
===================================================================
--- /issm/trunk/test/NightlyRun/test226.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test226.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranCflSSA2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test227.m
===================================================================
--- /issm/trunk/test/NightlyRun/test227.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test227.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranCflHO
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test227.py
===================================================================
--- /issm/trunk/test/NightlyRun/test227.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test227.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranCflHO
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test228.m
===================================================================
--- /issm/trunk/test/NightlyRun/test228.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test228.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranForceNeg2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test228.py
===================================================================
--- /issm/trunk/test/NightlyRun/test228.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test228.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranForceNeg2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test229.m
===================================================================
--- /issm/trunk/test/NightlyRun/test229.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test229.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranForcePos2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test229.py
===================================================================
--- /issm/trunk/test/NightlyRun/test229.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test229.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranForcePos2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test230.m
===================================================================
--- /issm/trunk/test/NightlyRun/test230.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test230.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranForceNeg3d
 md=triangle(model(),'../Exp/Square.exp',350000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test230.py
===================================================================
--- /issm/trunk/test/NightlyRun/test230.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test230.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranForceNeg3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test231.m
===================================================================
--- /issm/trunk/test/NightlyRun/test231.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test231.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranForcePos3d
 md=triangle(model(),'../Exp/Square.exp',350000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test231.py
===================================================================
--- /issm/trunk/test/NightlyRun/test231.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test231.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranForcePos3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test232.m
===================================================================
--- /issm/trunk/test/NightlyRun/test232.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test232.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTherTranForcTemp
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test232.py
===================================================================
--- /issm/trunk/test/NightlyRun/test232.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test232.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTherTranForcTemp
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test233.m
===================================================================
--- /issm/trunk/test/NightlyRun/test233.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test233.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranHOForcTemp
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test233.py
===================================================================
--- /issm/trunk/test/NightlyRun/test233.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test233.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranHOForcTemp
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test234.m
===================================================================
--- /issm/trunk/test/NightlyRun/test234.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test234.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranForceNeg2dDakotaSamp
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test235.m
===================================================================
--- /issm/trunk/test/NightlyRun/test235.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test235.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranForceNeg2dDakotaLocal
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test236.m
===================================================================
--- /issm/trunk/test/NightlyRun/test236.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test236.m	(revision 19105)
@@ -1,12 +1,19 @@
+%Test Name: SquareShelfTranIspddIsdeltaSSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
 
+%md.verbose=verbose('all');
+
 % Use of ispdd and isdelta18o methods
 md.surfaceforcings = SMBpdd();
 md.surfaceforcings.isdelta18o=1;
+md.surfaceforcings.ismungsm=0;
+
+%md.surfaceforcings.precipitation(1:md.mesh.numberofvertices,1:12)=0;
+%md.surfaceforcings.monthlytemperatures(1:md.mesh.numberofvertices,1:12)=273;
 
 % Add temperature, precipitation and delta18o needed to measure the surface mass balance
-% creating delta18o
+%  creating delta18o
 load '../Data/delta18o.data'
 md.surfaceforcings.delta18o=delta18o;
@@ -26,5 +33,6 @@
 end
 
-% creating initialization and spc temperatures initialization and spc
+% creating initialization and spc temperatures initialization and
+% spc
 md.thermal.spctemperature=mean(md.surfaceforcings.temperatures_lgm(1:md.mesh.numberofvertices,1:12),2); %-10*ones(md.mesh.numberofvertices,1);
 md.thermal.spctemperature=repmat(md.thermal.spctemperature,1,md.timestepping.final_time/md.timestepping.time_step);
@@ -37,9 +45,20 @@
 for imonth=0:11
     md.surfaceforcings.precipitations_presentday(1:md.mesh.numberofvertices,imonth+1)=-0.4*10^(-6)*md.mesh.y+0.5;
+    md.surfaceforcings.precipitations_lgm(1:md.mesh.numberofvertices,imonth+1)=-0.4*10^(-6)*md.mesh.y+0.5;
+    % Time for the last line:
     md.surfaceforcings.precipitations_presentday(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+    md.surfaceforcings.precipitations_lgm(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
 end
+
+% Interpolation factors
+md.surfaceforcings.Tdiff(1,1:md.timestepping.final_time)=0.5;
+md.surfaceforcings.sealev(1,1:md.timestepping.final_time)=0.5;
+% Year of each data point
+md.surfaceforcings.Tdiff(2,1:md.timestepping.final_time)=1:1:md.timestepping.final_time;
+md.surfaceforcings.sealev(2,1:md.timestepping.final_time)=1:1:md.timestepping.final_time;
 
 % time steps and resolution
 md.timestepping.time_step=20;
+md.settings.output_frequency=1;
 md.timestepping.final_time=60;
 
@@ -47,5 +66,5 @@
 md.transient.requested_outputs={'default','SurfaceforcingsMonthlytemperatures'};
 md=setflowequation(md,'SSA','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md.cluster=generic('name',oshostname(),'np',1); % 3 for the cluster
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test236.py
===================================================================
--- /issm/trunk/test/NightlyRun/test236.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test236.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranIspddIsdeltaSSA2d
 import numpy
 from model import *
@@ -16,4 +17,5 @@
 md.surfaceforcings = SMBpdd();
 md.surfaceforcings.isdelta18o=1
+md.surfaceforcings.ismungsm=0
 
 # Add temperature, precipitation and delta18o needed to measure the surface mass balance
@@ -47,11 +49,22 @@
 # creating precipitation
 md.surfaceforcings.precipitations_presentday=numpy.zeros((md.mesh.numberofvertices+1,12))
+md.surfaceforcings.precipitations_lgm=numpy.zeros((md.mesh.numberofvertices+1,12))
 for imonth in xrange(0,12):
     md.surfaceforcings.precipitations_presentday[0:md.mesh.numberofvertices,imonth]=-0.4*10**(-6)*md.mesh.y+0.5
     md.surfaceforcings.precipitations_presentday[md.mesh.numberofvertices,imonth]=((float(imonth)+1.)/12.)
+    md.surfaceforcings.precipitations_lgm[0:md.mesh.numberofvertices,imonth]=-0.4*10**(-6)*md.mesh.y+0.5
+    md.surfaceforcings.precipitations_lgm[md.mesh.numberofvertices,imonth]=((float(imonth)+1.)/12.)
+
+# Interpolation factors
+md.surfaceforcings.Tdiff=0.5*numpy.ones((2,md.timestepping.final_time))
+md.surfaceforcings.sealev=0.5*numpy.ones((2,md.timestepping.final_time))
+# Year of each data point
+md.surfaceforcings.Tdiff[1,1:md.timestepping.final_time]=numpy.arange(1.,md.timestepping.final_time)
+md.surfaceforcings.sealev[1,1:md.timestepping.final_time]=numpy.arange(1.,md.timestepping.final_time)
 
 # time steps and resolution
 md.timestepping.time_step=20.
 md.timestepping.final_time=60.
+
 
 # 
Index: /issm/trunk/test/NightlyRun/test237.m
===================================================================
--- /issm/trunk/test/NightlyRun/test237.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test237.m	(revision 19105)
@@ -1,18 +1,27 @@
+%Test Name: SquareShelfTranIspddIsdeltaSSA3d
 md=triangle(model(),'../Exp/Square.exp',600000.);%180000
 md=setmask(md,'all','');
-
-% Use of ispdd and isdelta18o methods
-md.surfaceforcings = SMBpdd();
-md.surfaceforcings.isdelta18o=1;
-
 md=parameterize(md,'../Par/SquareShelf.par');
 
+%md.verbose=verbose('all');
+
+% Use of ispdd methods
+md.surfaceforcings = SMBpdd();
+md.surfaceforcings.isdelta18o=0;
+md.surfaceforcings.ismungsm=1;
+
+if md.surfaceforcings.isdelta18o==0 & md.surfaceforcings.ismungsm==0
+    md.surfaceforcings.precipitation=zeros(md.mesh.numberofvertices,1);
+    md.surfaceforcings.monthlytemperatures=273*ones(md.mesh.numberofvertices,1);
+end
+    
+
 % Add temperature, precipitation and delta18o needed to measure the surface mass balance
-% creating delta18o
-load '../Data/delta18o.data'
-md.surfaceforcings.delta18o=delta18o;
-% creating delta18oSurface
-md.surfaceforcings.delta18o_surface(1,1:(length(delta18o))) = 0;
-md.surfaceforcings.delta18o_surface(2,:) = delta18o(2,:);
+% % creating delta18o
+% load '../Data/delta18o.data'
+% md.surfaceforcings.delta18o=delta18o;
+% % creating delta18oSurface
+% md.surfaceforcings.delta18o_surface(1,1:(length(delta18o))) = 0;
+% md.surfaceforcings.delta18o_surface(2,:) = delta18o(2,:);
 
 % creating Present day and lgm temperatures
@@ -38,6 +47,17 @@
 for imonth=0:11
     md.surfaceforcings.precipitations_presentday(1:md.mesh.numberofvertices,imonth+1)=-0.4*10^(-6)*md.mesh.y+0.5;
+    md.surfaceforcings.precipitations_lgm(1:md.mesh.numberofvertices,imonth+1)=-0.4*10^(-6)*md.mesh.y+0.5;
+    % Time for the last line:
     md.surfaceforcings.precipitations_presentday(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
+    md.surfaceforcings.precipitations_lgm(md.mesh.numberofvertices+1,imonth+1)=((imonth+1)/12);
 end
+
+md.surfaceforcings.Pfac(1,1:md.timestepping.final_time)=0.5;
+md.surfaceforcings.Tdiff(1,1:md.timestepping.final_time)=0.5;
+md.surfaceforcings.sealev(1,1:md.timestepping.final_time)=0.5;
+% Year of each data point
+md.surfaceforcings.Pfac(2,1:md.timestepping.final_time)=1:1:md.timestepping.final_time;
+md.surfaceforcings.Tdiff(2,1:md.timestepping.final_time)=1:1:md.timestepping.final_time;
+md.surfaceforcings.sealev(2,1:md.timestepping.final_time)=1:1:md.timestepping.final_time;
 
 % time steps and resolution
@@ -48,8 +68,9 @@
 %
 md.transient.requested_outputs={'default','SurfaceforcingsMonthlytemperatures'};
-md=extrude(md,3,1.);
+md=extrude(md,3,1);
+
 md=setflowequation(md,'SSA','all');
-md.cluster=generic('name',oshostname(),'np',1);
-md=solve(md,TransientSolutionEnum());
+md.cluster=generic('name',oshostname(),'np',1); % 3 for the cluster
+md=solve(md,TransientSolutionEnum);
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test237.py
===================================================================
--- /issm/trunk/test/NightlyRun/test237.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test237.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranIspddIsdeltaSSA3d
 import numpy
 from model import *
@@ -12,18 +13,19 @@
 md=triangle(model(),'../Exp/Square.exp',600000)    #180000
 md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
 
 # Use of ispdd and isdelta18o methods
 md.surfaceforcings = SMBpdd();
-md.surfaceforcings.isdelta18o=1
+md.surfaceforcings.isdelta18o=0
+md.surfaceforcings.ismungsm=1
 
-md=parameterize(md,'../Par/SquareShelf.py')
 
-# Add temperature, precipitation and delta18o needed to measure the surface mass balance
-# creating delta18o
-delta18o=numpy.loadtxt('../Data/delta18o.data')
-md.surfaceforcings.delta18o=delta18o
-# creating delta18oSurface
-md.surfaceforcings.delta18o_surface = numpy.zeros((2,numpy.size(delta18o,axis=1)))
-md.surfaceforcings.delta18o_surface[1,:] = delta18o[1,:]
+# # Add temperature, precipitation and delta18o needed to measure the surface mass balance
+# # creating delta18o
+# delta18o=numpy.loadtxt('../Data/delta18o.data')
+# md.surfaceforcings.delta18o=delta18o
+# # creating delta18oSurface
+# md.surfaceforcings.delta18o_surface = numpy.zeros((2,numpy.size(delta18o,axis=1)))
+# md.surfaceforcings.delta18o_surface[1,:] = delta18o[1,:]
 
 # creating Present day and lgm temperatures
@@ -49,7 +51,19 @@
 # creating precipitation
 md.surfaceforcings.precipitations_presentday=numpy.zeros((md.mesh.numberofvertices+1,12))
+md.surfaceforcings.precipitations_lgm=numpy.zeros((md.mesh.numberofvertices+1,12))
 for imonth in xrange(0,12):
     md.surfaceforcings.precipitations_presentday[0:md.mesh.numberofvertices,imonth]=-0.4*10**(-6)*md.mesh.y+0.5
     md.surfaceforcings.precipitations_presentday[md.mesh.numberofvertices,imonth]=((float(imonth)+1.)/12.)
+    md.surfaceforcings.precipitations_lgm[0:md.mesh.numberofvertices,imonth]=-0.4*10**(-6)*md.mesh.y+0.5
+    md.surfaceforcings.precipitations_lgm[md.mesh.numberofvertices,imonth]=((float(imonth)+1.)/12.)
+
+# Interpolation factors
+md.surfaceforcings.Pfac=0.5*numpy.ones((2,md.timestepping.final_time))
+md.surfaceforcings.Tdiff=0.5*numpy.ones((2,md.timestepping.final_time))
+md.surfaceforcings.sealev=0.5*numpy.ones((2,md.timestepping.final_time))
+# Year of each data point
+md.surfaceforcings.Pfac[1,1:md.timestepping.final_time]=numpy.arange(1.,md.timestepping.final_time)
+md.surfaceforcings.Tdiff[1,1:md.timestepping.final_time]=numpy.arange(1.,md.timestepping.final_time)
+md.surfaceforcings.sealev[1,1:md.timestepping.final_time]=numpy.arange(1.,md.timestepping.final_time)
 
 # time steps and resolution
Index: /issm/trunk/test/NightlyRun/test238.m
===================================================================
--- /issm/trunk/test/NightlyRun/test238.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test238.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranForceNoInterp2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test238.py
===================================================================
--- /issm/trunk/test/NightlyRun/test238.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test238.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranForceNoInterp2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test239.m
===================================================================
--- /issm/trunk/test/NightlyRun/test239.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test239.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranForceNoInterp3d
 md=triangle(model(),'../Exp/Square.exp',350000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test239.py
===================================================================
--- /issm/trunk/test/NightlyRun/test239.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test239.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranForceNoInterp3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test270.m
===================================================================
--- /issm/trunk/test/NightlyRun/test270.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test270.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressSSA2dDamage
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test270.py
===================================================================
--- /issm/trunk/test/NightlyRun/test270.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test270.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressSSA2dDamage
 import numpy
 from model import model
Index: /issm/trunk/test/NightlyRun/test271.m
===================================================================
--- /issm/trunk/test/NightlyRun/test271.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test271.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressSSA2dDamageTran
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test271.py
===================================================================
--- /issm/trunk/test/NightlyRun/test271.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test271.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressSSA2dDamageTran
 import numpy 
 from triangle import triangle
Index: /issm/trunk/test/NightlyRun/test272.m
===================================================================
--- /issm/trunk/test/NightlyRun/test272.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test272.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfCMZSSA2dDamage
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test272.py
===================================================================
--- /issm/trunk/test/NightlyRun/test272.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test272.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfCMZSSA2dDamage
 import numpy
 from model import model
Index: /issm/trunk/test/NightlyRun/test274.m
===================================================================
--- /issm/trunk/test/NightlyRun/test274.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test274.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressSSA2dDamageRift
 md=triangle(model(),'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000.);
 md=meshprocessrifts(md,'../Exp/Square.exp');
Index: /issm/trunk/test/NightlyRun/test274.py
===================================================================
--- /issm/trunk/test/NightlyRun/test274.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test274.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressSSA2dDamageRift
 import numpy
 from model import model
Index: /issm/trunk/test/NightlyRun/test275.m
===================================================================
--- /issm/trunk/test/NightlyRun/test275.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test275.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfDamageEvolutionSSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test275.py
===================================================================
--- /issm/trunk/test/NightlyRun/test275.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test275.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfDamageEvolutionSSA2d
 import numpy
 from triangle import triangle
Index: /issm/trunk/test/NightlyRun/test280.m
===================================================================
--- /issm/trunk/test/NightlyRun/test280.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test280.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressSSA2dHigherOrder
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test280.py
===================================================================
--- /issm/trunk/test/NightlyRun/test280.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test280.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressSSA2dHigherOrder
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test285.m
===================================================================
--- /issm/trunk/test/NightlyRun/test285.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test285.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressHOHigherOrder
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test285.py
===================================================================
--- /issm/trunk/test/NightlyRun/test285.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test285.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressHOHigherOrder
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test290.m
===================================================================
--- /issm/trunk/test/NightlyRun/test290.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test290.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressFSP2P1
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test290.py
===================================================================
--- /issm/trunk/test/NightlyRun/test290.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test290.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressFSP2P1
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test291.m
===================================================================
--- /issm/trunk/test/NightlyRun/test291.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test291.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfStressFSP4z
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test291.py
===================================================================
--- /issm/trunk/test/NightlyRun/test291.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test291.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfStressFSP4z
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test292.m
===================================================================
--- /issm/trunk/test/NightlyRun/test292.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test292.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfTranSSA2dFloatingMeltParam
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test292.py
===================================================================
--- /issm/trunk/test/NightlyRun/test292.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test292.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfTranSSA2dFloatingMeltParam
 from MatlabFuncs import *
 from model import *
Index: /issm/trunk/test/NightlyRun/test3001.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3001.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3001.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressSSA2dAdolc
 md=triangle(model(),'../Exp/Square.exp',50000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3001.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3001.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3001.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressSSA2dAdolc
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3002.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3002.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3002.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressSSA3dAdolc
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3002.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3002.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3002.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressSSA3dAdolc
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3003.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3003.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressHOAdolc
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3003.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3003.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressHOAdolc
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3004.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3004.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3004.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressFSAdolc
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3004.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3004.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3004.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressFSAdolc
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3005.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3005.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3005.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedMasstransp2dAdolc
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3005.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3005.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3005.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedMasstransp2dAdolc
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3006.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3006.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3006.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedMasstransp2dDGAdolc
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=meshconvert(md);
Index: /issm/trunk/test/NightlyRun/test3006.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3006.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3006.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedMasstransp2dDGAdolc
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3007.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3007.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3007.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedMasstransp3dAdolc
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3007.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3007.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3007.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedMasstransp3dAdolc
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3008.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3008.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3008.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTherSteaAdolc
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3008.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3008.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3008.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTherSteaAdolc
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3009.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3009.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3009.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTherTranAdolc
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3009.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3009.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3009.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTherTranAdolc
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test301.m
===================================================================
--- /issm/trunk/test/NightlyRun/test301.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test301.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedStressSSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test301.py
===================================================================
--- /issm/trunk/test/NightlyRun/test301.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test301.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedStressSSA2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3010.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3010.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3010.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTranSSA2dAdolc
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3010.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3010.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3010.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTranSSA2dAdolc
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3015.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3015.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3015.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedMasstransp2dAdolcForwardDifference
 %This test runs test3005 with autodiff on, and checks that 
 %the value of the scalar forward difference match a step-wise differential
Index: /issm/trunk/test/NightlyRun/test3015.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3015.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3015.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedMasstransp2dAdolcForwardDifference
 import numpy
 import copy
Index: /issm/trunk/test/NightlyRun/test3019.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3019.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3019.m	(revision 19105)
@@ -1,2 +1,6 @@
+%Test Name: SquareShelfConstrainedTherTranAdolcReverseVsForward
+SquareShelfConstrainedTherTranAdolcReverseVsForward
+%Test Name: SquareShelfConstrainedTherTranAdolcReverseVsForward
+SquareShelfConstrainedTherTranAdolcReverseVsForward
 %test reverse scalar vs forward vectorial drivers in ADOLC, using the test3009 setup, equivalent to test109 setup.
 md=triangle(model(),'../Exp/Square.exp',100000.);
Index: /issm/trunk/test/NightlyRun/test3019.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3019.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3019.py	(revision 19105)
@@ -1,2 +1,6 @@
+#Test Name: SquareShelfConstrainedTherTranAdolcReverseVsForward
+SquareShelfConstrainedTherTranAdolcReverseVsForward
+#Test Name: SquareShelfConstrainedTherTranAdolcReverseVsForward
+SquareShelfConstrainedTherTranAdolcReverseVsForward
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test302.m
===================================================================
--- /issm/trunk/test/NightlyRun/test302.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test302.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedStressSIA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test302.py
===================================================================
--- /issm/trunk/test/NightlyRun/test302.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test302.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedStressSIA2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3020.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3020.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3020.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTranAdolcReverseVsForward
 %This test runs test3020 with autodiff on, and checks that 
 %the value of the scalar forward difference match a step-wise differential
Index: /issm/trunk/test/NightlyRun/test3020.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3020.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3020.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTranAdolcReverseVsForward
 import numpy
 import copy
Index: /issm/trunk/test/NightlyRun/test303.m
===================================================================
--- /issm/trunk/test/NightlyRun/test303.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test303.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedStressSIASSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test303.py
===================================================================
--- /issm/trunk/test/NightlyRun/test303.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test303.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedStressSIASSA2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test304.m
===================================================================
--- /issm/trunk/test/NightlyRun/test304.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test304.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedStressSSA3d
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test304.py
===================================================================
--- /issm/trunk/test/NightlyRun/test304.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test304.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedStressSSA3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test305.m
===================================================================
--- /issm/trunk/test/NightlyRun/test305.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test305.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedStressSIA3d
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test305.py
===================================================================
--- /issm/trunk/test/NightlyRun/test305.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test305.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedStressSIA3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test306.m
===================================================================
--- /issm/trunk/test/NightlyRun/test306.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test306.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedStressSIASSA3d
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test306.py
===================================================================
--- /issm/trunk/test/NightlyRun/test306.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test306.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedStressSIASSA3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test307.m
===================================================================
--- /issm/trunk/test/NightlyRun/test307.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test307.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedStressHO
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test307.py
===================================================================
--- /issm/trunk/test/NightlyRun/test307.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test307.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedStressHO
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test308.m
===================================================================
--- /issm/trunk/test/NightlyRun/test308.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test308.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedStressFS
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test308.py
===================================================================
--- /issm/trunk/test/NightlyRun/test308.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test308.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedStressFS
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test309.m
===================================================================
--- /issm/trunk/test/NightlyRun/test309.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test309.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedMasstransp2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test309.py
===================================================================
--- /issm/trunk/test/NightlyRun/test309.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test309.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedMasstransp2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test310.m
===================================================================
--- /issm/trunk/test/NightlyRun/test310.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test310.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedMasstransp2dDG
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=meshconvert(md);
Index: /issm/trunk/test/NightlyRun/test310.py
===================================================================
--- /issm/trunk/test/NightlyRun/test310.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test310.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedMasstransp2dDG
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3101.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3101.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressSSA2dAdolcMumps
 md=triangle(model(),'../Exp/Square.exp',50000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3101.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3101.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3101.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressSSA2dAdolcMumps
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3102.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3102.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3102.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressSSA3dAdolcMumps
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3102.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3102.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3102.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressSSA3dAdolcMumps
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3103.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3103.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3103.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressHOAdolcMumps
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3103.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3103.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3103.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressHOAdolcMumps
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3104.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3104.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3104.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedStressFSAdolcMumps
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3104.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3104.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3104.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedStressFSAdolcMumps
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3105.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3105.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3105.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedMasstransp2dAdolcMumps
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3105.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3105.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3105.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedMasstransp2dAdolcMumps
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3106.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3106.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3106.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedMasstransp2dDGAdolcMumps
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=meshconvert(md);
Index: /issm/trunk/test/NightlyRun/test3106.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3106.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3106.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedMasstransp2dDGAdolcMumps
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3107.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3107.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3107.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedMasstransp3dAdolcMumps
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3107.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3107.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3107.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedMasstransp3dAdolcMumps
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3108.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3108.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3108.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTherSteaAdolcMumps
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3108.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3108.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3108.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTherSteaAdolcMumps
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3109.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3109.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3109.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTherTranAdolcMumps
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3109.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3109.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3109.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTherTranAdolcMumps
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test311.m
===================================================================
--- /issm/trunk/test/NightlyRun/test311.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test311.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedMasstransp3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test311.py
===================================================================
--- /issm/trunk/test/NightlyRun/test311.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test311.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedMasstransp3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test3110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3110.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3110.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareShelfConstrainedTranSSA2dAdolcMumps
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test3110.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3110.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3110.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareShelfConstrainedTranSSA2dAdolcMumps
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test312.m
===================================================================
--- /issm/trunk/test/NightlyRun/test312.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test312.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedTherStea
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test312.py
===================================================================
--- /issm/trunk/test/NightlyRun/test312.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test312.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedTherStea
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test313.m
===================================================================
--- /issm/trunk/test/NightlyRun/test313.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test313.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedTherTran
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test313.py
===================================================================
--- /issm/trunk/test/NightlyRun/test313.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test313.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedTherTran
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test314.m
===================================================================
--- /issm/trunk/test/NightlyRun/test314.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test314.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedTranSIA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test314.py
===================================================================
--- /issm/trunk/test/NightlyRun/test314.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test314.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedTranSIA2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test315.m
===================================================================
--- /issm/trunk/test/NightlyRun/test315.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test315.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedTranSIA3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test315.py
===================================================================
--- /issm/trunk/test/NightlyRun/test315.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test315.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedTranSIA3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test316.m
===================================================================
--- /issm/trunk/test/NightlyRun/test316.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test316.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedTranSSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test316.py
===================================================================
--- /issm/trunk/test/NightlyRun/test316.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test316.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedTranSSA2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test317.m
===================================================================
--- /issm/trunk/test/NightlyRun/test317.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test317.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedTranHO
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test317.py
===================================================================
--- /issm/trunk/test/NightlyRun/test317.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test317.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedTranHO
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test318.m
===================================================================
--- /issm/trunk/test/NightlyRun/test318.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test318.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedSteaSIA3d
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test318.py
===================================================================
--- /issm/trunk/test/NightlyRun/test318.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test318.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedSteaSIA3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test319.m
===================================================================
--- /issm/trunk/test/NightlyRun/test319.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test319.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedCMDragSSA2d
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test319.py
===================================================================
--- /issm/trunk/test/NightlyRun/test319.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test319.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedCMDragSSA2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test320.m
===================================================================
--- /issm/trunk/test/NightlyRun/test320.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test320.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedCMDragSSA3d
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test320.py
===================================================================
--- /issm/trunk/test/NightlyRun/test320.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test320.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedCMDragSSA3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test321.m
===================================================================
--- /issm/trunk/test/NightlyRun/test321.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test321.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedCMDragHO
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test321.py
===================================================================
--- /issm/trunk/test/NightlyRun/test321.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test321.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedCMDragHO
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test322.m
===================================================================
--- /issm/trunk/test/NightlyRun/test322.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test322.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedCMDragFS
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
@@ -23,5 +24,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy'};
-field_tolerances={5e-05,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,5e-08,5e-08,5e-08};
+field_tolerances={5e-05,1e-08,7e-08,5e-09,5e-09,5e-09,5e-09,5e-08,5e-08,5e-08};
 field_values={...
 	(md.results.StressbalanceSolution.Gradient1),...
Index: /issm/trunk/test/NightlyRun/test322.py
===================================================================
--- /issm/trunk/test/NightlyRun/test322.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test322.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedCMDragFS
 import numpy
 from model import *
@@ -35,5 +36,5 @@
 #Fields and tolerances to track changes
 field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy']
-field_tolerances=[5e-05,1e-08,1e-08,1e-09,5e-08,5e-08,5e-08]
+field_tolerances=[5e-05,1e-08,7e-08,5e-09,5e-09,5e-09,5e-09,5e-08,5e-08,5e-08]
 field_values=[\
 	md.results.StressbalanceSolution.Gradient1,\
Index: /issm/trunk/test/NightlyRun/test323.m
===================================================================
--- /issm/trunk/test/NightlyRun/test323.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test323.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedTranCflSSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test323.py
===================================================================
--- /issm/trunk/test/NightlyRun/test323.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test323.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedTranCflSSA2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test324.m
===================================================================
--- /issm/trunk/test/NightlyRun/test324.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test324.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedTranCflSIA3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test324.py
===================================================================
--- /issm/trunk/test/NightlyRun/test324.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test324.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedTranCflSIA3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test325.m
===================================================================
--- /issm/trunk/test/NightlyRun/test325.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test325.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedEnthalpyStea
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test325.py
===================================================================
--- /issm/trunk/test/NightlyRun/test325.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test325.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedEnthalpyStea
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test326.m
===================================================================
--- /issm/trunk/test/NightlyRun/test326.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test326.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedEnthalpyTran
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test326.py
===================================================================
--- /issm/trunk/test/NightlyRun/test326.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test326.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedEnthalpyTran
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test327.m
===================================================================
--- /issm/trunk/test/NightlyRun/test327.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test327.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedTransHOEnth
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test327.py
===================================================================
--- /issm/trunk/test/NightlyRun/test327.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test327.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedTransHOEnth
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test328.m
===================================================================
--- /issm/trunk/test/NightlyRun/test328.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test328.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedSmbGradients2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test328.py
===================================================================
--- /issm/trunk/test/NightlyRun/test328.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test328.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedSmbGradients2d
 import numpy
 import copy
Index: /issm/trunk/test/NightlyRun/test329.m
===================================================================
--- /issm/trunk/test/NightlyRun/test329.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test329.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedSmbGradients3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test329.py
===================================================================
--- /issm/trunk/test/NightlyRun/test329.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test329.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedSmbGradients3d
 import numpy
 import copy
Index: /issm/trunk/test/NightlyRun/test3300.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3300.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test3300.m	(revision 19105)
@@ -14,5 +14,5 @@
 md.initialization.sediment_head=0.0*ones(md.mesh.numberofvertices,1);
 md.hydrology.spcsediment_head=NaN*ones(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
+md.basalforcings.groundedice_melting_rate = 2.0*ones(md.mesh.numberofvertices,1);
 md.hydrology.sediment_transmitivity=1.5e-4*ones(md.mesh.numberofvertices,1);
 
@@ -24,26 +24,27 @@
 md.hydrology.epl_conductivity=1.5e-2;
 md.hydrology.epl_initial_thickness=1.0;
+md.hydrology.epl_colapse_thickness=1.0e-6;
+md.hydrology.epl_thick_comp=1;
 md.hydrology.epl_max_thickness=5.0;
 
-md.hydrology.transfer_flag=1;
-md.hydrology.leakage_factor=500;
+md.hydrology.transfer_flag=1.0;
+md.hydrology.leakage_factor=3.9e-12;
 
-times=0:0.2:8.0;
-md.basalforcings.melting_rate=ones(md.mesh.numberofvertices+1,length(times));
+times=0:0.002:8.0;
+md.basalforcings.groundedice_melting_rate=ones(md.mesh.numberofvertices+1,length(times));
 
 for i=1:length(times)
-	if(times(i)<1.2)
-		md.basalforcings.melting_rate(:,i)=1.0;
-	elseif(times(i)<6.0)
-		md.basalforcings.melting_rate(:,i)=-0.2;
+	if(times(i)<=1.0)
+		md.basalforcings.groundedice_melting_rate(:,i)=1.0;
+	elseif(times(i)<=6.0)
+		md.basalforcings.groundedice_melting_rate(:,i)=-0.2;
 	else
-		md.basalforcings.melting_rate(:,i)=0.0;
+		md.basalforcings.groundedice_melting_rate(:,i)=0.0;
  end
 end	
 
-md.basalforcings.melting_rate(end,:)=times;
+md.basalforcings.groundedice_melting_rate(end,:)=times;
 
-
-md.timestepping.time_step=0.2;
+md.timestepping.time_step=0.002;
 md.timestepping.final_time=8.0;
 
Index: /issm/trunk/test/NightlyRun/test332.m
===================================================================
--- /issm/trunk/test/NightlyRun/test332.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test332.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedHydrologyDC
 md=triangle(model(),'../Exp/Square.exp',100000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test332.py
===================================================================
--- /issm/trunk/test/NightlyRun/test332.py	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test332.py	(revision 19105)
@@ -0,0 +1,47 @@
+#Test Name: SquareSheetConstrainedHydrologyDC
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from transient import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',100000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+
+md.transient=transient.setallnullparameters(md.transient)
+md.transient.ishydrology=True
+
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md.hydrology=hydrologydc()
+md.hydrology=md.hydrology.initialize(md)
+
+md.hydrology.isefficientlayer=0
+md.hydrology.sedimentlimit_flag=1
+md.hydrology.sedimentlimit=8000.0
+md.initialization.sediment_head=numpy.zeros((md.mesh.numberofvertices,1))
+md.hydrology.spcsediment_head=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+pos=numpy.nonzero(md.mesh.y==0.)[0]
+md.hydrology.spcsediment_head[pos]=0.0
+md.basalforcings.groundedice_melting_rate = 2.0*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.floatingice_melting_rate = 0.0*numpy.ones((md.mesh.numberofvertices,1))
+md.hydrology.sediment_transmitivity= 3.0*numpy.ones((md.mesh.numberofvertices,1))
+md.timestepping.time_step=0
+md.timestepping.final_time=1.0
+md=solve(md,HydrologySolutionEnum())
+
+#Fields and tolerances to track changes
+#you can also compare with an analitic solution, but it is exact
+#only if no limits are applied
+#analitic=(md.mesh.y.^2-2*md.mesh.y*1.0e6)*(-2.0/(2*md.constants.yts*md.hydrology.sediment_transmitivity))
+field_names     =['SedimentWaterHead','SedimentHeadResidual']
+field_tolerances=[1e-13, 3e-10]
+field_values=[md.results.HydrologySolution.SedimentHead,md.results.HydrologySolution.SedimentHeadResidual]
Index: /issm/trunk/test/NightlyRun/test333.m
===================================================================
--- /issm/trunk/test/NightlyRun/test333.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test333.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetHydrologyDCTwoLayers
 md=triangle(model(),'../Exp/Square.exp',100000.);
 md=setmask(md,'','');
@@ -23,4 +24,6 @@
 md.hydrology.epl_conductivity=30;
 md.hydrology.epl_initial_thickness=1;
+md.hydrology.epl_thick_comp=1;
+md.hydrology.epl_colapse_thickness=1.0e-3;
 md.hydrology.epl_max_thickness=1;
 md.timestepping.time_step=0.2;
Index: /issm/trunk/test/NightlyRun/test333.py
===================================================================
--- /issm/trunk/test/NightlyRun/test333.py	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test333.py	(revision 19105)
@@ -0,0 +1,69 @@
+#Test Name: SquareSheetHydrologyDCTwoLayers
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from transient import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+from generic import generic
+
+md=triangle(model(),'../Exp/Square.exp',100000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.transient=transient.setallnullparameters(md.transient)
+md.transient.ishydrology=True
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',1)
+md.hydrology=hydrologydc()
+md.hydrology=md.hydrology.initialize(md)
+
+md.hydrology.isefficientlayer=1
+md.hydrology.sedimentlimit_flag=1
+md.hydrology.sedimentlimit=800.0
+md.initialization.sediment_head=numpy.zeros((md.mesh.numberofvertices,1))
+md.hydrology.spcsediment_head=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+
+md.basalforcings.groundedice_melting_rate = 2.0*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.floatingice_melting_rate = 0.0*numpy.ones((md.mesh.numberofvertices,1))
+md.hydrology.sediment_transmitivity= 3.0*numpy.ones((md.mesh.numberofvertices,1))
+
+md.initialization.epl_head=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.epl_thickness=numpy.ones((md.mesh.numberofvertices,1))
+md.hydrology.spcepl_head=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+md.hydrology.mask_eplactive_node=numpy.zeros((md.mesh.numberofvertices,1))
+md.hydrology.epl_conductivity=30
+md.hydrology.epl_initial_thickness=1
+md.hydrology.epl_colapse_thickness=1.0e-3
+md.hydrology.epl_thick_comp=1
+md.hydrology.epl_max_thickness=1
+md.timestepping.time_step=0.2
+md.timestepping.final_time=2.0
+
+md=solve(md,TransientSolutionEnum())
+
+field_names     =['SedimentWaterHead1','EplWaterHead1','SedimentHeadResidual1', \
+						'SedimentWaterHead4','EplWaterHead4','SedimentHeadResidual4', \
+						'SedimentWaterHead5','EplWaterHead5','SedimentHeadResidual5', \
+						'SedimentWaterHead9','EplWaterHead9','SedimentHeadResidual9']
+field_tolerances=[ \
+	1e-13, 1e-13, 1e-13, \
+	1e-13, 1e-13, 1e-13, \
+	1e-13, 5e-12, 8e-12, \
+	1e-13, 5e-12, 1e-11]
+field_values=[md.results.TransientSolution[0].SedimentHead, \
+							md.results.TransientSolution[0].EplHead, \
+							md.results.TransientSolution[0].SedimentHeadResidual, \
+							md.results.TransientSolution[3].SedimentHead, \
+							md.results.TransientSolution[3].EplHead, \
+							md.results.TransientSolution[3].SedimentHeadResidual, \
+							md.results.TransientSolution[4].SedimentHead, \
+							md.results.TransientSolution[4].EplHead, \
+							md.results.TransientSolution[4].SedimentHeadResidual, \
+							md.results.TransientSolution[8].SedimentHead, \
+							md.results.TransientSolution[8].EplHead, \
+							md.results.TransientSolution[8].SedimentHeadResidual]
Index: /issm/trunk/test/NightlyRun/test334.m
===================================================================
--- /issm/trunk/test/NightlyRun/test334.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test334.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedExtrudedHydrologyDC
 md=triangle(model(),'../Exp/Square.exp',100000.);
 md=setmask(md,'','');
Index: /issm/trunk/test/NightlyRun/test335.m
===================================================================
--- /issm/trunk/test/NightlyRun/test335.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test335.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetExtrudedHydrologyDCTwoLayers
 md=triangle(model(),'../Exp/Square.exp',100000.);
 md=setmask(md,'','');
@@ -23,4 +24,6 @@
 md.hydrology.epl_conductivity=30;
 md.hydrology.epl_initial_thickness=1;
+md.hydrology.epl_colapse_thickness=1.0e-3;
+md.hydrology.epl_thick_comp=1;
 md.hydrology.epl_max_thickness=1;
 md.timestepping.time_step=0.2;
Index: /issm/trunk/test/NightlyRun/test336.m
===================================================================
--- /issm/trunk/test/NightlyRun/test336.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test336.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedSmbComponents2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test336.py
===================================================================
--- /issm/trunk/test/NightlyRun/test336.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test336.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedSmbComponents2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test337.m
===================================================================
--- /issm/trunk/test/NightlyRun/test337.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test337.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedSmbComponents3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test337.py
===================================================================
--- /issm/trunk/test/NightlyRun/test337.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test337.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedSmbComponents3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test338.m
===================================================================
--- /issm/trunk/test/NightlyRun/test338.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test338.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedSmbMeltComponents2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test338.py
===================================================================
--- /issm/trunk/test/NightlyRun/test338.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test338.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedSmbMeltComponents2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test339.m
===================================================================
--- /issm/trunk/test/NightlyRun/test339.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test339.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetConstrainedSmbMeltComponents3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
Index: /issm/trunk/test/NightlyRun/test339.py
===================================================================
--- /issm/trunk/test/NightlyRun/test339.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test339.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetConstrainedSmbMeltComponents3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test340.m
===================================================================
--- /issm/trunk/test/NightlyRun/test340.m	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test340.m	(revision 19105)
@@ -0,0 +1,34 @@
+%Test Name: SquareSheetConstrainedCMtaoDragHO
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+
+%control parameters
+md.inversion=taoinversion(md.inversion);
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1.*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200.*ones(md.mesh.numberofvertices,1);
+md.inversion.maxsteps=2;
+md.inversion.maxiter=6;
+md.inversion.cost_functions=[102  501];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy'};
+field_tolerances={3e-08,1e-07,5e-10,1e-10,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.FrictionCoefficient),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/trunk/test/NightlyRun/test341.m
===================================================================
--- /issm/trunk/test/NightlyRun/test341.m	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test341.m	(revision 19105)
@@ -0,0 +1,33 @@
+%Test Name: SquareSheetConstrainedCMm1qn3DragHO
+md=triangle(model(),'../Exp/Square.exp',200000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareSheetConstrained.par');
+md=extrude(md,3,1.);
+md=setflowequation(md,'HO','all');
+
+%control parameters
+md.inversion=m1qn3inversion(md.inversion);
+md.inversion.iscontrol=1;
+md.inversion.control_parameters={'FrictionCoefficient'};
+md.inversion.min_parameters=1.*ones(md.mesh.numberofvertices,1);
+md.inversion.max_parameters=200.*ones(md.mesh.numberofvertices,1);
+md.inversion.maxsteps=2;
+md.inversion.maxiter=6;
+md.inversion.cost_functions=[102  501];
+md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices,2); md.inversion.cost_functions_coefficients(:,2)=2.*10^-7;
+md.inversion.vx_obs=md.initialization.vx; md.inversion.vy_obs=md.initialization.vy;
+
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Gradient','FrictionCoefficient','Pressure','Vel','Vx','Vy'};
+field_tolerances={1e-08,1e-10,1e-10,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.FrictionCoefficient),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
+};
Index: /issm/trunk/test/NightlyRun/test4001.m
===================================================================
--- /issm/trunk/test/NightlyRun/test4001.m	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test4001.m	(revision 19105)
@@ -0,0 +1,886 @@
+%Test Name: IceOcean
+%ISSM/MITgcm coupled set-up
+%
+%Script control parameters
+steps=1:15;
+final_time=1;
+
+%Organizer
+mkdir Models
+org=organizer('repository','Models/','prefix','IceOcean.','steps',steps);
+
+presentdirectory=pwd; 
+addpath(recursivepath([pwd '/../MITgcm']));
+
+% {{{ Parameters: 
+if perform(org,'Parameters'),
+	Nx=20; %number of longitude cells
+	Ny=40; %number of latitude cells
+	Nz=30; %number of MITgcm vertical cells
+	nPx=2; %number of MITgcm processes to use in x direction
+	nPy=4; %number of MITgcm processes to use in y direction
+	xgOrigin=0; %origin of longitude
+	ygOrigin=-80; %origin of latitude
+	dLong=.25; %longitude grid spacing
+	dLat=.05; %latitude grid spacing
+	delZ=30; %thickness of vertical levels
+	icefront_position_ratio=.75; 
+	ice_thickness=100;
+	rho_ice=917;
+	rho_water=1028.14;
+	di=rho_ice/rho_water;
+
+	% MITgcm initial and lateral boundary conditions
+	iniSalt  = 34.4; % initial salinity (PSU)
+	iniTheta = -1.9; % initial potential temperature (deg C)
+	obcSalt  = 34.4; % open boundary salinity (PSU)
+	obcTheta =  1.0; % open boundary potential temperature (deg C)
+	mlDepth  = 120.; % mixed layer depth (m)
+	mlSalt   = 33.4; % open boundary salinity (PSU)
+	mlTheta  = -1.9; % open boundary potential temperature (deg C)
+	obcUvel  = -0.1; % open boundary velocity (m/s)        
+
+	MITgcmDeltaT=600; % MITgcm time step in seconds
+	y2s=31536000; % year to seconds conversion, i.e., seconds per year
+
+	% start_time, final_time, and time_step
+	start_time=0; % in decimal years
+	time_step=1/12; % coupling interval in decimal years
+	async_step_MITgcm_multiplier=1/30; % used to reduce run time for MItgcm
+
+	% bedrock/bathymetry
+	hmax=1000;
+	trough_depth=200;
+	deltah=300;
+	sea_level=1095;
+
+	% issm settings:
+	numlayers=10;
+
+	savedata(org, Nx, Ny, nPx, nPy, Nz, dLong, dLat, delZ, xgOrigin, ...
+		ygOrigin, icefront_position_ratio, ice_thickness, rho_ice, ...
+		rho_water, di, hmax, trough_depth, deltah, sea_level, ...
+		iniSalt, iniTheta, obcSalt, obcTheta, mlDepth, mlSalt, ...
+		mlTheta, obcUvel, start_time, time_step, MITgcmDeltaT, y2s,...
+		numlayers,async_step_MITgcm_multiplier);
+end
+% }}}
+% {{{ Bathymetry: 
+if perform(org,'Bathymetry'),
+
+    loaddata(org,'Parameters');
+    %create lat,long
+    lat=(ygOrigin+dLat/2):dLat:(ygOrigin+Ny*dLat);
+    long=(xgOrigin+dLong/2):dLong:(xgOrigin+Nx*dLong);
+    [lat long]=meshgrid(lat,long);
+
+    longmin=min(long(:));
+    longmax=max(long(:));
+    latmin=min(lat(:));
+    latmax=max(lat(:));
+
+    %create bedrock/bathymetry:
+    bedrock=zeros(Nx,Ny);
+    bedrock=hmax-deltah*tanh(pi*(2*(lat-latmin)./(latmax-latmin)-1))+ ...
+            trough_depth*cos(2*pi*long./(longmax-longmin));
+
+    %save bathymetry file for MITgcm
+    bathymetry=bedrock-sea_level;
+    savedata(org,lat,long,bathymetry);
+
+end
+% }}}
+% {{{ IceSheetGeometry: 
+if perform(org,'IceSheetGeometry'),
+	
+	loaddata(org,'Parameters');
+	loaddata(org,'Bathymetry');
+	latmin=min(lat(:));
+	latmax=max(lat(:));
+
+	%put ice_thickness constant layer of ice over the bathymetry, unless it floats: 
+	s=size(bathymetry);
+	thickness=ice_thickness*ones(s);
+
+	%figure out ice shelf: 
+	pos=find(-di*thickness>bathymetry);
+	iceshelf_mask=zeros(s);
+	iceshelf_mask(pos)=1;
+
+	ice_mask=ones(s);
+	pos=find((lat-latmin)/(latmax-latmin)>(icefront_position_ratio));
+	ice_mask(pos)=0;
+	iceshelf_mask(pos)=0;
+
+	%compute draft of ice shelf: 
+	draft=bathymetry;
+	pos=find(iceshelf_mask);
+	draft(pos)=-di*thickness(pos);
+	pos=find(~ice_mask); 
+	draft(pos)=0;
+
+	savedata(org,ice_mask,iceshelf_mask,draft,thickness);
+end
+% }}}
+
+%Configure MITgcm
+% {{{ GetMITgcm: 
+if perform(org,'GetMITgcm'),
+  system([pwd '/../MITgcm/get_mitgcm.sh']);
+end
+% }}}
+% {{{ BuildMITgcm: 
+if perform(org,'BuildMITgcm'),
+
+    %load data: 
+    loaddata(org,'Parameters');
+
+    %specify computational grid in SIZE.h
+    fidi=fopen('../MITgcm/code/SIZE.h.bak','r');
+    fido=fopen('../MITgcm/code/SIZE.h','w');
+    tline = fgetl(fidi);
+    fprintf(fido,'%s\n',tline);
+    while 1
+        tline = fgetl(fidi);
+        if ~ischar(tline), break, end
+        %do the change here: 
+        if strcmpi(tline,'     &           sNx =  20,'),
+            fprintf(fido,'%s%i%s\n','     &           sNx =  ',round(Nx/nPx),',');
+            continue;
+        end
+        if strcmpi(tline,'     &           sNy =  20,'),
+            fprintf(fido,'%s%i%s\n','     &           sNy =  ',round(Ny/nPy),',');
+            continue;
+        end
+        if strcmpi(tline,'     &           nPx =   1,'),
+            fprintf(fido,'%s%i%s\n','     &           nPx = ',nPx,',');
+            continue;
+        end
+        if strcmpi(tline,'     &           nPy =   2,'),
+            fprintf(fido,'%s%i%s\n','     &           nPy = ',nPy,',');
+            continue;
+        end
+        fprintf(fido,'%s\n',tline);
+    end
+    %close  files
+    fclose(fidi);
+    fclose(fido);
+
+	 system(['../MITgcm/build.sh generic ' pwd]);
+end
+% }}}
+% {{{ RunUncoupledMITgcm: 
+if perform(org,'RunUncoupledMITgcm'),
+
+    %load data: 
+    loaddata(org,'Parameters');
+    loaddata(org,'Bathymetry');
+    loaddata(org,'IceSheetGeometry');
+	 endtime = round(MITgcmDeltaT * ...
+		 floor(time_step*y2s*async_step_MITgcm_multiplier/MITgcmDeltaT));
+
+    % {{{ prepare MITgcm 
+    % rename previous run directory and create new one
+    if exist ('run.old')
+        !\rm -rf run.old
+    end
+    if exist ('run')
+        !\mv run run.old
+    end
+    !\mkdir run
+    !\cp ../MITgcm/build/mitgcmuv run
+    !\cp ../MITgcm/input/* run
+    
+    %load data: 
+    loaddata(org,'Parameters');
+
+    % initial salinity
+    S=iniSalt*ones(Nx,Ny,Nz);
+    writebin('run/Salt.bin',S);
+    
+    % initial temperature
+    T=iniTheta*ones(Nx,Ny,Nz);
+    writebin('run/Theta.bin',T);
+    
+    % initial velocity
+    Z=zeros(Nx,Ny,Nz);
+    writebin('run/Uvel.bin',Z);
+    writebin('run/Vvel.bin',Z);
+    
+    % initial sea surface height
+    Z=zeros(Nx,Ny);
+    writebin('run/Etan.bin',Z);
+
+    % salinity boundary conditions
+    S=obcSalt*ones(Ny,Nz);
+    thk=delZ*ones(Nz,1);
+    bot=cumsum(thk);
+    ik=find(bot<=mlDepth);
+    S(:,ik)=mlSalt;
+    writebin('run/OBs.bin',S);
+
+    % temperature boundary conditions
+    T=obcTheta*ones(Ny,Nz);
+    T(:,ik)=mlTheta;
+    writebin('run/OBt.bin',T);
+
+    % zonal velocity boundary conditions
+    U=obcUvel*ones(Ny,Nz);
+    writebin('run/OBu.bin',U);
+    
+    % zero boundary conditions
+    Z=zeros(Ny,Nz);
+    writebin('run/zeros.bin',Z);
+
+    % build parameter file data.obcs
+    fidi=fopen('../MITgcm/input/data.obcs','r');
+    fido=fopen('run/data.obcs','w');
+    tline = fgetl(fidi);
+    fprintf(fido,'%s\n',tline);
+    while 1
+        tline = fgetl(fidi);
+        if ~ischar(tline), break, end
+        %do the change here: 
+        if strcmpi(tline,' OB_Iwest = 40*1,'),
+            fprintf(fido,'%s%i%s\n',' OB_Iwest = ',Ny,'*1,');
+            continue;
+        end
+        if strcmpi(tline,' OB_Ieast = 40*-1,'),
+            fprintf(fido,'%s%i%s\n',' OB_Ieast = ',Ny,'*-1,');
+            continue;
+        end
+        fprintf(fido,'%s\n',tline);
+    end
+    %close  files
+    fclose(fidi);
+    fclose(fido);
+
+    %save bathymetry and bedrock in run directory
+    writebin('run/bathymetry.bin',bathymetry);
+    writebin('run/icetopo.bin',draft);
+    % }}}
+
+    %start looping:  
+    for t=start_time:time_step:final_time,
+        disp(['Year: ' num2str(t)])
+        % {{{ generate MITgcm parameter file data 
+        fidi=fopen('../MITgcm/input/data','r');
+        fido=fopen('run/data','w');
+        tline = fgetl(fidi);
+        fprintf(fido,'%s\n',tline);
+        while 1
+            tline = fgetl(fidi);
+            if ~ischar(tline), break, end
+            %do the change here: 
+            if strcmpi(tline,' xgOrigin = 0.0,'),
+                fprintf(fido,'%s%i%s\n',' xgOrigin = ',xgOrigin,',');
+                continue;
+            end
+            if strcmpi(tline,' ygOrigin = -80.0,'),
+                fprintf(fido,'%s%i%s\n',' ygOrigin = ',ygOrigin,',');
+                continue;
+            end
+            if strcmpi(tline,' delX = 20*0.25,'),
+                fprintf(fido,'%s%i*%g%s\n',' delX = ',Nx,dLong,',');
+                continue;
+            end
+            if strcmpi(tline,' delY = 20*0.25,'),
+                fprintf(fido,'%s%i*%g%s\n',' delY = ',Ny,dLat,',');
+                continue;
+            end
+            if strcmpi(tline,' delZ = 30*30.0,'),
+                fprintf(fido,'%s%i*%g%s\n',' delZ = ',Nz,delZ,',');
+                continue;
+            end
+            if strcmpi(tline,' endTime=2592000.,'),
+                fprintf(fido,'%s%i%s\n',' endTime= ',endtime,',');
+                continue;
+            end
+            if strcmpi(tline,' deltaT=1200.0,'),
+                fprintf(fido,'%s%i%s\n',' deltaT= ',MITgcmDeltaT,',');
+                continue;
+            end
+            if strcmpi(tline,' pChkptFreq=2592000.,'),
+                fprintf(fido,'%s%i%s\n',' pChkptFreq= ',endtime,',');
+                continue;
+            end
+            if strcmpi(tline,' taveFreq=2592000.,'),
+                fprintf(fido,'%s%i%s\n',' taveFreq= ',endtime,',');
+                continue;
+            end
+            if strcmpi(tline,' rhoConst=1030.,'),
+                fprintf(fido,'%s%i%s\n',' rhoConst= ',rho_water,',');
+                continue;
+            end
+            if strcmpi(tline,' rhoNil=1030.,'),
+                fprintf(fido,'%s%i%s\n',' rhoNil= ',rho_water,',');
+                continue;
+            end
+            fprintf(fido,'%s\n',tline);
+        end
+        %close  files
+        fclose(fidi);
+        fclose(fido);
+        % }}}
+        % {{{ generate initial MITgcm conditions
+
+        ds=round(endtime/MITgcmDeltaT);
+        if t>start_time
+            % Read pickup file
+            fnm=['run/pickup.' myint2str(ds,10) '.data'];
+            U=readbin(fnm,[Nx Ny Nz],1,'real*8',0);
+            V=readbin(fnm,[Nx Ny Nz],1,'real*8',1);
+            T=readbin(fnm,[Nx Ny Nz],1,'real*8',2);
+            S=readbin(fnm,[Nx Ny Nz],1,'real*8',3);
+            E=readbin(fnm,[Nx Ny],1,'real*8',8*Nz);
+            writebin('run/Salt.bin' ,S);
+            writebin('run/Theta.bin',T);
+            writebin('run/Uvel.bin' ,U);
+            writebin('run/Vvel.bin' ,V);
+            writebin('run/Etan.bin' ,E);
+        end
+
+        % }}}
+        % {{{ system call to run MITgcm
+        cd run
+        eval(['!mpirun -np ' int2str(nPx*nPy) ' ./mitgcmuv']);
+        ts=round((t+time_step)*y2s/MITgcmDeltaT);
+        eval(['!\mv STDERR.0000 STDERR_' myint2str(ts,10) '.data'])
+        eval(['!\mv STDOUT.0000 STDOUT_' myint2str(ts,10) '.data'])
+        eval(['!\cp hFacC.data hFacC_' myint2str(ts,10) '.data'])
+        eval(['!\cp icetopo.bin icetopo_' myint2str(ts,10) '.data'])
+        for fld={'S','T','U','V','Eta', ...
+                 'SHICE_heatFluxtave','SHICE_fwFluxtave'}
+            eval(['!\mv ' fld{1} '.' myint2str(ds,10) '.data ' ...
+                  fld{1} '_' myint2str(ts,10) '.data'])
+        end
+        cd ..
+        % }}}
+    end
+end
+% }}}
+
+%Configure ISSM
+% {{{ CreateMesh: 
+if perform(org,'CreateMesh'),
+	
+	loaddata(org,'Parameters');
+	loaddata(org,'Bathymetry');
+	loaddata(org,'IceSheetGeometry');
+
+	%create model: 
+	md=model();
+	
+	%Grab lat,long from MITgcm: 
+	lat=lat(:);
+	long=long(:);
+
+	%project lat,long: 
+	[x,y]=ll2xy(lat,long,-1);
+
+	index=[];
+	%  C  D
+	%  A  B 
+	for j=1:Ny-1,
+		for i=1:Nx-1, 
+			A=(j-1)*Nx+i;
+			B=(j-1)*Nx+i+1;
+			C=j*Nx+i;
+			D=j*Nx+i+1;
+			index(end+1,:)=[A B C];
+			index(end+1,:)=[C B D];
+		end
+	end
+
+	%fill mesh and model: 
+	md=meshconvert(md,index,x,y);
+	md.mesh.lat=lat;
+	md.mesh.long=long;
+
+	savemodel(org,md);
+
+end
+% }}}
+% {{{ MeshGeometry: 
+if perform(org,'MeshGeometry'),
+	
+	loaddata(org,'Parameters');
+	loaddata(org,'CreateMesh');
+	loaddata(org,'Bathymetry');
+	loaddata(org,'IceSheetGeometry');
+
+	%transfer to vertices: 
+	bathymetry=bathymetry(:);
+	iceshelf_mask=iceshelf_mask(:);
+	ice_mask=ice_mask(:);
+	thickness=thickness(:);
+	draft=draft(:);
+
+	%start filling some of the fields 
+	md.geometry.bed=bathymetry;
+	md.geometry.thickness=thickness;
+	md.geometry.base=md.geometry.bed; 
+	pos=find(iceshelf_mask); md.geometry.base(pos)=draft(pos);
+	md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+	%nothing passes icefront: 
+	pos=find(~ice_mask);
+	md.geometry.thickness(pos)=1;
+	md.geometry.surface(pos)=(1-di)*md.geometry.thickness(pos);
+	md.geometry.base(pos)=-di*md.geometry.thickness(pos);
+
+	%level sets: 
+	md.mask.groundedice_levelset=-ones(md.mesh.numberofvertices,1);
+	md.mask.ice_levelset=ones(md.mesh.numberofvertices,1);
+
+	pos=find(ice_mask); md.mask.ice_levelset(pos)=-1; 
+	pos=find(~iceshelf_mask & ice_mask); md.mask.groundedice_levelset(pos)=1;
+
+	%identify edges of grounded ice: 
+	groundedice_levelset=md.mask.groundedice_levelset;
+	for i=1:md.mesh.numberofelements,
+		m=groundedice_levelset(md.mesh.elements(i,:));
+		if abs(sum(m))~=3,
+			pos=find(m==1); md.mask.groundedice_levelset(md.mesh.elements(i,pos))=0;
+		end
+	end
+
+	%identify edges of ice: 
+	ice_levelset=md.mask.ice_levelset;
+	for i=1:md.mesh.numberofelements,
+		m=ice_levelset(md.mesh.elements(i,:));
+		if abs(sum(m))~=3,
+			pos=find(m==-1); md.mask.ice_levelset(md.mesh.elements(i,pos))=0;
+		end
+	end
+
+	savemodel(org,md);
+end
+% }}}
+% {{{ ParameterizeIce: 
+if perform(org,'ParameterizeIce'),
+	
+	loaddata(org,'Parameters');
+	loaddata(org,'CreateMesh');
+	loaddata(org,'MeshGeometry');
+
+	%miscellaneous
+	md.miscellaneous.name='IceOcean';
+
+	%initial velocity: 
+	md.initialization.vx=zeros(md.mesh.numberofvertices,1);
+	md.initialization.vy=zeros(md.mesh.numberofvertices,1);
+	md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+
+	%friction: 
+	md.friction.coefficient=30*ones(md.mesh.numberofvertices,1);
+	pos=find(md.mask.groundedice_levelset<=0);
+	md.friction.coefficient(pos)=0;
+	md.friction.p=ones(md.mesh.numberofelements,1);
+	md.friction.q=ones(md.mesh.numberofelements,1);
+
+	%temperatures and surface mass balance:
+	md.initialization.temperature=(273.15-20)*ones(md.mesh.numberofvertices,1);
+	md.initialization.pressure=md.materials.rho_ice*md.constants.g*(md.geometry.surface-md.geometry.base);
+	md.surfaceforcings.mass_balance = [1*ones(md.mesh.numberofvertices,1); 1];
+
+	%Flow law 
+	md.materials.rheology_B=paterson(md.initialization.temperature);
+	md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+	md.damage.D=zeros(md.mesh.numberofvertices,1);
+	md.damage.spcdamage=NaN*ones(md.mesh.numberofvertices,1);
+	
+	%the spcs going
+	md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+	md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+	md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1); 
+
+	%deal with water: 
+	pos=find(md.mask.ice_levelset>0); 
+	md.stressbalance.spcvx(pos)=0;
+	md.stressbalance.spcvy(pos)=0;
+	md.stressbalance.spcvz(pos)=0;
+	md.masstransport.spcthickness(pos)=0;
+
+	%get some flux at the ice divide: 
+	pos=find(md.mesh.lat==min(md.mesh.lat));
+	md.stressbalance.spcvy(pos)=200;
+
+	%deal with boundaries, excluding icefront: 
+	vertex_on_boundary=zeros(md.mesh.numberofvertices,1);
+	vertex_on_boundary(md.mesh.segments(:,1:2))=1;
+	pos=find(vertex_on_boundary & md.mask.groundedice_levelset<=0);
+	md.stressbalance.spcvx(pos)=md.initialization.vx(pos);
+	md.stressbalance.spcvy(pos)=md.initialization.vy(pos);
+	md.stressbalance.spcvz(pos)=md.initialization.vz(pos);
+	md.masstransport.spcthickness(pos)=md.geometry.thickness(pos);
+
+	md.basalforcings.groundedice_melting_rate=zeros(md.mesh.numberofvertices,1);
+	md.basalforcings.floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
+	md.thermal.spctemperature=[md.initialization.temperature; 1]; %impose observed temperature on surface
+	md.basalforcings.geothermalflux=.064*ones(md.mesh.numberofvertices,1);
+
+	%flow equations: 
+	md=setflowequation(md,'SSA','all');
+
+	savemodel(org,md);
+end
+% }}}
+% {{{ RunUncoupledISSM: 
+if perform(org,'RunUncoupledISSM'),
+	
+	loaddata(org,'Parameters');
+	loaddata(org,'ParameterizeIce');
+
+	%timestepping: 
+	md.timestepping.final_time=final_time;
+	md.timestepping.time_step=time_step;
+	md.timestepping.time_adapt=0;
+	md.transient.isgroundingline=1;
+	md.transient.isthermal=0;
+	md.groundingline.migration='SubelementMigration2';
+
+	md.cluster=generic('name',oshostname(),'np',2);
+	md=solve(md,TransientSolutionEnum);
+
+	savemodel(org,md);
+end
+% }}}
+
+%Run MITgcm/ISSM
+% {{{ RunCoupledMITgcmISSM: 
+if perform(org,'RunCoupledMITgcmISSM'),
+
+	%load data: 
+	loaddata(org,'Parameters');
+	loaddata(org,'ParameterizeIce');
+	loaddata(org,'Bathymetry');
+	loaddata(org,'IceSheetGeometry');
+        endtime = round(MITgcmDeltaT * ...
+         floor(time_step*y2s*async_step_MITgcm_multiplier/MITgcmDeltaT));
+
+        % {{{ prepare MITgcm 
+        % rename previous run directory and create new one
+        if exist ('run.old')
+            !\rm -rf run.old
+        end
+        if exist ('run')
+            !\mv run run.old
+        end
+        !\mkdir run
+		  disp('-------------- file: test4001.m line: 578'); 
+        !\cp ../MITgcm/build/mitgcmuv run
+		  disp('-------------- file: test4001.m line: 580'); 
+        !\cp ../MITgcm/input/* run
+		  disp('-------------- file: test4001.m line: 582'); 
+
+        %load data: 
+        loaddata(org,'Parameters');
+
+        % initial salinity
+        S=iniSalt*ones(Nx,Ny,Nz);
+        writebin('run/Salt.bin',S);
+
+        % initial temperature
+        T=iniTheta*ones(Nx,Ny,Nz);
+        writebin('run/Theta.bin',T);
+
+        % initial velocity
+        Z=zeros(Nx,Ny,Nz);
+        writebin('run/Uvel.bin',Z);
+        writebin('run/Vvel.bin',Z);
+
+        % initial sea surface height
+        Z=zeros(Nx,Ny);
+        writebin('run/Etan.bin',Z);
+
+        % salinity boundary conditions
+        S=obcSalt*ones(Ny,Nz);
+        thk=delZ*ones(Nz,1);
+        bot=cumsum(thk);
+        ik=find(bot<=mlDepth);
+        S(:,ik)=mlSalt;
+        writebin('run/OBs.bin',S);
+
+        % temperature boundary conditions
+        T=obcTheta*ones(Ny,Nz);
+        T(:,ik)=mlTheta;
+        writebin('run/OBt.bin',T);
+
+        % zonal velocity boundary conditions
+        U=obcUvel*ones(Ny,Nz);
+        writebin('run/OBu.bin',U);
+
+        % zero boundary conditions
+        Z=zeros(Ny,Nz);
+        writebin('run/zeros.bin',Z);
+
+        % build parameter file data.obcs
+        fidi=fopen('../MITgcm/input/data.obcs','r');
+        fido=fopen('run/data.obcs','w');
+        tline = fgetl(fidi);
+        fprintf(fido,'%s\n',tline);
+        while 1
+            tline = fgetl(fidi);
+            if ~ischar(tline), break, end
+            %do the change here: 
+            if strcmpi(tline,' OB_Iwest = 40*1,'),
+                fprintf(fido,'%s%i%s\n',' OB_Iwest = ',Ny,'*1,');
+                continue;
+            end
+            if strcmpi(tline,' OB_Ieast = 40*-1,'),
+                fprintf(fido,'%s%i%s\n',' OB_Ieast = ',Ny,'*-1,');
+                continue;
+            end
+            fprintf(fido,'%s\n',tline);
+        end
+        %close  files
+        fclose(fidi);
+        fclose(fido);
+
+        %save bathymetry in MITgcm run directory
+        writebin('run/bathymetry.bin',bathymetry);
+        % }}}
+            
+	% {{{ ISSM settings:
+
+	setenv('DYLD_LIBRARY_PATH', '/usr/local/gfortran/lib') 
+	%timestepping: 
+	md.timestepping.start_time=start_time;
+	md.timestepping.final_time=final_time;
+	md.timestepping.time_step=time_step;
+	md.timestepping.time_adapt=0;
+	md.cluster=generic('name',oshostname(),'np',2);
+	md.results.TransientSolution.Base=md.geometry.base;
+	md.transient.isgroundingline=1;
+	md.transient.isthermal=0;
+	md.groundingline.migration='SubelementMigration2';
+
+	% }}}
+
+	%start looping:
+	results=md.results;
+
+	for t=start_time:time_step:final_time
+            disp(['Year: ' num2str(t)])
+
+	    %send draft from ISSM to MITgcm:
+	    draft=md.results.TransientSolution(end).Base;
+	    pos=find(md.mask.ice_levelset>0); draft(pos)=0;
+            if t>start_time
+                old_draft=readbin('run/icetopo.bin',[Nx,Ny]);
+            end
+            writebin('run/icetopo.bin',draft);
+
+	    % {{{ generate MITgcm parameter file data 
+	    fidi=fopen('../MITgcm/input/data','r');
+	    fido=fopen('run/data','w');
+	    tline = fgetl(fidi);
+	    fprintf(fido,'%s\n',tline);
+            while 1
+                tline = fgetl(fidi);
+                if ~ischar(tline), break, end
+		%do the change here: 
+		if strcmpi(tline,' xgOrigin = 0.0,'),
+		    fprintf(fido,'%s%i%s\n',' xgOrigin = ',xgOrigin,',');
+		    continue;
+		end
+		if strcmpi(tline,' ygOrigin = -80.0,'),
+		    fprintf(fido,'%s%i%s\n',' ygOrigin = ',ygOrigin,',');
+		    continue;
+		end
+		if strcmpi(tline,' delX = 20*0.25,'),
+		    fprintf(fido,'%s%i*%g%s\n',' delX = ',Nx,dLong,',');
+		    continue;
+		end
+		if strcmpi(tline,' delY = 20*0.25,'),
+		    fprintf(fido,'%s%i*%g%s\n',' delY = ',Ny,dLat,',');
+		    continue;
+		end
+                if strcmpi(tline,' delZ = 30*30.0,'),
+                    fprintf(fido,'%s%i*%g%s\n',' delZ = ',Nz,delZ,',');
+                    continue;
+                end
+		if strcmpi(tline,' endTime=2592000.,'),
+		    fprintf(fido,'%s%i%s\n',' endTime= ',endtime,',');
+		    continue;
+		end
+		if strcmpi(tline,' deltaT=1200.0,'),
+		    fprintf(fido,'%s%i%s\n',' deltaT= ',MITgcmDeltaT,',');
+		    continue;
+		end
+		if strcmpi(tline,' pChkptFreq=2592000.,'),
+		    fprintf(fido,'%s%i%s\n',' pChkptFreq= ',endtime,',');
+		    continue;
+		end
+		if strcmpi(tline,' taveFreq=2592000.,'),
+		    fprintf(fido,'%s%i%s\n',' taveFreq= ',endtime,',');
+		    continue;
+		end
+                if strcmpi(tline,' rhoConst=1030.,'),
+                    fprintf(fido,'%s%i%s\n',' rhoConst= ',rho_water,',');
+                    continue;
+                end
+                if strcmpi(tline,' rhoNil=1030.,'),
+                    fprintf(fido,'%s%i%s\n',' rhoNil= ',rho_water,',');
+                    continue;
+                end
+		fprintf(fido,'%s\n',tline);
+	    end
+	    %close  files
+	    fclose(fidi);
+	    fclose(fido);
+	    % }}}
+
+	    % {{{ generate initial MITgcm conditions
+            ds=round(endtime/MITgcmDeltaT);
+            if t>start_time
+                % Read pickup file
+                fnm=['run/pickup.' myint2str(ds,10) '.data'];
+                U=readbin(fnm,[Nx Ny Nz],1,'real*8',0);
+                V=readbin(fnm,[Nx Ny Nz],1,'real*8',1);
+                T=readbin(fnm,[Nx Ny Nz],1,'real*8',2);
+                S=readbin(fnm,[Nx Ny Nz],1,'real*8',3);
+                E=readbin(fnm,[Nx Ny],1,'real*8',8*Nz);
+
+                % find indices of locations where ice shelf retreated
+                h=readbin('run/hFacC.data',[Nx Ny Nz]);
+                msk=sum(h,3);
+                msk(find(msk))=1;
+                [iw jw]=find(msk); % horizontal indices where there is water
+                tmp=reshape(draft,[Nx,Ny])-old_draft;
+                tmp(find(tmp<0))=0;
+                [im jm]=find(tmp); % horizontal indices where there is melt
+                
+                % Extrapolate T/S to locations where ice shelf retreated
+                for i=1:length(im)
+
+                    % first try vertical extrapolation
+                    in=find(h(im(i),jm(i),:));
+                    if length(in)>0;
+                        S(im(i),jm(i),1:min(in)  ) = S(im(i),jm(i),min(in));
+                        T(im(i),jm(i),1:min(in)  ) = T(im(i),jm(i),min(in));
+                        continue
+                    end
+
+                    % if not succesful, use closest neighbor horizontal extrapolation
+                    [y c]=min((iw-im(i)).^2+(jw-jm(i)).^2);
+                    salt=squeeze(S(iw(c),jw(c),:)); % salinity profile of closest neighbor
+                    temp=squeeze(T(iw(c),jw(c),:)); % salinity profile of closest neighbor
+                    in=find(h(iw(c),jw(c),:));
+                    salt(1:min(in))=salt(min(in));
+                    temp(1:min(in))=temp(min(in));
+                    salt(max(in):end)=salt(max(in));
+                    temp(max(in):end)=temp(max(in));
+                    S(im(i),jm(i),:)=salt;
+                    T(im(i),jm(i),:)=temp;
+                end
+
+                % Write initial conditions
+                writebin('run/Salt.bin' ,S);
+                writebin('run/Theta.bin',T);
+                writebin('run/Uvel.bin' ,U);
+                writebin('run/Vvel.bin' ,V);
+                writebin('run/Etan.bin' ,E);
+            end
+            % }}}
+
+            % {{{ system call to run MITgcm 
+            cd run
+            eval(['!mpirun -np ' int2str(nPx*nPy) ' ./mitgcmuv']);
+            ts=round((t+time_step)*y2s/MITgcmDeltaT);
+            eval(['!\mv STDERR.0000 STDERR_' myint2str(ts,10) '.data'])
+            eval(['!\mv STDOUT.0000 STDOUT_' myint2str(ts,10) '.data'])
+            eval(['!\cp hFacC.data hFacC_' myint2str(ts,10) '.data'])
+            eval(['!\cp icetopo.bin icetopo_' myint2str(ts,10) '.data'])
+            for fld={'S','T','U','V','Eta', ...
+                     'SHICE_heatFluxtave','SHICE_fwFluxtave'}
+                eval(['!\mv ' fld{1} '.' myint2str(ds,10) '.data ' ...
+                      fld{1} '_' myint2str(ts,10) '.data'])
+            end
+            cd ..
+            % }}}
+
+	    %get melting rates from MITgcm
+	    %upward fresh water flux (kg/m^2/s):
+	    fnm=['run/SHICE_fwFluxtave_' myint2str(ts,10) '.data'];
+	    melting_rate=readbin(fnm,[Nx Ny]);
+
+	    %send averaged melting rate to ISSM
+	    %downward fresh water flux (m/y):
+	    melting_rate=-melting_rate(:)*y2s/rho_ice;
+		 md.basalforcings.floatingice_melting_rate=melting_rate;
+
+	    % {{{ run ISSM and recover results 
+
+	    md.timestepping.start_time=t;
+	    md.timestepping.final_time=t+time_step;;
+		md=solve(md,TransientSolutionEnum);
+
+		base=md.results.TransientSolution(end).Base;
+		thickness=md.results.TransientSolution(end).Thickness;
+		md.geometry.base=base;
+		md.geometry.thickness=thickness;
+		md.geometry.surface=md.geometry.base+md.geometry.thickness;
+		md.initialization.vx=md.results.TransientSolution(end).Vx;
+		md.initialization.vy=md.results.TransientSolution(end).Vy;
+		md.initialization.vel=md.results.TransientSolution(end).Vel;
+		md.initialization.pressure=md.results.TransientSolution(end).Pressure;
+		md.mask.groundedice_levelset=md.results.TransientSolution(end).MaskGroundediceLevelset;
+		md.results.TransientSolution(end).FloatingiceMeltingRate=md.basalforcings.floatingice_melting_rate;
+		
+		%save these results in the model, otherwise, they'll be wiped out
+		results(end+1)=md.results;
+
+		% }}}
+
+	end
+
+	md.results=results;
+	savemodel(org,md);
+end
+% }}}
+
+%Fields and tolerances to track changes
+fnm=['run/SHICE_fwFluxtave_0000004380.data'];
+melting_rate_1=readbin(fnm,[Nx Ny]);
+fnm=['run/SHICE_fwFluxtave_0000008760.data'];
+melting_rate_2=readbin(fnm,[Nx Ny]);
+fnm=['run/SHICE_fwFluxtave_0000013140.data'];
+melting_rate_3=readbin(fnm,[Nx Ny]);
+fnm=['run/SHICE_fwFluxtave_0000017520.data'];
+melting_rate_4=readbin(fnm,[Nx Ny]);
+field_names     ={'Base1','Melting1','Vx2','Vy2','Thickness2','Base2','MaskGroundediceLevelset2','FloatingiceMeltingRate2',...
+	'Melting2','Vx3','Vy3','Thickness3','Base3','MaskGroundediceLevelset3','FloatingiceMeltingRate3',...
+	'Melting3','Vx4','Vy4','Thickness4','Base4','MaskGroundediceLevelset4','FloatingiceMeltingRate4','Melting4'};
+field_tolerances={2e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+	1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13,...
+	1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13, 1e-13 };
+field_values={...
+	(md.results(1).TransientSolution(end).Base),...
+	(melting_rate_1(:)),...
+	(md.results(2).TransientSolution(end).Vx),...
+	(md.results(2).TransientSolution(end).Vy),...
+	(md.results(2).TransientSolution(end).Thickness),...
+	(md.results(2).TransientSolution(end).Base),...
+	(md.results(2).TransientSolution(end).MaskGroundediceLevelset),...
+	(md.results(2).TransientSolution(end).FloatingiceMeltingRate),...
+	(melting_rate_2(:)),...
+	(md.results(3).TransientSolution(end).Vx),...
+	(md.results(3).TransientSolution(end).Vy),...
+	(md.results(3).TransientSolution(end).Thickness),...
+	(md.results(3).TransientSolution(end).Base),...
+	(md.results(3).TransientSolution(end).MaskGroundediceLevelset),...
+	(md.results(3).TransientSolution(end).FloatingiceMeltingRate),...
+	(melting_rate_3(:)),...
+	(md.results(4).TransientSolution(end).Vx),...
+	(md.results(4).TransientSolution(end).Vy),...
+	(md.results(4).TransientSolution(end).Thickness),...
+	(md.results(4).TransientSolution(end).Base),...
+	(md.results(4).TransientSolution(end).MaskGroundediceLevelset),...
+	(md.results(4).TransientSolution(end).FloatingiceMeltingRate),...
+	(melting_rate_4(:)),...
+	};
Index: /issm/trunk/test/NightlyRun/test401.m
===================================================================
--- /issm/trunk/test/NightlyRun/test401.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test401.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressSSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test401.py
===================================================================
--- /issm/trunk/test/NightlyRun/test401.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test401.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressSSA2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test402.m
===================================================================
--- /issm/trunk/test/NightlyRun/test402.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test402.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressSSA3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test402.py
===================================================================
--- /issm/trunk/test/NightlyRun/test402.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test402.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressSSA3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test403.m
===================================================================
--- /issm/trunk/test/NightlyRun/test403.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test403.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressHO
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test403.py
===================================================================
--- /issm/trunk/test/NightlyRun/test403.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test403.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressHO
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test404.m
===================================================================
--- /issm/trunk/test/NightlyRun/test404.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test404.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressFS
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test404.py
===================================================================
--- /issm/trunk/test/NightlyRun/test404.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test404.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressFS
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test405.m
===================================================================
--- /issm/trunk/test/NightlyRun/test405.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test405.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressMHOPenalties
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test405.py
===================================================================
--- /issm/trunk/test/NightlyRun/test405.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test405.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressMHOPenalties
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test406.m
===================================================================
--- /issm/trunk/test/NightlyRun/test406.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test406.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfTherStea
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test406.py
===================================================================
--- /issm/trunk/test/NightlyRun/test406.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test406.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfTherStea
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test407.m
===================================================================
--- /issm/trunk/test/NightlyRun/test407.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test407.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfTherTran
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test407.py
===================================================================
--- /issm/trunk/test/NightlyRun/test407.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test407.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfTherTran
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test408.m
===================================================================
--- /issm/trunk/test/NightlyRun/test408.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test408.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfTranSSA2d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test408.py
===================================================================
--- /issm/trunk/test/NightlyRun/test408.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test408.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfTranSSA2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test409.m
===================================================================
--- /issm/trunk/test/NightlyRun/test409.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test409.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfTranMHOPenalties
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test409.py
===================================================================
--- /issm/trunk/test/NightlyRun/test409.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test409.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfTranMHOPenalties
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test410.m
===================================================================
--- /issm/trunk/test/NightlyRun/test410.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test410.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfSteaSSA3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test410.py
===================================================================
--- /issm/trunk/test/NightlyRun/test410.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test410.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfSteaSSA3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test411.m
===================================================================
--- /issm/trunk/test/NightlyRun/test411.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test411.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfSteaHO
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test411.py
===================================================================
--- /issm/trunk/test/NightlyRun/test411.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test411.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfSteaHO
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test412.m
===================================================================
--- /issm/trunk/test/NightlyRun/test412.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test412.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfDiadSSA3dDakota
 md=triangle(model(),'../Exp/Square.exp',300000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test413.m
===================================================================
--- /issm/trunk/test/NightlyRun/test413.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test413.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfDiadSSA3dDakotaPart
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test414.m
===================================================================
--- /issm/trunk/test/NightlyRun/test414.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test414.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfDiadSSA3dDakotaMassFlux
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test415.m
===================================================================
--- /issm/trunk/test/NightlyRun/test415.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test415.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfCMDragSteaSSA3d
 md=triangle(model(),'../Exp/Square.exp',170000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test415.py
===================================================================
--- /issm/trunk/test/NightlyRun/test415.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test415.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfCMDragSteaSSA3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test416.m
===================================================================
--- /issm/trunk/test/NightlyRun/test416.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test416.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfCMDragSteaHO
 md=triangle(model(),'../Exp/Square.exp',170000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test416.py
===================================================================
--- /issm/trunk/test/NightlyRun/test416.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test416.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfCMDragSteaHO
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test417.m
===================================================================
--- /issm/trunk/test/NightlyRun/test417.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test417.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfDiadSSA3dDakotaSamp
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test418.m
===================================================================
--- /issm/trunk/test/NightlyRun/test418.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test418.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfDiadSSA3dDakotaAreaAverage
 %test partitioning, and partition averaging
 md=triangle(model(),'../Exp/Square.exp',30000.);
Index: /issm/trunk/test/NightlyRun/test419.m
===================================================================
--- /issm/trunk/test/NightlyRun/test419.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test419.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressSSAHOTiling
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test419.py
===================================================================
--- /issm/trunk/test/NightlyRun/test419.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test419.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressSSAHOTiling
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test420.m
===================================================================
--- /issm/trunk/test/NightlyRun/test420.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test420.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfDakotaScaledResponse
 md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test421.m
===================================================================
--- /issm/trunk/test/NightlyRun/test421.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test421.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressHOFS3dTiling
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test421.py
===================================================================
--- /issm/trunk/test/NightlyRun/test421.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test421.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressHOFS3dTiling
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test422.m
===================================================================
--- /issm/trunk/test/NightlyRun/test422.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test422.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressSSAFS3dTiling
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test422.py
===================================================================
--- /issm/trunk/test/NightlyRun/test422.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test422.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressSSAFS3dTiling
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test423.m
===================================================================
--- /issm/trunk/test/NightlyRun/test423.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test423.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: RoundSheetShelfGLMigrationSSA2d
 radius=1.e6;
 shelfextent=2.e5;
Index: /issm/trunk/test/NightlyRun/test423.py
===================================================================
--- /issm/trunk/test/NightlyRun/test423.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test423.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: RoundSheetShelfGLMigrationSSA2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test424.m
===================================================================
--- /issm/trunk/test/NightlyRun/test424.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test424.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfGroundingLine2dAggressive
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test424.py
===================================================================
--- /issm/trunk/test/NightlyRun/test424.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test424.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfGroundingLine2dAggressive
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test425.m
===================================================================
--- /issm/trunk/test/NightlyRun/test425.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test425.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfGroundingLine2dSoft
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test425.py
===================================================================
--- /issm/trunk/test/NightlyRun/test425.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test425.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfGroundingLine2dSoft
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test426.m
===================================================================
--- /issm/trunk/test/NightlyRun/test426.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test426.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfGroundingLine3dAggressive
 md=triangle(model(),'../Exp/Square.exp',350000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test426.py
===================================================================
--- /issm/trunk/test/NightlyRun/test426.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test426.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfGroundingLine3dAggressive
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test427.m
===================================================================
--- /issm/trunk/test/NightlyRun/test427.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test427.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfGroundingLine3dSoft
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test427.py
===================================================================
--- /issm/trunk/test/NightlyRun/test427.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test427.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfGroundingLine3dSoft
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test428.m
===================================================================
--- /issm/trunk/test/NightlyRun/test428.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test428.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressSSA2dNewton
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test428.py
===================================================================
--- /issm/trunk/test/NightlyRun/test428.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test428.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressSSA2dNewton
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test429.m
===================================================================
--- /issm/trunk/test/NightlyRun/test429.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test429.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressHONewton
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test429.py
===================================================================
--- /issm/trunk/test/NightlyRun/test429.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test429.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressHONewton
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test431.m
===================================================================
--- /issm/trunk/test/NightlyRun/test431.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test431.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfSteaEnthalpySSA3d
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
@@ -13,6 +14,6 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','Water fraction','Enthalpy'};
-field_tolerances={1e-10,1e-10,1e-09,1e-10,1e-13,1e-10,1e-10,1e-10};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','Waterfraction','Enthalpy'};
+field_tolerances={8e-5,5e-5,5e-5,5e-5,1e-13,1e-5,5e-5,5e-5};
 field_values={...
 	(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test431.py
===================================================================
--- /issm/trunk/test/NightlyRun/test431.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test431.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfSteaEnthalpySSA3d
 import numpy
 from model import *
@@ -23,6 +24,6 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','Water fraction','Enthalpy']
-field_tolerances=[1e-10,1e-10,1e-09,1e-10,1e-13,1e-10,1e-10,1e-10]
+field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','Waterfraction','Enthalpy']
+field_tolerances=[8e-5,5e-5,5e-5,5e-5,1e-13,1e-5,5e-5,5e-5]
 field_values=[\
 	md.results.SteadystateSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test432.m
===================================================================
--- /issm/trunk/test/NightlyRun/test432.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test432.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfSteaEnthalpyHO
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
@@ -12,6 +13,6 @@
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','Water fraction','Enthalpy'};
-field_tolerances={2e-09,1e-09,1e-09,1e-09,1e-13,1e-10,1e-10,1e-10};
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','Waterfraction','Enthalpy'};
+field_tolerances={3e-09,1e-09,1e-09,1e-09,1e-13,1e-10,3e-10,3e-10};
 field_values={...
 	(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test432.py
===================================================================
--- /issm/trunk/test/NightlyRun/test432.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test432.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfSteaEnthalpyHO
 import numpy
 from model import *
@@ -22,6 +23,6 @@
 
 #Fields and tolerances to track changes
-field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','Water fraction','Enthalpy']
-field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-13,1e-10,1e-10,1e-10]
+field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','Waterfraction','Enthalpy']
+field_tolerances=[3e-09,1e-09,1e-09,1e-09,1e-13,1e-10,3e-10,3e-10]
 field_values=[\
 	md.results.SteadystateSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test433.m
===================================================================
--- /issm/trunk/test/NightlyRun/test433.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test433.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: RoundSheetShelfGLMigrationSSA3d
 radius=1.e6;
 shelfextent=2.e5;
Index: /issm/trunk/test/NightlyRun/test433.py
===================================================================
--- /issm/trunk/test/NightlyRun/test433.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test433.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: RoundSheetShelfGLMigrationSSA3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test434.m
===================================================================
--- /issm/trunk/test/NightlyRun/test434.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test434.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfL1L2
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test434.py
===================================================================
--- /issm/trunk/test/NightlyRun/test434.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test434.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfL1L2
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test435.m
===================================================================
--- /issm/trunk/test/NightlyRun/test435.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test435.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: MISMIP3DHO
 md=triangle(model(),'../Exp/Square.exp',100000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test436.m
===================================================================
--- /issm/trunk/test/NightlyRun/test436.m	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test436.m	(revision 19105)
@@ -0,0 +1,27 @@
+%Test Name: SquareSheetShelfSteaEnthalpyLliboutryDuvalHO
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md.timestepping.time_step=0.;
+md.thermal.isenthalpy=1;
+md.materials.rheology_law='LliboutryDuval';
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
+md=solve(md,SteadystateSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','Waterfraction','Enthalpy'};
+field_tolerances={2e-09,1e-09,1e-09,1e-09,1e-13,1e-10,5e-10,5e-10};
+field_values={...
+	(md.results.SteadystateSolution.Vx),...
+	(md.results.SteadystateSolution.Vy),...
+	(md.results.SteadystateSolution.Vz),...
+	(md.results.SteadystateSolution.Vel),...
+	(md.results.SteadystateSolution.Pressure),...
+	(md.results.SteadystateSolution.Temperature),...
+	(md.results.SteadystateSolution.Waterfraction),...
+	(md.results.SteadystateSolution.Enthalpy),...
+	};
Index: /issm/trunk/test/NightlyRun/test437.m
===================================================================
--- /issm/trunk/test/NightlyRun/test437.m	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test437.m	(revision 19105)
@@ -0,0 +1,79 @@
+%Test Name: ThermalEnthBasalcondsTrans
+md=triangle(model(),'../Exp/Square.exp',300000.);
+md=setmask(md,'','');
+md=parameterize(md,'../Par/SquareThermal.par');
+
+h=100.;
+md.geometry.thickness=h*ones(md.mesh.numberofvertices,1);
+md.geometry.base=-h*ones(md.mesh.numberofvertices,1);
+md.geometry.surface=md.geometry.base+md.geometry.thickness;
+
+md=extrude(md,41,2.);
+md=setflowequation(md,'HO','all');
+md.thermal.isenthalpy=1;
+md.thermal.isdynamicbasalspc=1;
+
+%Basal forcing
+Ts=273.15-3.; Tb=273.15-1.; Tsw=Tb;
+qgeo=md.materials.thermalconductivity/max(md.geometry.thickness)*(Tb-Ts); %qgeo=kappa*(Tb-Ts)/H
+md.basalforcings.geothermalflux(find(md.mesh.vertexonbase))=qgeo;
+md.initialization.temperature=qgeo/md.materials.thermalconductivity.*(md.geometry.surface-md.mesh.z)+Ts;
+
+%Surface forcing
+pos=find(md.mesh.vertexonsurface);
+SPC_cold=NaN(md.mesh.numberofvertices,1);
+SPC_warm=NaN(md.mesh.numberofvertices,1);
+SPC_cold(pos)=Ts;
+SPC_warm(pos)=Tsw;
+md.thermal.spctemperature=SPC_cold;
+md.timestepping.time_step=5.;
+t0=0.;
+t1=10.;
+t2=100.;
+md.timestepping.final_time=400.;
+md.thermal.spctemperature=[SPC_cold SPC_cold SPC_warm SPC_warm SPC_cold];
+md.thermal.spctemperature=[md.thermal.spctemperature; t0 t1-1 t1 t2-1 t2];
+
+%Additional settings
+md.transient.ismasstransport=0;
+md.transient.isstressbalance=0;
+md.transient.isthermal=1;
+md.thermal.stabilization = 0;
+
+%Go solve
+md.verbose=verbose(0);
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md, TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Enthalpy1','Temperature1','Waterfraction1','BasalMeltingRate1','Watercolumn1',...
+						'Enthalpy2','Temperature2','Waterfraction2','BasalMeltingRate2','Watercolumn2',...
+						'Enthalpy3','Temperature3','Waterfraction3','BasalMeltingRate3','Watercolumn3',...
+						'Enthalpy4','Temperature4','Waterfraction4','BasalMeltingRate4','Watercolumn4'};
+field_tolerances={1.e-10,1.e-10,1.e-10,1.e-9,1.e-10,...
+						1.e-10,1.e-10,1.e-10,1.e-9,2.e-10,...
+						1.e-10,1.e-10,1.e-10,1.e-9,1.e-10,...
+						1.e-10,1.e-10,1.e-10,1.e-9,1.e-10};
+i1=1;	i2=ceil(t2/md.timestepping.time_step)+2;	i3=ceil(md.timestepping.final_time/(2.*md.timestepping.time_step));	i4=size(md.results.TransientSolution,2);
+field_values={...
+	(md.results.TransientSolution(i1).Enthalpy),...
+	(md.results.TransientSolution(i1).Temperature),...
+	(md.results.TransientSolution(i1).Waterfraction),...
+	(md.results.TransientSolution(i1).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(i1).Watercolumn),...
+	(md.results.TransientSolution(i2).Enthalpy),...
+	(md.results.TransientSolution(i2).Temperature),...
+	(md.results.TransientSolution(i2).Waterfraction),...
+	(md.results.TransientSolution(i2).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(i2).Watercolumn),...
+	(md.results.TransientSolution(i3).Enthalpy),...
+	(md.results.TransientSolution(i3).Temperature),...
+	(md.results.TransientSolution(i3).Waterfraction),...
+	(md.results.TransientSolution(i3).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(i3).Watercolumn),...
+	(md.results.TransientSolution(i4).Enthalpy),...
+	(md.results.TransientSolution(i4).Temperature),...
+	(md.results.TransientSolution(i4).Waterfraction),...
+	(md.results.TransientSolution(i4).BasalforcingsGroundediceMeltingRate),...
+	(md.results.TransientSolution(i4).Watercolumn),...
+	};
Index: /issm/trunk/test/NightlyRun/test438.m
===================================================================
--- /issm/trunk/test/NightlyRun/test438.m	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test438.m	(revision 19105)
@@ -0,0 +1,38 @@
+%Test Name: TransientFrictionWaterlayer2D
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=setflowequation(md,'SSA','all');
+md.friction=frictionwaterlayer(md.friction);
+md.friction.water_layer=zeros(md.mesh.numberofvertices,2);
+md.friction.water_layer(:,2)=1;
+md.friction.water_layer(md.mesh.numberofvertices+1,:)=[1 2];
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,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).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk/test/NightlyRun/test439.m
===================================================================
--- /issm/trunk/test/NightlyRun/test439.m	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test439.m	(revision 19105)
@@ -0,0 +1,39 @@
+%Test Name: TransientFrictionWaterlayer3D
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,4,1);
+md=setflowequation(md,'HO','all');
+md.friction=frictionwaterlayer(md.friction);
+md.friction.water_layer=zeros(md.mesh.numberofvertices,2);
+md.friction.water_layer(:,2)=1;
+md.friction.water_layer(md.mesh.numberofvertices+1,:)=[1 2];
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Vx2','Vy2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Vx3','Vy3','Vel3','Pressure3','Bed3','Surface3','Thickness3'};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
+field_values={...
+	(md.results.TransientSolution(1).Vx),...
+	(md.results.TransientSolution(1).Vy),...
+	(md.results.TransientSolution(1).Vel),...
+	(md.results.TransientSolution(1).Pressure),...
+	(md.results.TransientSolution(1).Base),...
+	(md.results.TransientSolution(1).Surface),...
+	(md.results.TransientSolution(1).Thickness),...
+	(md.results.TransientSolution(2).Vx),...
+	(md.results.TransientSolution(2).Vy),...
+	(md.results.TransientSolution(2).Vel),...
+	(md.results.TransientSolution(2).Pressure),...
+	(md.results.TransientSolution(2).Base),...
+	(md.results.TransientSolution(2).Surface),...
+	(md.results.TransientSolution(2).Thickness),...
+	(md.results.TransientSolution(3).Vx),...
+	(md.results.TransientSolution(3).Vy),...
+	(md.results.TransientSolution(3).Vel),...
+	(md.results.TransientSolution(3).Pressure),...
+	(md.results.TransientSolution(3).Base),...
+	(md.results.TransientSolution(3).Surface),...
+	(md.results.TransientSolution(3).Thickness),...
+	};
Index: /issm/trunk/test/NightlyRun/test450.m
===================================================================
--- /issm/trunk/test/NightlyRun/test450.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test450.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressSSAHigherOrder
 md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test450.py
===================================================================
--- /issm/trunk/test/NightlyRun/test450.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test450.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressSSAHigherOrder
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test455.m
===================================================================
--- /issm/trunk/test/NightlyRun/test455.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test455.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: SquareSheetShelfStressHOHigherOrder
 md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test455.py
===================================================================
--- /issm/trunk/test/NightlyRun/test455.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test455.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: SquareSheetShelfStressHOHigherOrder
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test501.m
===================================================================
--- /issm/trunk/test/NightlyRun/test501.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test501.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigStressSSA2d
 md=triangle(model(),'../Exp/Pig.exp',20000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test501.py
===================================================================
--- /issm/trunk/test/NightlyRun/test501.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test501.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigStressSSA2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test502.m
===================================================================
--- /issm/trunk/test/NightlyRun/test502.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test502.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigStressHO
 md=triangle(model(),'../Exp/Pig.exp',20000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test502.py
===================================================================
--- /issm/trunk/test/NightlyRun/test502.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test502.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigStressHO
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test503.m
===================================================================
--- /issm/trunk/test/NightlyRun/test503.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test503.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigStressFS
 md=triangle(model(),'../Exp/Pig.exp',20000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test503.py
===================================================================
--- /issm/trunk/test/NightlyRun/test503.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test503.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigStressFS
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test504.m
===================================================================
--- /issm/trunk/test/NightlyRun/test504.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test504.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigTranSSA2d
 md=triangle(model(),'../Exp/Pig.exp',20000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test504.py
===================================================================
--- /issm/trunk/test/NightlyRun/test504.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test504.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigTranSSA2d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test505.m
===================================================================
--- /issm/trunk/test/NightlyRun/test505.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test505.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigTranSSA3d
 md=triangle(model(),'../Exp/Pig.exp',30000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test505.py
===================================================================
--- /issm/trunk/test/NightlyRun/test505.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test505.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigTranSSA3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test506.m
===================================================================
--- /issm/trunk/test/NightlyRun/test506.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test506.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigTranHO
 md=triangle(model(),'../Exp/Pig.exp',30000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test506.py
===================================================================
--- /issm/trunk/test/NightlyRun/test506.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test506.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigTranHO
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test507.m
===================================================================
--- /issm/trunk/test/NightlyRun/test507.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test507.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigTranFS
 md=triangle(model(),'../Exp/Pig.exp',30000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test507.py
===================================================================
--- /issm/trunk/test/NightlyRun/test507.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test507.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigTranFS
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test508.m
===================================================================
--- /issm/trunk/test/NightlyRun/test508.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test508.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigSteaSSA3d
 md=triangle(model(),'../Exp/Pig.exp',35000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test508.py
===================================================================
--- /issm/trunk/test/NightlyRun/test508.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test508.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigSteaSSA3d
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test509.m
===================================================================
--- /issm/trunk/test/NightlyRun/test509.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test509.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigSteaHO
 md=triangle(model(),'../Exp/Pig.exp',30000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test509.py
===================================================================
--- /issm/trunk/test/NightlyRun/test509.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test509.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigSteaHO
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test510.m
===================================================================
--- /issm/trunk/test/NightlyRun/test510.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test510.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigSteaFS
 md=triangle(model(),'../Exp/Pig.exp',20000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test510.py
===================================================================
--- /issm/trunk/test/NightlyRun/test510.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test510.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigSteaFS
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test511.m
===================================================================
--- /issm/trunk/test/NightlyRun/test511.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test511.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigCMBFS
 md=triangle(model(),'../Exp/Pig.exp',11000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test511.py
===================================================================
--- /issm/trunk/test/NightlyRun/test511.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test511.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigCMBFS
 import numpy
 from model import *
@@ -34,5 +35,5 @@
 md.inversion.vy_obs=md.initialization.vy
 
-md.cluster=generic('name',oshostname(),'np',3)
+md.cluster=generic('name',oshostname(),'np',1)
 md=solve(md,StressbalanceSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test512.m
===================================================================
--- /issm/trunk/test/NightlyRun/test512.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test512.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigCMDragHO
 md=triangle(model(),'../Exp/Pig.exp',20000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test512.py
===================================================================
--- /issm/trunk/test/NightlyRun/test512.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test512.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigCMDragHO
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test513.m
===================================================================
--- /issm/trunk/test/NightlyRun/test513.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test513.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigCMDragSteaSSA3d
 md=triangle(model(),'../Exp/Pig.exp',30000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
@@ -25,5 +26,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsGroundediceMeltingRate'};
-field_tolerances={1e-09,2e-10,1e-10,1e-10,3e-6,3e-6,3e-6,3e-6,2e-6,2e-06};
+field_tolerances={5e-08,2e-10,1e-10,1e-10,3e-6,3e-6,3e-6,3e-6,2e-6,2e-06};
 field_values={...
 	(md.results.SteadystateSolution.Gradient1),...
Index: /issm/trunk/test/NightlyRun/test513.py
===================================================================
--- /issm/trunk/test/NightlyRun/test513.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test513.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigCMDragSteaSSA3d
 from model import *
 from triangle import *
@@ -36,5 +37,5 @@
 # Fields and tolerances to track changes
 field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsGroundediceMeltingRate']
-field_tolerances=[1e-09,2e-10,1e-10,1e-10,3e-6,3e-6,3e-6,3e-6,2e-6,2e-06]
+field_tolerances=[5e-08,2e-10,1e-10,1e-10,3e-6,3e-6,3e-6,3e-6,2e-6,2e-06]
 field_values=[\
 	md.results.SteadystateSolution.Gradient1,\
Index: /issm/trunk/test/NightlyRun/test514.m
===================================================================
--- /issm/trunk/test/NightlyRun/test514.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test514.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigBamgMesh
 %Simple mesh 1
 hVertices=10000.*ones(27,1);
Index: /issm/trunk/test/NightlyRun/test514.py
===================================================================
--- /issm/trunk/test/NightlyRun/test514.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test514.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigBamgMesh
 import numpy
 import copy
Index: /issm/trunk/test/NightlyRun/test515.m
===================================================================
--- /issm/trunk/test/NightlyRun/test515.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test515.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigTherTranSUPG
 md=triangle(model(),'../Exp/Pig.exp',30000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test515.py
===================================================================
--- /issm/trunk/test/NightlyRun/test515.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test515.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigTherTranSUPG
 from model import *
 from triangle import *
Index: /issm/trunk/test/NightlyRun/test516.m
===================================================================
--- /issm/trunk/test/NightlyRun/test516.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test516.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigTherSteaSUPG
 md=triangle(model(),'../Exp/Pig.exp',30000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
Index: /issm/trunk/test/NightlyRun/test516.py
===================================================================
--- /issm/trunk/test/NightlyRun/test516.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test516.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigTherSteaSUPG
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test530.m
===================================================================
--- /issm/trunk/test/NightlyRun/test530.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test530.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigBalVel1
 md=triangle(model(),'../Exp/Pig.exp',20000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
@@ -7,9 +8,9 @@
 
 %Fields and tolerances to track changes
-field_names     ={'SurfaceSlopeX','SurfaceSlopeX','Vel'};
+field_names     ={'DrivingStressX','DrivingStressX','Vel'};
 field_tolerances={1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.BalancevelocitySolution.SurfaceSlopeX),...
-	(md.results.BalancevelocitySolution.SurfaceSlopeY),...
+	(md.results.BalancevelocitySolution.DrivingStressX),...
+	(md.results.BalancevelocitySolution.DrivingStressY),...
 	(md.results.BalancevelocitySolution.Vel),...
 	};
Index: /issm/trunk/test/NightlyRun/test530.py
===================================================================
--- /issm/trunk/test/NightlyRun/test530.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test530.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigBalVel1
 from model import *
 from triangle import *
@@ -16,9 +17,9 @@
 
 # Fields and tolerances to track changes
-field_names     =['SurfaceSlopeX','SurfaceSlopeY','Vel']
+field_names     =['DrivingStressX','DrivingStressY','Vel']
 field_tolerances=[1e-13,1e-13,1e-13]
 field_values=[\
-		md.results.BalancevelocitySolution.SurfaceSlopeX,\
-		md.results.BalancevelocitySolution.SurfaceSlopeY,\
+		md.results.BalancevelocitySolution.DrivingStressX,\
+		md.results.BalancevelocitySolution.DrivingStressY,\
 		md.results.BalancevelocitySolution.Vel,\
 		]
Index: /issm/trunk/test/NightlyRun/test531.m
===================================================================
--- /issm/trunk/test/NightlyRun/test531.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test531.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: PigBalVel2
 md=triangle(model(),'../Exp/Pig.exp',20000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
@@ -9,9 +10,9 @@
 
 %Fields and tolerances to track changes
-field_names     ={'SurfaceSlopeX','SurfaceSlopeX','Vel'};
+field_names     ={'DrivingStressX','DrivingStressX','Vel'};
 field_tolerances={1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.BalancevelocitySolution.SurfaceSlopeX),...
-	(md.results.BalancevelocitySolution.SurfaceSlopeY),...
+	(md.results.BalancevelocitySolution.DrivingStressX),...
+	(md.results.BalancevelocitySolution.DrivingStressY),...
 	(md.results.BalancevelocitySolution.Vel),...
 	};
Index: /issm/trunk/test/NightlyRun/test531.py
===================================================================
--- /issm/trunk/test/NightlyRun/test531.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test531.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: PigBalVel2
 from model import *
 from triangle import *
@@ -18,9 +19,9 @@
 
 # Fields and tolerances to track changes
-field_names     =['SurfaceSlopeX','SurfaceSlopeY','Vel']
+field_names     =['DrivingStressX','DrivingStressY','Vel']
 field_tolerances=[1e-13,1e-13,1e-13]
 field_values=[\
-		md.results.BalancevelocitySolution.SurfaceSlopeX,\
-		md.results.BalancevelocitySolution.SurfaceSlopeY,\
+		md.results.BalancevelocitySolution.DrivingStressX,\
+		md.results.BalancevelocitySolution.DrivingStressY,\
 		md.results.BalancevelocitySolution.Vel,\
 		]
Index: /issm/trunk/test/NightlyRun/test601.m
===================================================================
--- /issm/trunk/test/NightlyRun/test601.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test601.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: 79NorthMasstransp2d
 md=triangle(model(),'../Exp/79North.exp',10000.);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test601.py
===================================================================
--- /issm/trunk/test/NightlyRun/test601.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test601.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: 79NorthMasstransp2d
 from model import *
 from EnumDefinitions import *
Index: /issm/trunk/test/NightlyRun/test602.m
===================================================================
--- /issm/trunk/test/NightlyRun/test602.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test602.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: 79NorthMasstransp2dDG
 md=triangle(model(),'../Exp/79North.exp',10000.);
 md=meshconvert(md);
Index: /issm/trunk/test/NightlyRun/test602.py
===================================================================
--- /issm/trunk/test/NightlyRun/test602.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test602.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: 79NorthMasstransp2dDG
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test603.m
===================================================================
--- /issm/trunk/test/NightlyRun/test603.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test603.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: 79NorthMasstransp3d
 md=triangle(model(),'../Exp/79North.exp',10000.);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test603.py
===================================================================
--- /issm/trunk/test/NightlyRun/test603.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test603.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: 79NorthMasstransp3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test604.m
===================================================================
--- /issm/trunk/test/NightlyRun/test604.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test604.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: 79NorthSurfSlop2d
 md=triangle(model(),'../Exp/79North.exp',10000.);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test604.py
===================================================================
--- /issm/trunk/test/NightlyRun/test604.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test604.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: 79NorthSurfSlop2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test605.m
===================================================================
--- /issm/trunk/test/NightlyRun/test605.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test605.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: 79NorthSurfSlop3d
 md=triangle(model(),'../Exp/79North.exp',10000.);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test605.py
===================================================================
--- /issm/trunk/test/NightlyRun/test605.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test605.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: 79NorthSurfSlop3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test606.m
===================================================================
--- /issm/trunk/test/NightlyRun/test606.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test606.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: 79NorthBedSlop2d
 md=triangle(model(),'../Exp/79North.exp',10000.);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test606.py
===================================================================
--- /issm/trunk/test/NightlyRun/test606.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test606.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: 79NorthBedSlop2d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test607.m
===================================================================
--- /issm/trunk/test/NightlyRun/test607.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test607.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: 79NorthBedSlop3d
 md=triangle(model(),'../Exp/79North.exp',10000.);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test607.py
===================================================================
--- /issm/trunk/test/NightlyRun/test607.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test607.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: 79NorthBedSlop3d
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test608.m
===================================================================
--- /issm/trunk/test/NightlyRun/test608.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test608.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: 79NorthBalThic2d
 md=triangle(model(),'../Exp/79North.exp',10000.);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test608.py
===================================================================
--- /issm/trunk/test/NightlyRun/test608.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test608.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: 79NorthBalThic2d
 import numpy
 from model import *
Index: sm/trunk/test/NightlyRun/test609.m
===================================================================
--- /issm/trunk/test/NightlyRun/test609.m	(revision 19104)
+++ 	(revision )
@@ -1,15 +1,0 @@
-md=triangle(model(),'../Exp/79North.exp',10000.);
-md=meshconvert(md);
-md=setmask(md,'../Exp/79NorthShelf.exp','');
-md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'SSA','all');
-md.balancethickness.stabilization=3;
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum());
-
-%Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-13};
-field_values={...
-	(md.results.BalancethicknessSolution.Thickness),...
-	};
Index: sm/trunk/test/NightlyRun/test609.py
===================================================================
--- /issm/trunk/test/NightlyRun/test609.py	(revision 19104)
+++ 	(revision )
@@ -1,26 +1,0 @@
-import numpy
-from model import *
-from EnumDefinitions import *
-from MatlabFuncs import *
-from triangle import *
-from meshconvert import *
-from setmask import *
-from parameterize import *
-from setflowequation import *
-from solve import *
-
-md=triangle(model(),'../Exp/79North.exp',10000.)
-md=meshconvert(md)
-md=setmask(md,'../Exp/79NorthShelf.exp','')
-md=parameterize(md,'../Par/79North.py')
-md=setflowequation(md,'SSA','all')
-md.balancethickness.stabilization=3
-md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,BalancethicknessSolutionEnum())
-
-#Fields and tolerances to track changes
-field_names     =['Thickness']
-field_tolerances=[1e-13]
-field_values=[\
-	md.results.BalancethicknessSolution.Thickness,\
-	]
Index: sm/trunk/test/NightlyRun/test610.m
===================================================================
--- /issm/trunk/test/NightlyRun/test610.m	(revision 19104)
+++ 	(revision )
@@ -1,14 +1,0 @@
-md=triangle(model(),'../Exp/79North.exp',10000.);
-md=setmask(md,'../Exp/79NorthShelf.exp','');
-md=parameterize(md,'../Par/79North.par');
-md=extrude(md,3,1.);
-md=setflowequation(md,'SSA','all');
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum());
-
-%Fields and tolerances to track changes
-field_names     ={'Thickness'};
-field_tolerances={1e-12};
-field_values={...
-	(md.results.BalancethicknessSolution.Thickness),...
-	};
Index: sm/trunk/test/NightlyRun/test610.py
===================================================================
--- /issm/trunk/test/NightlyRun/test610.py	(revision 19104)
+++ 	(revision )
@@ -1,24 +1,0 @@
-import numpy
-from model import *
-from EnumDefinitions import *
-from MatlabFuncs import *
-from triangle import *
-from setmask import *
-from parameterize import *
-from setflowequation import *
-from solve import *
-
-md=triangle(model(),'../Exp/79North.exp',10000.)
-md=setmask(md,'../Exp/79NorthShelf.exp','')
-md=parameterize(md,'../Par/79North.py')
-md.extrude(3,1.)
-md=setflowequation(md,'SSA','all')
-md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,BalancethicknessSolutionEnum())
-
-#Fields and tolerances to track changes
-field_names     =['Thickness']
-field_tolerances=[1e-12]
-field_values=[\
-	md.results.BalancethicknessSolution.Thickness,\
-	]
Index: /issm/trunk/test/NightlyRun/test611.m
===================================================================
--- /issm/trunk/test/NightlyRun/test611.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test611.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: 79NorthCMBalThic2dCG
 md=triangle(model(),'../Exp/79North.exp',10000.);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
Index: /issm/trunk/test/NightlyRun/test611.py
===================================================================
--- /issm/trunk/test/NightlyRun/test611.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test611.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: 79NorthCMBalThic2dCG
 import numpy
 from model import *
Index: /issm/trunk/test/NightlyRun/test613.m
===================================================================
--- /issm/trunk/test/NightlyRun/test613.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test613.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: 79NorthCMBalThicVxVy
 md=triangle(model(),'../Exp/79North.exp',10000.);
 md=meshconvert(md);
Index: /issm/trunk/test/NightlyRun/test613.py
===================================================================
--- /issm/trunk/test/NightlyRun/test613.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test613.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: 79NorthCMBalThicVxVy
 import numpy
 import copy
Index: /issm/trunk/test/NightlyRun/test701.m
===================================================================
--- /issm/trunk/test/NightlyRun/test701.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test701.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: FlowbandFSshelf
 x =[1:100:3000]';
 h=linspace(1000,300,numel(x))';
@@ -38,8 +39,10 @@
 md=setflowequation(md,'FS','all');
 md.stressbalance.abstol=NaN;
+%md.stressbalance.reltol=10^-16;
 md.stressbalance.FSreconditioning=1;
 md.stressbalance.maxiter=20;
 md.flowequation.augmented_lagrangian_r=10000;
 md.miscellaneous.name = 'flowline';
+md.verbose=verbose('convergence',true);
 md.cluster=generic('np',2);
 
@@ -48,5 +51,6 @@
 field_tolerances={};
 field_values={};
-for i={'MINI','MINIcondensed','TaylorHood','XTaylorHood','LATaylorHood','CrouzeixRaviart'}
+%md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.y);
+for i={'MINI','MINIcondensed','TaylorHood','XTaylorHood','LATaylorHood','CrouzeixRaviart','LACrouzeixRaviart'}
 	disp(' ');
 	disp(['====== Testing ' i{1} ' Full-Stokes Finite element =====']);
@@ -54,5 +58,5 @@
 	md=solve(md,StressbalanceSolutionEnum());
 	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vel' i{1}],['Pressure' i{1}]};
-	field_tolerances={field_tolerances{:},8e-5,8e-5,8e-5,1e-10};
+	field_tolerances={field_tolerances{:},9e-5,8e-5,9e-5,1e-10};
 	field_values={field_values{:},...
 		(md.results.StressbalanceSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test702.m
===================================================================
--- /issm/trunk/test/NightlyRun/test702.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test702.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: FlowbandFSsheetshelf
 %mesh parameters
 x =[-5:.5:5]';
@@ -36,18 +37,29 @@
 %Misc
 md=setflowequation(md,'FS','all');
-md.flowequation.fe_FS='TaylorHood';
 md.stressbalance.abstol=NaN;
+md.stressbalance.FSreconditioning=1;
+md.stressbalance.maxiter=20;
+md.flowequation.augmented_lagrangian_r=10000;
+md.flowequation.augmented_lagrangian_rhop=10000;
+md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.y);
 md.miscellaneous.name = 'flowline';
-
-%Go solve
 md.cluster=generic('np',2);
-md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={2e-08,2e-08,2e-08,2e-08};
-field_values={...
-	(md.results.StressbalanceSolution.Vx),...
-	(md.results.StressbalanceSolution.Vy),...
-	(md.results.StressbalanceSolution.Vel),...
-	(md.results.StressbalanceSolution.Pressure)};
+field_names={};
+field_tolerances={};
+field_values={};
+for i={'MINI','MINIcondensed','TaylorHood','XTaylorHood','LATaylorHood','CrouzeixRaviart'}
+	disp(' ');
+	disp(['====== Testing ' i{1} ' Full-Stokes Finite element =====']);
+	md.flowequation.fe_FS=i{1};
+	md=solve(md,StressbalanceSolutionEnum());
+	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vel' i{1}],['Pressure' i{1}]};
+	field_tolerances={field_tolerances{:},8e-5,8e-5,8e-5,1e-08};
+	field_values={field_values{:},...
+		(md.results.StressbalanceSolution.Vx),...
+		(md.results.StressbalanceSolution.Vy),...
+		(md.results.StressbalanceSolution.Vel),...
+		(md.results.StressbalanceSolution.Pressure),...
+		};
+end
Index: /issm/trunk/test/NightlyRun/test703.m
===================================================================
--- /issm/trunk/test/NightlyRun/test703.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test703.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: FlowbandFSsheetshelfTrans
 %mesh parameters
 x =[-5:.5:5]';
Index: /issm/trunk/test/NightlyRun/test801.m
===================================================================
--- /issm/trunk/test/NightlyRun/test801.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test801.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ValleyGlacierLevelsetSSA2d
 md=triangle(model(),'../Exp/Square.exp',50000);
 md=setmask(md,'','');
@@ -8,4 +9,5 @@
 md.transient.isstressbalance=1;
 md.transient.islevelset=1;
+md.transient.iscalving=1;
 md.transient.ismasstransport=1;
 md.transient.isthermal=0;
Index: /issm/trunk/test/NightlyRun/test801.py
===================================================================
--- /issm/trunk/test/NightlyRun/test801.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test801.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ValleyGlacierLevelsetSSA2d
 from model import *
 from triangle import *
@@ -18,4 +19,5 @@
 md.transient.isstressbalance=True
 md.transient.islevelset=True
+md.transient.iscalving=True
 md.transient.ismasstransport=True
 md.transient.isthermal=False
Index: /issm/trunk/test/NightlyRun/test802.m
===================================================================
--- /issm/trunk/test/NightlyRun/test802.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test802.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ValleyGlacierLevelsetThermalSSA3d
 md=triangle(model(),'../Exp/Square.exp',50000);
 md=setmask(md,'','');
@@ -13,4 +14,5 @@
 md.transient.isstressbalance=1;
 md.transient.islevelset=1;
+md.transient.iscalving=1;
 md.transient.ismasstransport=1;
 md.transient.isthermal=1;
Index: /issm/trunk/test/NightlyRun/test802.py
===================================================================
--- /issm/trunk/test/NightlyRun/test802.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test802.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ValleyGlacierLevelsetThermalSSA3d
 from model import *
 from triangle import *
@@ -23,4 +24,5 @@
 md.transient.isstressbalance=True
 md.transient.islevelset=True
+md.transient.iscalving=True
 md.transient.ismasstransport=True
 md.transient.isthermal=True
Index: /issm/trunk/test/NightlyRun/test803.m
===================================================================
--- /issm/trunk/test/NightlyRun/test803.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test803.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ValleyGlacierLevelsetEnthalpyHO3d
 md=triangle(model(),'../Exp/Square.exp',50000);
 md=setmask(md,'','');
@@ -15,4 +16,5 @@
 md.transient.isstressbalance=1;
 md.transient.islevelset=1;
+md.transient.iscalving=1;
 md.transient.ismasstransport=1;
 md.transient.isthermal=1;
Index: /issm/trunk/test/NightlyRun/test803.py
===================================================================
--- /issm/trunk/test/NightlyRun/test803.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test803.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ValleyGlacierLevelsetEnthalpyHO3d
 from model import *
 from triangle import *
@@ -25,4 +26,5 @@
 md.transient.isstressbalance=True
 md.transient.islevelset=True
+md.transient.iscalving=True
 md.transient.ismasstransport=True
 md.transient.isthermal=True
Index: /issm/trunk/test/NightlyRun/test804.m
===================================================================
--- /issm/trunk/test/NightlyRun/test804.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test804.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ValleyGlacierLevelsetCalvingSIA2d
 md=triangle(model(),'../Exp/Square.exp',50000);
 md=setmask(md,'','');
@@ -12,6 +13,8 @@
 md.transient.isgroundingline=1;
 md.transient.isgia=0;
+md.transient.iscalving=1;
 
-md.masstransport.calvingrate=1000.*ones(md.mesh.numberofvertices,1);
+md.calving.calvingrate=1000.*ones(md.mesh.numberofvertices,1);
+md.calving.meltingrate=zeros(md.mesh.numberofvertices,1);
 
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test804.py
===================================================================
--- /issm/trunk/test/NightlyRun/test804.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test804.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ValleyGlacierLevelsetCalvingSIA2d
 from model import *
 from triangle import *
@@ -22,6 +23,8 @@
 md.transient.isgroundingline=True
 md.transient.isgia=False
+md.transient.iscalving=True;
 
-md.masstransport.calvingrate=1000.*numpy.ones((md.mesh.numberofvertices,1))
+md.calving.calvingrate=1000.*numpy.ones((md.mesh.numberofvertices,1))
+md.calving.meltingrate=numpy.zeros((md.mesh.numberofvertices,1))
 
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test805.m
===================================================================
--- /issm/trunk/test/NightlyRun/test805.m	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test805.m	(revision 19105)
@@ -1,2 +1,3 @@
+%Test Name: ValleyGlacierLevelsetEnthCalvingHO3d
 md=triangle(model(),'../Exp/Square.exp',50000);
 md=setmask(md,'','');
@@ -19,6 +20,8 @@
 md.transient.isgroundingline=1;
 md.transient.isgia=0;
+md.transient.iscalving=1;
 
-md.masstransport.calvingrate=1000.*ones(md.mesh.numberofvertices,1);
+md.calving.calvingrate=1000.*ones(md.mesh.numberofvertices,1);
+md.calving.meltingrate=zeros(md.mesh.numberofvertices,1);
 
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test805.py
===================================================================
--- /issm/trunk/test/NightlyRun/test805.py	(revision 19104)
+++ /issm/trunk/test/NightlyRun/test805.py	(revision 19105)
@@ -1,2 +1,3 @@
+#Test Name: ValleyGlacierLevelsetEnthCalvingHO3d
 from model import *
 from triangle import *
@@ -29,6 +30,8 @@
 md.transient.isgroundingline=True
 md.transient.isgia=False
+md.transient.iscalving=True;
 
-md.masstransport.calvingrate=1000.*numpy.ones((md.mesh.numberofvertices,1))
+md.calving.calvingrate=1000.*numpy.ones((md.mesh.numberofvertices,1))
+md.calving.meltingrate=numpy.zeros((md.mesh.numberofvertices,1))
 
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test806.m
===================================================================
--- /issm/trunk/test/NightlyRun/test806.m	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test806.m	(revision 19105)
@@ -0,0 +1,73 @@
+%Test Name: SquareShelfLevelsetCalvingSSA2dLevermann
+md=triangle(model(),'../Exp/Square.exp',50000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+x = md.mesh.x;
+xmin = min(x);
+xmax = max(x);
+Lx = (xmax-xmin);
+alpha = 2./3.;
+md.mask.ice_levelset = ((x - alpha*Lx)>0) - ((x - alpha*Lx)<0);
+
+md.timestepping.time_step=10;
+md.timestepping.final_time=30;
+
+%Transient
+md.transient.isstressbalance=1;
+md.transient.islevelset=1;
+md.transient.ismasstransport=1;
+md.transient.isthermal=0;
+md.transient.isgroundingline=0;
+md.transient.isgia=0;
+md.transient.iscalving=1;
+
+md.calving=calvinglevermann();
+md.calving.coeff=4.89e13*ones(md.mesh.numberofvertices,1);
+md.calving.meltingrate=zeros(md.mesh.numberofvertices,1);
+
+md.transient.requested_outputs={'default','StrainRateparallel','StrainRateperpendicular','Calvingratex','Calvingratey','CalvingCalvingrate'};
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1','StrainRateparallel1','StrainRateperpendicular1','CalvingCalvingrate1'...
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2','StrainRateparallel2','StrainRateperpendicular2','CalvingCalvingrate2'...
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3','StrainRateparallel3','StrainRateperpendicular3','CalvingCalvingrate3'};
+field_tolerances={1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,...
+		2e-11,2e-11,2e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,...
+		2e-11,2e-11,2e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11};
+field_values={...
+	md.results.TransientSolution(1).Vx,...
+	md.results.TransientSolution(1).Vy,...
+	md.results.TransientSolution(1).Vel,...
+	md.results.TransientSolution(1).Pressure,...
+	md.results.TransientSolution(1).Thickness,...
+	md.results.TransientSolution(1).Surface,...
+	md.results.TransientSolution(1).MaskIceLevelset,...
+	md.results.TransientSolution(1).StrainRateparallel,...
+	md.results.TransientSolution(1).StrainRateperpendicular,...
+	md.results.TransientSolution(1).CalvingCalvingrate,...
+	md.results.TransientSolution(2).Vx,...
+	md.results.TransientSolution(2).Vy,...
+	md.results.TransientSolution(2).Vel,...
+	md.results.TransientSolution(2).Pressure,...
+	md.results.TransientSolution(2).Thickness,...
+	md.results.TransientSolution(2).Surface,...
+	md.results.TransientSolution(2).MaskIceLevelset,...
+	md.results.TransientSolution(2).StrainRateparallel,...
+	md.results.TransientSolution(2).StrainRateperpendicular,...
+	md.results.TransientSolution(2).CalvingCalvingrate,...
+	md.results.TransientSolution(3).Vx,...
+	md.results.TransientSolution(3).Vy,...
+	md.results.TransientSolution(3).Vel,...
+	md.results.TransientSolution(3).Pressure,...
+	md.results.TransientSolution(3).Thickness,...
+	md.results.TransientSolution(3).Surface,...
+	md.results.TransientSolution(3).MaskIceLevelset,...
+	md.results.TransientSolution(3).StrainRateparallel,...
+	md.results.TransientSolution(3).StrainRateperpendicular,...
+	md.results.TransientSolution(3).CalvingCalvingrate,...
+	};
Index: /issm/trunk/test/NightlyRun/test806.py
===================================================================
--- /issm/trunk/test/NightlyRun/test806.py	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test806.py	(revision 19105)
@@ -0,0 +1,87 @@
+#Test Name: SquareShelfLevelsetCalvingSSA2dLevermann
+from model import *
+from triangle import *
+from squaremesh import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+import numpy
+
+md=triangle(model(),'../Exp/Square.exp',50000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+x = md.mesh.x
+xmin = min(x)
+xmax = max(x)
+Lx = (xmax-xmin)
+alpha = 2./3.
+md.mask.ice_levelset = numpy.float_((x - alpha*Lx)>0) - numpy.float_((x - alpha*Lx)<0)
+
+md.timestepping.time_step=10
+md.timestepping.final_time=30
+
+
+
+#Transient
+md.transient.isstressbalance=True
+md.transient.islevelset=True
+md.transient.ismasstransport=True
+md.transient.isthermal=False
+md.transient.isgroundingline=False
+md.transient.isgia=False
+md.transient.iscalving=True;
+
+md.calving=calvinglevermann()
+md.calving.coeff=4.89e13*numpy.ones((md.mesh.numberofvertices,1))
+md.calving.meltingrate=numpy.zeros((md.mesh.numberofvertices,1))
+
+md.transient.requested_outputs=['default','StrainRateparallel','StrainRateperpendicular','Calvingratex','Calvingratey','CalvingCalvingrate']
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1','StrainRateparallel1','StrainRateperpendicular1','CalvingCalvingrate1',\
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2','StrainRateparallel2','StrainRateperpendicular2','CalvingCalvingrate2',\
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3','StrainRateparallel3','StrainRateperpendicular3','CalvingCalvingrate3']
+field_tolerances=[1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,\
+		2e-11,2e-11,2e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,\
+		2e-11,2e-11,2e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].MaskIceLevelset,\
+	md.results.TransientSolution[0].StrainRateparallel,\
+	md.results.TransientSolution[0].StrainRateperpendicular,\
+	md.results.TransientSolution[0].CalvingCalvingrate,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].MaskIceLevelset,\
+	md.results.TransientSolution[1].StrainRateparallel,\
+	md.results.TransientSolution[1].StrainRateperpendicular,\
+	md.results.TransientSolution[1].CalvingCalvingrate,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].MaskIceLevelset,\
+	md.results.TransientSolution[2].StrainRateparallel,\
+	md.results.TransientSolution[2].StrainRateperpendicular,\
+	md.results.TransientSolution[2].CalvingCalvingrate,\
+
+	]
Index: /issm/trunk/test/NightlyRun/test807.m
===================================================================
--- /issm/trunk/test/NightlyRun/test807.m	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test807.m	(revision 19105)
@@ -0,0 +1,61 @@
+%Test Name: SquareShelfLevelsetMeltingSSA2d
+md=triangle(model(),'../Exp/Square.exp',50000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+x = md.mesh.x;
+xmin = min(x);
+xmax = max(x);
+Lx = (xmax-xmin);
+alpha = 2./3.;
+md.mask.ice_levelset = ((x - alpha*Lx)>0) - ((x - alpha*Lx)<0);
+
+md.timestepping.time_step=10;
+md.timestepping.final_time=30;
+
+%Transient
+md.transient.isstressbalance=1;
+md.transient.islevelset=1;
+md.transient.ismasstransport=1;
+md.transient.isthermal=0;
+md.transient.isgroundingline=0;
+md.transient.isgia=0;
+md.transient.iscalving=1;
+
+md.calving.calvingrate=zeros(md.mesh.numberofvertices,1);
+md.calving.meltingrate=10000*ones(md.mesh.numberofvertices,1);
+
+md=solve(md,TransientSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1'...
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2'...
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3'};
+field_tolerances={1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,...
+		2e-11,2e-11,2e-11,1e-11,1e-11,1e-11,1e-11,...
+		2e-11,2e-11,2e-11,1e-11,1e-11,1e-11,1e-11};
+field_values={...
+	md.results.TransientSolution(1).Vx,...
+	md.results.TransientSolution(1).Vy,...
+	md.results.TransientSolution(1).Vel,...
+	md.results.TransientSolution(1).Pressure,...
+	md.results.TransientSolution(1).Thickness,...
+	md.results.TransientSolution(1).Surface,...
+	md.results.TransientSolution(1).MaskIceLevelset,...
+	md.results.TransientSolution(2).Vx,...
+	md.results.TransientSolution(2).Vy,...
+	md.results.TransientSolution(2).Vel,...
+	md.results.TransientSolution(2).Pressure,...
+	md.results.TransientSolution(2).Thickness,...
+	md.results.TransientSolution(2).Surface,...
+	md.results.TransientSolution(2).MaskIceLevelset,...
+	md.results.TransientSolution(3).Vx,...
+	md.results.TransientSolution(3).Vy,...
+	md.results.TransientSolution(3).Vel,...
+	md.results.TransientSolution(3).Pressure,...
+	md.results.TransientSolution(3).Thickness,...
+	md.results.TransientSolution(3).Surface,...
+	md.results.TransientSolution(3).MaskIceLevelset,...
+	};
Index: /issm/trunk/test/NightlyRun/test807.py
===================================================================
--- /issm/trunk/test/NightlyRun/test807.py	(revision 19105)
+++ /issm/trunk/test/NightlyRun/test807.py	(revision 19105)
@@ -0,0 +1,75 @@
+#Test Name: SquareShelfLevelsetMeltingSSA2d
+from model import *
+from triangle import *
+from squaremesh import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+import numpy
+
+md=triangle(model(),'../Exp/Square.exp',50000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+x = md.mesh.x
+xmin = min(x)
+xmax = max(x)
+Lx = (xmax-xmin)
+alpha = 2./3.
+md.mask.ice_levelset = numpy.float_((x - alpha*Lx)>0) - numpy.float_((x - alpha*Lx)<0)
+
+md.timestepping.time_step=10
+md.timestepping.final_time=30
+
+
+
+#Transient
+md.transient.isstressbalance=True
+md.transient.islevelset=True
+md.transient.ismasstransport=True
+md.transient.isthermal=False
+md.transient.isgroundingline=False
+md.transient.isgia=False
+md.transient.iscalving=True;
+
+md.calving.calvingrate=numpy.zeros((md.mesh.numberofvertices,1))
+md.calving.meltingrate=10000*numpy.ones((md.mesh.numberofvertices,1))
+
+md=solve(md,TransientSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx1','Vy1','Vel1','Pressure1','Thickness1','Surface1','MaskIceLevelset1',\
+		'Vx2','Vy2','Vel2','Pressure2','Thickness2','Surface2','MaskIceLevelset2',\
+		'Vx3','Vy3','Vel3','Pressure3','Thickness3','Surface3','MaskIceLevelset3']
+field_tolerances=[1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,\
+		2e-11,2e-11,2e-11,1e-11,1e-11,1e-11,1e-11,\
+		2e-11,2e-11,2e-11,1e-11,1e-11,1e-11,1e-11]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].MaskIceLevelset,\
+	md.results.TransientSolution[1].Vx,\
+	md.results.TransientSolution[1].Vy,\
+	md.results.TransientSolution[1].Vel,\
+	md.results.TransientSolution[1].Pressure,\
+	md.results.TransientSolution[1].Thickness,\
+	md.results.TransientSolution[1].Surface,\
+	md.results.TransientSolution[1].MaskIceLevelset,\
+	md.results.TransientSolution[2].Vx,\
+	md.results.TransientSolution[2].Vy,\
+	md.results.TransientSolution[2].Vel,\
+	md.results.TransientSolution[2].Pressure,\
+	md.results.TransientSolution[2].Thickness,\
+	md.results.TransientSolution[2].Surface,\
+	md.results.TransientSolution[2].MaskIceLevelset,\
+
+	]
Index: /issm/trunk/test/Par/SquareSheetConstrained.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 19104)
+++ /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 19105)
@@ -30,5 +30,6 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
-md.masstransport.calvingrate=zeros(md.mesh.numberofvertices,1);
+%Calving
+md.calving.calvingrate=zeros(md.mesh.numberofvertices,1);
 
 %Friction
Index: /issm/trunk/test/Par/SquareSheetConstrained.py
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 19104)
+++ /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 19105)
@@ -40,6 +40,6 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
-#Masstransport
-md.masstransport.calvingrate=0.*numpy.ones((md.mesh.numberofvertices,1))
+#Calving
+md.calving.calvingrate=0.*numpy.ones((md.mesh.numberofvertices,1))
 
 #Friction
Index: /issm/trunk/test/Par/SquareThermal.par
===================================================================
--- /issm/trunk/test/Par/SquareThermal.par	(revision 19104)
+++ /issm/trunk/test/Par/SquareThermal.par	(revision 19105)
@@ -22,4 +22,7 @@
 disp('      creating temperatures');
 md.initialization.temperature=(273.-20.)*ones(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
 
 disp('      creating flow law parameter');
Index: /issm/trunk/test/Par/ValleyGlacierShelf.par
===================================================================
--- /issm/trunk/test/Par/ValleyGlacierShelf.par	(revision 19104)
+++ /issm/trunk/test/Par/ValleyGlacierShelf.par	(revision 19105)
@@ -75,5 +75,6 @@
 
 %Masstransport;
-md.masstransport.calvingrate = 0.*ones(md.mesh.numberofvertices,1);
+md.calving.calvingrate = 0.*ones(md.mesh.numberofvertices,1);
+md.calving.meltingrate = 0.*ones(md.mesh.numberofvertices,1);
 md.masstransport.stabilization = 1.;
 
Index: /issm/trunk/test/Par/ValleyGlacierShelf.py
===================================================================
--- /issm/trunk/test/Par/ValleyGlacierShelf.py	(revision 19104)
+++ /issm/trunk/test/Par/ValleyGlacierShelf.py	(revision 19105)
@@ -82,5 +82,6 @@
 
 #Masstransport
-md.masstransport.calvingrate=0.*numpy.ones((md.mesh.numberofvertices,1))
+md.calving.calvingrate=0.*numpy.ones((md.mesh.numberofvertices,1))
+md.calving.meltingrate=0.*numpy.ones((md.mesh.numberofvertices,1))
 md.masstransport.stabilization=1.
 
