Index: /issm/trunk/CMakeLists.txt
===================================================================
--- /issm/trunk/CMakeLists.txt	(revision 16136)
+++ /issm/trunk/CMakeLists.txt	(revision 16137)
@@ -13,24 +13,7 @@
 # }}}
 
-# Environment Variables {{{
-# Out of source build can be done here.
-set(CMAKE_BINARY_DIR ${ISSM_DIR})
-# }}}
-
-# Install Targets {{{
-# Install 'issm.exe'
-#install(TARGETS issm RUNTIME)
-
-# Install 'libISSMCore.a' and 'libISSMOverload.a'
-# install(TARGETS ISSMCore
-#                ISSMOverload
-#        ARCHIVE)
-# }}}
-# Optional Install {{{
-#if(${SHARED_LIBS} IS ON)
-#   install(TARGETS ISSMCore
-#                   ISSMOverload
-#           LIBRARY)
-#endif(${SHARED_LIBS} IS ON)
+# CMake Modules {{{
+include(CheckLanguage)
+include(./m4/issm_options.cmake)
 # }}}
 
Index: /issm/trunk/Makefile.am
===================================================================
--- /issm/trunk/Makefile.am	(revision 16136)
+++ /issm/trunk/Makefile.am	(revision 16137)
@@ -1,6 +1,5 @@
 EXTRA_DIST = reconf scripts test m4 examples cron etc doc packages contributors.txt 
 SUBDIRS = src
-bin_SCRIPTS=config.h startup.m README.rtf
+bin_SCRIPTS= README.rtf
 
 ACLOCAL_AMFLAGS = -I m4
-
Index: /issm/trunk/configs/config-arm-linux.sh
===================================================================
--- /issm/trunk/configs/config-arm-linux.sh	(revision 16136)
+++ /issm/trunk/configs/config-arm-linux.sh	(revision 16137)
@@ -3,5 +3,5 @@
 ./configure \
    --prefix=$ISSM_DIR\
-   --libdir=$ISSM_DIR/src/mobile/android/ISSM_APP/libs/armeabi\
+   --libdir=$ISSM_DIR/../mobile/android/ISSM_APP/libs/armeabi\
    --build="i386-apple-darwin10.8.0"\
    --host="arm-linux-androideabi"\
@@ -12,4 +12,3 @@
    --without-wrappers\
    --without-kriging\
-   --with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install\
-   --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install\
+   --with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install
Index: /issm/trunk/configs/config-discover.sh
===================================================================
--- /issm/trunk/configs/config-discover.sh	(revision 16136)
+++ /issm/trunk/configs/config-discover.sh	(revision 16137)
@@ -6,5 +6,5 @@
 ./configure \
  --prefix=$ISSM_DIR \
- --with-matlab-dir=$MATLAB_DIR \
+ --with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
  --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
  --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
Index: /issm/trunk/configs/config-linux64-ad.sh
===================================================================
--- /issm/trunk/configs/config-linux64-ad.sh	(revision 16136)
+++ /issm/trunk/configs/config-linux64-ad.sh	(revision 16137)
@@ -8,5 +8,5 @@
 	--without-control \
 	--without-hydrology \
-	--without-diagnostic \
+	--without-stressbalance \
 	--without-balanced \
 	--without-responses \
Index: /issm/trunk/configs/config-linux64-cmake.sh
===================================================================
--- /issm/trunk/configs/config-linux64-cmake.sh	(revision 16137)
+++ /issm/trunk/configs/config-linux64-cmake.sh	(revision 16137)
@@ -0,0 +1,2 @@
+rm $ISSM_DIR/CMakeCache.txt
+cmake -D GSL_DIR=${GSL_DIR} ${ISSM_DIR}
Index: /issm/trunk/configs/config-linux64-larsen-ad.sh
===================================================================
--- /issm/trunk/configs/config-linux64-larsen-ad.sh	(revision 16136)
+++ /issm/trunk/configs/config-linux64-larsen-ad.sh	(revision 16137)
@@ -8,4 +8,4 @@
 	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
 	--with-adolc-version=3 \
-	--with-matlab-dir=$MATLAB_DIR \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
Index: /issm/trunk/configs/config-linux64-larsen-gia.sh
===================================================================
--- /issm/trunk/configs/config-linux64-larsen-gia.sh	(revision 16136)
+++ /issm/trunk/configs/config-linux64-larsen-gia.sh	(revision 16137)
@@ -22,5 +22,4 @@
  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-scotch-dir="$ISSM_DIR/externalpackages/scotch/install" \
  --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
  --with-shapelib-dir="$ISSM_DIR/externalpackages/shapelib/install" \
Index: sm/trunk/configs/config-linux64-larsen-petsc3.2.sh
===================================================================
--- /issm/trunk/configs/config-linux64-larsen-petsc3.2.sh	(revision 16136)
+++ 	(revision )
@@ -1,34 +1,0 @@
-#!/bin/sh
-
-#External packages versions:
-#petsc 3.1 or 3.2
-#mpich 1.4
-
-./configure \
- --prefix=$ISSM_DIR \
- --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-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-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
- --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
- --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 \
- --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/ \
- --with-scotch-dir="$ISSM_DIR/externalpackages/scotch/install" \
- --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
- --with-shapelib-dir="$ISSM_DIR/externalpackages/shapelib/install" \
- --with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.6/ -lgfortran" \
- --with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
- --with-cxxoptflags="-march=opteron -O2" \
- --with-numthreads=16 \
- --enable-debugging
Index: /issm/trunk/configs/config-linux64-larsen.sh
===================================================================
--- /issm/trunk/configs/config-linux64-larsen.sh	(revision 16136)
+++ /issm/trunk/configs/config-linux64-larsen.sh	(revision 16137)
@@ -15,15 +15,11 @@
  --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
  --with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
- --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
  --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 \
  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-scotch-dir="$ISSM_DIR/externalpackages/scotch/install" \
  --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
- --with-shapelib-dir="$ISSM_DIR/externalpackages/shapelib/install" \
  --with-fortran-lib="-L/usr/lib/gcc/x86_64-linux-gnu/4.6/ -lgfortran" \
  --with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
Index: /issm/trunk/configs/config-linux64-murdo-ad.sh
===================================================================
--- /issm/trunk/configs/config-linux64-murdo-ad.sh	(revision 16136)
+++ /issm/trunk/configs/config-linux64-murdo-ad.sh	(revision 16137)
@@ -7,4 +7,4 @@
 	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
 	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
-	--with-matlab-dir=$MATLAB_DIR \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install
Index: /issm/trunk/configs/config-linux64-murdo-nopetsc.sh
===================================================================
--- /issm/trunk/configs/config-linux64-murdo-nopetsc.sh	(revision 16136)
+++ /issm/trunk/configs/config-linux64-murdo-nopetsc.sh	(revision 16137)
@@ -1,27 +1,16 @@
 #!/bin/sh
-
 ./configure \
- --prefix=$ISSM_DIR \
- --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
- --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich" \
- --with-matlab-dir=$MATLAB_DIR \
- --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
- --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
- --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install/lib \
- --with-graphics-lib=/usr/lib64/libX11.so \
- --with-scotch-dir="$ISSM_DIR/externalpackages/scotch/install" \
- --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
- --with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
- --with-numthreads=18 \
- --enable-debugging \
- --with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install
- 
- 
-# --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
-# --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" \
-# --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
-# --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
-# --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
-# --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+	--prefix=$ISSM_DIR\
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-metis-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" \
+	--with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
+	--with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
+	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install\
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-numthreads=18  \
+	--enable-debugging 
Index: /issm/trunk/configs/config-linux64-murdo.sh
===================================================================
--- /issm/trunk/configs/config-linux64-murdo.sh	(revision 16136)
+++ /issm/trunk/configs/config-linux64-murdo.sh	(revision 16137)
@@ -6,5 +6,5 @@
 ./configure \
 	--prefix=$ISSM_DIR \
-	--with-matlab-dir=$MATLAB_DIR \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
 	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
@@ -19,9 +19,8 @@
 	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
 	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
 	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
-	--with-scotch-dir="$ISSM_DIR/externalpackages/scotch/install" \
-	--with-graphics-lib=/usr/lib64/libX11.so \
+	--with-graphics-lib="/usr/lib/x86_64-linux-gnu/libX11.so" \
 	--with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
 	--with-numthreads=18 \
 	--enable-debugging 
+	#--with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
Index: /issm/trunk/configs/config-linux64-ubuntu64.sh
===================================================================
--- /issm/trunk/configs/config-linux64-ubuntu64.sh	(revision 16136)
+++ /issm/trunk/configs/config-linux64-ubuntu64.sh	(revision 16137)
@@ -3,5 +3,5 @@
 ./configure \
  --prefix=$ISSM_DIR \
- --with-matlab-dir=$MATLAB_DIR \
+ --with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
  --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
  --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
@@ -16,5 +16,4 @@
  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-scotch-dir="$ISSM_DIR/externalpackages/scotch/install" \
  --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
  --with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
Index: /issm/trunk/configs/config-macosx64-ad.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-ad.sh	(revision 16136)
+++ /issm/trunk/configs/config-macosx64-ad.sh	(revision 16137)
@@ -8,5 +8,5 @@
 	--without-control \
 	--without-hydrology \
-	--without-diagnostic \
+	--without-stressbalance \
 	--without-balanced \
 	--without-responses \
Index: sm/trunk/configs/config-macosx64-nicole.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-nicole.sh	(revision 16136)
+++ 	(revision )
@@ -1,26 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-export F77='/usr/local/gfortran/bin/x86_64-apple-darwin10-gfortran'
-
-./configure \
-	--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-petsc-dir=$ISSM_DIR/externalpackages/petsc/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-petsc-arch=$ISSM_ARCH \
-	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
-	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
-	--with-fortran-lib="/usr/local/gfortran/lib/gcc/x86_64-apple-darwin10/4.6.2/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
-	--with-numthreads=8
Index: sm/trunk/configs/config-macosx64-ogive.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-ogive.sh	(revision 16136)
+++ 	(revision )
@@ -1,31 +1,0 @@
-#!/bin/sh
-
-#petsc 3.2
-#mpich 1.4
-export FCFLAGS=" -m64"
-export FFLAGS=" -m64"
-export CFLAGS=" -arch x86_64"
-export CXXFLAGS=" -arch x86_64"
-
-./configure \
-	--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-petsc-dir=$ISSM_DIR/externalpackages/petsc/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-petsc-arch=$ISSM_ARCH \
-	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
-	--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/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/ \
-	--with-fortran-lib="/usr/local/gfortran/lib/x86_64/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
-	--with-numthreads=8
-	#--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
Index: /issm/trunk/configs/config-macosx64.sh
===================================================================
--- /issm/trunk/configs/config-macosx64.sh	(revision 16136)
+++ /issm/trunk/configs/config-macosx64.sh	(revision 16137)
@@ -1,27 +1,24 @@
 #!/bin/sh
 
-#petsc 3.2
-#mpich 1.4
-#python 2.7
+#petsc 3.4
+#mpich 3.0.4
 
 ./configure \
 	--prefix=$ISSM_DIR \
 	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
-	--with-python-dir="$ISSM_DIR/externalpackages/python/install" \
-	--with-python-numpy-dir="$ISSM_DIR/externalpackages/python/install/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/include/numpy" \
-	--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-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/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-petsc-arch=$ISSM_ARCH \
+	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/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-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
-	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
+	--with-fortran-lib="/usr/lib/gcc/i686-apple-darwin10/4.2.1/x86_64/libgfortran.a" \
 	--with-math-lib="/usr/lib/libm.dylib" \
 	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-numthreads=8 \
-	--with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-petsc-arch="$ISSM_ARCH" \
-	--with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
-	--with-blacs-dir="$ISSM_DIR/externalpackages/petsc/install/" \
-	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install/" \
-	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install/" \
-	--with-dakota-dir="$ISSM_DIR/externalpackages/dakota/install" 
+	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
+	--with-numthreads=8
Index: /issm/trunk/configs/config-pleiades-petsc3.4.sh
===================================================================
--- /issm/trunk/configs/config-pleiades-petsc3.4.sh	(revision 16136)
+++ /issm/trunk/configs/config-pleiades-petsc3.4.sh	(revision 16137)
@@ -10,5 +10,5 @@
  --with-mpi-libflags="-L/nasa/sgi/mpt/2.06rp16/ -lmpi" \
  --with-mkl-dir="/nasa/intel/Compiler/2013.1.117/composer_xe_2013.1.117/mkl/lib/intel64" \
- --with-petsc-arch=$ISSM_ARCH \
+ --with-gsl-dir="$ISSM_DIR/externalpackages/gsl/install" \
  --with-dakota-dir="$ISSM_DIR/externalpackages/dakota/install" \
  --with-metis-dir="$ISSM_DIR/externalpackages/petsc/install" \
Index: sm/trunk/configs/config-walgreen.sh
===================================================================
--- /issm/trunk/configs/config-walgreen.sh	(revision 16136)
+++ 	(revision )
@@ -1,17 +1,0 @@
-#!/bin/csh
-
-./configure \
- --prefix=$ISSM_DIR \
- --with-wrappers=no \
- --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
- --with-petsc-arch=$ISSM_ARCH \
- --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
- --with-mpi-include=$ISSM_DIR/externalpackages/mpich/install/include  \
- --with-mpi-libflags="-L$ISSM_DIR/externalpackages/mpich/install/lib/ -lmpich -lmpl " \
- --with-mkl-dir="/opt/intel/mkl/10.0.1.014/lib/64/lib/" \
- --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/lib/libX11.so" \
- --with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
- --with-cxxoptflags="-O3 " 
Index: /issm/trunk/configs/config-win7-32.sh
===================================================================
--- /issm/trunk/configs/config-win7-32.sh	(revision 16136)
+++ /issm/trunk/configs/config-win7-32.sh	(revision 16137)
@@ -5,5 +5,5 @@
    --disable-static \
    --with-vendor=intel-win7-32  \
-   --with-matlab-dir="$MATLAB_DIR" \
+   --with-matlab-dir=""$ISSM_DIR/externalpackages/matlab/install"" \
    --with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
    --with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
Index: /issm/trunk/configs/config-win7-64.sh
===================================================================
--- /issm/trunk/configs/config-win7-64.sh	(revision 16136)
+++ /issm/trunk/configs/config-win7-64.sh	(revision 16137)
@@ -5,5 +5,5 @@
    --disable-static \
 	--with-vendor=intel-win7-64  \
-	--with-matlab-dir="$MATLAB_DIR" \
+	--with-matlab-dir=""$ISSM_DIR/externalpackages/matlab/install"" \
 	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
 	--with-metis-dir="$ISSM_DIR/externalpackages/metis/install" \
Index: /issm/trunk/configure.ac
===================================================================
--- /issm/trunk/configure.ac	(revision 16136)
+++ /issm/trunk/configure.ac	(revision 16137)
@@ -2,5 +2,5 @@
 
 #AUTOCONF
-AC_INIT([ISSM],[4.3],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_INIT([ISSM],[4.4],[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
@@ -33,13 +33,15 @@
 
 #List all Makefiles
-AC_CONFIG_FILES([Makefile
-			src/Makefile
-			src/c/Makefile 
-			src/wrappers/Makefile
-			src/wrappers/python/Makefile
-			src/wrappers/matlab/Makefile
-			src/mobile/Makefile
-			src/mobile/native/Makefile
-			src/m/Makefile])
+AC_CONFIG_FILES([
+					  Makefile
+					  src/Makefile
+					  src/c/Makefile 
+					  src/wrappers/Makefile
+					  src/wrappers/python/Makefile
+					  src/wrappers/matlab/Makefile
+					  src/mobile/Makefile
+					  src/mobile/native/Makefile
+					  src/m/Makefile
+					  ])
 
 #End of configure.ac
Index: /issm/trunk/etc/environment.sh
===================================================================
--- /issm/trunk/etc/environment.sh	(revision 16136)
+++ /issm/trunk/etc/environment.sh	(revision 16137)
@@ -53,7 +53,4 @@
 	source $ISSM_DIR/externalpackages/windows/windows_environment.sh
 fi
-
-#Some basic path, in case it is not included by default
-libpathappend "/usr/local/lib"
 
 #Load ISSM scripts
@@ -219,8 +216,7 @@
 if [ -d "$PYTHON_DIR" ]; then
 	export PYTHONPATH="$PYTHONPATH:$ISSM_DIR/lib"
-	export PYTHONSTARTUP="$ISSM_DIR/startup.py"
 	pathprepend    "$PYTHON_DIR/bin"
+	libpathprepend "$PYTHON_DIR/lib"
 	libpathprepend "$ISSM_DIR/lib"
-	libpathprepend "$PYTHON_DIR/lib"
 fi
 
@@ -286,2 +282,5 @@
 #AUX-CONFIG
 pathappend   "$ISSM_DIR/aux-config"
+
+#INISHELL
+pathappend   "$ISSM_DIR/externalpackages/inishell/install"
Index: /issm/trunk/examples/Mesh/Square.exp
===================================================================
--- /issm/trunk/examples/Mesh/Square.exp	(revision 16137)
+++ /issm/trunk/examples/Mesh/Square.exp	(revision 16137)
@@ -0,0 +1,10 @@
+## Name:Square
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+0 0
+1 0
+1 1
+0 1
+0 0
Index: /issm/trunk/examples/Mesh/circles.m
===================================================================
--- /issm/trunk/examples/Mesh/circles.m	(revision 16137)
+++ /issm/trunk/examples/Mesh/circles.m	(revision 16137)
@@ -0,0 +1,7 @@
+function vel=circles(x,y),
+
+u=4*x-2; v=4*y-2;
+
+vel=tanh(30*(u.^2+v.^2-0.25)) ...
+	+tanh(30*((u-0.75).^2+(v-0.75).^2-0.25)) +tanh(30*((u-0.75).^2+(v+0.75).^2-0.25)) ...
+	+tanh(30*((u+0.75).^2+(v-0.75).^2-0.25)) +tanh(30*((u+0.75).^2+(v+0.75).^2-0.25)) ;
Index: /issm/trunk/examples/Mesh/shock.m
===================================================================
--- /issm/trunk/examples/Mesh/shock.m	(revision 16137)
+++ /issm/trunk/examples/Mesh/shock.m	(revision 16137)
@@ -0,0 +1,3 @@
+function vel=shock(x,y),
+
+vel=exp(-(sqrt((x+0.1).^2+(y+0.1).^2)-0.75).^2*10^6)+((x+0.1).^2+(y+0.1).^2)/2;
Index: /issm/trunk/externalpackages/adjoinablempi/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/adjoinablempi/install-macosx64.sh	(revision 16137)
+++ /issm/trunk/externalpackages/adjoinablempi/install-macosx64.sh	(revision 16137)
@@ -0,0 +1,29 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src  install
+
+#Mercurial cloning: 
+hg clone http://mercurial.mcs.anl.gov//ad/AdjoinableMPI src
+
+export C_INCLUDE_PATH=:/usr/include/sys/:$C_INCLUDE_PATH
+
+#Configure adjoinablempi
+cd src
+autoreconf -fi
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/adjoinablempi/install" \
+	--libdir="$ISSM_DIR/externalpackages/adjoinablempi/install/lib" \
+	--with-mpi-root="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-requestOnTrace
+
+#Compile adjoinablempi 
+make clean
+if [ $# -eq 0 ]; then
+	make 
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/adjoinablempi/install.sh
===================================================================
--- /issm/trunk/externalpackages/adjoinablempi/install.sh	(revision 16137)
+++ /issm/trunk/externalpackages/adjoinablempi/install.sh	(revision 16137)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src  install
+
+#Mercurial cloning: 
+hg clone http://mercurial.mcs.anl.gov//ad/AdjoinableMPI src
+
+#Configure adjoinablempi
+cd src
+autoreconf -fi
+
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/adjoinablempi/install" \
+	--libdir="$ISSM_DIR/externalpackages/adjoinablempi/install/lib" \
+	--with-mpi-root="$ISSM_DIR/externalpackages/mpich/install" \
+	--enable-requestOnTrace
+
+#Compile adjoinablempi 
+make clean
+if [ $# -eq 0 ]; then
+	make 
+else
+	make -j $1
+fi
+make install
Index: sm/trunk/externalpackages/adolc/install-2.2.0.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-2.2.0.sh	(revision 16136)
+++ 	(revision )
@@ -1,60 +1,0 @@
-#!/bin/bash
-set -eu
-
-#some issues on macosx64 with ISSM's autoconf. you might want to run native to mac on this.
-
-#Some cleanup
-rm -rf install ADOL-C-2.2.0 src trunk
-
-#Create install directories
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ADOL-C-2.2.0.tar.gz' 'ADOL-C-2.2.0.tar.gz'
-
-#Untar 
-tar -zxvf  ADOL-C-2.2.0.tar.gz
-
-#Move ADOL-C into install directory
-mv ADOL-C-2.2.0/* src
-rm -rf ADOL-C-2.2.0
-
-#Compile ADOL-C
-cd src 
-
-#export CC=gcc
-#export CXX=g++
-#export CFLAGS="-arch x86_64"
-#export CXXFLAGS="-arch x86_64"
-
-./configure \
-	--prefix=$ISSM_DIR/externalpackages/adolc/install \
-	--enable-sparse \
-	--enable-docexa \
-	--enable-addexa \
-	--disable-shave
-
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
-
-
-#Ok, bug with libtool: replace all LIBTOOL= by LIBTOOL=libtool 
-#in all Makefiles
-for i in `find ./ -name Makefile `
-do
-	echo $i
-	cat $i | sed 's/LIBTOOL =/LIBTOOL = libtool/g' > $i.bak 
-	mv $i.bak $i
-done
-
-#remake: 
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
Index: sm/trunk/externalpackages/adolc/install-dev.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-dev.sh	(revision 16136)
+++ 	(revision )
@@ -1,21 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf install adolc*issm
-
-git clone -b 2.3.x_ISSM  git://git.mcs.anl.gov/adol-c.git adolc_issm
-#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
-
-#Compile ADOL-C
-cd adolc_issm
-
-autoreconf -f -i 
-./configure --prefix=$ISSM_DIR/externalpackages/adolc/install 
-
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
Index: sm/trunk/externalpackages/adolc/install-update-dev.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-update-dev.sh	(revision 16136)
+++ 	(revision )
@@ -1,27 +1,0 @@
-#!/bin/bash
-set -eu
-
-#This script is very specific to the larour larsen nightly using adolc. 
-#It relies on just an update of adolc, and symlink to an existing adolc 
-#repo. 
-
-#Some cleanup
-rm -rf install adolc_issm
-
-#symlink: 
-ln -s /proj/ice/larour2/issm-uci/trunk-jpl/externalpackages/adolc/adolc_issm ./adolc_issm
-
-#update and compile
-cd adolc_issm
-git pull
-#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
-
-autoreconf -f -i 
-./configure --prefix=$ISSM_DIR/externalpackages/adolc/install 
-
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
Index: /issm/trunk/externalpackages/adolc/install-withampi-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-withampi-macosx64.sh	(revision 16137)
+++ /issm/trunk/externalpackages/adolc/install-withampi-macosx64.sh	(revision 16137)
@@ -0,0 +1,30 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+
+git clone -b ampi git://git.mcs.anl.gov/adol-c.git src
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+#Compile ADOL-C
+cd src
+autoreconf -f -i 
+
+export CFLAGS="-O2 -L$ISSM_DIR/externalpackages/mpich/install/lib -lpmpich"
+export CXXFLAGS="-O2 -L$ISSM_DIR/externalpackages/mpich/install/lib -lpmpich"
+
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install  \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib \
+	--with-mpi-root=$ISSM_DIR/externalpackages/mpich/install \
+	--enable-ampi \
+	--with-ampi=$ISSM_DIR/externalpackages/adjoinablempi/install \
+	--disable-tapedoc-values
+
+make clean
+if [ $# -eq 0 ]; then
+	make V=1
+else
+	make -j $1 V=1
+fi
+make V=1 install
Index: /issm/trunk/externalpackages/adolc/install-withampi.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-withampi.sh	(revision 16137)
+++ /issm/trunk/externalpackages/adolc/install-withampi.sh	(revision 16137)
@@ -0,0 +1,27 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+
+git clone -b ampi git://git.mcs.anl.gov/adol-c.git src
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+#Compile ADOL-C
+cd src
+autoreconf -f -i 
+
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install  \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib \
+	--with-mpi-root=$ISSM_DIR/externalpackages/mpich/install \
+	--enable-ampi \
+	--with-ampi=$ISSM_DIR/externalpackages/adjoinablempi/install \
+	--disable-tapedoc-values
+
+make clean
+if [ $# -eq 0 ]; then
+	make V=1
+else
+	make -j $1 V=1
+fi
+make V=1 install
Index: /issm/trunk/externalpackages/adolc/install.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install.sh	(revision 16137)
+++ /issm/trunk/externalpackages/adolc/install.sh	(revision 16137)
@@ -0,0 +1,22 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+
+git clone -b ampi git://git.mcs.anl.gov/adol-c.git src
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+#Compile ADOL-C
+cd src
+
+autoreconf -f -i 
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib 
+
+if [ $# -eq 0 ]; then
+	make V=1
+else
+	make -j $1 V=1
+fi
+make V=1 install
Index: /issm/trunk/externalpackages/adolc/old/install-2.2.0.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/old/install-2.2.0.sh	(revision 16137)
+++ /issm/trunk/externalpackages/adolc/old/install-2.2.0.sh	(revision 16137)
@@ -0,0 +1,60 @@
+#!/bin/bash
+set -eu
+
+#some issues on macosx64 with ISSM's autoconf. you might want to run native to mac on this.
+
+#Some cleanup
+rm -rf install ADOL-C-2.2.0 src trunk
+
+#Create install directories
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ADOL-C-2.2.0.tar.gz' 'ADOL-C-2.2.0.tar.gz'
+
+#Untar 
+tar -zxvf  ADOL-C-2.2.0.tar.gz
+
+#Move ADOL-C into install directory
+mv ADOL-C-2.2.0/* src
+rm -rf ADOL-C-2.2.0
+
+#Compile ADOL-C
+cd src 
+
+#export CC=gcc
+#export CXX=g++
+#export CFLAGS="-arch x86_64"
+#export CXXFLAGS="-arch x86_64"
+
+./configure \
+	--prefix=$ISSM_DIR/externalpackages/adolc/install \
+	--enable-sparse \
+	--enable-docexa \
+	--enable-addexa \
+	--disable-shave
+
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+
+#Ok, bug with libtool: replace all LIBTOOL= by LIBTOOL=libtool 
+#in all Makefiles
+for i in `find ./ -name Makefile `
+do
+	echo $i
+	cat $i | sed 's/LIBTOOL =/LIBTOOL = libtool/g' > $i.bak 
+	mv $i.bak $i
+done
+
+#remake: 
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/adolc/old/update.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/old/update.sh	(revision 16137)
+++ /issm/trunk/externalpackages/adolc/old/update.sh	(revision 16137)
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+cd adolc_issm
+git pull
+
+autoreconf -f -i 
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install 
+
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/adolc/update-existing.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/update-existing.sh	(revision 16137)
+++ /issm/trunk/externalpackages/adolc/update-existing.sh	(revision 16137)
@@ -0,0 +1,29 @@
+#!/bin/bash
+set -eu
+
+#This script is very specific to the larour larsen nightly using adolc. 
+#It relies on just an update of adolc, and symlink to an existing adolc 
+#repo. 
+
+#Some cleanup
+rm -rf install src
+
+#symlink: 
+ln -s /proj/ice/larour2/issm-uci/trunk-jpl/externalpackages/adolc/adolc_issm ./src
+
+#update and compile
+cd src
+git pull origin
+git checkout ampi
+#git reset --hard b254b2a001a1b7a024a9184cd087ae06eb975cad
+
+autoreconf -f -i 
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install \
+	--libdir=$ISSM_DIR/externalpackages/adolc/install/lib 
+
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: sm/trunk/externalpackages/adolc/update.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/update.sh	(revision 16136)
+++ 	(revision )
@@ -1,14 +1,0 @@
-#!/bin/bash
-
-cd adolc_issm
-git pull
-
-autoreconf -f -i 
-./configure --prefix=$ISSM_DIR/externalpackages/adolc/install 
-
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
Index: /issm/trunk/externalpackages/atlas/install.sh
===================================================================
--- /issm/trunk/externalpackages/atlas/install.sh	(revision 16137)
+++ /issm/trunk/externalpackages/atlas/install.sh	(revision 16137)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install ATLAS build
+mkdir src install build
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/atlas3.10.0.tar.bz2' 'atlas3.10.0.tar.bz2'
+
+#Untar 
+tar -zxvf  atlas3.10.0.tar.bz2
+
+#Move atlas into src directory
+mv ATLAS/* src
+rm -rf ATLAS
+
+#Configure atlas
+cd build
+
+export CFLAGS=" -arch x86_64"
+
+../src/configure \
+	--prefix="$ISSM_DIR/externalpackages/atlas/install" 
+
+#Compile atlas
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/dakota/configs/5.3.1/ParallelLibrary.cpp.patch
===================================================================
--- /issm/trunk/externalpackages/dakota/configs/5.3.1/ParallelLibrary.cpp.patch	(revision 16136)
+++ /issm/trunk/externalpackages/dakota/configs/5.3.1/ParallelLibrary.cpp.patch	(revision 16137)
@@ -3,21 +3,16 @@
 133a135
 >   initialized=0; //we run serially all the time!
-141a144,176
+141a144,171
 > /** This constructor is provided for the ISSM software, to run serial
 >  * Dakota in a parallel MPI ring: */
 > ParallelLibrary::ParallelLibrary(char* serial_mode):
->   worldRank(0), worldSize(1),
+>   dakotaMPIComm(MPI_COMM_WORLD), worldRank(0), worldSize(1),
 >   mpirunFlag(false), ownMPIFlag(false), dummyFlag(false),
 >   stdOutputToFile(false), stdErrorToFile(false), checkFlag(false),
 >   preRunFlag(true), runFlag(true), postRunFlag(true), userModesFlag(false),
->   startClock(0), stopRestartEvals(0),
+>   outputTimings(true), startClock(0), stopRestartEvals(0),
 >   currPLIter(parallelLevels.end()), currPCIter(parallelConfigurations.end())
 > {
->   startClock   = clock();
-> #ifdef DAKOTA_UTILIB
->   utilib::exception_mngr::set_mode(utilib::exception_mngr::Abort);
->   startCPUTime = CPUSeconds();       // see utilib/src/sys/seconds.cpp
->   startWCTime  = WallClockSeconds(); // see utilib/src/sys/seconds.cpp
-> #endif // DAKOTA_UTILIB
+>   initialize_timers();
 > 
 >   // do not initialize MPI.  Get worldRank/worldSize if available
@@ -25,8 +20,8 @@
 > #ifdef HAVE_MPI // mpi available, we still don't want to run in parallel for Dakota!
 >   pl.serverIntraComm = MPI_COMM_NULL;
->   Cout << "Running Dakota 5.3.1 MPI executable in serial mode on CPU 0 for ISSM.";
+>   Cout << "Running Dakota 5.3.1 MPI executable in serial mode on CPU 0 for ISSM." << std::endl;
 > #else // mpi not available
 >   pl.serverIntraComm = MPI_COMM_NULL;
->   Cout << "Running Dakota 5.3.1 serial executable in serial mode for ISSM.\n";
+>   Cout << "Running Dakota 5.3.1 serial executable in serial mode for ISSM." << std::endl;
 > #endif // HAVE_MPI
 > 
@@ -37,4 +32,4 @@
 > 
 > 
-1536a1572
+1536a1567
 >   initialized=0; //we run serially all the time!
Index: /issm/trunk/externalpackages/doxygen/install.sh
===================================================================
--- /issm/trunk/externalpackages/doxygen/install.sh	(revision 16136)
+++ /issm/trunk/externalpackages/doxygen/install.sh	(revision 16137)
@@ -7,5 +7,5 @@
 
 #Download latest version
-svn co https://doxygen.svn.sourceforge.net/svnroot/doxygen/trunk src
+svn co https://svn.code.sf.net/p/doxygen/code/trunk src
 
 #Configure doxygen
Index: /issm/trunk/externalpackages/inishell/install.sh
===================================================================
--- /issm/trunk/externalpackages/inishell/install.sh	(revision 16137)
+++ /issm/trunk/externalpackages/inishell/install.sh	(revision 16137)
@@ -0,0 +1,40 @@
+#!/bin/bash
+#inishell install package:  this package is not distributed by ISSM. Please request access to the code by 
+#contacting Mathias Bavay () or logging onto http://models.slf.ch/ and registering.  Once you have a tarball 
+#of the code, please use this script to install.
+
+#we assume you have a inishell-src-*.tgz  tarball
+set -eu
+
+#Do some inquiry about the names of the tar balls: 
+source_tar=`ls inishell-src-*.tgz`
+source_version=`echo $source_tar | sed 's/inishell-src-//g' | sed 's/.tgz//g'`
+
+if [[ $source_tar == "" ]]; then 
+	echo "Could not identify a tar ball for the source code, name should be inishell-src-*.tgz"
+	exit 1
+fi
+if [[ $source_version == "" ]]; then 
+	echo "Could not identify a tar ball version for the source code"
+	exit 1
+fi
+
+
+#Some cleanup
+rm -rf src install inishell-$source_version
+mkdir install
+
+#First deal with source code 
+tar -zxvf  $source_tar
+mv inishell-$source_version src
+rm -rf inishell-$source_version
+
+#Build inishell
+cd src && ant snowpack
+
+#Put the .jar in the install directory
+cp dist/inishell.jar ../install
+
+#Install script to launch inishell jar file directly
+cd ..
+cp scripts/inishell install
Index: /issm/trunk/externalpackages/inishell/scripts/inishell
===================================================================
--- /issm/trunk/externalpackages/inishell/scripts/inishell	(revision 16137)
+++ /issm/trunk/externalpackages/inishell/scripts/inishell	(revision 16137)
@@ -0,0 +1,3 @@
+#/bin/bash
+
+java -jar $ISSM_DIR/externalpackages/inishell/install/inishell.jar
Index: /issm/trunk/externalpackages/ipython/install.sh
===================================================================
--- /issm/trunk/externalpackages/ipython/install.sh	(revision 16136)
+++ /issm/trunk/externalpackages/ipython/install.sh	(revision 16137)
@@ -4,16 +4,16 @@
 #Some cleanup
 rm -rf src
-rm -rf ipython-0.13
+rm -rf ipython-1.0.0
 mkdir src 
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ipython-0.13.tar.gz' 'ipython-0.13.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ipython-1.0.0.tar.gz' 'ipython-1.0.0.tar.gz'
 
 #Untar 
-tar -zxvf  ipython-0.13.tar.gz
+tar -zxvf  ipython-1.0.0.tar.gz
 
 #Move ipython into src directory
-mv ipython-0.13/* src
-rm -rf ipython-0.13
+mv ipython-1.0.0/* src
+rm -rf ipython-1.0.0
 
 #install  ipython
Index: /issm/trunk/externalpackages/matplotlib/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/matplotlib/install-macosx64.sh	(revision 16136)
+++ /issm/trunk/externalpackages/matplotlib/install-macosx64.sh	(revision 16137)
@@ -1,4 +1,6 @@
 #/bin/bash
 set -eu
+
+rm -rf src deps 
 
 export C_INCLUDE_PATH="$C_INCLUDE_PATH:/usr/include/c++/4.2.1"
@@ -23,4 +25,7 @@
 #python -c "import matplotlib; print 'Installed matplotlib', matplotlib.__version__, matplotlib.__file__"
 
+#comments: try exporting this first before calling python setup.py build
+CFLAGS=-mmacosx-version-min=10.7 
+
 #to be tried:  first get freetype and zlib and libpng installed in sudo mode
 python setup.py build
Index: /issm/trunk/externalpackages/meteoio/install.sh
===================================================================
--- /issm/trunk/externalpackages/meteoio/install.sh	(revision 16137)
+++ /issm/trunk/externalpackages/meteoio/install.sh	(revision 16137)
@@ -0,0 +1,39 @@
+#!/bin/bash
+#METEOIO install package:  this package is not distributed by ISSM. Please request access to the code by 
+#contacting Mathias Bavay () or logging onto http://models.slf.ch/ and registering.  Once you have a tarball 
+#of the code, please use this script to install.
+
+#we assume you have a MeteoIO-*-tar.gz  tarball
+set -eu
+
+#Do some inquiry about the names of the tar balls: 
+source_tar=`ls MeteoIO-*.tar.gz`
+source_version=`echo $source_tar | sed 's/MeteoIO-//g' | sed 's/.tar.gz//g'`
+
+if [[ $source_tar == "" ]]; then 
+	echo "Could not identify a tar ball for the source code, name should be MeteoIO-*-tar.gz"
+	exit 1
+fi
+if [[ $source_version == "" ]]; then 
+	echo "Could not identify a tar ball version for the source code"
+	exit 1
+fi
+
+#Some cleanup
+rm -rf src install MeteoIO-$source_version
+
+#First deal with source code 
+tar -zxvf  $source_tar
+mv MeteoIO-$source_version/usr src
+rm -rf MeteoIO-$source_version
+
+#Reset makefile: 
+cd src && rm -rf CMakeCache.txt 
+cmake -DCMAKE_INSTALL_PREFIX:PATH=$ISSM_DIR/externalpackages/meteoio/install .
+
+#Compile 
+if [ $# -eq 0 ]; then
+	make all install
+else
+	make -j $1 all install
+fi
Index: /issm/trunk/externalpackages/mpich/install-3.0-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich/install-3.0-linux64.sh	(revision 16136)
+++ /issm/trunk/externalpackages/mpich/install-3.0-linux64.sh	(revision 16137)
@@ -21,6 +21,5 @@
 	--prefix="$ISSM_DIR/externalpackages/mpich/install" \
 	--enable-shared \
-	--enable-sharedlibs=gcc \
-	--enable-f91=gfortran 
+	--enable-sharedlibs=gcc
 
 #Compile mpich (this new version supports parallel make)
Index: /issm/trunk/externalpackages/petsc/install-3.4-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-linux64.sh	(revision 16136)
+++ /issm/trunk/externalpackages/petsc/install-3.4-linux64.sh	(revision 16137)
@@ -3,14 +3,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.4.1 src
+rm -rf install petsc-3.4.2 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.1.tar.gz' 'petsc-3.4.1.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.2.tar.gz' 'petsc-3.4.2.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.4.1.tar.gz
-mv petsc-3.4.1/* src/
-rm -rf petsc-3.4.1
+tar -zxvf  petsc-3.4.2.tar.gz
+mv petsc-3.4.2/* src/
+rm -rf petsc-3.4.2
 
 #configure
Index: /issm/trunk/externalpackages/petsc/install-3.4-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-macosx64.sh	(revision 16136)
+++ /issm/trunk/externalpackages/petsc/install-3.4-macosx64.sh	(revision 16137)
@@ -3,14 +3,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.4.1 src
+rm -rf install petsc-3.4.2 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.1.tar.gz' 'petsc-3.4.1.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.2.tar.gz' 'petsc-3.4.2.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.4.1.tar.gz
-mv petsc-3.4.1/* src/
-rm -rf petsc-3.4.1
+tar -zxvf  petsc-3.4.2.tar.gz
+mv petsc-3.4.2/* src/
+rm -rf petsc-3.4.2
 
 #configure
Index: /issm/trunk/externalpackages/petsc/install-3.4-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.4-pleiades.sh	(revision 16136)
+++ /issm/trunk/externalpackages/petsc/install-3.4-pleiades.sh	(revision 16137)
@@ -2,14 +2,14 @@
 
 #Some cleanup
-rm -rf install petsc-3.4.1 src
+rm -rf install petsc-3.4.2 src
 mkdir install src
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.1.tar.gz' 'petsc-3.4.1.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.4.2.tar.gz' 'petsc-3.4.2.tar.gz'
 
 #Untar and move petsc to install directory
-tar -zxvf  petsc-3.4.1.tar.gz
-mv petsc-3.4.1/* src/
-rm -rf petsc-3.4.1
+tar -zxvf  petsc-3.4.2.tar.gz
+mv petsc-3.4.2/* src/
+rm -rf petsc-3.4.2
 
 #configure
Index: /issm/trunk/externalpackages/snowpack/install.sh
===================================================================
--- /issm/trunk/externalpackages/snowpack/install.sh	(revision 16137)
+++ /issm/trunk/externalpackages/snowpack/install.sh	(revision 16137)
@@ -0,0 +1,56 @@
+#!/bin/bash
+#SNOWPACK install package:  this package is not distributed by ISSM. Please request access to the code by 
+#contacting Mathias Bavay () or logging onto http://models.slf.ch/ and registering.  Once you have a tarball 
+#of the code, please use this script to install.
+
+#we assume you have a Snowpack-*-src.tar.gz  tarball
+set -eu
+
+#Do some inquiry about the names of the tar balls: 
+source_tar=`ls Snowpack-*-src.tar.gz`
+source_version=`echo $source_tar | sed 's/Snowpack-//g' | sed 's/-src.tar.gz//g'`
+
+if [[ $source_tar == "" ]]; then 
+	echo "Could not identify a tar ball for the source code, name should be Snowpack-*-src.tar.gz"
+	exit 1
+fi
+if [[ $source_version == "" ]]; then 
+	echo "Could not identify a tar ball version for the source code"
+	exit 1
+fi
+
+#Some cleanup
+rm -rf src install Snowpack-$source_version
+
+#First deal with source code 
+tar -zxvf  $source_tar
+mv Snowpack-$source_version/usr src
+rm -rf Snowpack-$source_version
+
+#Build library
+cd src && rm -rf CMakeCache.txt 
+cmake -DCMAKE_INSTALL_PREFIX:PATH=$ISSM_DIR/externalpackages/snowpack/install \
+	-DMETEOIO_INCLUDE_DIR:PATH=$ISSM_DIR/externalpackages/meteoio/install/include \
+	-DMETEOIO_LIBRARY:PATH=$ISSM_DIR/externalpackages/meteoio/install/lib/libmeteoio.dylib\
+	.
+	#-DCMAKE_VERBOSE_MAKEFILE=true \
+
+#Compile
+if [ $# -eq 0 ]; then
+	make  all install
+else
+	make -j $1  all install
+fi
+
+#Build binary: 
+cd applications/snowpack
+cmake -DCMAKE_MODULE_PATH:PATH=/Users/larour/issm-uci/trunk-jpl/externalpackages/snowpack/src/tools/cmake/      -DMETEOIO_INCLUDE_DIR:PATH=$ISSM_DIR/externalpackages/meteoio/install/include  .
+
+#Compile
+if [ $# -eq 0 ]; then
+	make  all install
+else
+	make -j $1  all install
+fi
+
+
Index: /issm/trunk/externalpackages/triangle/configs/altix64/configure.make
===================================================================
--- /issm/trunk/externalpackages/triangle/configs/altix64/configure.make	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/configs/altix64/configure.make	(revision 16137)
@@ -1,4 +1,4 @@
 CC=gcc
-CSWITCHES = $(CFLAGS) -I$(MATLAB_DIR)/extern/include  -I$(MATLAB_DIR)/include -DLIN64 -fPIC
+CSWITCHES = $(CFLAGS) -DNO_TIMER -DLINUX -fPIC
 OBJ_EXT=o
 LIB_EXT=a
Index: /issm/trunk/externalpackages/triangle/configs/android/configure.make
===================================================================
--- /issm/trunk/externalpackages/triangle/configs/android/configure.make	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/configs/android/configure.make	(revision 16137)
@@ -13,5 +13,5 @@
 AR=${host_triplet}-ar
 RANLIB=${host_triplet}-ranlib
-CSWITCHES = $(CFLAGS)
+CSWITCHES = $(CFLAGS) -DNO_TIMER 
 TRILIBDEFS = -DTRILIBRARY
 OBJ_EXT=o
Index: /issm/trunk/externalpackages/triangle/configs/linux64/configure.make
===================================================================
--- /issm/trunk/externalpackages/triangle/configs/linux64/configure.make	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/configs/linux64/configure.make	(revision 16137)
@@ -1,4 +1,4 @@
 CC=gcc
-CSWITCHES = $(CFLAGS) -I$(MATLAB_DIR)/extern/include  -I$(MATLAB_DIR)/include -DLIN64 -fPIC
+CSWITCHES = $(CFLAGS) -DNO_TIMER -DLINUX -fPIC
 OBJ_EXT=o
 LIB_EXT=a
Index: /issm/trunk/externalpackages/triangle/configs/macosx32/configure.make
===================================================================
--- /issm/trunk/externalpackages/triangle/configs/macosx32/configure.make	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/configs/macosx32/configure.make	(revision 16137)
@@ -1,4 +1,4 @@
 CC=gcc -arch i386
-CSWITCHES = $(CFLAGS)  -I/usr/X11R6/include -L/usr/X11R6/lib -I$(MATLAB_DIR)/extern/include -fPIC -I$(MATLAB_DIR)/include
+CSWITCHES = $(CFLAGS) -DNO_TIMER -fPIC 
 TRILIBDEFS = -DTRILIBRARY
 OBJ_EXT=o
Index: /issm/trunk/externalpackages/triangle/configs/macosx64/configure.make
===================================================================
--- /issm/trunk/externalpackages/triangle/configs/macosx64/configure.make	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/configs/macosx64/configure.make	(revision 16137)
@@ -1,4 +1,4 @@
 CC=gcc -arch x86_64
-CSWITCHES = $(CFLAGS)  -I/usr/X11R6/include -L/usr/X11R6/lib -I$(MATLAB_DIR)/extern/include -fPIC -I$(MATLAB_DIR)/include
+CSWITCHES = $(CFLAGS) -DNO_TIMER -fPIC
 TRILIBDEFS = -DTRILIBRARY
 OBJ_EXT=o
Index: /issm/trunk/externalpackages/triangle/configs/pleiades/configure.make
===================================================================
--- /issm/trunk/externalpackages/triangle/configs/pleiades/configure.make	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/configs/pleiades/configure.make	(revision 16137)
@@ -1,4 +1,4 @@
 CC=gcc
-CSWITCHES = $(CFLAGS) -I$(MATLAB_DIR)/extern/include  -I$(MATLAB_DIR)/include -DLIN64 -fPIC
+CSWITCHES = $(CFLAGS) -DNO_TIMER -DLINUX -fPIC
 OBJ_EXT=o
 LIB_EXT=a
Index: /issm/trunk/externalpackages/triangle/configs/win32/configure.make
===================================================================
--- /issm/trunk/externalpackages/triangle/configs/win32/configure.make	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/configs/win32/configure.make	(revision 16137)
@@ -1,4 +1,4 @@
 CC=icl
-CSWITCHES = $(CFLAGS) -I$(MATLAB_DIR)/extern/include  -I$(MATLAB_DIR)/include -DWIN32
+CSWITCHES = $(CFLAGS) -DNO_TIMER -DWIN32
 OBJ_EXT=obj
 LIB_EXT=a
Index: /issm/trunk/externalpackages/triangle/configs/win7/configure.make
===================================================================
--- /issm/trunk/externalpackages/triangle/configs/win7/configure.make	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/configs/win7/configure.make	(revision 16137)
@@ -1,4 +1,4 @@
 CC=cl
-CSWITCHES = $(CFLAGS) -I$(MATLAB_DIR)/extern/include  -I$(MATLAB_DIR)/include -DWIN32
+CSWITCHES = $(CFLAGS) -DNO_TIMER 
 OBJ_EXT=obj
 LIB_EXT=lib
Index: /issm/trunk/externalpackages/triangle/install-altix64.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-altix64.sh	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/install-altix64.sh	(revision 16137)
@@ -18,7 +18,4 @@
 cp ../makefile ./
 
-#Patch triangle.c 
-patch triangle.c ../triangle.c.patch
-
 #Compile triangle
 make
Index: /issm/trunk/externalpackages/triangle/install-android.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-android.sh	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/install-android.sh	(revision 16137)
@@ -20,7 +20,4 @@
 cp ../makefile ./
 
-#Patch triangle.c 
-patch triangle.c ../triangle.c.patch
-
 #Compile triangle
 make
Index: /issm/trunk/externalpackages/triangle/install-discover.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-discover.sh	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/install-discover.sh	(revision 16137)
@@ -18,7 +18,4 @@
 cp ../makefile ./
 
-#Patch triangle.c 
-patch triangle.c ../triangle.c.patch
-
 #Compile triangle
 make
Index: /issm/trunk/externalpackages/triangle/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-linux64.sh	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/install-linux64.sh	(revision 16137)
@@ -18,7 +18,4 @@
 cp ../makefile ./
 
-#Patch triangle.c 
-patch triangle.c ../triangle.c.patch
-
 #Compile triangle
 make
Index: /issm/trunk/externalpackages/triangle/install-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-macosx32.sh	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/install-macosx32.sh	(revision 16137)
@@ -18,7 +18,4 @@
 cp ../makefile ./
 
-#Patch triangle.c 
-patch triangle.c ../triangle.c.patch
-
 #Compile triangle
 make
Index: /issm/trunk/externalpackages/triangle/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-macosx64.sh	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/install-macosx64.sh	(revision 16137)
@@ -18,7 +18,4 @@
 cp ../makefile ./
 
-#Patch triangle.c 
-patch triangle.c ../triangle.c.patch
-
 #Compile triangle
 make
Index: /issm/trunk/externalpackages/triangle/install-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-pleiades.sh	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/install-pleiades.sh	(revision 16137)
@@ -18,7 +18,4 @@
 cp ../makefile ./
 
-#Patch triangle.c 
-patch triangle.c ../triangle.c.patch
-
 #Compile triangle
 make
Index: /issm/trunk/externalpackages/triangle/install-win32.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-win32.sh	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/install-win32.sh	(revision 16137)
@@ -18,7 +18,4 @@
 cp ../makefile ./
 
-#Patch triangle.c 
-patch triangle.c ../triangle.c.patch
-
 #Compile triangle
 make
Index: /issm/trunk/externalpackages/triangle/install-win7.sh
===================================================================
--- /issm/trunk/externalpackages/triangle/install-win7.sh	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/install-win7.sh	(revision 16137)
@@ -18,7 +18,4 @@
 cp ../configs/win7/makefile ./
 
-#Patch triangle.c 
-patch triangle.c ../triangle.c.patch
-
 #Compile triangle
 make
Index: sm/trunk/externalpackages/triangle/triangle.c.patch
===================================================================
--- /issm/trunk/externalpackages/triangle/triangle.c.patch	(revision 16136)
+++ 	(revision )
@@ -1,164 +1,0 @@
-0a1,10
-> /*Notes for the Ice code: 
->  * to be able to compile Triangle within a mex function that can run within 
->  * matlab, we had to change the allocation routine trimalloc, as well as the 
->  * double precision activation in exactinit(); The rest is not changed. 
->  * We also created the ice_makefile to compile Triangle into a library. */
-> /* #include <mat.h>
-> #include <matrix.h> */
-> #define ANSI_DECLARATORS
-> #define NO_TIMER
-> 
-347a358
-> #ifndef _WIN_
-348a360
-> #endif
-641d652
-< 
-817a829,922
-> /*Some missing prototypes: */
-> int scale_expansion_zeroelim(int elen, REAL *e, REAL b, REAL *h);
-> int fast_expansion_sum_zeroelim(int elen, REAL *e, int flen, REAL *f, REAL *h);
-> void poolzero(struct memorypool *pool);
-> int triunsuitable(vertex triorg, vertex tridest, vertex triapex, REAL area);
-> triangle *triangletraverse(struct mesh *m);
-> void pooldeinit(struct memorypool *pool);
-> void printtriangle(struct mesh *m, struct behavior *b, struct otri *t);
-> VOID *poolalloc(struct memorypool *pool);
-> void enqueuebadtriang(struct mesh *m, struct behavior *b,
->                       struct badtriang *badtri);
-> void triangulatepolygon(struct mesh *m, struct behavior *b,
->                         struct otri *firstedge, struct otri *lastedge,
->                         int edgecount, int doflip, int triflaws);
-> void triangledealloc(struct mesh *m, triangle *dyingtriangle);
-> void unflip(struct mesh *m, struct behavior *b, struct otri *flipedge);
-> void vertexmedian(vertex *sortarray, int arraysize, int median, int axis);
-> REAL counterclockwiseadapt(vertex pa, vertex pb, vertex pc, REAL detsum);
-> REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent);
-> void enqueuebadtri(struct mesh *m, struct behavior *b, struct otri *enqtri,
->                    REAL minedge, vertex enqapex, vertex enqorg, vertex enqdest);
-> void alternateaxes(vertex *sortarray, int arraysize, int axis);
-> REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent);
-> void maketriangle(struct mesh *m, struct behavior *b, struct otri *newotri);
-> REAL counterclockwise(struct mesh *m, struct behavior *b,
->                       vertex pa, vertex pb, vertex pc);
-> vertex vertextraverse(struct mesh *m);
-> void mergehulls(struct mesh *m, struct behavior *b, struct otri *farleft,
->                 struct otri *innerleft, struct otri *innerright,
->                 struct otri *farright, int axis);
-> REAL incircle(struct mesh *m, struct behavior *b,
->               vertex pa, vertex pb, vertex pc, vertex pd);
-> void poolrestart(struct memorypool *pool);
-> void trifree(VOID *memptr);
-> struct splaynode *splay(struct mesh *m, struct splaynode *splaytree,
->                         vertex searchpoint, struct otri *searchtri);
-> void eventheapdelete(struct event **heap, int heapsize, int eventnum);
-> void eventheapdelete(struct event **heap, int heapsize, int eventnum);
-> void flip(struct mesh *m, struct behavior *b, struct otri *flipedge);
-> void check4deadevent(struct otri *checktri, struct event **freeevents,
->                      struct event **eventheap, int *heapsize);
-> REAL orient3d(struct mesh *m, struct behavior *b,
->               vertex pa, vertex pb, vertex pc, vertex pd,
->               REAL aheight, REAL bheight, REAL cheight, REAL dheight);
-> REAL circletop(struct mesh *m, vertex pa, vertex pb, vertex pc, REAL ccwabc);
-> void poolinit(struct memorypool *pool, int bytecount, int itemcount,
->               int firstitemcount, int alignment);
-> void eventheapinsert(struct event **heap, int heapsize, struct event *newevent);
-> int rightofhyperbola(struct mesh *m, struct otri *fronttri, vertex newsite);
-> void insertsubseg(struct mesh *m, struct behavior *b, struct otri *tri,
->                   int subsegmark);
-> int scoutsegment(struct mesh *m, struct behavior *b, struct otri *searchtri,
->                  vertex endpoint2, int newmark);
-> vertex getvertex(struct mesh *m, struct behavior *b, int number);
-> void internalerror();
-> unsigned long randomnation(unsigned int choices);
-> struct splaynode *splayinsert(struct mesh *m, struct splaynode *splayroot,
->                               struct otri *newkey, vertex searchpoint);
-> void delaunayfixup(struct mesh *m, struct behavior *b,
->                    struct otri *fixuptri, int leftside);
-> void traversalinit(struct memorypool *pool);
-> enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,
->                                      vertex newvertex, struct otri *searchtri,
->                                      struct osub *splitseg,
->                                      int segmentflaws, int triflaws);
-> void conformingedge(struct mesh *m, struct behavior *b,
->                     vertex endpoint1, vertex endpoint2, int newmark);
-> enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,
->                                        struct otri *searchtri,
->                                        vertex searchpoint);
-> VOID *traverse(struct memorypool *pool);
-> void deletevertex(struct mesh *m, struct behavior *b, struct otri *deltri);
-> void pooldealloc(struct memorypool *pool, VOID *dyingitem);
-> int checkseg4encroach(struct mesh *m, struct behavior *b,
->                       struct osub *testsubseg);
-> void badsubsegdealloc(struct mesh *m, struct badsubseg *dyingseg);
-> void vertexdealloc(struct mesh *m, vertex dyingvertex);
-> void vertexsort(vertex *sortarray, int arraysize);
-> void tallyencs(struct mesh *m, struct behavior *b);
-> void splittriangle(struct mesh *m, struct behavior *b,
->                    struct badtriang *badtri);
-> subseg *subsegtraverse(struct mesh *m);
-> enum locateresult locate(struct mesh *m, struct behavior *b,
->                          vertex searchpoint, struct otri *searchtri);
-> void writenodes(struct mesh *m, struct behavior *b, REAL **pointlist,
->                 REAL **pointattriblist, int **pointmarkerlist);
-> void writevoronoi(struct mesh *m, struct behavior *b, REAL **vpointlist,
->                   REAL **vpointattriblist, int **vpointmarkerlist,
->                   int **vedgelist, int **vedgemarkerlist, REAL **vnormlist);
-> void writeneighbors(struct mesh *m, struct behavior *b, int **neighborlist);
-> void testtriangle(struct mesh *m, struct behavior *b, struct otri *testtri);
-> void triangleinit(struct mesh *m);
-> 
-> 
-1408a1514
-> void triexit(int status);
-1410d1515
-< #ifdef ANSI_DECLARATORS
-1412,1416d1516
-< #else /* not ANSI_DECLARATORS */
-< void triexit(status)
-< int status;
-< #endif /* not ANSI_DECLARATORS */
-< 
-1421c1521
-< #ifdef ANSI_DECLARATORS
----
-> VOID *trimalloc(int size);
-1423,1427d1522
-< #else /* not ANSI_DECLARATORS */
-< VOID *trimalloc(size)
-< int size;
-< #endif /* not ANSI_DECLARATORS */
-< 
-1431c1526,1527
-<   memptr = (VOID *) malloc((unsigned int) size);
----
->   //memptr = (VOID *) mxMalloc((unsigned int) size);
->   memptr = (VOID *) malloc((unsigned int) size);
-1447c1543,1544
-<   free(memptr);
----
->   free(memptr);
->   //mxFree(memptr);
-3665,3670c3762,3767
-< void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
-< #else /* not ANSI_DECLARATORS */
-< void printtriangle(m, b, t)
-< struct mesh *m;
-< struct behavior *b;
-< struct otri *t;
----
-> void printtriangle(struct mesh *m, struct behavior *b, struct otri *t){
-> //#else /* not ANSI_DECLARATORS */
-> //void printtriangle(m, b, t)
-> //struct mesh *m;
-> //struct behavior *b;
-> //struct otri *t;
-3673c3770
-< {
----
-> //{
-4910c5007
-<   _FPU_SETCW(cword);
----
->   //_FPU_SETCW(cword); //taken care of by Matlab
Index: sm/trunk/externalpackages/triangle/triangle.h
===================================================================
--- /issm/trunk/externalpackages/triangle/triangle.h	(revision 16136)
+++ 	(revision )
@@ -1,291 +1,0 @@
-/*****************************************************************************/
-/*                                                                           */
-/*  (triangle.h)                                                             */
-/*                                                                           */
-/*  Include file for programs that call Triangle.                            */
-/*                                                                           */
-/*  Accompanies Triangle Version 1.6                                         */
-/*  July 28, 2005                                                            */
-/*                                                                           */
-/*  Copyright 1996, 2005                                                     */
-/*  Jonathan Richard Shewchuk                                                */
-/*  2360 Woolsey #H                                                          */
-/*  Berkeley, California  94705-1927                                         */
-/*  jrs@cs.berkeley.edu                                                      */
-/*                                                                           */
-/*****************************************************************************/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  How to call Triangle from another program                                */
-/*                                                                           */
-/*                                                                           */
-/*  If you haven't read Triangle's instructions (run "triangle -h" to read   */
-/*  them), you won't understand what follows.                                */
-/*                                                                           */
-/*  Triangle must be compiled into an object file (triangle.o) with the      */
-/*  TRILIBRARY symbol defined (generally by using the -DTRILIBRARY compiler  */
-/*  switch).  The makefile included with Triangle will do this for you if    */
-/*  you run "make trilibrary".  The resulting object file can be called via  */
-/*  the procedure triangulate().                                             */
-/*                                                                           */
-/*  If the size of the object file is important to you, you may wish to      */
-/*  generate a reduced version of triangle.o.  The REDUCED symbol gets rid   */
-/*  of all features that are primarily of research interest.  Specifically,  */
-/*  the -DREDUCED switch eliminates Triangle's -i, -F, -s, and -C switches.  */
-/*  The CDT_ONLY symbol gets rid of all meshing algorithms above and beyond  */
-/*  constrained Delaunay triangulation.  Specifically, the -DCDT_ONLY switch */
-/*  eliminates Triangle's -r, -q, -a, -u, -D, -Y, -S, and -s switches.       */
-/*                                                                           */
-/*  IMPORTANT:  These definitions (TRILIBRARY, REDUCED, CDT_ONLY) must be    */
-/*  made in the makefile or in triangle.c itself.  Putting these definitions */
-/*  in this file (triangle.h) will not create the desired effect.            */
-/*                                                                           */
-/*                                                                           */
-/*  The calling convention for triangulate() follows.                        */
-/*                                                                           */
-/*      void triangulate(triswitches, in, out, vorout)                       */
-/*      char *triswitches;                                                   */
-/*      struct triangulateio *in;                                            */
-/*      struct triangulateio *out;                                           */
-/*      struct triangulateio *vorout;                                        */
-/*                                                                           */
-/*  `triswitches' is a string containing the command line switches you wish  */
-/*  to invoke.  No initial dash is required.  Some suggestions:              */
-/*                                                                           */
-/*  - You'll probably find it convenient to use the `z' switch so that       */
-/*    points (and other items) are numbered from zero.  This simplifies      */
-/*    indexing, because the first item of any type always starts at index    */
-/*    [0] of the corresponding array, whether that item's number is zero or  */
-/*    one.                                                                   */
-/*  - You'll probably want to use the `Q' (quiet) switch in your final code, */
-/*    but you can take advantage of Triangle's printed output (including the */
-/*    `V' switch) while debugging.                                           */
-/*  - If you are not using the `q', `a', `u', `D', `j', or `s' switches,     */
-/*    then the output points will be identical to the input points, except   */
-/*    possibly for the boundary markers.  If you don't need the boundary     */
-/*    markers, you should use the `N' (no nodes output) switch to save       */
-/*    memory.  (If you do need boundary markers, but need to save memory, a  */
-/*    good nasty trick is to set out->pointlist equal to in->pointlist       */
-/*    before calling triangulate(), so that Triangle overwrites the input    */
-/*    points with identical copies.)                                         */
-/*  - The `I' (no iteration numbers) and `g' (.off file output) switches     */
-/*    have no effect when Triangle is compiled with TRILIBRARY defined.      */
-/*                                                                           */
-/*  `in', `out', and `vorout' are descriptions of the input, the output,     */
-/*  and the Voronoi output.  If the `v' (Voronoi output) switch is not used, */
-/*  `vorout' may be NULL.  `in' and `out' may never be NULL.                 */
-/*                                                                           */
-/*  Certain fields of the input and output structures must be initialized,   */
-/*  as described below.                                                      */
-/*                                                                           */
-/*****************************************************************************/
-
-/*****************************************************************************/
-/*                                                                           */
-/*  The `triangulateio' structure.                                           */
-/*                                                                           */
-/*  Used to pass data into and out of the triangulate() procedure.           */
-/*                                                                           */
-/*                                                                           */
-/*  Arrays are used to store points, triangles, markers, and so forth.  In   */
-/*  all cases, the first item in any array is stored starting at index [0].  */
-/*  However, that item is item number `1' unless the `z' switch is used, in  */
-/*  which case it is item number `0'.  Hence, you may find it easier to      */
-/*  index points (and triangles in the neighbor list) if you use the `z'     */
-/*  switch.  Unless, of course, you're calling Triangle from a Fortran       */
-/*  program.                                                                 */
-/*                                                                           */
-/*  Description of fields (except the `numberof' fields, which are obvious): */
-/*                                                                           */
-/*  `pointlist':  An array of point coordinates.  The first point's x        */
-/*    coordinate is at index [0] and its y coordinate at index [1], followed */
-/*    by the coordinates of the remaining points.  Each point occupies two   */
-/*    REALs.                                                                 */
-/*  `pointattributelist':  An array of point attributes.  Each point's       */
-/*    attributes occupy `numberofpointattributes' REALs.                     */
-/*  `pointmarkerlist':  An array of point markers; one int per point.        */
-/*                                                                           */
-/*  `trianglelist':  An array of triangle corners.  The first triangle's     */
-/*    first corner is at index [0], followed by its other two corners in     */
-/*    counterclockwise order, followed by any other nodes if the triangle    */
-/*    represents a nonlinear element.  Each triangle occupies                */
-/*    `numberofcorners' ints.                                                */
-/*  `triangleattributelist':  An array of triangle attributes.  Each         */
-/*    triangle's attributes occupy `numberoftriangleattributes' REALs.       */
-/*  `trianglearealist':  An array of triangle area constraints; one REAL per */
-/*    triangle.  Input only.                                                 */
-/*  `neighborlist':  An array of triangle neighbors; three ints per          */
-/*    triangle.  Output only.                                                */
-/*                                                                           */
-/*  `segmentlist':  An array of segment endpoints.  The first segment's      */
-/*    endpoints are at indices [0] and [1], followed by the remaining        */
-/*    segments.  Two ints per segment.                                       */
-/*  `segmentmarkerlist':  An array of segment markers; one int per segment.  */
-/*                                                                           */
-/*  `holelist':  An array of holes.  The first hole's x and y coordinates    */
-/*    are at indices [0] and [1], followed by the remaining holes.  Two      */
-/*    REALs per hole.  Input only, although the pointer is copied to the     */
-/*    output structure for your convenience.                                 */
-/*                                                                           */
-/*  `regionlist':  An array of regional attributes and area constraints.     */
-/*    The first constraint's x and y coordinates are at indices [0] and [1], */
-/*    followed by the regional attribute at index [2], followed by the       */
-/*    maximum area at index [3], followed by the remaining area constraints. */
-/*    Four REALs per area constraint.  Note that each regional attribute is  */
-/*    used only if you select the `A' switch, and each area constraint is    */
-/*    used only if you select the `a' switch (with no number following), but */
-/*    omitting one of these switches does not change the memory layout.      */
-/*    Input only, although the pointer is copied to the output structure for */
-/*    your convenience.                                                      */
-/*                                                                           */
-/*  `edgelist':  An array of edge endpoints.  The first edge's endpoints are */
-/*    at indices [0] and [1], followed by the remaining edges.  Two ints per */
-/*    edge.  Output only.                                                    */
-/*  `edgemarkerlist':  An array of edge markers; one int per edge.  Output   */
-/*    only.                                                                  */
-/*  `normlist':  An array of normal vectors, used for infinite rays in       */
-/*    Voronoi diagrams.  The first normal vector's x and y magnitudes are    */
-/*    at indices [0] and [1], followed by the remaining vectors.  For each   */
-/*    finite edge in a Voronoi diagram, the normal vector written is the     */
-/*    zero vector.  Two REALs per edge.  Output only.                        */
-/*                                                                           */
-/*                                                                           */
-/*  Any input fields that Triangle will examine must be initialized.         */
-/*  Furthermore, for each output array that Triangle will write to, you      */
-/*  must either provide space by setting the appropriate pointer to point    */
-/*  to the space you want the data written to, or you must initialize the    */
-/*  pointer to NULL, which tells Triangle to allocate space for the results. */
-/*  The latter option is preferable, because Triangle always knows exactly   */
-/*  how much space to allocate.  The former option is provided mainly for    */
-/*  people who need to call Triangle from Fortran code, though it also makes */
-/*  possible some nasty space-saving tricks, like writing the output to the  */
-/*  same arrays as the input.                                                */
-/*                                                                           */
-/*  Triangle will not free() any input or output arrays, including those it  */
-/*  allocates itself; that's up to you.  You should free arrays allocated by */
-/*  Triangle by calling the trifree() procedure defined below.  (By default, */
-/*  trifree() just calls the standard free() library procedure, but          */
-/*  applications that call triangulate() may replace trimalloc() and         */
-/*  trifree() in triangle.c to use specialized memory allocators.)           */
-/*                                                                           */
-/*  Here's a guide to help you decide which fields you must initialize       */
-/*  before you call triangulate().                                           */
-/*                                                                           */
-/*  `in':                                                                    */
-/*                                                                           */
-/*    - `pointlist' must always point to a list of points; `numberofpoints'  */
-/*      and `numberofpointattributes' must be properly set.                  */
-/*      `pointmarkerlist' must either be set to NULL (in which case all      */
-/*      markers default to zero), or must point to a list of markers.  If    */
-/*      `numberofpointattributes' is not zero, `pointattributelist' must     */
-/*      point to a list of point attributes.                                 */
-/*    - If the `r' switch is used, `trianglelist' must point to a list of    */
-/*      triangles, and `numberoftriangles', `numberofcorners', and           */
-/*      `numberoftriangleattributes' must be properly set.  If               */
-/*      `numberoftriangleattributes' is not zero, `triangleattributelist'    */
-/*      must point to a list of triangle attributes.  If the `a' switch is   */
-/*      used (with no number following), `trianglearealist' must point to a  */
-/*      list of triangle area constraints.  `neighborlist' may be ignored.   */
-/*    - If the `p' switch is used, `segmentlist' must point to a list of     */
-/*      segments, `numberofsegments' must be properly set, and               */
-/*      `segmentmarkerlist' must either be set to NULL (in which case all    */
-/*      markers default to zero), or must point to a list of markers.        */
-/*    - If the `p' switch is used without the `r' switch, then               */
-/*      `numberofholes' and `numberofregions' must be properly set.  If      */
-/*      `numberofholes' is not zero, `holelist' must point to a list of      */
-/*      holes.  If `numberofregions' is not zero, `regionlist' must point to */
-/*      a list of region constraints.                                        */
-/*    - If the `p' switch is used, `holelist', `numberofholes',              */
-/*      `regionlist', and `numberofregions' is copied to `out'.  (You can    */
-/*      nonetheless get away with not initializing them if the `r' switch is */
-/*      used.)                                                               */
-/*    - `edgelist', `edgemarkerlist', `normlist', and `numberofedges' may be */
-/*      ignored.                                                             */
-/*                                                                           */
-/*  `out':                                                                   */
-/*                                                                           */
-/*    - `pointlist' must be initialized (NULL or pointing to memory) unless  */
-/*      the `N' switch is used.  `pointmarkerlist' must be initialized       */
-/*      unless the `N' or `B' switch is used.  If `N' is not used and        */
-/*      `in->numberofpointattributes' is not zero, `pointattributelist' must */
-/*      be initialized.                                                      */
-/*    - `trianglelist' must be initialized unless the `E' switch is used.    */
-/*      `neighborlist' must be initialized if the `n' switch is used.  If    */
-/*      the `E' switch is not used and (`in->numberofelementattributes' is   */
-/*      not zero or the `A' switch is used), `elementattributelist' must be  */
-/*      initialized.  `trianglearealist' may be ignored.                     */
-/*    - `segmentlist' must be initialized if the `p' or `c' switch is used,  */
-/*      and the `P' switch is not used.  `segmentmarkerlist' must also be    */
-/*      initialized under these circumstances unless the `B' switch is used. */
-/*    - `edgelist' must be initialized if the `e' switch is used.            */
-/*      `edgemarkerlist' must be initialized if the `e' switch is used and   */
-/*      the `B' switch is not.                                               */
-/*    - `holelist', `regionlist', `normlist', and all scalars may be ignored.*/
-/*                                                                           */
-/*  `vorout' (only needed if `v' switch is used):                            */
-/*                                                                           */
-/*    - `pointlist' must be initialized.  If `in->numberofpointattributes'   */
-/*      is not zero, `pointattributelist' must be initialized.               */
-/*      `pointmarkerlist' may be ignored.                                    */
-/*    - `edgelist' and `normlist' must both be initialized.                  */
-/*      `edgemarkerlist' may be ignored.                                     */
-/*    - Everything else may be ignored.                                      */
-/*                                                                           */
-/*  After a call to triangulate(), the valid fields of `out' and `vorout'    */
-/*  will depend, in an obvious way, on the choice of switches used.  Note    */
-/*  that when the `p' switch is used, the pointers `holelist' and            */
-/*  `regionlist' are copied from `in' to `out', but no new space is          */
-/*  allocated; be careful that you don't free() the same array twice.  On    */
-/*  the other hand, Triangle will never copy the `pointlist' pointer (or any */
-/*  others); new space is allocated for `out->pointlist', or if the `N'      */
-/*  switch is used, `out->pointlist' remains uninitialized.                  */
-/*                                                                           */
-/*  All of the meaningful `numberof' fields will be properly set; for        */
-/*  instance, `numberofedges' will represent the number of edges in the      */
-/*  triangulation whether or not the edges were written.  If segments are    */
-/*  not used, `numberofsegments' will indicate the number of boundary edges. */
-/*                                                                           */
-/*****************************************************************************/
-typedef double REAL;
-typedef void VOID;
-
-extern "C" struct triangulateio {
-  REAL *pointlist;                                               /* In / out */
-  REAL *pointattributelist;                                      /* In / out */
-  int *pointmarkerlist;                                          /* In / out */
-  int numberofpoints;                                            /* In / out */
-  int numberofpointattributes;                                   /* In / out */
-
-  int *trianglelist;                                             /* In / out */
-  REAL *triangleattributelist;                                   /* In / out */
-  REAL *trianglearealist;                                         /* In only */
-  int *neighborlist;                                             /* Out only */
-  int numberoftriangles;                                         /* In / out */
-  int numberofcorners;                                           /* In / out */
-  int numberoftriangleattributes;                                /* In / out */
-
-  int *segmentlist;                                              /* In / out */
-  int *segmentmarkerlist;                                        /* In / out */
-  int numberofsegments;                                          /* In / out */
-
-  REAL *holelist;                        /* In / pointer to array copied out */
-  int numberofholes;                                      /* In / copied out */
-
-  REAL *regionlist;                      /* In / pointer to array copied out */
-  int numberofregions;                                    /* In / copied out */
-
-  int *edgelist;                                                 /* Out only */
-  int *edgemarkerlist;            /* Not used with Voronoi diagram; out only */
-  REAL *normlist;                /* Used only with Voronoi diagram; out only */
-  int numberofedges;                                             /* Out only */
-};
-
-#ifdef ANSI_DECLARATORS
-extern "C" void triangulate(char *, struct triangulateio *, struct triangulateio *,
-                 struct triangulateio *);
-extern "C" void trifree(VOID *memptr);
-#else /* not ANSI_DECLARATORS */
-void triangulate();
-void trifree();
-#endif /* not ANSI_DECLARATORS */
Index: /issm/trunk/externalpackages/triangle/triangle.h.patch
===================================================================
--- /issm/trunk/externalpackages/triangle/triangle.h.patch	(revision 16136)
+++ /issm/trunk/externalpackages/triangle/triangle.h.patch	(revision 16137)
@@ -1,25 +1,12 @@
-249a250,251
-> #ifndef _TRIANGLE_LIBRARY_H_
-> #define _TRIANGLE_LIBRARY_H_
-251c253,259
-< struct triangulateio {
----
-> 
+250a251,257
+> /*Patch for ISSM*/
 > #ifndef REAL
 > typedef double REAL;
 > typedef void VOID;
 > #endif
+> /*End patch*/
 > 
-> extern "C" struct triangulateio {
-283c291
+283c290
 < void triangulate(char *, struct triangulateio *, struct triangulateio *,
 ---
 > extern "C" void triangulate(char *, struct triangulateio *, struct triangulateio *,
-285c293
-< void trifree(VOID *memptr);
----
-> extern "C" void trifree(VOID *memptr);
-289a298,300
-> 
-> 
-> #endif //#ifndef _TRIANGLE_LIBRARY_H_
Index: /issm/trunk/externalpackages/valgrind/install-altix64.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-altix64.sh	(revision 16136)
+++ /issm/trunk/externalpackages/valgrind/install-altix64.sh	(revision 16137)
@@ -3,16 +3,16 @@
 
 #Some cleanup
-rm -rf install valgrind-3.8.0
+rm -rf install valgrind-3.8.1
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.0.tar.bz2' 'valgrind-3.8.0.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.8.0.tar.bz2
+tar -jxvf  valgrind-3.8.1.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.8.0/* install
-rm -rf valgrind-3.8.0
+mv valgrind-3.8.1/* install
+rm -rf valgrind-3.8.1
 
 #configure
Index: /issm/trunk/externalpackages/valgrind/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-linux64.sh	(revision 16136)
+++ /issm/trunk/externalpackages/valgrind/install-linux64.sh	(revision 16137)
@@ -3,16 +3,16 @@
 
 #Some cleanup
-rm -rf install valgrind-3.8.0
+rm -rf install valgrind-3.8.1
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.0.tar.bz2' 'valgrind-3.8.0.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.8.0.tar.bz2
+tar -jxvf  valgrind-3.8.1.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.8.0/* install
-rm -rf valgrind-3.8.0
+mv valgrind-3.8.1/* install
+rm -rf valgrind-3.8.1
 
 #configure
Index: /issm/trunk/externalpackages/valgrind/install-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-macosx32.sh	(revision 16136)
+++ /issm/trunk/externalpackages/valgrind/install-macosx32.sh	(revision 16137)
@@ -3,16 +3,16 @@
 
 #Some cleanup
-rm -rf install valgrind-3.8.0
+rm -rf install valgrind-3.8.1
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.0.tar.bz2' 'valgrind-3.8.0.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.8.0.tar.bz2
+tar -jxvf  valgrind-3.8.1.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.8.0/* install
-rm -rf valgrind-3.8.0
+mv valgrind-3.8.1/* install
+rm -rf valgrind-3.8.1
 
 #configure
Index: /issm/trunk/externalpackages/valgrind/install-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-macosx64.sh	(revision 16136)
+++ /issm/trunk/externalpackages/valgrind/install-macosx64.sh	(revision 16137)
@@ -3,16 +3,16 @@
 
 #Some cleanup
-rm -rf install valgrind-3.8.0
+rm -rf install valgrind-3.8.1
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.0.tar.bz2' 'valgrind-3.8.0.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.8.0.tar.bz2
+tar -jxvf  valgrind-3.8.1.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.8.0/* install
-rm -rf valgrind-3.8.0
+mv valgrind-3.8.1/* install
+rm -rf valgrind-3.8.1
 
 #configure
@@ -21,4 +21,4 @@
 
 #Compile valgrind
-make  -j 4
+make  -j 8
 make install
Index: /issm/trunk/externalpackages/valgrind/install-win32.sh
===================================================================
--- /issm/trunk/externalpackages/valgrind/install-win32.sh	(revision 16136)
+++ /issm/trunk/externalpackages/valgrind/install-win32.sh	(revision 16137)
@@ -3,16 +3,16 @@
 
 #Some cleanup
-rm -rf install valgrind-3.8.0
+rm -rf install valgrind-3.8.1
 mkdir install
 
 #Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.0.tar.bz2' 'valgrind-3.8.0.tar.bz2'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/valgrind-3.8.1.tar.bz2' 'valgrind-3.8.1.tar.bz2'
 
 #Untar 
-tar -jxvf  valgrind-3.8.0.tar.bz2
+tar -jxvf  valgrind-3.8.1.tar.bz2
 
 #Move valgrind into install directory
-mv valgrind-3.8.0/* install
-rm -rf valgrind-3.8.0
+mv valgrind-3.8.1/* install
+rm -rf valgrind-3.8.1
 
 #configure
Index: /issm/trunk/externalpackages/valgrind/issm.supp
===================================================================
--- /issm/trunk/externalpackages/valgrind/issm.supp	(revision 16136)
+++ /issm/trunk/externalpackages/valgrind/issm.supp	(revision 16137)
@@ -3,76 +3,35 @@
 #
 # to add errors:
-#   1. in m/public/queue/ClusterScript.m,
+#   1. in m/classes/clusters/generic.m,
 #      add: --gen-suppressions=all
 #   2. in the errlog, copy and paste the suppression log
 #      in this file.
 
-#General errors from MPI, Petsc
-#PETSC General {{{1
+#OS specific errors{{{
+#http://stackoverflow.com/questions/14474691/wifstream-with-imbue-locale-produces-valgrind-errors (larsen)
 {
-	petsc1general
-	  Memcheck:User
-	  fun:check_mem_is_defined_untyped
-	  fun:PMPI_Allreduce
-	  fun:MPI_ALLREDUCE
-	  fun:dmumps_276_
-	  fun:dmumps_
-	  fun:dmumps_f77_
-	  fun:dmumps_c
-	  fun:MatFactorNumeric_AIJMUMPS
-	  fun:MatLUFactorNumeric
-	  fun:PCSetUp_LU
-	  fun:PCSetUp
-	  fun:KSPSetUp
+   <OS1>
+   Memcheck:Addr8
+   fun:wcscmp
+   fun:_ZNSt10moneypunctIwLb1EED1Ev
+   fun:_ZNSt10moneypunctIwLb1EED0Ev
 }
 {
-	petsc2general
-	  Memcheck:User
-	  fun:check_mem_is_defined_untyped
-	  fun:PMPI_Bcast
-	  fun:PMPI_BCAST
-	  fun:dmumps_300_
-	  fun:dmumps_
-	  fun:dmumps_f77_
-	  fun:dmumps_c
-	  fun:MatFactorNumeric_AIJMUMPS
-	  fun:MatLUFactorNumeric
-	  fun:PCSetUp_LU
-	  fun:PCSetUp
-	  fun:KSPSetUp
+   <OS0>
+   Memcheck:Addr8
+   fun:wcscmp
+   fun:_ZNSt10moneypunctIwLb0EED1Ev
+   fun:_ZNSt10moneypunctIwLb0EED0Ev
+   fun:_ZNSt6locale5_ImplD1Ev
+   fun:_ZNSt6localeD1Ev
+   fun:__cxa_finalize
+   obj:/u/astrid-r1b/morlighe/issmjpl/cron/trunk-jpl/externalpackages/boost/install/lib/libboost_filesystem.so.1.49.0
+   obj:/u/astrid-r1b/morlighe/issmjpl/cron/trunk-jpl/externalpackages/boost/install/lib/libboost_filesystem.so.1.49.0
+   fun:__run_exit_handlers
+   fun:exit
+   fun:(below main)
 }
 {
-	petsc3general
-	  Memcheck:User
-	  fun:check_mem_is_defined_untyped
-	  fun:PMPI_Bcast
-	  fun:PMPI_BCAST
-	  fun:dmumps_
-	  fun:dmumps_f77_
-	  fun:dmumps_c
-	  fun:MatFactorNumeric_AIJMUMPS
-	  fun:MatLUFactorNumeric
-	  fun:PCSetUp_LU
-	  fun:PCSetUp
-	  fun:KSPSetUp
-	  fun:KSPSolve
-}
-{
-	petsc4firstcall
-	  Memcheck:User
-	  fun:check_mem_is_defined_untyped
-	  fun:walk_type
-	  fun:PMPI_Allreduce
-	  fun:MPIR_Get_contextid
-	  fun:MPIR_Comm_copy
-	  fun:PMPI_Comm_dup
-	  fun:PMPI_Comm_dup
-	  fun:PetscCommDuplicate
-	  fun:PetscHeaderCreate_Private
-}
-#}}}1
-#Dakota {{{1
-{
-   dakota1
+   <OS2>
    Memcheck:Leak
    fun:_Znwm
@@ -80,63 +39,144 @@
    fun:_ZNSs12_S_constructIPKcEEPcT_S3_RKSaIcESt20forward_iterator_tag
    fun:_ZNSsC1EPKcRKSaIcE
-   fun:_ZN4JEGA10Algorithms17SOGAOperatorGroup4NameEv
-   fun:_Z41__static_initialization_and_destruction_0ii
+}
+#}}}
+#PETSc {{{
+{
+   <petsc0>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:maybe_complete
+   fun:PMPI_Waitany
+   fun:MatStashScatterGetMesg_Private
+   fun:MatAssemblyEnd_MPIAIJ
+   fun:MatAssemblyEnd
 }
 {
-   dakota2
-   Memcheck:Leak
-   fun:_Znwm
-   fun:_ZNSs4_Rep9_S_createEmmRKSaIcE
-   fun:_ZNSs12_S_constructIPKcEEPcT_S3_RKSaIcESt20forward_iterator_tag
-   fun:_ZNSsC1EPKcRKSaIcE
-   fun:_ZN4JEGA10Algorithms26FavorFeasibleOperatorGroup4NameEv
-   fun:_Z41__static_initialization_and_destruction_0ii
+   <petsc1>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:maybe_complete
+   fun:PMPI_Waitany
+   fun:VecStashScatterGetMesg_Private
+   fun:VecAssemblyEnd_MPI
+   fun:VecAssemblyEnd
+   fun:_ZN8PetscVec8AssembleEv
 }
 {
-   dakota3
-   Memcheck:Leak
-   fun:_Znwm
-   fun:_ZNSs4_Rep9_S_createEmmRKSaIcE
-   fun:_ZNSs12_S_constructIPKcEEPcT_S3_RKSaIcESt20forward_iterator_tag
-   fun:_ZNSsC1EPKcRKSaIcE
-   fun:_ZN4JEGA10Algorithms17MOGAOperatorGroup4NameEv
-   fun:_Z41__static_initialization_and_destruction_0ii
+   <petsc2>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:_Z14VecToMPISerialPPdP6_p_Veci
+   fun:_ZN8PetscVec11ToMPISerialEv
 }
 {
-   dakota4
+   <petsc3>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:maybe_complete
+   fun:PMPI_Waitany
+   fun:VecScatterCreate_PtoS
+   fun:VecScatterCreate
+   fun:MatSetUpMultiply_MPIAIJ
+   fun:MatAssemblyEnd_MPIAIJ
+   fun:MatAssemblyEnd
+}
+{
+   <mumps0>
    Memcheck:Leak
-   fun:_Znwm
-   fun:_ZNSs4_Rep9_S_createEmmRKSaIcE
-   fun:_ZNSs12_S_constructIPKcEEPcT_S3_RKSaIcESt20forward_iterator_tag
-   fun:_ZNSsC1EPKcRKSaIcE
-   fun:_ZN4JEGA10Algorithms28DominationCountOperatorGroup4NameEv
-   fun:_Z41__static_initialization_and_destruction_0ii
+   fun:malloc
+   fun:mumps_397.3148
+   fun:__mumps_static_mapping_MOD_mumps_369
+   fun:dmumps_537_
+   fun:dmumps_26_
+   fun:dmumps_
+   fun:dmumps_f77_
+   fun:dmumps_c
+   fun:MatLUFactorSymbolic_AIJMUMPS
+   fun:MatLUFactorSymbolic
+   fun:PCSetUp_LU
+   fun:PCSetUp
+}
+{
+   <mumps1>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:mpi_recv
+   fun:dmumps_664_
+}
+{
+   <mumps2>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:maybe_complete
+   fun:PMPI_Waitany
+   fun:mpi_waitany
+   fun:dmumps_664_
+}
+{
+   <mumps3>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:mpi_recv
+   fun:dmumps_282_
+}
+{
+   <mumps4>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:mpi_recv
+   fun:dmumps_255_
+}
+{
+   <mumps5>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:maybe_complete
+   fun:PMPI_Wait
+   fun:PMPI_WAIT
+   fun:dmumps_255_
+}
+{
+   <mump6>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:mpi_recv
+   fun:dmumps_638_
+}
+{
+   <mumps7>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:PMPI_Recv
+   fun:mpi_recv
+   fun:dmumps_640.3488
+}
+{
+   <mumps8>
+   Memcheck:User
+   fun:PMPI_Get_count
+   fun:MPI_GET_COUNT
+   fun:dmumps_638_
+}
+{
+   <mumps9>
+   Memcheck:User
+   fun:check_mem_is_defined_untyped
+   fun:PMPI_Pack
+   fun:PMPI_PACK
+   fun:__dmumps_comm_buffer_MOD_dmumps_62
+}
+{
+   <mumps10>
+   Memcheck:User
+   fun:check_mem_is_defined_untyped
+   fun:PMPI_Pack
+   fun:PMPI_PACK
+   fun:__dmumps_comm_buffer_MOD_dmumps_62
 }
 #}}}
-#Miscellaneous {{{1
-{
-	miscellaneous1
-	  Memcheck:Free
-	  fun:free
-	  obj:/lib64/libc-2.5.so
-	  obj:/lib64/libc-2.5.so
-	  fun:_vgnU_freeres
-	  fun:exit
-	  fun:(below main)
-}
-#}}}
-#Solution specific errors to ignore
-#solver_diagnostic_nonlinear{{{1
-{
-	petsc1diagnosticcore
-	  Memcheck:Cond
-	  fun:dmumps_
-	  fun:dmumps_f77_
-	  fun:dmumps_c
-	  fun:MatFactorNumeric_AIJMUMPS
-	  fun:MatLUFactorNumeric
-	  fun:PCSetUp_LU
-	  fun:PCSetUp
-	  fun:KSPSetUp
-	  fun:KSPSolve
-}
Index: /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 16136)
+++ /issm/trunk/externalpackages/vim/addons/vim/syntax/Synchronize.sh	(revision 16137)
@@ -14,5 +14,5 @@
 cat c.vim | sed "/ISSM's objects begin/,/vim: ts=8/d" > temp
 echo "\"ISSM's objects begin" >> temp
-find ../../../../../src/c/classes -name "*.cpp" | sed -e "s/\// /g" -e "s/\.cpp//"| awk '{print  $(NF)}' | awk '{ printf "syn keyword cType " $1 "\n"}'>> temp
+find ../../../../../src/c/classes -name "*.cpp" -o -name "*.h" | sed -e "s/\// /g" -e "s/\.cpp//" -e "s/\.h//" | awk '{print  $(NF)}' | sort | uniq | awk '{ printf "syn keyword cType " $1 "\n"}'>> temp
 echo "\"ISSM's objects end" >> temp
 cat c.vim | sed "1,/ISSM's objects end/d" >> temp
Index: /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 16136)
+++ /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 16137)
@@ -410,84 +410,103 @@
 
 "ISSM's objects begin
+syn keyword cType BoolElementResult
+syn keyword cType BoolInput
+syn keyword cType BoolParam
+syn keyword cType Constraint
+syn keyword cType Constraints
+syn keyword cType Contour
+syn keyword cType Contours
+syn keyword cType ControlInput
+syn keyword cType DataSetParam
+syn keyword cType DatasetInput
+syn keyword cType DependentObject
+syn keyword cType DofIndexing
+syn keyword cType DoubleElementResult
+syn keyword cType DoubleInput
+syn keyword cType DoubleMatArrayParam
+syn keyword cType DoubleMatParam
+syn keyword cType DoubleParam
+syn keyword cType DoubleTransientMatParam
+syn keyword cType DoubleVecParam
+syn keyword cType Element
+syn keyword cType ElementHook
+syn keyword cType ElementMatrix
+syn keyword cType ElementResult
+syn keyword cType ElementVector
+syn keyword cType Elements
+syn keyword cType ExponentialVariogram
+syn keyword cType ExternalResult
+syn keyword cType FemModel
+syn keyword cType FileParam
+syn keyword cType Friction
+syn keyword cType GaussPenta
+syn keyword cType GaussTria
+syn keyword cType GaussianVariogram
+syn keyword cType GenericExternalResult
+syn keyword cType GenericOption
+syn keyword cType GenericParam
+syn keyword cType GiaDeflectionCoreArgs
+syn keyword cType Hook
+syn keyword cType IndependentObject
+syn keyword cType Input
+syn keyword cType Inputs
+syn keyword cType IntInput
+syn keyword cType IntMatParam
+syn keyword cType IntParam
+syn keyword cType IntVecParam
+syn keyword cType IoModel
+syn keyword cType Load
+syn keyword cType Loads
 syn keyword cType Matdamageice
+syn keyword cType Material
 syn keyword cType Materials
 syn keyword cType Matice
 syn keyword cType Matpar
-syn keyword cType DofIndexing
-syn keyword cType IntVecParam
-syn keyword cType BoolParam
-syn keyword cType IntMatParam
-syn keyword cType DoubleTransientMatParam
-syn keyword cType StringParam
-syn keyword cType DoubleVecParam
-syn keyword cType DoubleMatParam
-syn keyword cType FileParam
-syn keyword cType Parameters
-syn keyword cType DataSetParam
-syn keyword cType IntParam
-syn keyword cType VectorParam
 syn keyword cType MatrixParam
-syn keyword cType StringArrayParam
-syn keyword cType TransientParam
-syn keyword cType DoubleParam
-syn keyword cType DoubleMatArrayParam
-syn keyword cType ExponentialVariogram
-syn keyword cType PowerVariogram
-syn keyword cType Quadtree
+syn keyword cType Node
+syn keyword cType Nodes
+syn keyword cType Numericalflux
+syn keyword cType Observation
 syn keyword cType Observations
-syn keyword cType GaussianVariogram
-syn keyword cType SphericalVariogram
-syn keyword cType Observation
-syn keyword cType RiftStruct
+syn keyword cType Option
 syn keyword cType OptionUtilities
 syn keyword cType Options
+syn keyword cType Param
+syn keyword cType Parameters
+syn keyword cType Patch
+syn keyword cType Pengrid
 syn keyword cType Penpair
-syn keyword cType Loads
-syn keyword cType Icefront
-syn keyword cType Friction
+syn keyword cType Penta
+syn keyword cType PentaInput
+syn keyword cType PentaP1ElementResult
+syn keyword cType PentaRef
+syn keyword cType PowerVariogram
+syn keyword cType Profiler
+syn keyword cType Quadtree
+syn keyword cType Results
+syn keyword cType RiftStruct
 syn keyword cType Riftfront
-syn keyword cType Numericalflux
-syn keyword cType Pengrid
-syn keyword cType Contours
-syn keyword cType Vertex
-syn keyword cType ElementMatrix
-syn keyword cType ElementVector
-syn keyword cType Profiler
-syn keyword cType Results
-syn keyword cType PentaP1ElementResult
-syn keyword cType DoubleElementResult
-syn keyword cType BoolElementResult
-syn keyword cType TriaP1ElementResult
-syn keyword cType Elements
-syn keyword cType TriaHook
-syn keyword cType PentaHook
-syn keyword cType Tria
-syn keyword cType Penta
-syn keyword cType TriaRef
-syn keyword cType PentaRef
-syn keyword cType GaussTria
-syn keyword cType GaussPenta
-syn keyword cType DependentObject
-syn keyword cType Patch
-syn keyword cType Hook
-syn keyword cType ControlInput
-syn keyword cType DatasetInput
-syn keyword cType IntInput
-syn keyword cType BoolInput
-syn keyword cType Inputs
-syn keyword cType TransientInput
-syn keyword cType PentaP1Input
-syn keyword cType DoubleInput
-syn keyword cType TriaInput
-syn keyword cType Constraints
+syn keyword cType Segment
 syn keyword cType SpcDynamic
 syn keyword cType SpcStatic
 syn keyword cType SpcTransient
-syn keyword cType Nodes
-syn keyword cType IndependentObject
+syn keyword cType SphericalVariogram
+syn keyword cType StringArrayParam
+syn keyword cType StringParam
+syn keyword cType TransientInput
+syn keyword cType TransientParam
+syn keyword cType Tria
+syn keyword cType TriaInput
+syn keyword cType TriaP1ElementResult
+syn keyword cType TriaRef
+syn keyword cType Update
+syn keyword cType Variogram
+syn keyword cType VectorParam
+syn keyword cType Vertex
 syn keyword cType Vertices
-syn keyword cType Node
-syn keyword cType IoModel
-syn keyword cType FemModel
+syn keyword cType classes
+syn keyword cType gaussobjects
+syn keyword cType krigingobjects
+syn keyword cType matrixobjects
 "ISSM's objects end
 "ISSM's Enums begin
@@ -524,34 +543,38 @@
 syn keyword cConstant ConstantsYtsEnum
 syn keyword cConstant DependentObjectEnum
-syn keyword cConstant DiagnosticAbstolEnum
-syn keyword cConstant DiagnosticIcefrontEnum
-syn keyword cConstant DiagnosticIsnewtonEnum
-syn keyword cConstant DiagnosticMaxiterEnum
-syn keyword cConstant DiagnosticNumRequestedOutputsEnum
-syn keyword cConstant DiagnosticPenaltyFactorEnum
-syn keyword cConstant DiagnosticReferentialEnum
-syn keyword cConstant DiagnosticReltolEnum
-syn keyword cConstant DiagnosticRequestedOutputsEnum
-syn keyword cConstant DiagnosticRestolEnum
-syn keyword cConstant DiagnosticRiftPenaltyLockEnum
-syn keyword cConstant DiagnosticRiftPenaltyThresholdEnum
-syn keyword cConstant DiagnosticShelfDampeningEnum
-syn keyword cConstant DiagnosticSpcvxEnum
-syn keyword cConstant DiagnosticSpcvyEnum
-syn keyword cConstant DiagnosticSpcvzEnum
-syn keyword cConstant DiagnosticStokesreconditioningEnum
-syn keyword cConstant DiagnosticVertexPairingEnum
-syn keyword cConstant DiagnosticViscosityOvershootEnum
+syn keyword cConstant StressbalanceAbstolEnum
+syn keyword cConstant StressbalanceIcefrontEnum
+syn keyword cConstant StressbalanceIsnewtonEnum
+syn keyword cConstant StressbalanceMaxiterEnum
+syn keyword cConstant StressbalanceNumRequestedOutputsEnum
+syn keyword cConstant StressbalancePenaltyFactorEnum
+syn keyword cConstant StressbalanceReferentialEnum
+syn keyword cConstant StressbalanceReltolEnum
+syn keyword cConstant StressbalanceRequestedOutputsEnum
+syn keyword cConstant StressbalanceRestolEnum
+syn keyword cConstant StressbalanceRiftPenaltyLockEnum
+syn keyword cConstant StressbalanceRiftPenaltyThresholdEnum
+syn keyword cConstant StressbalanceShelfDampeningEnum
+syn keyword cConstant StressbalanceSpcvxEnum
+syn keyword cConstant StressbalanceSpcvyEnum
+syn keyword cConstant StressbalanceSpcvzEnum
+syn keyword cConstant StressbalanceFSreconditioningEnum
+syn keyword cConstant StressbalanceVertexPairingEnum
+syn keyword cConstant StressbalanceViscosityOvershootEnum
 syn keyword cConstant LoadingforceXEnum
 syn keyword cConstant LoadingforceYEnum
 syn keyword cConstant LoadingforceZEnum
-syn keyword cConstant FlowequationBordermacayealEnum
-syn keyword cConstant FlowequationBorderpattynEnum
-syn keyword cConstant FlowequationBorderstokesEnum
+syn keyword cConstant FlowequationBorderSSAEnum
+syn keyword cConstant FlowequationBorderHOEnum
+syn keyword cConstant FlowequationBorderFSEnum
 syn keyword cConstant FlowequationElementEquationEnum
-syn keyword cConstant FlowequationIshutterEnum
-syn keyword cConstant FlowequationIsl1l2Enum
-syn keyword cConstant FlowequationIsmacayealpattynEnum
-syn keyword cConstant FlowequationIsstokesEnum
+syn keyword cConstant FlowequationIsSIAEnum
+syn keyword cConstant FlowequationIsSSAEnum
+syn keyword cConstant FlowequationIsL1L2Enum
+syn keyword cConstant FlowequationIsHOEnum
+syn keyword cConstant FlowequationIsFSEnum
+syn keyword cConstant FlowequationFeSSAEnum
+syn keyword cConstant FlowequationFeHOEnum
+syn keyword cConstant FlowequationFeFSEnum
 syn keyword cConstant FlowequationVertexEquationEnum
 syn keyword cConstant FrictionCoefficientEnum
@@ -623,8 +646,7 @@
 syn keyword cConstant MaskElementonfloatingiceEnum
 syn keyword cConstant MaskElementongroundediceEnum
-syn keyword cConstant MaskElementonwaterEnum
 syn keyword cConstant MaskVertexonfloatingiceEnum
 syn keyword cConstant MaskVertexongroundediceEnum
-syn keyword cConstant MaskVertexonwaterEnum
+syn keyword cConstant MaskIceLevelsetEnum
 syn keyword cConstant MaterialsBetaEnum
 syn keyword cConstant MaterialsHeatcapacityEnum
@@ -650,6 +672,4 @@
 syn keyword cConstant MeshAverageVertexConnectivityEnum
 syn keyword cConstant MeshDimensionEnum
-syn keyword cConstant MeshEdgesEnum
-syn keyword cConstant MeshElementconnectivityEnum
 syn keyword cConstant MeshElementonbedEnum
 syn keyword cConstant MeshElementonsurfaceEnum
@@ -657,5 +677,4 @@
 syn keyword cConstant MeshElementsEnum
 syn keyword cConstant MeshLowerelementsEnum
-syn keyword cConstant MeshNumberofedgesEnum
 syn keyword cConstant MeshNumberofelements2dEnum
 syn keyword cConstant MeshNumberofelementsEnum
@@ -670,12 +689,13 @@
 syn keyword cConstant MeshZEnum
 syn keyword cConstant MiscellaneousNameEnum
-syn keyword cConstant PrognosticHydrostaticAdjustmentEnum
-syn keyword cConstant PrognosticMinThicknessEnum
-syn keyword cConstant PrognosticPenaltyFactorEnum
-syn keyword cConstant PrognosticSpcthicknessEnum
-syn keyword cConstant PrognosticStabilizationEnum
-syn keyword cConstant PrognosticVertexPairingEnum
-syn keyword cConstant PrognosticNumRequestedOutputsEnum
-syn keyword cConstant PrognosticRequestedOutputsEnum
+syn keyword cConstant MasstransportHydrostaticAdjustmentEnum
+syn keyword cConstant MasstransportIsfreesurfaceEnum
+syn keyword cConstant MasstransportMinThicknessEnum
+syn keyword cConstant MasstransportPenaltyFactorEnum
+syn keyword cConstant MasstransportSpcthicknessEnum
+syn keyword cConstant MasstransportStabilizationEnum
+syn keyword cConstant MasstransportVertexPairingEnum
+syn keyword cConstant MasstransportNumRequestedOutputsEnum
+syn keyword cConstant MasstransportRequestedOutputsEnum
 syn keyword cConstant QmuIsdakotaEnum
 syn keyword cConstant MassFluxSegmentsEnum
@@ -687,4 +707,5 @@
 syn keyword cConstant QmuResponsedescriptorsEnum
 syn keyword cConstant QmuVariabledescriptorsEnum
+syn keyword cConstant QmuMaterialsRheologyBEnum
 syn keyword cConstant RiftsNumriftsEnum
 syn keyword cConstant RiftsRiftstructEnum
@@ -736,7 +757,7 @@
 syn keyword cConstant TimesteppingTimeAdaptEnum
 syn keyword cConstant TimesteppingTimeStepEnum
-syn keyword cConstant TransientIsdiagnosticEnum
+syn keyword cConstant TransientIsstressbalanceEnum
 syn keyword cConstant TransientIsgroundinglineEnum
-syn keyword cConstant TransientIsprognosticEnum
+syn keyword cConstant TransientIsmasstransportEnum
 syn keyword cConstant TransientIsthermalEnum
 syn keyword cConstant TransientIsgiaEnum
@@ -754,14 +775,14 @@
 syn keyword cConstant BalancethicknessAnalysisEnum
 syn keyword cConstant BalancethicknessSolutionEnum
-syn keyword cConstant WeakBalancethicknessAnalysisEnum
-syn keyword cConstant WeakBalancethicknessSolutionEnum
+syn keyword cConstant BalancethicknessSoftAnalysisEnum
+syn keyword cConstant BalancethicknessSoftSolutionEnum
 syn keyword cConstant BedSlopeAnalysisEnum
 syn keyword cConstant BedSlopeSolutionEnum
 syn keyword cConstant BedSlopeXAnalysisEnum
 syn keyword cConstant BedSlopeYAnalysisEnum
-syn keyword cConstant DiagnosticHorizAnalysisEnum
-syn keyword cConstant DiagnosticHutterAnalysisEnum
-syn keyword cConstant DiagnosticSolutionEnum
-syn keyword cConstant DiagnosticVertAnalysisEnum
+syn keyword cConstant StressbalanceAnalysisEnum
+syn keyword cConstant StressbalanceSIAAnalysisEnum
+syn keyword cConstant StressbalanceSolutionEnum
+syn keyword cConstant StressbalanceVerticalAnalysisEnum
 syn keyword cConstant EnthalpyAnalysisEnum
 syn keyword cConstant EnthalpySolutionEnum
@@ -773,6 +794,8 @@
 syn keyword cConstant HydrologySolutionEnum
 syn keyword cConstant MeltingAnalysisEnum
-syn keyword cConstant PrognosticAnalysisEnum
-syn keyword cConstant PrognosticSolutionEnum
+syn keyword cConstant MasstransportAnalysisEnum
+syn keyword cConstant MasstransportSolutionEnum
+syn keyword cConstant FreeSurfaceBaseAnalysisEnum
+syn keyword cConstant FreeSurfaceTopAnalysisEnum
 syn keyword cConstant SteadystateSolutionEnum
 syn keyword cConstant SurfaceSlopeAnalysisEnum
@@ -787,12 +810,14 @@
 syn keyword cConstant ApproximationEnum
 syn keyword cConstant NoneApproximationEnum
-syn keyword cConstant HutterApproximationEnum
-syn keyword cConstant MacAyealApproximationEnum
-syn keyword cConstant MacAyealPattynApproximationEnum
-syn keyword cConstant MacAyealStokesApproximationEnum
+syn keyword cConstant SIAApproximationEnum
+syn keyword cConstant SSAApproximationEnum
+syn keyword cConstant SSAHOApproximationEnum
+syn keyword cConstant SSAFSApproximationEnum
 syn keyword cConstant L1L2ApproximationEnum
-syn keyword cConstant PattynApproximationEnum
-syn keyword cConstant PattynStokesApproximationEnum
-syn keyword cConstant StokesApproximationEnum
+syn keyword cConstant HOApproximationEnum
+syn keyword cConstant HOFSApproximationEnum
+syn keyword cConstant FSApproximationEnum
+syn keyword cConstant FSvelocityEnum
+syn keyword cConstant FSpressureEnum
 syn keyword cConstant ConstraintsEnum
 syn keyword cConstant LoadsEnum
@@ -829,6 +854,6 @@
 syn keyword cConstant TransientParamEnum
 syn keyword cConstant IceFrontTypeEnum
-syn keyword cConstant MacAyeal2dIceFrontEnum
-syn keyword cConstant MacAyeal3dIceFrontEnum
+syn keyword cConstant SSA2dIceFrontEnum
+syn keyword cConstant SSA3dIceFrontEnum
 syn keyword cConstant MaticeEnum
 syn keyword cConstant MatdamageiceEnum
@@ -839,9 +864,9 @@
 syn keyword cConstant ParamEnum
 syn keyword cConstant L1L2IceFrontEnum
-syn keyword cConstant PattynIceFrontEnum
+syn keyword cConstant HOIceFrontEnum
 syn keyword cConstant PengridEnum
 syn keyword cConstant PenpairEnum
 syn keyword cConstant PentaEnum
-syn keyword cConstant PentaP1InputEnum
+syn keyword cConstant PentaInputEnum
 syn keyword cConstant ProfilerEnum
 syn keyword cConstant MatrixParamEnum
@@ -855,5 +880,5 @@
 syn keyword cConstant SpcStaticEnum
 syn keyword cConstant SpcTransientEnum
-syn keyword cConstant StokesIceFrontEnum
+syn keyword cConstant FSIceFrontEnum
 syn keyword cConstant StringArrayParamEnum
 syn keyword cConstant StringParamEnum
@@ -900,4 +925,7 @@
 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
@@ -924,8 +952,8 @@
 syn keyword cConstant VyPicardEnum
 syn keyword cConstant VzEnum
-syn keyword cConstant VzMacAyealEnum
-syn keyword cConstant VzPattynEnum
+syn keyword cConstant VzSSAEnum
+syn keyword cConstant VzHOEnum
 syn keyword cConstant VzPicardEnum
-syn keyword cConstant VzStokesEnum
+syn keyword cConstant VzFSEnum
 syn keyword cConstant VxMeshEnum
 syn keyword cConstant VyMeshEnum
@@ -944,4 +972,5 @@
 syn keyword cConstant WatercolumnEnum
 syn keyword cConstant BasalFrictionEnum
+syn keyword cConstant BasalMeltrateEnum
 syn keyword cConstant ViscousHeatingEnum
 syn keyword cConstant QmuTemperatureEnum
@@ -961,6 +990,14 @@
 syn keyword cConstant P1Enum
 syn keyword cConstant P1DGEnum
+syn keyword cConstant P1bubbleEnum
+syn keyword cConstant P1bubblecondensedEnum
+syn keyword cConstant P2Enum
+syn keyword cConstant P2xP1Enum
+syn keyword cConstant P1xP2Enum
+syn keyword cConstant P1P1Enum
+syn keyword cConstant P1P1GLSEnum
 syn keyword cConstant MINIEnum
-syn keyword cConstant P2Enum
+syn keyword cConstant MINIcondensedEnum
+syn keyword cConstant TaylorHoodEnum
 syn keyword cConstant SaveResultsEnum
 syn keyword cConstant BoolElementResultEnum
@@ -1000,6 +1037,6 @@
 syn keyword cConstant SubelementMigrationEnum
 syn keyword cConstant SubelementMigration2Enum
-syn keyword cConstant GLlevelsetEnum
-syn keyword cConstant StokesSolverEnum
+syn keyword cConstant MaskGroundediceLevelsetEnum
+syn keyword cConstant FSSolverEnum
 syn keyword cConstant AdjointEnum
 syn keyword cConstant ColinearEnum
@@ -1034,5 +1071,5 @@
 syn keyword cConstant NearestInterpEnum
 syn keyword cConstant XYEnum
-syn keyword cConstant XYZPEnum
+syn keyword cConstant XYZEnum
 syn keyword cConstant DenseEnum
 syn keyword cConstant MpiDenseEnum
@@ -1048,4 +1085,5 @@
 syn keyword cConstant PatersonEnum
 syn keyword cConstant ArrheniusEnum
+syn keyword cConstant LliboutryDuvalEnum
 "ISSM's Enums end
 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
Index: /issm/trunk/externalpackages/vim/addons/vimrc
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vimrc	(revision 16136)
+++ /issm/trunk/externalpackages/vim/addons/vimrc	(revision 16137)
@@ -93,4 +93,7 @@
 nnoremap <silent> <Space> :silent noh<Bar>echo<CR> 
 
+"increment number
+nnoremap <C-i> <C-a>
+
 "line numbering in flip-flop
 map num :set number!<CR>
@@ -152,4 +155,6 @@
 " and here some nice options for cindenting
 set cinoptions={.5s,+.5s,t0,n-2,p2s,(03s,=.5s,>1s,=1s,:1s 
+" pound sign identation
+inoremap # X<c-h>#
 " ----------------------------------------------------------------------}}}
 " TEX special{{{
@@ -198,17 +203,19 @@
 	return (c =~ a:pat) ? '' : c
 endfunc
-au BufRead,BufNewFile *.html     iabbr <silent> H1 <h1></h1><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.html     iabbr <silent> H2 <h2></h2><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.html     iabbr <silent> H3 <h3></h3><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.html     iabbr <silent> CO <code></code><Left><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.html     iabbr <silent> PP <p></p><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.m        iabbr <silent> p1  disp('');<Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.m        iab <expr> p0  "disp('-------------- file: ".expand('%')." line: ".line(".")."');"
-au BufRead,BufNewFile *.c*       iabbr <silent> p1  printf("\n");<Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.c*,*.h   iabbr <silent> ER  _error_("");<Left><Left><Left><C-R>=Eatchar('\s')<CR>
-au BufRead,BufNewFile *.c*       ab VV VecView(ug,PETSC_VIEWER_STDOUT_WORLD);
-au BufRead,BufNewFile *.c*       ab AS _assert_();
-au BufRead,BufNewFile *.c*       iab <expr> p0  "printf(\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);"
-au BufRead,BufNewFile *.c*       iab <expr> pp0 "PetscSynchronizedPrintf(MPI_COMM_WORLD,\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);\nPetscSynchronizedFlush(MPI_COMM_WORLD);"
+au BufRead,BufNewFile *.html   iabbr <silent> H1 <h1></h1><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html   iabbr <silent> H2 <h2></h2><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html   iabbr <silent> H3 <h3></h3><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html   iabbr <silent> CO <code></code><Left><Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.html   iabbr <silent> PP <p></p><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+"au BufRead,BufNewFile *.m      iabbr <silent> p1  disp('');<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.m      iab <expr> p0  "disp('-------------- file: ".expand('%')." line: ".line(".")."');"
+au BufRead,BufNewFile *.c*,*.h iabbr <silent> p1  printf("\n");<Left><Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.c*,*.h iabbr <silent> ER  _error_("");<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.py     iabbr <silent> ER  raise NameError('')<Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.m      iabbr <silent> ER  error('');<Left><Left><Left><C-R>=Eatchar('\s')<CR>
+au BufRead,BufNewFile *.c*     ab VV VecView(ug,PETSC_VIEWER_STDOUT_WORLD);
+au BufRead,BufNewFile *.c*,*.h ab AS _assert_();
+au BufRead,BufNewFile *.c*,*.h iab <expr> p0  "printf(\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);"
+au BufRead,BufNewFile *.c*,*.h iab <expr> pp0 "PetscSynchronizedPrintf(MPI_COMM_WORLD,\"-------------- file: ".expand('%')." line: %i\\n\",__LINE__);\nPetscSynchronizedFlush(MPI_COMM_WORLD);"
 "tex
 au BufRead,BufNewFile *.tex iab EQ 
Index: /issm/trunk/m4/issm_options.cmake
===================================================================
--- /issm/trunk/m4/issm_options.cmake	(revision 16137)
+++ /issm/trunk/m4/issm_options.cmake	(revision 16137)
@@ -0,0 +1,37 @@
+# ISSM Options {{{
+option(DAKOTA "DAKOTA" OFF)
+option(PETSC "PETSC" OFF)
+option(MUMPS "MUMPS" OFF)
+#option(GSL "GSL" OFF)
+option(TRANSIENT "TRANSIENT" ON)
+option(STEADYSTATE "STEADYSTATE" ON)
+option(PROGNOSTIC "PROGNOSTIC" ON)
+option(THERMAL "THERMAL" ON)
+option(GIA "GIA" OFF)
+option(CONTROL "CONTROL" ON)
+option(HYDROLOGY "HYDROLOGY" ON)
+option(DIAGNOSTIC "DIAGNOSTIC" ON)
+option(BALANCED "BALANCED" ON)
+option(SLOPE "SLOPE" ON)
+option(GROUNDINGLINE "GROUNDINGLINE" ON)
+option(RIFTS "RIFTS" ON)
+option(ANDROID "ANDROID" OFF)
+option(THREED "THREED" ON)
+option(MPI "MPI" OFF)
+option(METIS "METIS" OFF)
+option(KRIGING "KRIGING" OFF)
+# }}}
+
+if(NOT GSL_DIR)
+    message(FATAL_ERROR "Non GSL build not supported")
+else(NOT GSL_DIR)
+    find_path(GSL lib ${GSL_DIR})
+
+    if(GSL)
+        message("Found GSL: ${GSL_DIR}")
+        set(GSL_INC_DIR ${GSL_DIR}/include)
+        set(GSL_LIB_DIR ${GSL_DIR}/lib)
+    else(GSL)
+        message(FATAL_ERROR "GSL installation directory not found!")
+    endif(GSL)
+endif(NOT GSL_DIR)
Index: /issm/trunk/m4/issm_options.m4
===================================================================
--- /issm/trunk/m4/issm_options.m4	(revision 16136)
+++ /issm/trunk/m4/issm_options.m4	(revision 16137)
@@ -2,4 +2,8 @@
 
 AC_DEFUN([ISSM_OPTIONS],[
+
+	AC_MSG_NOTICE(============================================================================)
+	AC_MSG_NOTICE(=                      Checking ISSM specific options                      =)
+	AC_MSG_NOTICE(============================================================================)
 
 	dnl ISSM's internal options
@@ -9,9 +13,21 @@
 		[enable_debugging=$enableval],                                 dnl action if given
 		[enable_debugging=no])                                         dnl action if not given
+
+	AC_MSG_CHECKING(for debugging support)
 	if test "x$enable_debugging" = xyes; then
 		AC_DEFINE([_ISSM_DEBUG_],[1],[Macro to enable debugging in ISSM])
 	fi
-
-	dnl }}}
+	AC_MSG_RESULT($enable_debugging)
+	dnl }}}
+	dnl Development{{{
+	AC_ARG_ENABLE([development],                                      dnl feature
+		AS_HELP_STRING([--enable-development],[turn development on]),  dnl help string
+		[enable_development=$enableval],                                 dnl action if given
+		[enable_development=no])                                      dnl action if not given
+
+	AC_MSG_CHECKING(for development support)
+	AM_CONDITIONAL([DEVELOPMENT], [test x$enable_development = xyes])
+	AC_MSG_RESULT($enable_development)
+	 dnl }}}
     dnl Shared build {{{
     AC_ARG_ENABLE([sharedlibs],                                                dnl feature
@@ -19,17 +35,20 @@
         [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 }}}
     dnl Version{{{
-    AC_ARG_ENABLE([version],                                                dnl feature
-        AS_HELP_STRING([--enable-version], [produce libISSM.so.0]),         dnl help string
-        [enable_version=$enableval],                                        dnl action if given
-        [enable_version=no])                                                dnl action if not given
+    AC_ARG_ENABLE([version],                                   dnl feature
+    AS_HELP_STRING([--enable-version],[produce libISSM.so.0]), dnl help string
+    [enable_version=$enableval],                               dnl action if given
+    [enable_version=no])                                       dnl action if not given
     AM_CONDITIONAL([VERSION], [test x$enable_VERSION = xyes])
     dnl }}}
 	dnl Wrappers build {{{
-	AC_ARG_WITH([wrappers],
-		AS_HELP_STRING([--with-wrappers = value],[wrappers compilation. ]),
-		[WRAPPERS_VALUE=$withval],[WRAPPERS_VALUE="yes"])
+	AC_ARG_WITH([wrappers],                                           dnl feature
+	AS_HELP_STRING([--with-wrappers = value],[wrappers compilation]), dnl help string
+	[WRAPPERS_VALUE=$withval],                                        dnl action if given
+	[WRAPPERS_VALUE="yes"])                                           dnl action if not given
 	AC_MSG_CHECKING(for wrappers compilation)
 	AM_CONDITIONAL([WRAPPERS], [test x$WRAPPERS_VALUE = xyes])
@@ -43,10 +62,10 @@
 	dnl ISSM's externalpackages
 	dnl vendor{{{
-	AC_ARG_WITH([vendor],
-	  AS_HELP_STRING([--with-vendor = VENDOR], [vendor name, ex: intel]),
-	  [VENDOR=$withval],[VENDOR=""]) 
+	AC_ARG_WITH([vendor],                                              dnl feature
+	AS_HELP_STRING([--with-vendor = VENDOR],[vendor name, ex: intel]), dnl help string
+	[VENDOR=$withval],                                                 dnl action if given
+	[VENDOR=""])                                                       dnl action if not given
 	AC_MSG_CHECKING(for vendor compilers)
 	if test -n "$VENDOR"; then
-
 		if  test $VENDOR = intel-win32; then
 			export CC=icl
@@ -97,16 +116,20 @@
 
 	dnl 1. See if matlab has been provided
-	AC_ARG_WITH([matlab-dir],
-		AS_HELP_STRING([--with-matlab-dir=DIR], [matlab root directory. necessary for serial build.]),
-		[MATLAB_ROOT=$withval],[MATLAB_ROOT=""]) 
+	AC_ARG_WITH([matlab-dir],                                         dnl feature
+	AS_HELP_STRING([--with-matlab-dir=DIR],[matlab root directory.]), dnl help string
+	[MATLAB_ROOT=$withval],                                           dnl action if given
+	[MATLAB_ROOT="no"])                                               dnl action if not given
 
 	AC_MSG_CHECKING([whether matlab is enabled])
-	if test -d "$MATLAB_ROOT"; then
+	if test "x$MATLAB_ROOT" = "xno" ; then
+		 HAVE_MATLAB=no
+	else
 		HAVE_MATLAB=yes
-	else
-		HAVE_MATLAB=no
-	fi
-	if test x$HAVE_MATLAB = xyes; then
-		AC_DEFINE([_HAVE_MATLAB_],[1],[with Matlab in ISSM src])
+		if ! test -d "$MATLAB_ROOT"; then
+		  AC_MSG_ERROR([matlab directory provided ($MATLAB_ROOT) does not exist]);
+		fi
+		if ! test -f "$MATLAB_ROOT/extern/include/mex.h"; then
+			AC_MSG_ERROR([Couldn't find mex.h... check your installation of matlab])
+	   fi
 	fi
 	AC_MSG_RESULT($HAVE_MATLAB)
@@ -114,11 +137,10 @@
 
 	dnl 2. Get Matlab libraries
-	if test x$HAVE_MATLAB = xyes; then
-
-		AC_MSG_CHECKING(for matlab headers and libraries in $MATLAB_ROOT)
+	if test "x$HAVE_MATLAB" = "xyes"; then
+
+		AC_DEFINE([_HAVE_MATLAB_],[1],[with matlab in ISSM src])
   		MATLABINCL="-I$MATLAB_ROOT/extern/include/"
 		
-		dnl 4. get MEXLIB MEXLINK and MEXEXT (experimental)
-      dnl OS-dependent variables and checks
+		dnl 4. get MEXLIB MEXLINK and MEXEXT (experimental) except for windows
   		case "${host_os}" in
   			*cygwin*) 
@@ -139,6 +161,4 @@
   			;;
       esac
-	   AC_MSG_RESULT(done)
-
 		AC_SUBST([MATLABINCL])
 		AC_SUBST([MEX])
@@ -151,14 +171,26 @@
 	dnl triangle {{{
 	AC_ARG_WITH([triangle-dir],
-			  AS_HELP_STRING([--with-triangle-dir=DIR], [triangle root directory. necessary for serial build]),
-			 [TRIANGLE_ROOT=$withval],[TRIANGLE_ROOT=""]) 
-	AC_MSG_CHECKING(for triangle headers and libraries)
-
-	if test -d "$TRIANGLE_ROOT"; then
-
-		dnl defaults
+			  AS_HELP_STRING([--with-triangle-dir=DIR], [triangle root directory.]),
+			 [TRIANGLE_ROOT=$withval],[TRIANGLE_ROOT="no"]) 
+
+  dnl Check whether triangle is enabled
+	AC_MSG_CHECKING([for triangle])
+	if test "x$TRIANGLE_ROOT" = "xno" ; then
+		HAVE_TRIANGLE=no
+	else
 		HAVE_TRIANGLE=yes
+		if ! test -d "$TRIANGLE_ROOT"; then
+			AC_MSG_ERROR([triangle directory provided ($TRIANGLE_ROOT) does not exist]);
+		fi
+		if ! test -f "$TRIANGLE_ROOT/triangle.h" ; then
+			AC_MSG_ERROR([Couldn't find triangle.h... check your installation of triangle])
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_TRIANGLE)
+	AM_CONDITIONAL([TRIANGLE],[test x$HAVE_TRIANGLE = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_TRIANGLE" = "xyes"; then
 		TRIANGLEINCL=-I$TRIANGLE_ROOT/
-
 		case "${host_os}" in
 				*cygwin*)
@@ -172,26 +204,58 @@
 				;;
 			esac
-
 		AC_DEFINE([_HAVE_TRIANGLE_],[1],[with Triangle in ISSM src])
 		AC_SUBST([TRIANGLEINCL])
 		AC_SUBST([TRIANGLELIB])
-
-	else
-		HAVE_TRIANGLE=no
-	fi
-	AC_MSG_RESULT($HAVE_TRIANGLE)
+	fi
+	dnl }}}
+	dnl boost{{{
+	AC_ARG_WITH([boost-dir],
+	  AS_HELP_STRING([--with-boost-dir=DIR], [boost root directory.]),
+	  [BOOST_ROOT=$withval],[BOOST_ROOT="no"]) 
+
+	dnl Check whether boost is enabled
+	AC_MSG_CHECKING([for boost])
+	if test "x$BOOST_ROOT" = "xno" ; then
+		HAVE_BOOST=no
+	else
+		HAVE_BOOST=yes
+		if ! test -d "$BOOST_ROOT"; then
+			AC_MSG_ERROR([boost directory provided ($BOOST_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_BOOST)
+	AM_CONDITIONAL([BOOST],[test x$HAVE_BOOST = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_BOOST" = "xyes"; then
+		BOOSTINCL=-I$BOOST_ROOT/include
+		BOOSTLIB="-L$BOOST_ROOT/lib -lboost_python"
+		AC_DEFINE([_HAVE_BOOST_],[1],[with Boost in ISSM src])
+		AC_SUBST([BOOSTINCL])
+		AC_SUBST([BOOSTLIB])
+	fi
 	dnl }}}
 	dnl dakota{{{
 	AC_ARG_WITH([dakota-dir],
-	  AS_HELP_STRING([--with-dakota-dir=DIR], [dakota root directory. necessary for serial build]),
-	  [DAKOTA_ROOT=$withval],[DAKOTA_ROOT=""]) 
-	AC_MSG_CHECKING(for dakota)
-	
-	if test -d "$DAKOTA_ROOT"; then
-
-		dnl defaults
+	  AS_HELP_STRING([--with-dakota-dir=DIR], [dakota root directory.]),
+	  [DAKOTA_ROOT=$withval],[DAKOTA_ROOT="no"]) 
+	
+	dnl Check whether dakota is enabled
+	AC_MSG_CHECKING([for dakota])
+	if test "x$DAKOTA_ROOT" = "xno" ; then
+		HAVE_DAKOTA=no
+	else
 		HAVE_DAKOTA=yes
-		AC_MSG_RESULT($HAVE_DAKOTA)
+		if ! test -d "$DAKOTA_ROOT"; then
+			AC_MSG_ERROR([dakota directory provided ($DAKOTA_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_DAKOTA)
+	AM_CONDITIONAL([DAKOTA],[test x$HAVE_DAKOTA = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_DAKOTA" = "xyes"; then
 		DAKOTAINCL=-I$DAKOTA_ROOT/include
+
 		AC_MSG_CHECKING(for dakota version)
 		if test -f "$DAKOTA_ROOT/../src/src/CommandLineHandler.C"; then
@@ -203,7 +267,7 @@
 		fi
 		fi
-
 		AC_MSG_RESULT($DAKOTA_VERSION)
 		AC_DEFINE_UNQUOTED([_DAKOTA_VERSION_],"$DAKOTA_VERSION",[Dakota version number])
+
 		DAKOTAFLAGS=""
 		case "${host_os}" in
@@ -212,5 +276,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 -lboost_system"
+					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"
 				else
 					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
@@ -225,5 +289,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"
+					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 "
 				else
 					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
@@ -245,5 +309,4 @@
 			;;
 		esac
-		AC_DEFINE([_HAVE_DAKOTA_],[1],[with Dakota in ISSM src])
 
 		case $DAKOTA_VERSION in
@@ -277,73 +340,49 @@
 		AC_DEFINE_UNQUOTED([_DAKOTA_BUILD_],$DAKOTA_BUILD,[Dakota build version number])
 
+		AC_DEFINE([_HAVE_DAKOTA_],[1],[with Dakota in ISSM src])
 		AC_SUBST([DAKOTAINCL])
 		AC_SUBST([DAKOTAFLAGS])
 		AC_SUBST([DAKOTALIB])
-
-	else
-		HAVE_DAKOTA=no
-		AC_MSG_RESULT($HAVE_DAKOTA)
-	fi
-
-	AM_CONDITIONAL([DAKOTA], [test x$HAVE_DAKOTA = xyes])
-	dnl }}}
-	dnl boost{{{
-	AC_ARG_WITH([boost-dir],
-	  AS_HELP_STRING([--with-boost-dir=DIR], [boost root directory.]),
-	  [BOOST_ROOT=$withval],[BOOST_ROOT=""]) 
-	AC_MSG_CHECKING(for boost)
-	
-	if test -d "$BOOST_ROOT"; then
-		dnl defaults
-		HAVE_BOOST=yes
-		BOOSTINCL=-I$BOOST_ROOT/include
-		BOOSTLIB="-L$BOOST_ROOT/lib -lboost_python"
-
-		AC_DEFINE([_HAVE_BOOST_],[1],[with Boost in ISSM src])
-		AC_SUBST([BOOSTINCL])
-		AC_SUBST([BOOSTLIB])
-	else
-		HAVE_BOOST=no
-	fi
-	AM_CONDITIONAL([BOOST], [test x$HAVE_BOOST = xyes])
-	AC_MSG_RESULT($HAVE_BOOST)
+	fi
 	dnl }}}
 	dnl python{{{
 	AC_ARG_WITH([python-dir],
 	  AS_HELP_STRING([--with-python-dir=DIR], [python root directory.]),
-	  [PYTHON_ROOT=$withval],[PYTHON_ROOT=""]) 
-
-	AC_MSG_CHECKING(for python)
-	if test -d "$PYTHON_ROOT"; then
-		HAVE_PYTHON="yes"
-		AC_DEFINE([_HAVE_PYTHON_],[1],[with Python in ISSM src])
-	else
+	  [PYTHON_ROOT=$withval],[PYTHON_ROOT="no"]) 
+
+	dnl Check whether python is enabled
+	AC_MSG_CHECKING([for python])
+	if test "x$PYTHON_ROOT" = "xno" ; then
 		HAVE_PYTHON=no
+		HAVE_PYTHON3=no
+	else
+		HAVE_PYTHON=yes
+		if ! test -d "$PYTHON_ROOT"; then
+			AC_MSG_ERROR([python directory provided ($PYTHON_ROOT) does not exist]);
+		fi
 	fi
 	AC_MSG_RESULT($HAVE_PYTHON)
-
-	dnl get python version
-	if test x$HAVE_PYTHON = xyes; then
+	AM_CONDITIONAL([PYTHON],[test x$HAVE_PYTHON = xyes])
+
+	dnl python specifics
+	if test "x$HAVE_PYTHON" = "xyes"; then
 		AC_MSG_CHECKING(for python version)
-		dnl Query Python for its version number.  Getting [:3] seems to be
-		dnl the best way to do this; it's what "site.py" does in the standard
-		dnl library.
+		dnl Query Python for its version number.  Getting [:3] seems to be the
+		dnl best way to do this; it's what "site.py" does in the standard library.
 		PYTHON_VERSION=$($PYTHON_ROOT/bin/python -c "import sys; print sys.version[[:3]]")
 		AC_MSG_RESULT($PYTHON_VERSION)
 
-		dnl recover major: 
+		dnl recover major 
 		PYTHON_MAJOR=${PYTHON_VERSION%.*}
-		if test x$PYTHON_MAJOR = x3; then
-			dnl are we running python 3?
+		AC_DEFINE_UNQUOTED([_PYTHON_MAJOR_],$PYTHON_MAJOR,[python version major])
+		if test "x$PYTHON_MAJOR" = "x3"; then
 			HAVE_PYTHON3="yes"
 		else
 			HAVE_PYTHON3="no"
 		fi
-		AC_DEFINE_UNQUOTED([_PYTHON_MAJOR_],$PYTHON_MAJOR,[python version major])
 
 		PYTHONINCL=-I$PYTHON_ROOT/include
 		PYTHONLIB="-L$PYTHON_ROOT/lib -lpython$PYTHON_VERSION"
 		PYTHONEXT=.so
-
 		case "${host_os}" in
 			*cygwin*)
@@ -357,5 +396,5 @@
 			;;
 		esac
-
+		AC_DEFINE([_HAVE_PYTHON_],[1],[with python in ISSM src])
 		AC_SUBST([PYTHONINCL])
 		AC_SUBST([PYTHONLIB])
@@ -364,5 +403,4 @@
 		AC_SUBST([PYTHONLINK])
 	fi
-	AM_CONDITIONAL([PYTHON], [test x$HAVE_PYTHON = xyes])
 	AM_CONDITIONAL([PYTHON3], [test x$HAVE_PYTHON3 = xyes])
 	dnl }}}
@@ -370,62 +408,77 @@
 	AC_ARG_WITH([python-numpy-dir],
 	  AS_HELP_STRING([--with-python-numpy-dir=DIR], [python-numpy root directory.]),
-	  [PYTHON_NUMPY_ROOT=$withval],[PYTHON_NUMPY_ROOT=""]) 
+	  [PYTHON_NUMPY_ROOT=$withval],[PYTHON_NUMPY_ROOT="no"]) 
+	
+	dnl Check whether numpy is enabled
 	AC_MSG_CHECKING(for python-numpy)
-	
-	if test -d "$PYTHON_NUMPY_ROOT"; then
-		dnl defaults
+	if test "x$PYTHON_NUMPY_ROOT" = "xno" ; then
+		HAVE_PYTHON_NUMPY=no
+	else
 		HAVE_PYTHON_NUMPY=yes
+		if ! test -d "$PYTHON_NUMPY_ROOT"; then
+			AC_MSG_ERROR([numpy directory provided ($PYTHON_NUMPY_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_PYTHON_NUMPY)
+
+	dnl numpy lib
+	if test "x$HAVE_PYTHON_NUMPY" = "xyes"; then
 		PYTHON_NUMPYINCL="-I$PYTHON_NUMPY_ROOT -I$PYTHON_NUMPY_ROOT/core/include/numpy"
-
 		AC_DEFINE([_HAVE_PYTHON_NUMPY_],[1],[with Python-Numpy in ISSM src])
 		AC_SUBST([PYTHON_NUMPYINCL])
-	else
-		HAVE_PYTHON_NUMPY=no
-	fi
-	AC_MSG_RESULT($HAVE_PYTHON_NUMPY)
+	fi
 	dnl }}}
 	dnl chaco{{{
 	AC_ARG_WITH([chaco-dir],
 	  AS_HELP_STRING([--with-chaco-dir=DIR], [chaco root directory.]),
-	  [CHACO_ROOT=$withval],[CHACO_ROOT=""]) 
-	AC_MSG_CHECKING(for chaco)
-	
-	if test -d "$CHACO_ROOT"; then
-
-		dnl defaults
+	  [CHACO_ROOT=$withval],[CHACO_ROOT="no"]) 
+	
+	dnl Check whether chaco is enabled
+	AC_MSG_CHECKING([for chaco])
+	if test "x$CHACO_ROOT" = "xno" ; then
+		HAVE_CHACO=no
+	else
 		HAVE_CHACO=yes
+		if ! test -d "$CHACO_ROOT"; then
+			AC_MSG_ERROR([chaco directory provided ($CHACO_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_CHACO)
+	AM_CONDITIONAL([CHACO],[test x$HAVE_CHACO = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_CHACO" = "xyes"; then
 		CHACOINCL=-I$CHACO_ROOT/include
 		CHACOLIB="-L$CHACO_ROOT/lib -lchacominusblas"
-
 		AC_DEFINE([_HAVE_CHACO_],[1],[with Chaco in ISSM src])
 		AC_SUBST([CHACOINCL])
 		AC_SUBST([CHACOLIB])
-
-	else
-		HAVE_CHACO=no
-	fi
-	AC_MSG_RESULT($HAVE_CHACO)
+	fi
 	dnl }}}
 	dnl scotch{{{
 	AC_ARG_WITH([scotch-dir],
 	  AS_HELP_STRING([--with-scotch-dir=DIR], [scotch root directory.]),
-	  [SCOTCH_ROOT=$withval],[SCOTCH_ROOT=""]) 
-	AC_MSG_CHECKING(for scotch)
-	
-	if test -d "$SCOTCH_ROOT"; then
-
-		dnl defaults
+	  [SCOTCH_ROOT=$withval],[SCOTCH_ROOT="no"]) 
+
+  dnl Check whether scotch is enabled
+	AC_MSG_CHECKING([for scotch])
+	if test "x$SCOTCH_ROOT" = "xno" ; then
+		HAVE_SCOTCH=no
+	else
 		HAVE_SCOTCH=yes
+		if ! test -d "$SCOTCH_ROOT"; then
+			AC_MSG_ERROR([scotch directory provided ($SCOTCH_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SCOTCH)
+	
+	dnl scotch libraries
+	if test "x$HAVE_SCOTCH" = "xyes"; then
 		SCOTCHINCL="-DNOFILEIO -I$SCOTCH_ROOT/include -DSCOTCH_VERSION=\\\"UNKNOWN\\\""
 		SCOTCHLIB="-L$SCOTCH_ROOT/lib -lnfioscotch -lnfioscotcherr -lnfioscotcherrexit -lscotchmetis"
-
 		AC_DEFINE([_HAVE_SCOTCH_],[1],[with Scotch in ISSM src])
 		AC_SUBST([SCOTCHINCL])
 		AC_SUBST([SCOTCHLIB])
-
-	else
-		HAVE_SCOTCH=no
-	fi
-	AC_MSG_RESULT($HAVE_SCOTCH)
+	fi
 	dnl }}}
 	dnl adolc{{{
@@ -433,27 +486,27 @@
 		AS_HELP_STRING([--with-adolc-dir=DIR], [adolc root directory.]),
 		[ADOLC_ROOT=$withval],[ADOLC_ROOT="no"]) 
-	AC_MSG_CHECKING(for adolc)
-
-	if test "x$ADOLC_ROOT" = "xno"; then
+
+	dnl Check whether adolc is enabled
+	AC_MSG_CHECKING([for adolc])
+	if test "x$ADOLC_ROOT" = "xno" ; then
 		HAVE_ADOLC=no
 	else
-		if test -d "$ADOLC_ROOT"; then
-
-			dnl defaults
-			HAVE_ADOLC=yes
-			ADOLCINCL="-I$ADOLC_ROOT/include"
-			ADOLCLIB="-L$ADOLC_ROOT/lib64 -ladolc"
-
-			AC_DEFINE([_HAVE_ADOLC_],[1],[with adolc in ISSM src])
-			AC_SUBST([ADOLCINCL])
-			AC_SUBST([ADOLCLIB])
-
-		else
-			echo  "Specified directory does not exist!"
-			exit 1
-		fi
+		HAVE_ADOLC=yes
+		if ! test -d "$ADOLC_ROOT"; then
+			AC_MSG_ERROR([adolc directory provided ($ADOLC_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_ADOLC)
+	
+	dnl adolc headers and libraries
+	if test "x$HAVE_ADOLC" == "xyes"; then
+		ADOLCINCL="-I$ADOLC_ROOT/include"
+		dnl ADOLCLIB="-L$ADOLC_ROOT/lib64 -ladolc" used to be the path
+		ADOLCLIB="-L$ADOLC_ROOT/lib -ladolc"
+		AC_DEFINE([_HAVE_ADOLC_],[1],[with adolc in ISSM src])
+		AC_SUBST([ADOLCINCL])
+		AC_SUBST([ADOLCLIB])
 	fi
 	AM_CONDITIONAL([ADOLC], [test x$HAVE_ADOLC = xyes])
-	AC_MSG_RESULT($HAVE_ADOLC)
 	dnl }}}
 	dnl adolc-version{{{
@@ -470,73 +523,154 @@
 	  AS_HELP_STRING([--with-adic2-dir=DIR], [adic2 root directory.]),
 	  [ADIC2_ROOT=$withval],[ADIC2_ROOT="no"]) 
-	AC_MSG_CHECKING(for adic2)
-
-	if test "x$ADIC2_ROOT" = "xno"; then
+
+	dnl Check whether adic2 is enabled
+	AC_MSG_CHECKING([for adic2])
+	if test "x$ADIC2_ROOT" = "xno" ; then
 		HAVE_ADIC2=no
 	else
-		if test -d "$ADIC2_ROOT"; then
-
-			dnl defaults
-			HAVE_ADIC2=yes
-			ADIC2INCL="-DADIC2_DENSE -I$ADIC2_ROOT/include -I$ADIC2_ROOT/share/runtime_dense/"
-			ADIC2LIB=""
-
-			AC_DEFINE([_HAVE_ADIC2_],[1],[with adic2 in ISSM src])
-			AC_SUBST([ADIC2INCL])
-			AC_SUBST([ADIC2LIB])
-
-		else
-			echo  "Specified directory does not exist!"
-			exit 1
-		fi
+		HAVE_ADIC2=yes
+		if ! test -d "$ADIC2_ROOT"; then
+			AC_MSG_ERROR([adic2 directory provided ($ADIC2_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_ADIC2)
+
+	dnl adic2 headers and libraries
+	if test "x$HAVE_ADIC2" == "xyes"; then
+		ADIC2INCL="-DADIC2_DENSE -I$ADIC2_ROOT/include -I$ADIC2_ROOT/share/runtime_dense/"
+		ADIC2LIB=""
+		AC_DEFINE([_HAVE_ADIC2_],[1],[with adic2 in ISSM src])
+		AC_SUBST([ADIC2INCL])
+		AC_SUBST([ADIC2LIB])
 	fi
 	AM_CONDITIONAL([ADIC2], [test x$HAVE_ADIC2 = xyes])
-	AC_MSG_RESULT($HAVE_ADIC2)
+	dnl }}}
+	dnl atlas{{{
+	AC_ARG_WITH([atlas-dir],
+	  AS_HELP_STRING([--with-atlas-dir=DIR],[atlas root directory]),
+	  [ATLAS_ROOT=$withval],[ATLAS_ROOT="no"])
+			  
+	dnl Check whether atlas is enabled
+	AC_MSG_CHECKING(for atlas and cblas libraries)
+	if test "x$ATLAS_ROOT" = "xno" ; then
+		HAVE_ATLAS=no
+	else
+		HAVE_ATLAS=yes
+		if ! test -d "$ATLAS_ROOT"; then
+			AC_MSG_ERROR([atlas directory provided ($ATLAS_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_ATLAS)
+
+	dnl atlas headers and libraries
+	if test "x$HAVE_ATLAS" == "xyes"; then
+		dnl: branch on whether we are running on windows or linux.
+		case "${host_os}" in
+			*cygwin*)
+			ATLASLIB="-L`cygpath -m $ATLAS_ROOT` -Wl,libatlas.lib  -Wl,libcblas.lib"
+			;;
+			*linux*)
+			ATLASLIB=-L"$ATLAS_ROOT/lib -lcblas -latlas -lm " 
+			;;
+			*darwin*)
+			ATLASLIB=-L"$ATLAS_ROOT/lib -lcblas -latlas -lm" 
+			;;
+		esac
+		AC_DEFINE([_HAVE_ATLAS_],[1],[with ATLAS in ISSM src])
+		AC_SUBST([ATLASLIB])
+	fi
 	dnl }}}
 	dnl gsl{{{
 	AC_ARG_WITH([gsl-dir],
 	  AS_HELP_STRING([--with-gsl-dir=DIR], [gsl root directory.]),
-	  [GSL_ROOT=$withval],[GSL_ROOT=""]) 
-	AC_MSG_CHECKING(for gsl)
-	
-	if test -d "$GSL_ROOT"; then
-
-		dnl defaults
+	  [GSL_ROOT=$withval],[GSL_ROOT="no"]) 
+
+	dnl Check whether gsl is enabled
+	AC_MSG_CHECKING([for gsl])
+	if test "x$GSL_ROOT" = "xno" ; then
+		HAVE_GSL=no
+	else
 		HAVE_GSL=yes
+		if ! test -d "$GSL_ROOT"; then
+			AC_MSG_ERROR([gsl directory provided ($GSL_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_GSL)
+	
+	dnl gsl headers and libraries
+	if test "x$HAVE_GSL" == "xyes"; then
 		GSLINCL="-I$GSL_ROOT/include"
-		GSLLIB="-dy -L$GSL_ROOT/lib -lgsl -lgslcblas -lm"
-
+		if test "x$HAVE_ATLAS" = "xyes" ; then
+			GSLLIB="-dy -L$GSL_ROOT/lib -lgsl -L$ATLAS_ROOT/lib -lcblas -latlas -lm"
+		else
+			GSLLIB="-dy -L$GSL_ROOT/lib -lgsl -lgslcblas -lm"
+		fi
 		AC_DEFINE([_HAVE_GSL_],[1],[with gsl in ISSM src])
 		AC_SUBST([GSLINCL])
 		AC_SUBST([GSLLIB])
-
-	else
-		HAVE_GSL=no
 	fi
 	AM_CONDITIONAL([GSL], [test x$HAVE_GSL = xyes])
-	AC_MSG_RESULT($HAVE_GSL)
+	dnl }}}
+	dnl adjoinable-mpi{{{
+	AC_ARG_WITH([ampi-dir],
+	  AS_HELP_STRING([--with-ampi-dir=DIR], [adjoinable mpi root directory.]),
+	  [AMPI_ROOT=$withval],[AMPI_ROOT="no"]) 
+
+	dnl Check whether ampi is enabled
+	AC_MSG_CHECKING([for ampi])
+	if test "x$AMPI_ROOT" = "xno" ; then
+		HAVE_AMPI=no
+	else
+		HAVE_AMPI=yes
+		if ! test -d "$AMPI_ROOT"; then
+			AC_MSG_ERROR([ampi directory provided ($AMPI_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_AMPI)
+	
+	dnl ampi headers and libraries
+	if test "x$HAVE_AMPI" == "xyes"; then
+		AMPIINCL="-I$AMPI_ROOT/include"
+		if test "x$ADOLC_ROOT" == "xno"; then
+			AC_MSG_ERROR([cannot run adjoinable mpi without adolc]);
+		fi
+		dnl AMPILIB="-dy -L$AMPI_ROOT/lib -lampiCommon -L$ADOLC_ROOT/lib -ladolc -L$AMPI_ROOT/lib -lampiCommon -lampiBookkeeping -lampiTape"
+		dnl AMPILIB="-dy -L$AMPI_ROOT/lib  -L$ADOLC_ROOT/lib -Wl,--start-group,-lampiCommon,-ladolc,-lampiCommon,-lampiBookkeeping,-lampiTape,-lampiPlainC,-lampiADtoolStubsST,--end-group"
+		dnl AMPILIB="-L$AMPI_ROOT/lib  -L$ADOLC_ROOT/lib -Wl,--start-group -lampiCommon -ladolc -lampiCommon -lampiBookkeeping -lampiTape -lampiPlainC -lampiADtoolStubsST -Wl,--end-group"
+		dnl AMPILIB="$AMPI_ROOT/lib/libampiCommon.so $ADOLC_ROOT/lib/libadolc.so  $AMPI_ROOT/lib/libampiCommon.so $AMPI_ROOT/lib/libampiBookkeeping.so $AMPI_ROOT/lib/libampiTape.so $AMPI_ROOT/lib/libampiPlainC.so  $AMPI_ROOT/lib/libampiADtoolStubsST.so"
+		dnl AMPILIB="-dy -L$AMPI_ROOT/lib  -L$ADOLC_ROOT/lib -lampiCommon -ladolc -lampiCommon -lampiBookkeeping -lampiTape -lampiPlainC -lampiADtoolStubsST"
+		AMPILIB="-dy -L$AMPI_ROOT/lib  -lampiCommon -lampiBookkeeping -lampiTape"
+		AC_DEFINE([_HAVE_AMPI_],[1],[with adjoinable mpi in ISSM src])
+		AC_SUBST([AMPIINCL])
+		AC_SUBST([AMPILIB])
+	fi
+	AM_CONDITIONAL([AMPI], [test x$HAVE_AMPI = xyes])
 	dnl }}}
 	dnl rose{{{
 	AC_ARG_WITH([rose-dir],
 	  AS_HELP_STRING([--with-rose-dir=DIR], [rose root directory.]),
-	  [ROSE_ROOT=$withval],[ROSE_ROOT=""]) 
-	AC_MSG_CHECKING(for rose)
-	
-	if test -d "$ROSE_ROOT"; then
-
-		dnl defaults
+	  [ROSE_ROOT=$withval],[ROSE_ROOT="no"]) 
+
+	dnl Check whether rose is enabled
+	AC_MSG_CHECKING([for rose])
+	if test "x$ROSE_ROOT" = "xno" ; then
+		HAVE_ROSE=no
+	else
 		HAVE_ROSE=yes
+		if ! test -d "$ROSE_ROOT"; then
+			AC_MSG_ERROR([rose directory provided ($ROSE_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_ROSE)
+	AM_CONDITIONAL([ROSE],[test x$HAVE_ROSE = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_ROSE" = "xyes"; then
 		ROSEINCL="-I$ROSE_ROOT/include"
 		ROSELIB=""
-
 		AC_DEFINE([_HAVE_ROSE_],[1],[with rose in ISSM src])
 		AC_SUBST([ROSEINCL])
 		AC_SUBST([ROSELIB])
-
-	else
-		HAVE_ROSE=no
-	fi
-	AM_CONDITIONAL([ROSE], [test x$HAVE_ROSE = xyes])
-	AC_MSG_RESULT($HAVE_ROSE)
+	fi
 	dnl }}}
 	dnl mpi{{{
@@ -582,5 +716,4 @@
 		AC_SUBST([MPILIB])
 	fi
-
 	AM_CONDITIONAL([MPI], [test x$HAVE_MPI = xyes])
 	AC_MSG_RESULT($HAVE_MPI)
@@ -589,8 +722,25 @@
 	AC_ARG_WITH([petsc-dir],
 	  AS_HELP_STRING([--with-petsc-dir=DIR],[PETSc root directory, necessary for parallel build]),
-	  [PETSC_ROOT=$withval],[PETSC_ROOT=""])
+	  [PETSC_ROOT=$withval],[PETSC_ROOT="no"])
 		
-	if test -d "$PETSC_ROOT"; then
+	dnl Check whether petsc is enabled
+	AC_MSG_CHECKING([for petsc])
+	if test "x$PETSC_ROOT" = "xno" ; then
+		HAVE_PETSC=no
+	else
+		HAVE_PETSC=yes
+		if ! test -d "$PETSC_ROOT"; then
+			AC_MSG_ERROR([petsc directory provided ($PETSC_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_PETSC)
+	AM_CONDITIONAL([PETSC],[test x$HAVE_PETSC = xyes])
+
+	dnl library and header files
+	if test "x$HAVE_PETSC" = "xyes"; then
 		AC_MSG_CHECKING(for petsc version)
+	   if ! test -f "$PETSC_ROOT/include/petscversion.h"; then
+			AC_MSG_ERROR([PETSc not instaled corretly: file ($PETSC_ROOT/include/petscversion.h) does not exist]);
+		fi
 		PETSC_MAJOR=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_MAJOR" | sed 's/#define PETSC_VERSION_MAJOR//' | sed 's/ //g'`
 		PETSC_MINOR=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_MINOR" | sed 's/#define PETSC_VERSION_MINOR//' | sed 's/ //g'`
@@ -610,66 +760,56 @@
 			AC_MSG_RESULT(no)
 		fi
-	fi
-	
-	AC_ARG_WITH([petsc-arch],
-	  AS_HELP_STRING([--with-petsc-arch=DIR],[PETSc arch , necessary for parallel build]),
-	  [PETSC_ARCH=$withval],[PETSC_ARCH=""])
-
-	AC_MSG_CHECKING(for petsc headers and libraries in $PETSC_ROOT for architecture $PETSC_ARCH)
-	
-	dnl To ge PETSc's libraries:
-	dnl cd externalpackages/petsc/src
-	dnl make getlinklibs
-	if test -d "$PETSC_ROOT"; then
-
-	 PETSCINCL=" -I$PETSC_ROOT/include"
-	 dnl Add other location (maybe not needed anymore)
-	 if test -d "$PETSC_ROOT/$PETSC_ARCH/include"; then
-	  PETSCINCL+=" $PETSC_ROOT/$PETSC_ARCH/include"
-	 fi
-	 if test -d "$PETSC_ROOT/include/$PETSC_ARCH"; then
-	  PETSCINCL+=" $PETSC_ROOT/include/$PETSC_ARCH"
-	 fi
-	
-	 case "${host_os}" in
-			*cygwin*)
-			if test $PETSC_MAJOR -lt 3 ; then
-				PETSCLIB=-Wl,/LIBPATH:`cygpath -w $PETSC_ROOT/lib`  -Wl,libpetscksp.lib  -Wl,libpetscdm.lib  -Wl,libpetscmat.lib  -Wl,libpetscvec.lib  -Wl,libpetscsnes.lib  -Wl,libpetscts.lib  -Wl,libmpiuni.lib  -Wl,libpetsc.lib
-			else
-				PETSCLIB="-L$PETSC_ROOT/lib  -Wl,libpetsc.lib"
-				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+="  -Wl,libmetis.lib"; fi
-			fi
-			;;
-			*linux*)
-			if test $PETSC_MAJOR -lt 3 ; then
-				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lmpiuni -lpetsc"
-			else
-				PETSCLIB="-L$PETSC_ROOT/lib -lpetsc -ldl"
-				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
-			fi
-			;;
-			*darwin*)
-			if test $PETSC_MAJOR -lt 3 ; then
-				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
-			else
-				PETSCLIB="-L$PETSC_ROOT/lib -lpetsc"
-				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
-			fi
-			;;
+	
+		AC_ARG_WITH([petsc-arch],
+		  AS_HELP_STRING([--with-petsc-arch=DIR],[PETSc arch, necessary for PETSc < 3.0]),
+		  [PETSC_ARCH=$withval],[PETSC_ARCH=""])
+
+		AC_MSG_CHECKING(for petsc headers and libraries in $PETSC_ROOT)
+		dnl To ge PETSc's libraries:
+		dnl cd externalpackages/petsc/src
+		dnl make getlinklibs
+		PETSCINCL=" -I$PETSC_ROOT/include"
+		dnl Add other location (not needed anymore since at least PETSc 3.0)
+		if test "x$PETSC_ARCH" != "x" && test -d "$PETSC_ROOT/$PETSC_ARCH/include"; then
+		 PETSCINCL+=" $PETSC_ROOT/$PETSC_ARCH/include"
+		fi
+		if test "x$PETSC_ARCH" != "x" && test -d "$PETSC_ROOT/include/$PETSC_ARCH"; then
+		 PETSCINCL+=" $PETSC_ROOT/include/$PETSC_ARCH"
+		fi
+		
+		case "${host_os}" in
+				*cygwin*)
+				if test $PETSC_MAJOR -lt 3 ; then
+					PETSCLIB=-Wl,/LIBPATH:`cygpath -w $PETSC_ROOT/lib`  -Wl,libpetscksp.lib  -Wl,libpetscdm.lib  -Wl,libpetscmat.lib  -Wl,libpetscvec.lib  -Wl,libpetscsnes.lib  -Wl,libpetscts.lib  -Wl,libmpiuni.lib  -Wl,libpetsc.lib
+				else
+					PETSCLIB="-L$PETSC_ROOT/lib  -Wl,libpetsc.lib"
+					if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+="  -Wl,libmetis.lib"; fi
+				fi
+				;;
+				*linux*)
+				if test $PETSC_MAJOR -lt 3 ; then
+					PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lmpiuni -lpetsc"
+				else
+					PETSCLIB="-L$PETSC_ROOT/lib -lpetsc -ldl"
+					if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
+				fi
+				;;
+				*darwin*)
+				if test $PETSC_MAJOR -lt 3 ; then
+					PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
+				else
+					PETSCLIB="-L$PETSC_ROOT/lib -lpetsc"
+					if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
+				fi
+				;;
 		esac
+		AC_MSG_RESULT(done)
 		AC_DEFINE([_HAVE_PETSC_],[1],[with PETSc in ISSM src])
 		AC_SUBST([PETSCINCL])
 		AC_SUBST([PETSCLIB])
-		HAVE_PETSC=yes
-	else
-		HAVE_PETSC=no
-	fi
-	
-	AM_CONDITIONAL([PETSC], [test x$HAVE_PETSC = xyes])
-	AC_MSG_RESULT($HAVE_PETSC)
+	fi
 	dnl }}}
 	dnl metis{{{
 	if test "$HAVE_PETSC" = "yes" && test "x$PETSC_MAJOR" = "x3" && test $PETSC_MINOR -ge 3; then
-
 		dnl in petsc >=3.3, metis is provided
 		HAVE_METIS="yes"
@@ -679,10 +819,23 @@
 		AC_ARG_WITH([metis-dir],
 		  AS_HELP_STRING([--with-metis-dir=DIR],[metis root directory. necessary for serial build]),
-		  [METIS_ROOT=$withval],[METIS_ROOT=""])
-
-		AC_MSG_CHECKING(for metis headers and libraries in $METIS_ROOT)
-
-		if test -d "$METIS_ROOT"; then
-
+		  [METIS_ROOT=$withval],[METIS_ROOT="no"])
+
+		dnl Check whether metis is enabled
+		AC_MSG_CHECKING([for metis])
+		if test "x$METIS_ROOT" = "xno" ; then
+			HAVE_METIS=no
+		else
+			HAVE_METIS=yes
+			if ! test -d "$METIS_ROOT"; then
+				AC_MSG_ERROR([metis directory provided ($METIS_ROOT) does not exist]);
+			fi
+		fi
+		AC_MSG_RESULT($HAVE_METIS)
+		AM_CONDITIONAL([METIS],[test x$HAVE_METIS = xyes])
+
+		dnl library and header files
+		if test "x$HAVE_METIS" = "xyes"; then
+
+			AC_MSG_CHECKING(for metis headers and libraries in $METIS_ROOT)
 			dnl first figure out version of metis: does the VERSION file exist?
 			if test -e "$METIS_ROOT/VERSION"; then
@@ -692,9 +845,5 @@
 			fi
 
-			dnl defaults
-			HAVE_METIS=yes
-
 			if test "$METIS_VERSION" = "4" ; then
-					
 				METISINCL=-I"$METIS_ROOT/Lib" 
 				case "${host_os}" in
@@ -709,9 +858,8 @@
 					;;
 				esac
-
-					AC_DEFINE([_METIS_VERSION_],[4],[ Metis version number])
+				AC_DEFINE([_METIS_VERSION_],[4],[ Metis version number])
 			fi
+
 			if test "$METIS_VERSION" = "5" ; then
-		
 				case "${host_os}" in
 					*cygwin*)
@@ -725,5 +873,4 @@
 					;;
 				esac
-
 				METISINCL=-I"$METIS_ROOT/include" 
 				AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
@@ -733,81 +880,105 @@
 			AC_SUBST([METISINCL])
 			AC_SUBST([METISLIB])
-		else
-			HAVE_METIS=no
-		fi
-		AC_MSG_RESULT($HAVE_METIS)
-	fi
-	AM_CONDITIONAL([METIS], [test x$HAVE_METIS = xyes])
+		fi
+	fi
+	AM_CONDITIONAL([METIS],[test x$HAVE_METIS = xyes])
 	dnl }}}
 	dnl tao{{{
 	AC_ARG_WITH([tao-dir],
 		AS_HELP_STRING([--with-tao-dir=DIR], [tao root directory.]),
-		[TAO_ROOT=$withval],[TAO_ROOT=""]) 
-	AC_MSG_CHECKING(for tao)
-
-	if test -d "$TAO_ROOT"; then
-
-	  HAVE_TAO=yes
+		[TAO_ROOT=$withval],[TAO_ROOT="no"]) 
+
+	dnl Check whether tao is enabled
+	AC_MSG_CHECKING([for tao])
+	if test "x$TAO_ROOT" = "xno" ; then
+		HAVE_TAO=no
+	else
+		HAVE_TAO=yes
+		if ! test -d "$TAO_ROOT"; then
+			AC_MSG_ERROR([tao directory provided ($TAO_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_TAO)
+	
+	dnl tao headers and libraries
+	if test "x$HAVE_TAO" == "xyes"; then
 	  TAOINCL="-I$TAO_ROOT/ -I$TAO_ROOT/include -I$TAO_ROOT/bmake/ "
 	  TAOLIB="-L$TAO_ROOT/lib -ltao -lpetsc"
-
 	  AC_DEFINE([_HAVE_TAO_],[1],[with Tao in ISSM src])
 	  AC_SUBST([TAOINCL])
 	  AC_SUBST([TAOLIB])
-	else
-		HAVE_TAO=no
-	fi
-	AC_MSG_RESULT($HAVE_TAO)
+	fi
 	dnl }}}
 	dnl slepc{{{
 	AC_ARG_WITH([slepc-dir],
 	  AS_HELP_STRING([--with-slepc-dir=DIR],[slepc root directory]),
-	  [SLEPC_ROOT=$withval],[SLEPC_ROOT=""])
+	  [SLEPC_ROOT=$withval],[SLEPC_ROOT="no"])
 			  
-	AC_MSG_CHECKING(for slepc headers and libraries in $SLEPC_ROOT)
-	if test -d "$SLEPC_ROOT"; then
+	dnl Check whether slepc is enabled
+	AC_MSG_CHECKING([for slepc])
+	if test "x$SLEPC_ROOT" = "xno" ; then
+		HAVE_SLEPC=no
+	else
 		HAVE_SLEPC=yes
+		if ! test -d "$SLEPC_ROOT"; then
+			AC_MSG_ERROR([slepc directory provided ($SLEPC_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SLEPC)
+	
+	dnl slepc headers and libraries
+	if test "x$HAVE_SLEPC" == "xyes"; then
 		SLEPCINCL=-I"$SLEPC_ROOT/include"
 		SLEPCLIB=-L"$SLEPC_ROOT/lib/ -lslepc"
-
 		AC_DEFINE([_HAVE_SLEPC_],[1],[with Slepc in ISSM src])
 		AC_SUBST([SLEPCINCL])
 		AC_SUBST([SLEPCLIB])
-	else
-		HAVE_SLEPC=no
-	fi
-	AC_MSG_RESULT($HAVE_SLEPC)
+	fi
 	dnl }}}
 	dnl shapelib{{{
 	AC_ARG_WITH([shapelib-dir],
 	  AS_HELP_STRING([--with-shapelib-dir=DIR], [shapelib root directory]),
-	  [SHAPELIB_ROOT=$withval],[SHAPELIB_ROOT=""])
+	  [SHAPELIB_ROOT=$withval],[SHAPELIB_ROOT="no"])
 			  
-	AC_MSG_CHECKING(for shapelib headers and libraries in $SHAPELIB_ROOT)
-	if test -d "$SHAPELIB_ROOT"; then
-
-		dnl defaults
+	dnl Check whether shapelib is enabled
+	AC_MSG_CHECKING([for shapelib])
+	if test "x$SHAPELIB_ROOT" = "xno" ; then
+		HAVE_SHAPELIB=no
+	else
 		HAVE_SHAPELIB=yes
+		if ! test -d "$SHAPELIB_ROOT"; then
+			AC_MSG_ERROR([shapelib directory provided ($SHAPELIB_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SHAPELIB)
+	
+	dnl shapelib headers and libraries
+	if test "x$HAVE_SHAPELIB" == "xyes"; then
 		SHAPELIBINCL=-I"$SHAPELIB_ROOT/include"
 		SHAPELIBLIB=-L"$SHAPELIB_ROOT/lib/ -lshape"
-
 		AC_DEFINE([_HAVE_SHAPELIB_],[1],[with Shapelib in ISSM src])
 		AC_SUBST([SHAPELIBINCL])
 		AC_SUBST([SHAPELIBLIB])
-	else
-		HAVE_SHAPELIB=no
-	fi
-	AC_MSG_RESULT($HAVE_SHAPELIB)
+	fi
 	dnl }}}
 	dnl scalapack{{{
 	AC_ARG_WITH([scalapack-dir],
 	  AS_HELP_STRING([--with-scalapack-dir=DIR],[scalapack root directory]),
-	  [SCALAPACK_ROOT=$withval],[SCALAPACK_ROOT=""])
+	  [SCALAPACK_ROOT=$withval],[SCALAPACK_ROOT="no"])
 			  
-	AC_MSG_CHECKING(for scalapack headers and libraries in $SCALAPACK_ROOT)
-	if test -d "$SCALAPACK_ROOT"; then
-
-		dnl defaults
+	dnl Check whether scalapack is enabled
+	AC_MSG_CHECKING([for scalapack])
+	if test "x$SCALAPACK_ROOT" = "xno" ; then
+		HAVE_SCALAPACK=no
+	else
 		HAVE_SCALAPACK=yes
+		if ! test -d "$SCALAPACK_ROOT"; then
+			AC_MSG_ERROR([scalapack directory provided ($SCALAPACK_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SCALAPACK)
+	
+	dnl scalapack headers and libraries
+	if test "x$HAVE_SCALAPACK" == "xyes"; then
 		if test x$VENDOR = xintel-discover; then
 		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lmkl_scalapack_lp64"
@@ -815,72 +986,78 @@
 		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lscalapack"
 		fi
-
 		AC_DEFINE([_HAVE_SCALAPACK_],[1],[with Scalapack in ISSM src])
 		AC_SUBST([SCALAPACKLIB])
-	else
-		HAVE_SCALAPACK=no
-	fi
-	AC_MSG_RESULT($HAVE_SCALAPACK)
-	dnl }}}
-	dnl blas{{{
+	fi
+	dnl }}}
+	dnl blas-lapack{{{
 	AC_ARG_WITH([blas-lapack-dir],
 	  AS_HELP_STRING([--with-blas-lapack-dir=DIR],[blas-lapack root directory]),
-	  [BLASLAPACK_ROOT=$withval],[BLASLAPACK_ROOT=""])
+	  [BLASLAPACK_ROOT=$withval],[BLASLAPACK_ROOT="no"])
 			  
-	AC_MSG_CHECKING(for blas and lapack headers and libraries in $BLASLAPACK_ROOT)
-	if test -d "$BLASLAPACK_ROOT"; then
-
-		dnl defaults
+	dnl Check whether blas-lapack is enabled
+	AC_MSG_CHECKING([for blas-lapack])
+	if test "x$BLASLAPACK_ROOT" = "xno" ; then
+		HAVE_BLASLAPACK=no
+	else
 		HAVE_BLASLAPACK=yes
+		if ! test -d "$BLASLAPACK_ROOT"; then
+			AC_MSG_ERROR([blas-lapack directory provided ($BLASLAPACK_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_BLASLAPACK)
+	
+	dnl blas-lapack headers and libraries
+	if test "x$HAVE_BLASLAPACK" == "xyes"; then
 		BLASLAPACKINCL=""
-	
 		if test x$VENDOR = xintel-discover; then
-		 BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lmkl_lapack -lmkl -lguide -lpthread"
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lmkl_lapack -lmkl -lguide -lpthread"
 		else
-		dnl: branch on whether we are running on windows or linux.
-		case "${host_os}" in
-			*cygwin*)
-			BLASLAPACKLIB="-L`cygpath -m $BLASLAPACK_ROOT` -Wl,libf2cblas.lib  -Wl,libf2clapack.lib"
-			;;
-			*linux*)
-			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
-			;;
-			*darwin*)
-			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
-			;;
-		esac
-		fi
-
+			dnl: branch on whether we are running on windows or linux.
+			case "${host_os}" in
+				*cygwin*)
+				BLASLAPACKLIB="-L`cygpath -m $BLASLAPACK_ROOT` -Wl,libf2cblas.lib  -Wl,libf2clapack.lib"
+				;;
+				*linux*)
+				BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
+				;;
+				*darwin*)
+				BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
+				;;
+			esac
+		fi
 		AC_DEFINE([_HAVE_BLASLAPACK_],[1],[with blas lapack in ISSM src])
 		AC_SUBST([BLASLAPACKLIB])
 		AC_SUBST([BLASLAPACKINCL])
-	else
-		HAVE_BLASLAPACK=no
-	fi
-	AC_MSG_RESULT($HAVE_BLASLAPACK)
+	fi
 	dnl }}}
 	dnl mkl{{{
 	AC_ARG_WITH([mkl-dir],
 	  AS_HELP_STRING([--with-mkl-dir=DIR],[mkl root directory]),
-	  [MKL_ROOT=$withval],[MKL_ROOT=""])
+	  [MKL_ROOT=$withval],[MKL_ROOT="no"])
 			  
-	AC_MSG_CHECKING(for mkl headers and libraries in $MKL_ROOT)
-	if test -d "$MKL_ROOT"; then
-
-		dnl defaults
+	dnl Check whether mkl is enabled
+	AC_MSG_CHECKING([for mkl])
+	if test "x$MKL_ROOT" = "xno" ; then
+		HAVE_MKL=no
+	else
 		HAVE_MKL=yes
+		if ! test -d "$MKL_ROOT"; then
+			AC_MSG_ERROR([mkl directory provided ($MKL_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_MKL)
+	
+	dnl mkl headers and libraries
+	if test "x$HAVE_MKL" == "xyes"; then
 		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_intel_lp64 -lmkl_intel_thread -lmkl_core -liomp5 -lpthread"
 		else
-		 MKLLIB=-L"$MKL_ROOT -lmkl -lmkl_lapack -lmkl_scalapack_ilp64 -lmkl_blacs_sgimpt_ilp64 -lguide -lpthread"
+			MKLLIB=-L"$MKL_ROOT -lmkl -lmkl_lapack -lmkl_scalapack_ilp64 -lmkl_blacs_sgimpt_ilp64 -lguide -lpthread"
 		fi
 		AC_DEFINE([_HAVE_MKL_],[1],[with mkl in ISSM src])
 		AC_SUBST([MKLLIB])
 		AC_SUBST([MKLINCL])
-	else
-		HAVE_MKL=no
-	fi
-	AC_MSG_RESULT($HAVE_MKL)
+	fi
 	dnl }}}
 	dnl plapack{{{
@@ -899,9 +1076,7 @@
 		if test -n "$PLAPACK_INCLUDE"; then
 		
-			dnl defaults
 			HAVE_PLAPACK=yes
 			PLAPACKINCL="$PLAPACK_INCLUDE"
 			PLAPACKLIB="$PLAPACK_LIB"
-
 			AC_DEFINE([_HAVE_PLAPACK_],[1],[with Plapack in ISSM src])
 			AC_SUBST([PLAPACKINCL])
@@ -918,38 +1093,52 @@
 	AC_ARG_WITH([mumps-dir],
 	  AS_HELP_STRING([--with-mumps-dir=DIR],[mumps root directory]),
-	  [MUMPS_ROOT=$withval],[MUMPS_ROOT=""])
+	  [MUMPS_ROOT=$withval],[MUMPS_ROOT="no"])
 			  
-	AC_MSG_CHECKING(for mumps headers and libraries in $MUMPS_ROOT)
-	if test -d "$MUMPS_ROOT"; then
-
-		dnl defaults
+	dnl Check whether mumps is enabled
+	AC_MSG_CHECKING([for mumps])
+	if test "x$MUMPS_ROOT" = "xno" ; then
+		HAVE_MUMPS=no
+	else
 		HAVE_MUMPS=yes
+		if ! test -d "$MUMPS_ROOT"; then
+			AC_MSG_ERROR([mumps directory provided ($MUMPS_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_MUMPS)
+	
+	dnl mumps headers and libraries
+	if test "x$HAVE_MUMPS" == "xyes"; then
 		MUMPSINCL=-I"$MUMPS_ROOT/include"
 		if test "$PETSC_MAJOR" = "2" ; then
-		MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lpord "
+			MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lpord "
 		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"
-		fi
-
+			dnl MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lmumps_common -lpord -lparmetis -lzmumps"
+			MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lmumps_common -lpord -lparmetis"
+		fi
 		AC_DEFINE([_HAVE_MUMPS_],[1],[with Mumps in ISSM src])
 		AC_SUBST([MUMPSINCL])
 		AC_SUBST([MUMPSLIB])
-	else
-		HAVE_MUMPS=no
 	fi
 	AM_CONDITIONAL([MUMPS], [test x$HAVE_MUMPS = xyes])
-	AC_MSG_RESULT($HAVE_MUMPS)
 	dnl }}}
 	dnl blacs{{{
 	AC_ARG_WITH([blacs-dir],
 		AS_HELP_STRING([--with-blacs-dir=DIR],[blacs root directory]),
-			  [BLACS_ROOT=$withval],[BLACS_ROOT=""])
+			  [BLACS_ROOT=$withval],[BLACS_ROOT="no"])
 			  
-	AC_MSG_CHECKING(for blacs headers and libraries in $BLACS_ROOT)
-	if test -d "$BLACS_ROOT"; then
-
-		dnl defaults
+	dnl Check whether blacs is enabled
+	AC_MSG_CHECKING([for blacs])
+	if test "x$BLACS_ROOT" = "xno" ; then
+		HAVE_BLACS=no
+	else
 		HAVE_BLACS=yes
+		if ! test -d "$BLACS_ROOT"; then
+			AC_MSG_ERROR([blacs directory provided ($BLACS_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_BLACS)
+	
+	dnl blacs headers and libraries
+	if test "x$HAVE_BLACS" == "xyes"; then
 		BLACSINCL=""
 		if test x$VENDOR = xintel-discover; then
@@ -958,180 +1147,216 @@
 		 BLACSLIB=-L"$BLACS_ROOT/ -lblacs"
 		fi
-        
 		AC_DEFINE([_HAVE_BLACS_],[1],[with Blacs in ISSM src])
 		AC_SUBST([BLACSINCL])
 		AC_SUBST([BLACSLIB])
-	else
-		HAVE_BLACS=no
-	fi
-	AC_MSG_RESULT($HAVE_BLACS)
+	fi
 	dnl }}}
 	dnl hypre{{{
 	AC_ARG_WITH([hypre-dir],
 	  AS_HELP_STRING([--with-hypre-dir=DIR],[hypre root directory]),
-			  [HYPRE_ROOT=$withval],[HYPRE_ROOT=""])
+			  [HYPRE_ROOT=$withval],[HYPRE_ROOT="no"])
 			  
-	AC_MSG_CHECKING(for hypre headers and libraries in $HYPRE_ROOT)
-	if test -d "$HYPRE_ROOT"; then
-
-		dnl defaults
+	dnl Check whether hypre is enabled
+	AC_MSG_CHECKING([for hypre])
+	if test "x$HYPRE_ROOT" = "xno" ; then
+		HAVE_HYPRE=no
+	else
 		HAVE_HYPRE=yes
+		if ! test -d "$HYPRE_ROOT"; then
+			AC_MSG_ERROR([hypre directory provided ($HYPRE_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_HYPRE)
+
+	dnl hypre headers and libraries
+	if test "x$HAVE_HYPRE" == "xyes"; then
 		HYPREINCL=""
 		HYPRELIB=-L"$HYPRE_ROOT/lib -lHYPRE"
-        
-		AC_DEFINE([_HAVE_HYPRE_],[1],[with Blacs in ISSM src])
+		AC_DEFINE([_HAVE_HYPRE_],[1],[with Hypre in ISSM src])
 		AC_SUBST([HYPREINCL])
 		AC_SUBST([HYPRELIB])
-	else
-		HAVE_HYPRE=no
-	fi
-	AC_MSG_RESULT($HAVE_HYPRE)
+	fi
 	dnl }}}
 	dnl prometheus{{{
-		AC_ARG_WITH([prometheus-dir],
-					AS_HELP_STRING([--with-prometheus-dir=DIR],[prometheus root directory]),
-					[PROMETHEUS_ROOT=$withval],[PROMETHEUS_ROOT=""])
-
-		  AC_MSG_CHECKING(for prometheus headers and libraries in $PROMETHEUS_ROOT)
-		  if test -d "$PROMETHEUS_ROOT"; then
-
-			dnl defaults
-			  HAVE_PROMETHEUS=yes
-			  PROMETHEUSINCL=-I"$PROMETHEUS_ROOT/include"
-			  PROMETHEUSLIB=-L"$PROMETHEUS_ROOT/lib -lpromfei -lprometheus -lparmetis"
-
-			  AC_DEFINE([_HAVE_PROMETHEUS_],[1],[with Prometheus in ISSM src])
-			  AC_SUBST([PROMETHEUSINCL])
-			  AC_SUBST([PROMETHEUSLIB])
-		  else
-				HAVE_PROMETHEUS=no
+	AC_ARG_WITH([prometheus-dir],
+				AS_HELP_STRING([--with-prometheus-dir=DIR],[prometheus root directory]),
+				[PROMETHEUS_ROOT=$withval],[PROMETHEUS_ROOT="no"])
+
+		dnl Check whether prometheus is enabled
+		AC_MSG_CHECKING([for prometheus])
+		if test "x$PROMETHEUS_ROOT" = "xno" ; then
+			HAVE_PROMETHEUS=no
+		else
+			HAVE_PROMETHEUS=yes
+			if ! test -d "$PROMETHEUS_ROOT"; then
+				AC_MSG_ERROR([prometheus directory provided ($PROMETHEUS_ROOT) does not exist]);
 			fi
-			AC_MSG_RESULT($HAVE_PROMETHEUS)
+		fi
+		AC_MSG_RESULT($HAVE_PROMETHEUS)
+
+		dnl prometheus headers and libraries
+		if test "x$HAVE_PROMETHEUS" == "xyes"; then
+			 PROMETHEUSINCL=-I"$PROMETHEUS_ROOT/include"
+			 PROMETHEUSLIB=-L"$PROMETHEUS_ROOT/lib -lpromfei -lprometheus -lparmetis"
+			 AC_DEFINE([_HAVE_PROMETHEUS_],[1],[with Prometheus in ISSM src])
+			 AC_SUBST([PROMETHEUSINCL])
+			 AC_SUBST([PROMETHEUSLIB])
+	   fi
 		dnl }}}
 dnl spai{{{
 	AC_ARG_WITH([spai-dir],
 				AS_HELP_STRING([--with-spai-dir=DIR],[spai root directory]),
-				[SPAI_ROOT=$withval],[SPAI_ROOT=""])
-
-	  AC_MSG_CHECKING(for spai headers and libraries in $SPAI_ROOT)
-	  if test -d "$SPAI_ROOT"; then
-
-		dnl defaults
-		  HAVE_SPAI=yes
-		  SPAIINCL=-I"$SPAI_ROOT/include"
-		  SPAILIB=-L"$SPAI_ROOT/lib -lspai"
-
-		  AC_DEFINE([_HAVE_SPAI_],[1],[with Spai in ISSM src])
-		  AC_SUBST([SPAIINCL])
-		  AC_SUBST([SPAILIB])
-	  else
-		HAVE_SPAI=no
-		  fi
-		  AC_MSG_RESULT($HAVE_SPAI)
-		  dnl }}}
+				[SPAI_ROOT=$withval],[SPAI_ROOT="no"])
+
+		dnl Check whether spai is enabled
+		AC_MSG_CHECKING([for spai])
+		if test "x$SPAI_ROOT" = "xno" ; then
+			HAVE_SPAI=no
+		else
+			HAVE_SPAI=yes
+			if ! test -d "$SPAI_ROOT"; then
+				AC_MSG_ERROR([spai directory provided ($SPAI_ROOT) does not exist]);
+			fi
+		fi
+		AC_MSG_RESULT($HAVE_SPAI)
+
+		dnl spai headers and libraries
+		if test "x$HAVE_SPAI" == "xyes"; then
+			SPAIINCL=-I"$SPAI_ROOT/include"
+			SPAILIB=-L"$SPAI_ROOT/lib -lspai"
+			AC_DEFINE([_HAVE_SPAI_],[1],[with Spai in ISSM src])
+			AC_SUBST([SPAIINCL])
+			AC_SUBST([SPAILIB])
+		fi
+	  dnl }}}
 dnl superlu{{{ 
 	AC_ARG_WITH([superlu-dir],
 				AS_HELP_STRING([--with-superlu-dir=DIR],[superlu root directory]),
-				[SUPERLU_ROOT=$withval],[SUPERLU_ROOT=""])
-
-	  AC_MSG_CHECKING(for superlu headers and libraries in $SUPERLU_ROOT)
-	  if test -d "$SUPERLU_ROOT"; then
-
-		dnl defaults
-		  HAVE_SUPERLU=yes
+				[SUPERLU_ROOT=$withval],[SUPERLU_ROOT="no"])
+
+	dnl Check whether superlu is enabled
+	AC_MSG_CHECKING([for superlu])
+	if test "x$SUPERLU_ROOT" = "xno" ; then
+		HAVE_SUPERLU=no
+	else
+		HAVE_SUPERLU=yes
+		if ! test -d "$SUPERLU_ROOT"; then
+			AC_MSG_ERROR([superlu directory provided ($SUPERLU_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SUPERLU)
+	
+	dnl superlu headers and libraries
+	if test "x$HAVE_SUPERLU" == "xyes"; then
 		  SUPERLUINCL=-I"$SUPERLU_ROOT/include"
 		  SUPERLULIB=-L"$SUPERLU_ROOT/lib -lsuperlu_4.3"
-
 		  AC_DEFINE([_HAVE_SUPERLU_],[1],[with Superlu in ISSM src])
 		  AC_SUBST([SUPERLUINCL])
 		  AC_SUBST([SUPERLULIB])
-	  else
-		HAVE_SUPERLU=no
-		  fi
-		  AC_MSG_RESULT($HAVE_SUPERLU)
-		  dnl }}}
+	 fi
+	 dnl }}}
 dnl spooles{{{ 
 	AC_ARG_WITH([spooles-dir],
 				AS_HELP_STRING([--with-spooles-dir=DIR],[spooles root directory]),
-				[SPOOLES_ROOT=$withval],[SPOOLES_ROOT=""])
-
-	  AC_MSG_CHECKING(for spooles headers and libraries in $SPOOLES_ROOT)
-	  if test -d "$SPOOLES_ROOT"; then
-
-		dnl defaults
-		  HAVE_SPOOLES=yes
+				[SPOOLES_ROOT=$withval],[SPOOLES_ROOT="no"])
+
+	dnl Check whether spooles is enabled
+	AC_MSG_CHECKING([for spooles])
+	if test "x$SPOOLES_ROOT" = "xno" ; then
+		HAVE_SPOOLES=no
+	else
+		HAVE_SPOOLES=yes
+		if ! test -d "$SPOOLES_ROOT"; then
+			AC_MSG_ERROR([spooles directory provided ($SPOOLES_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SPOOLES)
+	
+	dnl spooles headers and libraries
+	if test "x$HAVE_SPOOLES" == "xyes"; then
 		  SPOOLESINCL=-I"$SPOOLES_ROOT/include"
 		  SPOOLESLIB=-L"$SPOOLES_ROOT/lib -lspooles"
-
 		  AC_DEFINE([_HAVE_SPOOLES_],[1],[with Spooles in ISSM src])
 		  AC_SUBST([SPOOLESINCL])
 		  AC_SUBST([SPOOLESLIB])
-	  else
-		HAVE_SPOOLES=no
-		  fi
-		  AC_MSG_RESULT($HAVE_SPOOLES)
-		  dnl }}}
+	 fi
+	 dnl }}}
 dnl pastix{{{ 
 	AC_ARG_WITH([pastix-dir],
 				AS_HELP_STRING([--with-pastix-dir=DIR],[pastix root directory]),
-				[PASTIX_ROOT=$withval],[PASTIX_ROOT=""])
-
-	  AC_MSG_CHECKING(for pastix headers and libraries in $PASTIX_ROOT)
-	  if test -d "$PASTIX_ROOT"; then
-
-		dnl defaults
-		  HAVE_PASTIX=yes
+				[PASTIX_ROOT=$withval],[PASTIX_ROOT="no"])
+
+	dnl Check whether pastix is enabled
+	AC_MSG_CHECKING([for pastix])
+	if test "x$PASTIX_ROOT" = "xno" ; then
+		HAVE_PASTIX=no
+	else
+		HAVE_PASTIX=yes
+		if ! test -d "$PASTIX_ROOT"; then
+			AC_MSG_ERROR([pastix directory provided ($PASTIX_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_PASTIX)
+	
+	dnl pastix headers and libraries
+	if test "x$HAVE_PASTIX" == "xyes"; then
 		  PASTIXINCL=-I"$PASTIX_ROOT/include"
 		  PASTIXLIB=-L"$PASTIX_ROOT/lib -lpastix_XXbit_mpi_smp_nobubble_int32_simple_real_scotch_i686_pc_linux -lptscotch -lptscotcherr -lpastix"
-
 		  AC_DEFINE([_HAVE_PASTIX_],[1],[with Pastix in ISSM src])
 		  AC_SUBST([PASTIXINCL])
 		  AC_SUBST([PASTIXLIB])
-	  else
-		HAVE_PASTIX=no
-		  fi
-		  AC_MSG_RESULT($HAVE_PASTIX)
-		  dnl }}}
+  fi
+  dnl }}}
 	dnl ml{{{
 	AC_ARG_WITH([ml-dir],
 	  AS_HELP_STRING([--with-ml-dir=DIR],[ml root directory]),
-			  [ML_ROOT=$withval],[ML_ROOT=""])
+			  [ML_ROOT=$withval],[ML_ROOT="no"])
 			  
-	AC_MSG_CHECKING(for ml headers and libraries in $ML_ROOT)
-	if test -d "$ML_ROOT"; then
-
-		dnl defaults
+	dnl Check whether ml is enabled
+	AC_MSG_CHECKING([for ml])
+	if test "x$ML_ROOT" = "xno" ; then
+		HAVE_ML=no
+	else
 		HAVE_ML=yes
+		if ! test -d "$ML_ROOT"; then
+			AC_MSG_ERROR([ml directory provided ($ML_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_ML)
+	
+	dnl ml headers and libraries
+	if test "x$HAVE_ML" == "xyes"; then
 		MLINCL=-I"$ML_ROOT/include"
 		MLLIB=-L"$ML_ROOT/lib -lml"
-        
 		AC_DEFINE([_HAVE_ML_],[1],[with Blacs in ISSM src])
 		AC_SUBST([MLINCL])
 		AC_SUBST([MLLIB])
-	else
-		HAVE_ML=no
-	fi
-	AC_MSG_RESULT($HAVE_ML)
+	fi
 	dnl }}}
 	dnl umfpack{{{
 		AC_ARG_WITH([umfpack-dir],
 		  AS_HELP_STRING([--with-umfpack-dir=DIR],[UMFPACK root directory]),
-					[UMFPACK_ROOT=$withval],[UMFPACK_ROOT=""])
-
-		AC_MSG_CHECKING(for UMFPACK headers and libraries in $UMFPACK_ROOT)
-		if test -d "$UMFPACK_ROOT"; then
-
-			dnl defaults
-			HAVE_UMFPACK=yes
-			UMFPACKINCL=""
-			UMFPACKLIB=-L"$UMFPACK_ROOT/lib -lumfpack -lumfpack.5.5.1"
-
-			AC_DEFINE([_HAVE_UMFPACK_],[1],[with UMFPACK in ISSM src])
-			AC_SUBST([UMFPACKINCL])
-			AC_SUBST([UMFPACKLIB])
-		else
-			HAVE_UMFPACK=no
-		fi
-		AC_MSG_RESULT($HAVE_UMFPACK)
+					[UMFPACK_ROOT=$withval],[UMFPACK_ROOT="no"])
+			  
+	dnl Check whether umfpack is enabled
+	AC_MSG_CHECKING([for umfpack])
+	if test "x$UMFPACK_ROOT" = "xno" ; then
+		HAVE_UMFPACK=no
+	else
+		HAVE_UMFPACK=yes
+		if ! test -d "$UMFPACK_ROOT"; then
+			AC_MSG_ERROR([umfpack directory provided ($UMFPACK_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_UMFPACK)
+	
+	dnl umfpack headers and libraries
+	if test "x$HAVE_UMFPACK" == "xyes"; then
+		UMFPACKINCL=""
+		UMFPACKLIB=-L"$UMFPACK_ROOT/lib -lumfpack -lumfpack.5.5.1"
+		AC_DEFINE([_HAVE_UMFPACK_],[1],[with UMFPACK in ISSM src])
+		AC_SUBST([UMFPACKINCL])
+		AC_SUBST([UMFPACKLIB])
+	fi
 	dnl }}}
 dnl math{{{
@@ -1145,9 +1370,32 @@
 		HAVE_MATH=yes
 		MATHLIB="$MATH_LIB"
-
 		AC_DEFINE([_HAVE_MATH_],[1],[with MATH in ISSM src])
 		AC_SUBST([MATHLIB])
 	fi
 	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl math77{{{
+		AC_ARG_WITH([math77-dir],
+					AS_HELP_STRING([--with-math77-dir=DIR], [math77 root directory.]),
+					[MATH77_ROOT=$withval],[MATH77_ROOT="no"]) 
+		  
+	dnl Check whether math77 is enabled
+	AC_MSG_CHECKING([for math77])
+	if test "x$MATH77_ROOT" = "xno" ; then
+		HAVE_MATH77=no
+	else
+		HAVE_MATH77=yes
+		if ! test -d "$MATH77_ROOT"; then
+			AC_MSG_ERROR([math77 directory provided ($MATH77_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_MATH77)
+	
+	dnl math77 headers and libraries
+	if test "x$HAVE_MATH77" == "xyes"; then
+		MATH77LIB="-L$MATH77_ROOT/ -lmath77"
+		AC_DEFINE([_HAVE_MATH77_],[1],[with math77 in ISSM src])
+		AC_SUBST([MATH77LIB])
+   fi
 	dnl }}}
 	dnl fortran{{{
@@ -1159,5 +1407,4 @@
 		dnl defaults
 		HAVE_FORTRAN=yes
-
 		AC_DEFINE([_HAVE_FORTRAN_],[1],[with fortran capability])
 	else
@@ -1202,5 +1449,4 @@
 
 	dnl check that --with-graphics-lib may have been provided
-	
 	if test -n "$GRAPHICS_LIB" ; then
 		dnl check that library provided EXISTS!
@@ -1221,4 +1467,60 @@
 	AC_MSG_RESULT(done)
 	dnl }}}
+	dnl meteoio{{{
+	AC_ARG_WITH([meteoio-dir],
+	  AS_HELP_STRING([--with-meteoio-dir=DIR], [use meteoio in conjunction with snowpack model.]),
+	  [METEOIO_ROOT=$withval],[METEOIO_ROOT="no"]) 
+
+	dnl Check whether meteoio is enabled
+	AC_MSG_CHECKING([for meteoio])
+	if test "x$METEOIO_ROOT" = "xno" ; then
+		HAVE_METEOIO=no
+	else
+		HAVE_METEOIO=yes
+		if ! test -d "$METEOIO_ROOT"; then
+			AC_MSG_ERROR([meteoio directory provided ($METEOIO_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_METEOIO)
+	
+	dnl meteoio headers and libraries
+	if test "x$HAVE_METEOIO" == "xyes"; then
+		METEOIOINCL="-I$METEOIO_ROOT/include"
+		METEOIOLIB="-dy -L$METEOIO_ROOT/lib  -lmeteoio "
+
+		AC_DEFINE([_HAVE_METEOIO_],[1],[with meteoio])
+		AC_SUBST([METEOIOINCL])
+		AC_SUBST([METEOIOLIB])
+	fi
+	AM_CONDITIONAL([METEOIO], [test x$HAVE_METEOIO = xyes])
+	dnl }}}
+	dnl snowpack{{{
+	AC_ARG_WITH([snowpack-dir],
+	  AS_HELP_STRING([--with-snowpack-dir=DIR], [use snowpack for surface mass balance model.]),
+	  [SNOWPACK_ROOT=$withval],[SNOWPACK_ROOT="no"]) 
+
+	dnl Check whether snowpack is enabled
+	AC_MSG_CHECKING([for snowpack])
+	if test "x$SNOWPACK_ROOT" = "xno" ; then
+		HAVE_SNOWPACK=no
+	else
+		HAVE_SNOWPACK=yes
+		if ! test -d "$SNOWPACK_ROOT"; then
+			AC_MSG_ERROR([snowpack directory provided ($SNOWPACK_ROOT) does not exist]);
+		fi
+	fi
+	AC_MSG_RESULT($HAVE_SNOWPACK)
+	
+	dnl snowpack headers and libraries
+	if test "x$HAVE_SNOWPACK" == "xyes"; then
+		SNOWPACKINCL="-I$SNOWPACK_ROOT/include"
+		SNOWPACKLIB="-dy -L$SNOWPACK_ROOT/lib  -lsnowpack "
+
+		AC_DEFINE([_HAVE_SNOWPACK_],[1],[with snowpack for surface mass balance model])
+		AC_SUBST([SNOWPACKINCL])
+		AC_SUBST([SNOWPACKLIB])
+	fi
+	AM_CONDITIONAL([SNOWPACK], [test x$HAVE_SNOWPACK = xyes])
+	dnl }}}
 
 	dnl Capabilities
@@ -1307,21 +1609,21 @@
 	AC_MSG_RESULT($HAVE_THERMAL)
 	dnl }}}
-	dnl with-prognostic{{{
-	AC_ARG_WITH([prognostic],
-		AS_HELP_STRING([--with-prognostic = YES], [compile with prognostic capabilities (default is yes)]),
-		[PROGNOSTIC=$withval],[PROGNOSTIC=yes]) 
-	AC_MSG_CHECKING(for prognostic capability compilation)
-
-	if test "x$PROGNOSTIC" = "xyes"; then
+	dnl with-masstransport{{{
+	AC_ARG_WITH([masstransport],
+		AS_HELP_STRING([--with-masstransport = YES], [compile with masstransport capabilities (default is yes)]),
+		[MASSTRANSPORT=$withval],[MASSTRANSPORT=yes]) 
+	AC_MSG_CHECKING(for masstransport capability compilation)
+
+	if test "x$MASSTRANSPORT" = "xyes"; then
 
 		dnl defaults
-		HAVE_PROGNOSTIC=yes
-
-		AC_DEFINE([_HAVE_PROGNOSTIC_],[1],[with prognostic capability])
-	else
-		HAVE_PROGNOSTIC=no
-	fi
-	AM_CONDITIONAL([PROGNOSTIC], [test x$HAVE_PROGNOSTIC = xyes])
-	AC_MSG_RESULT($HAVE_PROGNOSTIC)
+		HAVE_MASSTRANSPORT=yes
+
+		AC_DEFINE([_HAVE_MASSTRANSPORT_],[1],[with masstransport capability])
+	else
+		HAVE_MASSTRANSPORT=no
+	fi
+	AM_CONDITIONAL([MASSTRANSPORT], [test x$HAVE_MASSTRANSPORT = xyes])
+	AC_MSG_RESULT($HAVE_MASSTRANSPORT)
 	dnl }}}
 	dnl with-control{{{
@@ -1361,21 +1663,21 @@
 	AC_MSG_RESULT($HAVE_HYDROLOGY)
 	dnl }}}
-	dnl with-diagnostic{{{
-	AC_ARG_WITH([diagnostic],
-		AS_HELP_STRING([--with-diagnostic = YES], [compile with diagnostic capabilities (default is yes)]),
-		[DIAGNOSTIC=$withval],[DIAGNOSTIC=yes]) 
-	AC_MSG_CHECKING(for diagnostic capability compilation)
-
-	if test "x$DIAGNOSTIC" = "xyes"; then
+	dnl with-stressbalance{{{
+	AC_ARG_WITH([stressbalance],
+		AS_HELP_STRING([--with-stressbalance = YES], [compile with stressbalance capabilities (default is yes)]),
+		[STRESSBALANCE=$withval],[STRESSBALANCE=yes]) 
+	AC_MSG_CHECKING(for stressbalance capability compilation)
+
+	if test "x$STRESSBALANCE" = "xyes"; then
 
 		dnl defaults
-		HAVE_DIAGNOSTIC=yes
-
-		AC_DEFINE([_HAVE_DIAGNOSTIC_],[1],[with diagnostic capability])
-	else
-		HAVE_DIAGNOSTIC=no
-	fi
-	AM_CONDITIONAL([DIAGNOSTIC], [test x$HAVE_DIAGNOSTIC = xyes])
-	AC_MSG_RESULT($HAVE_DIAGNOSTIC)
+		HAVE_STRESSBALANCE=yes
+
+		AC_DEFINE([_HAVE_STRESSBALANCE_],[1],[with stressbalance capability])
+	else
+		HAVE_STRESSBALANCE=no
+	fi
+	AM_CONDITIONAL([STRESSBALANCE], [test x$HAVE_STRESSBALANCE = xyes])
+	AC_MSG_RESULT($HAVE_STRESSBALANCE)
 	dnl }}}
 	dnl with-balanced{{{
@@ -1468,22 +1770,4 @@
 	AM_CONDITIONAL([RIFTS], [test x$HAVE_RIFTS = xyes])
 	AC_MSG_RESULT($HAVE_RIFTS)
-	dnl }}}
-	dnl math77{{{
-	AC_ARG_WITH([math77-dir],
-		AS_HELP_STRING([--with-math77-dir=DIR], [math77 root directory.]),
-		[MATH77_ROOT=$withval],[MATH77_ROOT=""]) 
-	AC_MSG_CHECKING(for math77)
-
-	if test -d "$MATH77_ROOT"; then
-
-	  HAVE_MATH77=yes
-	  MATH77LIB="-L$MATH77_ROOT/ -lmath77"
-
-	  AC_DEFINE([_HAVE_MATH77_],[1],[with math77 in ISSM src])
-	  AC_SUBST([MATH77LIB])
-	else
-		HAVE_MATH77=no
-	fi
-	AC_MSG_RESULT($HAVE_MATH77)
 	dnl }}}
 	dnl with-gia{{{
@@ -1591,26 +1875,4 @@
 	AM_CONDITIONAL([THREED], [test x$HAVE_3D = xyes])
 	AC_MSG_RESULT($HAVE_3D)
-	dnl }}}
-	dnl checks{{{
-	AC_MSG_CHECKING(consistency between all libraries)
-	
-	dnl check that if petsc is requested , mpi should be specified
-	if test "$HAVE_PETSC" = "yes" ; then
-		if test "$HAVE_MPI" = "NO";  then
-			AC_MSG_ERROR([petsc requires mpi!]);
-		fi
-	fi
-
-	dnl check that we have either python or matlab support if we compile the modules
-	if test "$MODULES_VALUE" = "yes"  && test "$HAVE_MATLAB" = "no" && test "$HAVE_PYTHON" = "no"; then
-		AC_MSG_ERROR([need at least python or matlab support to compile modules (or use --with-modules=no)]);
-	fi
-
-	dnl check that if we have MPI, we have metis
-	if test "$HAVE_METIS" = "yes"  && test "$HAVE_MPI" = "no" ; then
-	AC_MSG_ERROR([need mpi if using the metis partitioner!]);
-	fi
-
-	AC_MSG_RESULT(done)
 	dnl }}}
 
@@ -1668,3 +1930,45 @@
 	AC_MSG_RESULT($USE_64BIT_INDICES)
 	dnl }}}
+
+	dnl Checks
+	dnl checks{{{
+		AC_MSG_CHECKING(consistency between all libraries)
+
+		  dnl check that if petsc is requested , mpi should be specified
+		  if test "$HAVE_PETSC" = "yes" ; then
+			if test "$HAVE_MPI" = "NO";  then
+			 AC_MSG_ERROR([petsc requires mpi!]);
+		fi
+		  fi
+
+		  dnl check that we have either python or matlab support if we compile the modules
+		  if test "$MODULES_VALUE" = "yes"  && test "$HAVE_MATLAB" = "no" && test "$HAVE_PYTHON" = "no"; then
+			AC_MSG_ERROR([need at least python or matlab support to compile modules (or use --with-modules=no)]);
+		fi
+
+		  dnl check that if we have MPI, we have metis
+		  if test "$HAVE_METIS" = "yes"  && test "$HAVE_MPI" = "no" ; then
+			AC_MSG_ERROR([need mpi if using the metis partitioner!]);
+		fi
+		
+		dnl check that if we run adolc, we don't compile krigging.exe
+		  if test "$HAVE_ADOLC" = "yes"  && test "$HAVE_KRIGING" = "yes" ; then
+			AC_MSG_ERROR([cannot compile kriging.exe under adolc conditions!]);
+		fi
+		dnl check that if we run meteoio, we have snowpack also
+		  if test "$HAVE_METEOIO" = "yes"  && test "$HAVE_SNOWPACK" = "no" ; then
+			AC_MSG_ERROR([cannot compile MeteoIO package without Snowpack!]);
+		fi
+		dnl check that if we run snowpack, we have meteoio also
+		  if test "$HAVE_METEOIO" = "no"  && test "$HAVE_SNOWPACK" = "yes" ; then
+			AC_MSG_ERROR([cannot compile Snowpack package without MeteoIO!]);
+		fi
+
+
+
+
+
+
+		  AC_MSG_RESULT(done)
+		  dnl }}}
 ])
Index: /issm/trunk/packagers/ubuntu/README
===================================================================
--- /issm/trunk/packagers/ubuntu/README	(revision 16136)
+++ /issm/trunk/packagers/ubuntu/README	(revision 16137)
@@ -1,2 +1,4 @@
+TARBALL INSTALLATION:
+
 To install ISSM, untar ISSM-Ubuntu32.tar.gz 
 You will get an ISSM directory. 
@@ -13,2 +15,46 @@
 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/issmpkg/README
===================================================================
--- /issm/trunk/packagers/ubuntu/issmpkg/README	(revision 16137)
+++ /issm/trunk/packagers/ubuntu/issmpkg/README	(revision 16137)
@@ -0,0 +1,138 @@
+UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION 
+
+PREFACE:
+	There are configuration files included in the dir where this document
+	 resides. Use them, that's why they're there. But I know, since some of
+	 you like to go against the grain, at least one of you is going to try
+	 building a package from an install that differs from mine.
+
+	If you choose to go down that dark road, then bear in mind that there
+	 are ways to do this right, and there are ways to do this wrong....
+	 Make sure that you mind where you decide to install the bin and lib.
+	 If you specify a target outside of the trunk, and don't, let's say,
+	 write the same dir somewhere else, then the package won't work. 
+
+	Make sure when putting together a dir hierarchy for a package, that you
+	 create something sime to what you specifed during compile. If you
+	 change "--bindir" then create a dir in the package that corresponds to
+	 that. The trunk doesn't necessarily have to be in the same place as it
+	 is on the build system.
+
+-------------------------------------------------------------------------------
+		    Installing ISSM to create a deb package:
+-------------------------------------------------------------------------------
+
+1.	Install mpich from the ubuntu repositories:
+
+		> sudo apt-get install mpich2 (or something similar)
+
+		Check to make sure that it installs the "-dev" libs
+			if not:
+			 > sudo apt-get install libmpich-dev (or something similar)
+			Otherwise you won't get "/usr/lib/mpich2"
+
+		You can use "apt-cache search" to find a package's full name
+
+2a.	Compile petsc and metis (preferred versions: 3.2 and 4.0, respectively):
+
+		Make sure that petsc's installer file is pointing to the
+		 correct mpich dir
+
+			You should use "/usr/lib/mpich2" (or something similar)
+
+		As of now, it is preferable to use the separate mpich package
+		 because the infrastructure of the mpich package under petsc
+		 is having issues with being packaged
+
+		Also make sure that you mind the target of the installation.
+			Right now /usr/share/petsc and /usr/share/metis are the
+			 best options suffixed by version numbers
+
+2b.	Install dependencies from the ubuntu repositories
+
+		Use apt-get install to install:
+			triangle-bin, libtriangle-dev, python2.7-dev, 
+			 python-scipy, python-netcdf4, netcdf-bin, python-nose, 
+			 libnetcdfc++4, hdf5-tools
+
+		REMEMBER: that this tutorial assumes you are creating the
+		 python interface
+			
+3.	Be sure to patch the system triangle.h file
+
+		> sudo patch /usr/include/triangle.h $ISSM_DIR/externalpackages/triangle/triangle.h.patch
+			the header may also be called "libtriangle.h"
+
+		Just like always, this will move the original to 
+		 "triangle.h.old" incase you need to revert
+
+4.	Compile ISSM
+
+		> autoreconf -iv && configs/config-*-packaging.sh && make && sudo -E make install
+
+-------------------------------------------------------------------------------
+		          Creating an issm.deb package
+-------------------------------------------------------------------------------
+	THIS ASSUMES YOU ARE USING THE CONFIG FILE SUPPLIED HERE.
+	IF YOU ARE DOING AN ALTERNATE CONFIG, MAKE SURE THE DIR
+	HIERARCHY IS PROPERLY REFLECTED BY THE BINDIR AND LIBDIR!
+
+1.	Make a directory to work from (the dir dpkg-deb will build)
+		Anywhere will do, but using a ~/tmp dir works best
+
+		> mkdir issmpkgdir
+		> cd issmpkgdir
+
+2.	Create the dir hierarchy:
+
+		> mkdir -p usr/{bin,lib,share/issm-trunk} etc/issm DEBIAN
+
+		This is will create:
+		issmpkgdir/
+		|_ usr/
+		|  |_ bin/
+		|  |_ lib/
+		|  |_ share/
+		|     |_issm-trunk/ - this is the trunk
+		|_ etc/
+		|  |_ issm/ - this is where issmrc and other conf files go
+		|_DEBIAN/ - where control files and install scripts go
+
+		As stated, if you change "--bindir" or "--libdir" in the config
+		 file, then make sure that you create matching dirs in this
+		 step, or vice-versa.
+
+3.	Copy the contents of the package over:
+
+		> sudo cp -r /usr/bin/issm usr/bin
+		> sudo cp -r /usr/lib/issm usr/lib
+		> cp -r $ISSM_DIR/* usr/share/issm-trunk
+
+		When you copy the trunk over, this your opportunity to weed out
+		 anything you don't want included in the build.
+		Again, the config file installs the bin and lib files to a dir
+		 that's separate from the rest of the bin and lib files. If you
+		 change "--bindir" or "--libdir", make sure you install them to
+		 a subdirectory of your target to keep things neat or else 
+		 you'll have to pick them out, one-by-one to complete this step.
+
+4.	Write your control file. A template is provided, that is the bare minimum to
+		 create the package 
+
+		You will NEED the following dependencies:
+		mpich2, petsc3.2-issm, metis4.0-issm, triangle-bin, libtriangle-dev, 
+		 python2.7-dev, python-scipy, python-netcdf4, netcdf-bin, python-nose, 
+		 libnetcdfc++4, hdf5-tools
+
+5.	Create any install/uninstall scripts needed (preinst, postinst, prerm, postrm)
+		There are already some templates provided for you.
+
+		Make sure you address the issue of any user created content. By
+		 default, apt-get won't remove anything that wasn't created by
+		 the installer, even if you use purge. Put this in a rm script.
+
+6.	Build the package:
+
+		> dpkg-deb --build <workingDir> <nameOfPackage>
+
+UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION - UNDER CONSTRUCTION 
Index: /issm/trunk/packagers/ubuntu/issmpkg/environment.sh
===================================================================
--- /issm/trunk/packagers/ubuntu/issmpkg/environment.sh	(revision 16137)
+++ /issm/trunk/packagers/ubuntu/issmpkg/environment.sh	(revision 16137)
@@ -0,0 +1,287 @@
+#ISSM_DIR and ISSM_ARCH should have been defined already in your shell settings file (.bashrc, .cshrc, etc ...)
+
+pathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
+		export PATH="$1:$PATH"
+	fi
+} #}}}
+pathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
+		export PATH="$PATH:$1"
+	fi
+} #}}}
+libpathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$LD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export LD_LIBRARY_PATH="$1:$LD_LIBRARY_PATH"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$1:$LD_RUN_PATH"
+	fi
+} #}}}
+libpathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$LD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$1"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$LD_RUN_PATH:$1"
+	fi
+} #}}}
+dylibpathprepend(){ #{{{
+	if [ -d "$1" ] && [[ ":$DYLD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export DYLD_LIBRARY_PATH="$1:$DYLD_LIBRARY_PATH"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$1:$LD_RUN_PATH"
+	fi
+} #}}}
+dylibpathappend(){ #{{{
+	if [ -d "$1" ] && [[ ":$DYLD_LIBRARY_PATH:" != *":$1:"* ]]; then
+		export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$1"
+	fi
+	if [ -d "$1" ] && [[ ":$LD_RUN_PATH:" != *":$1:"* ]]; then
+		export LD_RUN_PATH="$LD_RUN_PATH:$1"
+	fi
+} #}}}
+
+#FIXME: during installation packages are installed one by one but environment.sh was sourced
+#before so new packages are NOT in the path.
+#may resource environment.sh with:
+#if [ -z $(echo "$PATH" | grep "$MATLAB_DIR") ]; then export $PATH...; fi
+
+#Windows compilers: 
+if [[ "$ISSM_ARCH" == "cygwin-intel" ]]; then
+	source $ISSM_DIR/externalpackages/windows/windows_environment.sh
+fi
+
+#Some basic path, in case it is not included by default
+libpathappend "/usr/local/lib"
+
+#Load ISSM scripts
+pathappend "$ISSM_DIR/scripts"
+
+MATLAB_DIR="$ISSM_DIR/externalpackages/matlab/install"
+export MATLAB_DIR
+pathprepend   "$MATLAB_DIR/bin" #take precedence over /usr/local/bin/matlab
+libpathappend "$MATLAB_DIR/lib"
+
+#legacy mpich2 (To be removed)
+MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
+if [ -d "$MPI_DIR" ]; then
+	export MPI_DIR
+	pathprepend   "$MPI_DIR/bin"
+	libpathappend "$MPI_DIR/lib"
+fi
+
+MPI_DIR="$ISSM_DIR/externalpackages/mpich/install"
+if [ -d "$MPI_DIR" ]; then
+	export MPI_DIR
+	pathprepend   "$MPI_DIR/bin"
+	libpathappend "$MPI_DIR/lib"
+fi
+
+PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
+export PETSC_DIR
+libpathappend "$PETSC_DIR/lib"
+
+SLEPC_DIR="$ISSM_DIR/externalpackages/slepc/install"
+libpathappend "$SLEPC_DIR/lib"
+
+TAO_DIR="$ISSM_DIR/externalpackages/tao/install"
+libpathappend "$TAO_DIR/lib"
+
+DAKOTA_DIR="$ISSM_DIR/externalpackages/dakota/install"
+pathappend "$DAKOTA_DIR/bin"
+libpathappend "$DAKOTA_DIR/lib"
+
+DOXYGEN_DIR="$ISSM_DIR/externalpackages/doxygen/install"
+pathprepend "$DOXYGEN_DIR/bin"
+
+AUTOTOOLS_DIR="$ISSM_DIR/externalpackages/autotools/install"
+pathprepend "$AUTOTOOLS_DIR/bin"
+
+SDK_DIR="C:/MicrosoftVisualStudio 9.0/Microsoft Visual C++ 2008 Express Edition with SP1 - ENU"
+pathappend "$SDK_DIR"
+
+SSH_DIR="$ISSM_DIR/externalpackages/ssh"
+pathappend "$SSH_DIR"
+
+VALGRIND_DIR="$ISSM_DIR/externalpackages/valgrind/install"
+pathprepend "$VALGRIND_DIR/bin"
+
+CPPCHECK_DIR="$ISSM_DIR/externalpackages/cppcheck/install"
+pathappend "$CPPCHECK_DIR/bin"
+
+GDAL_DIR="$ISSM_DIR/externalpackages/gdal/install"
+pathprepend "$GDAL_DIR/bin"
+libpathappend "$GDAL_DIR/lib"
+
+PROJ4_DIR="$ISSM_DIR/externalpackages/proj.4/install"
+libpathappend "$PROJ4_DIR/lib"
+
+MERCURIAL_DIR="$ISSM_DIR/externalpackages/mercurial/install"
+if [ -d "$MERCURIAL_DIR" ]; then
+	export PYTHONPATH="$PYTHONPATH:$MERCURIAL_DIR/mercurial/pure/"
+	pathappend "$MERCURIAL_DIR"
+fi
+
+BOOST_DIR="$ISSM_DIR/externalpackages/boost/install"
+BOOSTROOT="$ISSM_DIR/externalpackages/boost/install"
+if [ -d "$BOOST_DIR" ]; then
+	export BOOSTROOT
+	export BOOST_DIR
+	libpathappend   "$BOOST_DIR/lib"
+	dylibpathappend "$BOOST_DIR/lib"
+	pathappend      "$BOOST_DIR/bin"
+fi
+
+XERCESROOT="$ISSM_DIR/externalpackages/xerces/install"
+XERCESCROOT="$ISSM_DIR/externalpackages/xerces/src"
+if [ -d "$XERCESROOT" ]; then
+	export XERCESROOT 
+	export XERCESCROOT
+fi
+
+XAIF_DIR="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
+XAIFBOOSTERROOT="$ISSM_DIR/externalpackages/xaifbooster/"
+XAIFBOOSTER_HOME="$ISSM_DIR/externalpackages/xaifbooster/xaifBooster"
+PLATFORM="x86-Linux"
+if [ -d "$XAIF_DIR" ]; then
+	export XAIFBOOSTERROOT
+	export XAIFBOOSTER_HOME
+	export XAIF_DIR
+	export PLATFORM
+fi
+
+ANGELROOT="$ISSM_DIR/externalpackages/angel/angel"
+if [ -d "$ANGELROOT" ]; then
+	export ANGELROOT
+fi
+
+OPENANALYSISROOT="$ISSM_DIR/externalpackages/openanalysis/install"
+if [ -d "$OPENANALYSISROOT" ]; then
+	export OPENANALYSISROOT
+	libpathappend "$OPENANALYSISROOT/lib"
+fi
+
+JVM_DIR="/usr/local/gcc/4.3.2/lib64/gcj-4.3.2-9/"
+libpathappend "$JVM_DIR"
+
+BBFTP_DIR="$ISSM_DIR/externalpackages/bbftp/install"
+pathappend "$BBFTP_DIR/bin"
+
+ADIC_DIR="$ISSM_DIR/externalpackages/adic/install"
+pathappend "$ADIC_DIR/bin"
+libpathappend "$ADIC_DIR/lib"
+
+COLPACK_DIR="$ISSM_DIR/externalpackages/colpack/install"
+libpathappend "$COLPACK_DIR/lib"
+
+ECLIPSE_DIR="$ISSM_DIR/externalpackages/eclipse/install"
+pathappend "$ECLIPSE_DIR"
+
+APPSCAN_DIR="$ISSM_DIR/externalpackages/appscan/install"
+pathappend "$APPSCAN_DIR/bin"
+
+RATS_DIR="$ISSM_DIR/externalpackages/rats/install"
+pathappend "$RATS_DIR/bin"
+
+DYSON_DIR="$ISSM_DIR/externalpackages/dyson/"
+pathappend "$DYSON_DIR"
+
+CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
+pathprepend "$CMAKE_DIR/bin"
+
+SHAPELIB_DIR="$ISSM_DIR/externalpackages/shapelib/install"
+pathappend "$SHAPELIB_DIR/exec"
+
+CCCL_DIR="$ISSM_DIR/externalpackages/cccl/install"
+pathappend "$CCCL_DIR/bin"
+
+PACKAGEMAKER_DIR="$ISSM_DIR/externalpackages/packagemaker/install"
+pathappend "$PACKAGEMAKER_DIR"
+
+#android-dev-dir
+export ANDROID_DIR="$ISSM_DIR/externalpackages/android"
+
+export ANDROID_NDK_DIR="$ANDROID_DIR/android-ndk/install"
+pathappend "$ANDROID_NDK_DIR/arm-linux-android-install/bin"
+
+export ANDROID_SDK_DIR="$ANDROID_DIR/android-sdk/install"
+pathappend "$ANDROID_SDK_DIR/"
+
+GSL_DIR="$ISSM_DIR/externalpackages/gsl/install"
+libpathappend "$GSL_DIR/lib"
+
+GMAKE_DIR="$ISSM_DIR/externalpackages/gmake/install"
+pathprepend "$GMAKE_DIR/bin"
+
+PYTHON_DIR="/usr"
+if [ -d "$PYTHON_DIR" ]; then
+	export PYTHONPATH="$PYTHONPATH:$ISSM_DIR/lib"
+	export PYTHONSTARTUP="$ISSM_DIR/startup.py"
+	pathprepend    "/usr"
+	libpathprepend "$ISSM_DIR/lib"
+	libpathprepend "/usr/lib/python2.7"
+fi
+
+MODELE_DIR="$ISSM_DIR/externalpackages/modelE/install"
+pathappend "$MODELE_DIR/src/exec"
+
+GIT_DIR="$ISSM_DIR/externalpackages/git/install"
+pathprepend "$GIT_DIR/bin"
+
+NCVIEW_DIR="$ISSM_DIR/externalpackages/ncview/install"
+pathappend "$NCVIEW_DIR"
+
+TCLX_DIR="$ISSM_DIR/externalpackages/tclx/install/lib/tclx8.4"
+libpathappend "$TCLX_DIR"
+
+ASPELL_DIR="$ISSM_DIR/externalpackages/aspell/install"
+pathappend "$ASPELL_DIR/bin"
+
+HDF5_DIR="$ISSM_DIR/externalpackages/hdf5/install"
+dylibpathappend "$HDF5_DIR/lib"
+libpathappend "$HDF5_DIR/lib"
+if [ -d "$HDF5_DIR" ]; then
+	export LIBRARY_PATH="$LIBRARY_PATH:$HDF5_DIR/lib"
+	export C_INCLUDE_PATH="$C_INCLUDE_PATH:$HDF5_DIR/include"
+fi
+
+NETCDF_DIR="$ISSM_DIR/externalpackages/netcdf/install"
+pathappend "$NETCDF_DIR/bin"
+dylibpathappend "$NETCDF_DIR/lib"
+libpathappend "$NETCDF_DIR/lib"
+if [ -d "$NETCDF_DIR" ]; then
+	export LIBRARY_PATH="$LIBRARY_PATH:$NETCDF_DIR/lib"
+	dylibpathappend "$NETCDF_DIR/lib"
+	libpathappend "$NETCDF_DIR/lib"
+	export C_INCLUDE_PATH="$C_INCLUDE_PATH:$NETCDF_DIR/include"
+fi
+
+NETCDF_CXX_DIR="$ISSM_DIR/externalpackages/netcdf-cxx/install"
+libpathappend "$NETCDF_CXX_DIR/lib"
+
+SVN_DIR="$ISSM_DIR/externalpackages/svn/install"
+pathprepend   "$SVN_DIR/bin"
+libpathappend "$SVN_DIR/lib"
+
+APR_DIR="$ISSM_DIR/externalpackages/apr/install"
+pathappend    "$APR_DIR/bin"
+libpathappend "$APR_DIR/lib"
+
+APR_UTIL_DIR="$ISSM_DIR/externalpackages/apr-util/install"
+pathappend   "$APR_UTIL_DIR/bin:$PATH"
+libpathappend "$APR_UTIL_DIR/lib"
+
+SQLITE_DIR="$ISSM_DIR/externalpackages/sqlite/install"
+pathappend   "$SQLITE_DIR/bin"
+libpathappend "$SQLITE_DIR/lib"
+
+YAMS_DIR="$ISSM_DIR/externalpackages/yams/install"
+pathappend   "$YAMS_DIR"
+
+SWIG_DIR="$ISSM_DIR/externalpackages/swig/install"
+pathappend   "$SWIG_DIR"
+
+#AUX-CONFIG
+pathappend   "$ISSM_DIR/aux-config"
Index: /issm/trunk/packagers/ubuntu/issmpkg/install-3.2-linux64.sh
===================================================================
--- /issm/trunk/packagers/ubuntu/issmpkg/install-3.2-linux64.sh	(revision 16137)
+++ /issm/trunk/packagers/ubuntu/issmpkg/install-3.2-linux64.sh	(revision 16137)
@@ -0,0 +1,37 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install petsc-3.2-p3 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-3.2-p3.tar.gz' 'petsc-3.2-p3.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.2-p3.tar.gz
+mv petsc-3.2-p3/* src/
+rm -rf petsc-3.2-p3
+
+#configure
+cd src
+./config/configure.py \
+	--prefix="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-mpi-dir="/usr/lib/mpich2/" \
+	--with-clanguage=C++ \
+	--PETSC_ARCH=linux-gnu-amd64 \
+	--PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+	--with-debugging=0 \
+	--with-shared-libraries=1 \
+	--download-mumps=yes \
+	--download-scalapack=yes \
+	--download-blacs=yes \
+	--download-blas=yes \
+	--download-f-blas-lapack=yes \
+	--download-plapack=yes \
+	--download-parmetis=yes \
+	--with-pic=1
+
+#Compile petsc and install it
+make
+make install
Index: /issm/trunk/packagers/ubuntu/issmpkg/issm_options.m4
===================================================================
--- /issm/trunk/packagers/ubuntu/issmpkg/issm_options.m4	(revision 16137)
+++ /issm/trunk/packagers/ubuntu/issmpkg/issm_options.m4	(revision 16137)
@@ -0,0 +1,1690 @@
+dnl ISSM Options
+
+AC_DEFUN([ISSM_OPTIONS],[
+
+	dnl ISSM's internal options
+	dnl Debugging {{{
+	AC_ARG_ENABLE([debugging],                                        dnl feature
+		AS_HELP_STRING([--enable-debugging],[turn debug support on]),  dnl help string
+		[enable_debugging=$enableval],                                 dnl action if given
+		[enable_debugging=no])                                         dnl action if not given
+	if test "x$enable_debugging" = xyes; then
+		AC_DEFINE([_ISSM_DEBUG_],[1],[Macro to enable debugging in ISSM])
+	fi
+
+	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
+    AM_CONDITIONAL([SHAREDLIBS], [test x$enable_sharedlibs = xyes])
+    dnl }}}
+    dnl Version{{{
+    AC_ARG_ENABLE([version],                                                dnl feature
+        AS_HELP_STRING([--enable-version], [produce libISSM.so.0]),         dnl help string
+        [enable_version=$enableval],                                        dnl action if given
+        [enable_version=no])                                                dnl action if not given
+    AM_CONDITIONAL([VERSION], [test x$enable_VERSION = xyes])
+    dnl }}}
+	dnl Wrappers build {{{
+	AC_ARG_WITH([wrappers],
+		AS_HELP_STRING([--with-wrappers = value],[wrappers compilation. ]),
+		[WRAPPERS_VALUE=$withval],[WRAPPERS_VALUE="yes"])
+	AC_MSG_CHECKING(for wrappers compilation)
+	AM_CONDITIONAL([WRAPPERS], [test x$WRAPPERS_VALUE = xyes])
+	AC_MSG_RESULT($WRAPPERS_VALUE) 
+	dnl }}}
+	dnl Extensions{{{
+	ISSMEXT=".exe"
+	AC_SUBST([ISSMEXT])
+	dnl }}}
+
+	dnl ISSM's externalpackages
+	dnl vendor{{{
+	AC_ARG_WITH([vendor],
+	  AS_HELP_STRING([--with-vendor = VENDOR], [vendor name, ex: intel]),
+	  [VENDOR=$withval],[VENDOR=""]) 
+	AC_MSG_CHECKING(for vendor compilers)
+	if test -n "$VENDOR"; then
+
+		if  test $VENDOR = intel-win32; then
+			export CC=icl
+			export CXX=icl
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_"
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_"
+		elif  test $VENDOR = intel-win7-32; then
+			export CC=cl
+			export CXX=cccl
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export AR="ar-lib lib"
+			export OS_LDFLAG="-Wl,"
+			export RANLIB=true
+			OSLIBS="-Wl,kernel32.lib -Wl,user32.lib -Wl,gdi32.lib -Wl,winspool.lib -Wl,comdlg32.lib -Wl,advapi32.lib -Wl,shell32.lib -Wl,ole32.lib -Wl,oleaut32.lib -Wl,uuid.lib -Wl,odbc32.lib -Wl,odbccp32.lib"
+		elif  test $VENDOR = intel-win7-64; then
+			export CC=cl
+			export CXX=cccl
+			export CXXFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export CFLAGS="-DWIN32 -D_INTEL_WIN_ -EHsc"
+			export AR="ar-lib lib"
+			export OS_LDFLAG="-Wl,"
+			export RANLIB=true
+			OSLIBS="-Wl,kernel32.lib -Wl,user32.lib -Wl,gdi32.lib -Wl,winspool.lib -Wl,comdlg32.lib -Wl,advapi32.lib -Wl,shell32.lib -Wl,ole32.lib -Wl,oleaut32.lib -Wl,uuid.lib -Wl,odbc32.lib -Wl,odbccp32.lib"
+		elif test $VENDOR = intel-linux; 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
+			export CXX=icpc
+			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ -DMPICH_IGNORE_CXX_SEEK"
+			export CFLAGS=" -O3 -D_INTEL_LINUX_ -DMPICH_IGNORE_CXX_SEEK"
+		elif test $VENDOR = intel-pleiades; then
+			export CC=icc
+			export CXX=icpc
+			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ "
+			export CFLAGS=" -O3 -D_INTEL_LINUX_ "
+        else
+		AC_MSG_ERROR([unknown compiler vendor!])
+		fi
+	fi
+	AC_SUBST([OSLIBS]) 
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl matlab{{{
+
+	dnl 1. See if matlab has been provided
+	AC_ARG_WITH([matlab-dir],
+		AS_HELP_STRING([--with-matlab-dir=DIR], [matlab root directory. necessary for serial build.]),
+		[MATLAB_ROOT=$withval],[MATLAB_ROOT=""]) 
+
+	AC_MSG_CHECKING([whether matlab is enabled])
+	if test -d "$MATLAB_ROOT"; then
+		HAVE_MATLAB=yes
+	else
+		HAVE_MATLAB=no
+	fi
+	if test x$HAVE_MATLAB = xyes; then
+		AC_DEFINE([_HAVE_MATLAB_],[1],[with Matlab in ISSM src])
+	fi
+	AC_MSG_RESULT($HAVE_MATLAB)
+	AM_CONDITIONAL([MATLAB], [test x$HAVE_MATLAB = xyes])
+
+	dnl 2. Get Matlab libraries
+	if test x$HAVE_MATLAB = xyes; then
+
+		AC_MSG_CHECKING(for matlab headers and libraries in $MATLAB_ROOT)
+  		MATLABINCL="-I$MATLAB_ROOT/extern/include/"
+		
+		dnl 4. get MEXLIB MEXLINK and MEXEXT (experimental)
+      dnl OS-dependent variables and checks
+  		case "${host_os}" in
+  			*cygwin*) 
+  				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" 
+  				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" 
+  				fi
+  				MEXEXT=`$MATLAB_ROOT/bin/mexext.bat`
+  				MEXEXT=".$MEXEXT"
+  			;;
+		   *)
+		      MEXLINK=$(mex -v 2>&1 < /dev/null | grep LDFLAGS     | sed -e "s/         LDFLAGS            = //g")
+	         MEXLIB=$( mex -v 2>&1 < /dev/null | grep CXXLIBS     | sed -e "s/         CXXLIBS            = //g")
+		      MEXEXT=$( mex -v 2>&1 < /dev/null | grep LDEXTENSION | sed -e "s/         LDEXTENSION        = //g")
+  			;;
+      esac
+	   AC_MSG_RESULT(done)
+
+		AC_SUBST([MATLABINCL])
+		AC_SUBST([MEX])
+		MATLABWRAPPEREXT=$MEXEXT
+		AC_SUBST([MATLABWRAPPEREXT])
+	   AC_SUBST([MEXLIB]) 
+		AC_SUBST([MEXLINK])
+	fi
+	dnl }}}
+	dnl triangle {{{
+	AC_ARG_WITH([triangle-dir],
+		AS_HELP_STRING([--with-triangle-dir=DIR], [triangle root directory. necessary for serial build]),
+		[TRIANGLE_ROOT=$withval],
+		[TRIANGLE_ROOT=""]) 
+	AC_ARG_WITH([triangle-include-dir],
+		AS_HELP_STRING([--with-triangle-include-dir], [triangle include dir]),
+		[TRIANGLE_INCL=$withval],
+		[TRIANGLE_INCL="$TRIANGLE_ROOT"])
+	AC_ARG_WITH([triangle-lib-dir],
+		AS_HELP_STRING([--with-triangle-lib-dir], [triangle lib dir]),
+		[TRIANGLE_LIB=$withval],
+		[TRIANGLE_LIB="$TRIANGLE_ROOT"])
+	AC_MSG_CHECKING(for triangle headers and libraries)
+
+	if test -d "$TRIANGLE_ROOT"; then
+
+		dnl defaults
+		HAVE_TRIANGLE=yes
+		TRIANGLEINCL=-I$TRIANGLE_INCL
+
+		case "${host_os}" in
+				*cygwin*)
+				TRIANGLELIB="-Wl,`cygpath -m $TRIANGLE_LIB/`triangle.lib"
+				;;
+				*linux*)
+				TRIANGLELIB="-ltriangle"
+				;;
+				*darwin*)
+				TRIANGLELIB=$TRIANGLE_LIB/triangle.a
+				;;
+			esac
+
+		AC_DEFINE([_HAVE_TRIANGLE_],[1],[with Triangle in ISSM src])
+		AC_SUBST([TRIANGLEINCL])
+		AC_SUBST([TRIANGLELIB])
+
+	else
+		HAVE_TRIANGLE=no
+	fi
+	AC_MSG_RESULT($HAVE_TRIANGLE)
+	dnl }}}
+	dnl boost{{{
+	AC_ARG_WITH([boost-dir],
+	  AS_HELP_STRING([--with-boost-dir=DIR], [boost root directory.]),
+	  [BOOST_ROOT=$withval],[BOOST_ROOT=""]) 
+	AC_MSG_CHECKING(for boost)
+	
+	if test -d "$BOOST_ROOT"; then
+		dnl defaults
+		HAVE_BOOST=yes
+		BOOSTINCL=-I$BOOST_ROOT/include
+		BOOSTLIB="-L$BOOST_ROOT/lib -lboost_python"
+
+		AC_DEFINE([_HAVE_BOOST_],[1],[with Boost in ISSM src])
+		AC_SUBST([BOOSTINCL])
+		AC_SUBST([BOOSTLIB])
+	else
+		HAVE_BOOST=no
+	fi
+	AM_CONDITIONAL([BOOST], [test x$HAVE_BOOST = xyes])
+	AC_MSG_RESULT($HAVE_BOOST)
+	dnl }}}
+	dnl dakota{{{
+	AC_ARG_WITH([dakota-dir],
+	  AS_HELP_STRING([--with-dakota-dir=DIR], [dakota root directory. necessary for serial build]),
+	  [DAKOTA_ROOT=$withval],[DAKOTA_ROOT=""]) 
+	AC_MSG_CHECKING(for dakota)
+	
+	if test -d "$DAKOTA_ROOT"; then
+
+		dnl defaults
+		HAVE_DAKOTA=yes
+		AC_MSG_RESULT($HAVE_DAKOTA)
+		DAKOTAINCL=-I$DAKOTA_ROOT/include
+		AC_MSG_CHECKING(for dakota version)
+		if test -f "$DAKOTA_ROOT/../src/src/CommandLineHandler.C"; then
+			DAKOTA_VERSION=`cat $DAKOTA_ROOT/../src/src/CommandLineHandler.C | grep 'DAKOTA version' | grep 'release' | grep -v // | sed 's/.*DAKOTA version //' | sed 's/ .*//' `
+		else if test -f "$DAKOTA_ROOT/../src/src/CommandLineHandler.cpp"; then
+			DAKOTA_VERSION=`cat $DAKOTA_ROOT/../src/src/CommandLineHandler.cpp | grep 'DAKOTA version' | grep 'release' | grep -v // | sed 's/.*DAKOTA version //' | sed 's/ .*//' `
+		else
+			AC_MSG_ERROR([Dakota CommandLineHandler.C or CommandLineHandler.cpp file not found to determine DAKOTA_VERSION!]);
+		fi
+		fi
+
+		AC_MSG_RESULT($DAKOTA_VERSION)
+		AC_DEFINE_UNQUOTED([_DAKOTA_VERSION_],"$DAKOTA_VERSION",[Dakota version number])
+		DAKOTAFLAGS=""
+		case "${host_os}" in
+			*cygwin*)
+				if      test x$DAKOTA_VERSION = x4.2 || test x$DAKOTA_VERSION = x4.2+; then
+					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"
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+			;;
+			*linux*)
+				if      test x$DAKOTA_VERSION = x4.2 || test x$DAKOTA_VERSION = x4.2+; then
+					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 -lboost_system -ldl"
+				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 "
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+				fi
+			;;
+			*darwin*)
+				if      test x$DAKOTA_VERSION = x4.2 || test x$DAKOTA_VERSION = x4.2+; then
+					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" 
+					dnl DAKOTALIB+= "-lgslcblas -L/usr/lib -lblas -llapack"
+				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 -lboost_system"
+					dnl DAKOTALIB+= "-lgslcblas -L/usr/lib -lblas -llapack"
+				else
+					AC_MSG_ERROR([Dakota version not found or version ($DAKOTA_VERSION) not supported!]);
+				fi
+				fi
+			;;
+		esac
+		AC_DEFINE([_HAVE_DAKOTA_],[1],[with Dakota in ISSM src])
+
+		case $DAKOTA_VERSION in
+			@<:@1-9@:>@.@<:@0-9@:>@.@<:@0-9@:>@)
+				DAKOTA_MAJOR=`echo $DAKOTA_VERSION | sed -e 's/^\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_MINOR=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_BUILD=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/'`
+			;;
+			@<:@1-9@:>@.@<:@0-9@:>@)
+				DAKOTA_MAJOR=`echo $DAKOTA_VERSION | sed -e 's/^\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_MINOR=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/'`
+				DAKOTA_BUILD=0
+			;;
+			@<:@1-9@:>@.@<:@0-9@:>@+)
+				DAKOTA_MAJOR=`echo $DAKOTA_VERSION | sed -e 's/^\(@<:@0-9@:>@*\)\..*/\1/'`
+				DAKOTA_MINOR=`echo $DAKOTA_VERSION | sed -e 's/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/'`
+				DAKOTA_BUILD=0
+			;;
+			*)
+				AC_MSG_ERROR([Dakota version ($DAKOTA_VERSION) not supported!]);
+		   ;;
+		esac
+		AC_MSG_CHECKING(for dakota major version)
+		AC_MSG_RESULT($DAKOTA_MAJOR)
+		AC_DEFINE_UNQUOTED([_DAKOTA_MAJOR_],$DAKOTA_MAJOR,[Dakota major version number])
+		AC_MSG_CHECKING(for dakota minor version)
+		AC_MSG_RESULT($DAKOTA_MINOR)
+		AC_DEFINE_UNQUOTED([_DAKOTA_MINOR_],$DAKOTA_MINOR,[Dakota minor version number])
+		AC_MSG_CHECKING(for dakota build version)
+		AC_MSG_RESULT($DAKOTA_BUILD)
+		AC_DEFINE_UNQUOTED([_DAKOTA_BUILD_],$DAKOTA_BUILD,[Dakota build version number])
+
+		AC_SUBST([DAKOTAINCL])
+		AC_SUBST([DAKOTAFLAGS])
+		AC_SUBST([DAKOTALIB])
+
+	else
+		HAVE_DAKOTA=no
+		AC_MSG_RESULT($HAVE_DAKOTA)
+	fi
+
+	AM_CONDITIONAL([DAKOTA], [test x$HAVE_DAKOTA = xyes])
+	dnl }}}
+	dnl python{{{
+	AC_ARG_WITH([python-dir],
+		AS_HELP_STRING([--with-python-dir=DIR], [python root directory.]),
+		[PYTHON_ROOT=$withval],
+		[PYTHON_ROOT=""]) 
+
+	AC_ARG_WITH([python-include-dir],
+		AS_HELP_STRING([--with-python-include-dir=DIR], [python include directory.]),
+		[PYTHON_INCL=$withval],
+		[PYTHON_INCL="$PYTHON_ROOT/include"]) 
+
+	AC_ARG_WITH([python-lib-dir],
+		AS_HELP_STRING([--with-python-lib-dir=DIR], [python lib directory.]),
+		[PYTHON_LIB=$withval],
+		[PYTHON_LIB="$PYTHON_ROOT/lib"]) 
+
+	AC_MSG_CHECKING(for python)
+	if test -d "$PYTHON_ROOT"; then
+		HAVE_PYTHON="yes"
+		AC_DEFINE([_HAVE_PYTHON_],[1],[with Python in ISSM src])
+	else
+		HAVE_PYTHON=no
+	fi
+	AC_MSG_RESULT($HAVE_PYTHON)
+
+	dnl get python version
+	if test x$HAVE_PYTHON = xyes; then
+		AC_MSG_CHECKING(for python version)
+		dnl Query Python for its version number.  Getting [:3] seems to be
+		dnl the best way to do this; it's what "site.py" does in the standard
+		dnl library.
+		PYTHON_VERSION=$($PYTHON_ROOT/bin/python -c "import sys; print sys.version[[:3]]")
+		AC_MSG_RESULT($PYTHON_VERSION)
+
+		dnl recover major: 
+		PYTHON_MAJOR=${PYTHON_VERSION%.*}
+		if test x$PYTHON_MAJOR = x3; then
+			dnl are we running python 3?
+			HAVE_PYTHON3="yes"
+		else
+			HAVE_PYTHON3="no"
+		fi
+		AC_DEFINE_UNQUOTED([_PYTHON_MAJOR_],$PYTHON_MAJOR,[python version major])
+
+		PYTHONINCL="-I$PYTHON_INCL"
+		PYTHONLIB="-L$PYTHON_LIB -lpython$PYTHON_VERSION"
+		PYTHONEXT=.so
+
+		case "${host_os}" in
+			*cygwin*)
+			PYTHONLINK="-shared"
+			;;
+			*linux*)
+			PYTHONLINK="-shared"
+			;;
+			*darwin*)
+			PYTHONLINK="-dynamiclib"
+			;;
+		esac
+
+		AC_SUBST([PYTHONINCL])
+		AC_SUBST([PYTHONLIB])
+		PYTHONWRAPPEREXT=$PYTHONEXT
+		AC_SUBST([PYTHONWRAPPEREXT])
+		AC_SUBST([PYTHONLINK])
+	fi
+	AM_CONDITIONAL([PYTHON], [test x$HAVE_PYTHON = xyes])
+	AM_CONDITIONAL([PYTHON3], [test x$HAVE_PYTHON3 = xyes])
+	dnl }}}
+	dnl python-numpy{{{
+	AC_ARG_WITH([python-numpy-dir],
+	  AS_HELP_STRING([--with-python-numpy-dir=DIR], [python-numpy root directory.]),
+	  [PYTHON_NUMPY_ROOT=$withval],[PYTHON_NUMPY_ROOT=""]) 
+	AC_MSG_CHECKING(for python-numpy)
+	
+	if test -d "$PYTHON_NUMPY_ROOT"; then
+		dnl defaults
+		HAVE_PYTHON_NUMPY=yes
+		PYTHON_NUMPYINCL="-I$PYTHON_NUMPY_ROOT -I$PYTHON_NUMPY_ROOT/core/include/numpy"
+
+		AC_DEFINE([_HAVE_PYTHON_NUMPY_],[1],[with Python-Numpy in ISSM src])
+		AC_SUBST([PYTHON_NUMPYINCL])
+	else
+		HAVE_PYTHON_NUMPY=no
+	fi
+	AC_MSG_RESULT($HAVE_PYTHON_NUMPY)
+	dnl }}}
+	dnl chaco{{{
+	AC_ARG_WITH([chaco-dir],
+	  AS_HELP_STRING([--with-chaco-dir=DIR], [chaco root directory.]),
+	  [CHACO_ROOT=$withval],[CHACO_ROOT=""]) 
+	AC_MSG_CHECKING(for chaco)
+	
+	if test -d "$CHACO_ROOT"; then
+
+		dnl defaults
+		HAVE_CHACO=yes
+		CHACOINCL=-I$CHACO_ROOT/include
+		CHACOLIB="-L$CHACO_ROOT/lib -lchacominusblas"
+
+		AC_DEFINE([_HAVE_CHACO_],[1],[with Chaco in ISSM src])
+		AC_SUBST([CHACOINCL])
+		AC_SUBST([CHACOLIB])
+
+	else
+		HAVE_CHACO=no
+	fi
+	AC_MSG_RESULT($HAVE_CHACO)
+	dnl }}}
+	dnl scotch{{{
+	AC_ARG_WITH([scotch-dir],
+	  AS_HELP_STRING([--with-scotch-dir=DIR], [scotch root directory.]),
+	  [SCOTCH_ROOT=$withval],[SCOTCH_ROOT=""]) 
+	AC_MSG_CHECKING(for scotch)
+	
+	if test -d "$SCOTCH_ROOT"; then
+
+		dnl defaults
+		HAVE_SCOTCH=yes
+		SCOTCHINCL="-DNOFILEIO -I$SCOTCH_ROOT/include -DSCOTCH_VERSION=\\\"UNKNOWN\\\""
+		SCOTCHLIB="-L$SCOTCH_ROOT/lib -lnfioscotch -lnfioscotcherr -lnfioscotcherrexit -lscotchmetis"
+
+		AC_DEFINE([_HAVE_SCOTCH_],[1],[with Scotch in ISSM src])
+		AC_SUBST([SCOTCHINCL])
+		AC_SUBST([SCOTCHLIB])
+
+	else
+		HAVE_SCOTCH=no
+	fi
+	AC_MSG_RESULT($HAVE_SCOTCH)
+	dnl }}}
+	dnl adolc{{{
+	AC_ARG_WITH([adolc-dir],
+		AS_HELP_STRING([--with-adolc-dir=DIR], [adolc root directory.]),
+		[ADOLC_ROOT=$withval],[ADOLC_ROOT="no"]) 
+	AC_MSG_CHECKING(for adolc)
+
+	if test "x$ADOLC_ROOT" = "xno"; then
+		HAVE_ADOLC=no
+	else
+		if test -d "$ADOLC_ROOT"; then
+
+			dnl defaults
+			HAVE_ADOLC=yes
+			ADOLCINCL="-I$ADOLC_ROOT/include"
+			ADOLCLIB="-L$ADOLC_ROOT/lib64 -ladolc"
+
+			AC_DEFINE([_HAVE_ADOLC_],[1],[with adolc in ISSM src])
+			AC_SUBST([ADOLCINCL])
+			AC_SUBST([ADOLCLIB])
+
+		else
+			echo  "Specified directory does not exist!"
+			exit 1
+		fi
+	fi
+	AM_CONDITIONAL([ADOLC], [test x$HAVE_ADOLC = xyes])
+	AC_MSG_RESULT($HAVE_ADOLC)
+	dnl }}}
+	dnl adolc-version{{{
+	AC_ARG_WITH([adolc-version],
+		AS_HELP_STRING([--with-adolc-version=number], [adolc version.]),
+		[ADOLC_VERSION=$withval],[ADOLC_VERSION=2]) 
+	AC_MSG_CHECKING(for adolc-version) 
+
+	AC_DEFINE_UNQUOTED([_ADOLC_VERSION_],$ADOLC_VERSION,[ADOLC version])
+	AC_MSG_RESULT($ADOLC_VERSION)
+	dnl }}}
+	dnl adic2{{{
+	AC_ARG_WITH([adic2-dir],
+	  AS_HELP_STRING([--with-adic2-dir=DIR], [adic2 root directory.]),
+	  [ADIC2_ROOT=$withval],[ADIC2_ROOT="no"]) 
+	AC_MSG_CHECKING(for adic2)
+
+	if test "x$ADIC2_ROOT" = "xno"; then
+		HAVE_ADIC2=no
+	else
+		if test -d "$ADIC2_ROOT"; then
+
+			dnl defaults
+			HAVE_ADIC2=yes
+			ADIC2INCL="-DADIC2_DENSE -I$ADIC2_ROOT/include -I$ADIC2_ROOT/share/runtime_dense/"
+			ADIC2LIB=""
+
+			AC_DEFINE([_HAVE_ADIC2_],[1],[with adic2 in ISSM src])
+			AC_SUBST([ADIC2INCL])
+			AC_SUBST([ADIC2LIB])
+
+		else
+			echo  "Specified directory does not exist!"
+			exit 1
+		fi
+	fi
+	AM_CONDITIONAL([ADIC2], [test x$HAVE_ADIC2 = xyes])
+	AC_MSG_RESULT($HAVE_ADIC2)
+	dnl }}}
+	dnl gsl{{{
+	AC_ARG_WITH([gsl-dir],
+	  AS_HELP_STRING([--with-gsl-dir=DIR], [gsl root directory.]),
+	  [GSL_ROOT=$withval],[GSL_ROOT=""]) 
+	AC_MSG_CHECKING(for gsl)
+	
+	if test -d "$GSL_ROOT"; then
+
+		dnl defaults
+		HAVE_GSL=yes
+		GSLINCL="-I$GSL_ROOT/include"
+		GSLLIB="-dy -L$GSL_ROOT/lib -lgsl -lgslcblas -lm"
+
+		AC_DEFINE([_HAVE_GSL_],[1],[with gsl in ISSM src])
+		AC_SUBST([GSLINCL])
+		AC_SUBST([GSLLIB])
+
+	else
+		HAVE_GSL=no
+	fi
+	AM_CONDITIONAL([GSL], [test x$HAVE_GSL = xyes])
+	AC_MSG_RESULT($HAVE_GSL)
+	dnl }}}
+	dnl rose{{{
+	AC_ARG_WITH([rose-dir],
+	  AS_HELP_STRING([--with-rose-dir=DIR], [rose root directory.]),
+	  [ROSE_ROOT=$withval],[ROSE_ROOT=""]) 
+	AC_MSG_CHECKING(for rose)
+	
+	if test -d "$ROSE_ROOT"; then
+
+		dnl defaults
+		HAVE_ROSE=yes
+		ROSEINCL="-I$ROSE_ROOT/include"
+		ROSELIB=""
+
+		AC_DEFINE([_HAVE_ROSE_],[1],[with rose in ISSM src])
+		AC_SUBST([ROSEINCL])
+		AC_SUBST([ROSELIB])
+
+	else
+		HAVE_ROSE=no
+	fi
+	AM_CONDITIONAL([ROSE], [test x$HAVE_ROSE = xyes])
+	AC_MSG_RESULT($HAVE_ROSE)
+	dnl }}}
+	dnl mpi{{{
+	AC_MSG_CHECKING(for mpi)
+	
+	AC_ARG_WITH([mpi-include],
+	  AS_HELP_STRING([--with-mpi-include=DIR],[mpi include directory, necessary for parallel build]),
+	  [MPI_INCLUDE=$withval],[MPI_INCLUDE=""])
+
+	AC_ARG_WITH([mpi-libdir],
+	  AS_HELP_STRING([--with-mpi-libdir=DIR],[mpi lib directory, necessary for parallel build]),
+	  [MPI_LIBDIR=$withval],[MPI_LIBDIR=""])
+
+	AC_ARG_WITH([mpi-libflags],
+	  AS_HELP_STRING([--with-mpi-libflags=LIBS],[mpi libraries to be used, necessary for parallel build]),
+	  [MPI_LIBFLAGS=$withval],[MPI_LIBFLAGS=""])
+
+	
+	if test -z "$MPI_INCLUDE" ; then
+		HAVE_MPI=no
+	else
+		HAVE_MPI=yes
+
+		dnl Processing for windows
+		if  test x$VENDOR = xintel-win7-32; then
+			MPI_LIBDIR=`cygpath -m $MPI_LIBDIR`
+			MPIINCL=`cygpath -m $MPI_INCLUDE`
+		elif test x$VENDOR = xintel-win7-64; then
+			MPI_LIBDIR=`cygpath -m $MPI_LIBDIR`
+			MPI_INCLUDE=`cygpath -m $MPI_INCLUDE`
+		fi
+
+		if test -z "$MPI_LIBDIR"; then
+			MPIINCL=-I"$MPI_INCLUDE"
+			MPILIB="$MPI_LIBFLAGS"
+		else
+			MPIINCL=-I"$MPI_INCLUDE"
+			MPILIB="-L$MPI_LIBDIR $MPI_LIBFLAGS"
+		fi
+		AC_DEFINE([_HAVE_MPI_],[1],[with Mpi in ISSM src])
+		AC_DEFINE([HAVE_MPI],[1],[Mpi Flag for Dakota (DO NOT REMOVE)])
+		AC_SUBST([MPIINCL])
+		AC_SUBST([MPILIB])
+	fi
+
+	AM_CONDITIONAL([MPI], [test x$HAVE_MPI = xyes])
+	AC_MSG_RESULT($HAVE_MPI)
+	dnl }}}
+	dnl petsc{{{
+	AC_ARG_WITH([petsc-dir],
+	  AS_HELP_STRING([--with-petsc-dir=DIR],[PETSc root directory, necessary for parallel build]),
+	  [PETSC_ROOT=$withval],[PETSC_ROOT=""])
+		
+	if test -d "$PETSC_ROOT"; then
+		AC_MSG_CHECKING(for petsc version)
+		PETSC_MAJOR=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_MAJOR" | sed 's/#define PETSC_VERSION_MAJOR//' | sed 's/ //g'`
+		PETSC_MINOR=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_MINOR" | sed 's/#define PETSC_VERSION_MINOR//' | sed 's/ //g'`
+		AC_DEFINE_UNQUOTED([_PETSC_MAJOR_],$PETSC_MAJOR,[PETSc version major])
+		AC_DEFINE_UNQUOTED([_PETSC_MINOR_],$PETSC_MINOR,[PETSc version minor])
+		AC_MSG_RESULT($PETSC_MAJOR.$PETSC_MINOR)
+
+		PETSC_VERSION_DATE_HG=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_DATE_HG" | sed 's/#define PETSC_VERSION_DATE_HG//' | sed 's/ //g' | sed -e 's/\"//g' `
+		PETSC_RELEASE=`cat $PETSC_ROOT/include/petscversion.h | grep "#define PETSC_VERSION_RELEASE" | sed 's/#define PETSC_VERSION_RELEASE//' | sed 's/ //g'`
+
+		AC_MSG_CHECKING(whether petsc is the development version)
+		dnl if test x$PETSC_VERSION_DATE_HG = xunknown; then
+		if test "$PETSC_RELEASE" = "0"; then
+		   AC_DEFINE([_HAVE_PETSCDEV_],[1],[with PETSc-dev])
+			AC_MSG_RESULT(yes)
+		else
+			AC_MSG_RESULT(no)
+		fi
+	fi
+	
+	AC_ARG_WITH([petsc-arch],
+	  AS_HELP_STRING([--with-petsc-arch=DIR],[PETSc arch , necessary for parallel build]),
+	  [PETSC_ARCH=$withval],[PETSC_ARCH=""])
+
+	AC_MSG_CHECKING(for petsc headers and libraries in $PETSC_ROOT for architecture $PETSC_ARCH)
+	
+	dnl To ge PETSc's libraries:
+	dnl cd externalpackages/petsc/src
+	dnl make getlinklibs
+	if test -d "$PETSC_ROOT"; then
+
+	 PETSCINCL=" -I$PETSC_ROOT/include"
+	 dnl Add other location (not needed anymore since at least PETSc 3.0)
+	 if test "x$PETSC_ARCH" != "x" && test -d "$PETSC_ROOT/$PETSC_ARCH/include"; then
+	  PETSCINCL+=" $PETSC_ROOT/$PETSC_ARCH/include"
+	 fi
+	 if test "x$PETSC_ARCH" != "x" && test -d "$PETSC_ROOT/include/$PETSC_ARCH"; then
+	  PETSCINCL+=" $PETSC_ROOT/include/$PETSC_ARCH"
+	 fi
+	
+	 case "${host_os}" in
+			*cygwin*)
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB=-Wl,/LIBPATH:`cygpath -w $PETSC_ROOT/lib`  -Wl,libpetscksp.lib  -Wl,libpetscdm.lib  -Wl,libpetscmat.lib  -Wl,libpetscvec.lib  -Wl,libpetscsnes.lib  -Wl,libpetscts.lib  -Wl,libmpiuni.lib  -Wl,libpetsc.lib
+			else
+				PETSCLIB="-L$PETSC_ROOT/lib  -Wl,libpetsc.lib"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+="  -Wl,libmetis.lib"; fi
+			fi
+			;;
+			*linux*)
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lmpiuni -lpetsc"
+			else
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetsc -ldl"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
+			fi
+			;;
+			*darwin*)
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
+			else
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetsc"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
+			fi
+			;;
+		esac
+		AC_DEFINE([_HAVE_PETSC_],[1],[with PETSc in ISSM src])
+		AC_SUBST([PETSCINCL])
+		AC_SUBST([PETSCLIB])
+		HAVE_PETSC=yes
+	else
+		HAVE_PETSC=no
+	fi
+	
+	AM_CONDITIONAL([PETSC], [test x$HAVE_PETSC = xyes])
+	AC_MSG_RESULT($HAVE_PETSC)
+	dnl }}}
+	dnl metis{{{
+	if test "$HAVE_PETSC" = "yes" && test "x$PETSC_MAJOR" = "x3" && test $PETSC_MINOR -ge 3; then
+
+		dnl in petsc >=3.3, metis is provided
+		HAVE_METIS="yes"
+		AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
+		AC_DEFINE([_HAVE_METIS_],[1],[with Metis in ISSM src])
+	else
+		AC_ARG_WITH([metis-dir],
+		  AS_HELP_STRING([--with-metis-dir=DIR],[metis root directory. necessary for serial build]),
+		  [METIS_ROOT=$withval],[METIS_ROOT=""])
+
+		AC_MSG_CHECKING(for metis headers and libraries in $METIS_ROOT)
+
+		if test -d "$METIS_ROOT"; then
+
+			dnl first figure out version of metis: does the VERSION file exist?
+			if test -e "$METIS_ROOT/VERSION"; then
+				METIS_VERSION=4
+			else
+				METIS_VERSION=5
+			fi
+
+			dnl defaults
+			HAVE_METIS=yes
+
+			if test "$METIS_VERSION" = "4" ; then
+					
+				METISINCL=-I"$METIS_ROOT/Lib" 
+				case "${host_os}" in
+					*cygwin*)
+					METISLIB="-L$METIS_ROOT -Wl,libmetis.lib"
+					;;
+					*linux*)
+					METISLIB=-L"$METIS_ROOT/ -lmetis"
+					;;
+					*darwin*)
+					METISLIB=-L"$METIS_ROOT/ -lmetis"
+					;;
+				esac
+
+					AC_DEFINE([_METIS_VERSION_],[4],[ Metis version number])
+			fi
+			if test "$METIS_VERSION" = "5" ; then
+		
+				case "${host_os}" in
+					*cygwin*)
+					METISLIB="-L$METIS_ROOT libmetis.lib"
+					;;
+					*linux*)
+					METISLIB=-L"$METIS_ROOT/lib -lmetis"
+					;;
+					*darwin*)
+					METISLIB=-L"$METIS_ROOT/lib -lmetis"
+					;;
+				esac
+
+				METISINCL=-I"$METIS_ROOT/include" 
+				AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
+			fi
+
+			AC_DEFINE([_HAVE_METIS_],[1],[with Metis in ISSM src])
+			AC_SUBST([METISINCL])
+			AC_SUBST([METISLIB])
+		else
+			HAVE_METIS=no
+		fi
+		AC_MSG_RESULT($HAVE_METIS)
+	fi
+	AM_CONDITIONAL([METIS], [test x$HAVE_METIS = xyes])
+	dnl }}}
+	dnl tao{{{
+	AC_ARG_WITH([tao-dir],
+		AS_HELP_STRING([--with-tao-dir=DIR], [tao root directory.]),
+		[TAO_ROOT=$withval],[TAO_ROOT=""]) 
+	AC_MSG_CHECKING(for tao)
+
+	if test -d "$TAO_ROOT"; then
+
+	  HAVE_TAO=yes
+	  TAOINCL="-I$TAO_ROOT/ -I$TAO_ROOT/include -I$TAO_ROOT/bmake/ "
+	  TAOLIB="-L$TAO_ROOT/lib -ltao -lpetsc"
+
+	  AC_DEFINE([_HAVE_TAO_],[1],[with Tao in ISSM src])
+	  AC_SUBST([TAOINCL])
+	  AC_SUBST([TAOLIB])
+	else
+		HAVE_TAO=no
+	fi
+	AC_MSG_RESULT($HAVE_TAO)
+	dnl }}}
+	dnl slepc{{{
+	AC_ARG_WITH([slepc-dir],
+	  AS_HELP_STRING([--with-slepc-dir=DIR],[slepc root directory]),
+	  [SLEPC_ROOT=$withval],[SLEPC_ROOT=""])
+			  
+	AC_MSG_CHECKING(for slepc headers and libraries in $SLEPC_ROOT)
+	if test -d "$SLEPC_ROOT"; then
+		HAVE_SLEPC=yes
+		SLEPCINCL=-I"$SLEPC_ROOT/include"
+		SLEPCLIB=-L"$SLEPC_ROOT/lib/ -lslepc"
+
+		AC_DEFINE([_HAVE_SLEPC_],[1],[with Slepc in ISSM src])
+		AC_SUBST([SLEPCINCL])
+		AC_SUBST([SLEPCLIB])
+	else
+		HAVE_SLEPC=no
+	fi
+	AC_MSG_RESULT($HAVE_SLEPC)
+	dnl }}}
+	dnl shapelib{{{
+	AC_ARG_WITH([shapelib-dir],
+	  AS_HELP_STRING([--with-shapelib-dir=DIR], [shapelib root directory]),
+	  [SHAPELIB_ROOT=$withval],[SHAPELIB_ROOT=""])
+			  
+	AC_MSG_CHECKING(for shapelib headers and libraries in $SHAPELIB_ROOT)
+	if test -d "$SHAPELIB_ROOT"; then
+
+		dnl defaults
+		HAVE_SHAPELIB=yes
+		SHAPELIBINCL=-I"$SHAPELIB_ROOT/include"
+		SHAPELIBLIB=-L"$SHAPELIB_ROOT/lib/ -lshape"
+
+		AC_DEFINE([_HAVE_SHAPELIB_],[1],[with Shapelib in ISSM src])
+		AC_SUBST([SHAPELIBINCL])
+		AC_SUBST([SHAPELIBLIB])
+	else
+		HAVE_SHAPELIB=no
+	fi
+	AC_MSG_RESULT($HAVE_SHAPELIB)
+	dnl }}}
+	dnl scalapack{{{
+	AC_ARG_WITH([scalapack-dir],
+	  AS_HELP_STRING([--with-scalapack-dir=DIR],[scalapack root directory]),
+	  [SCALAPACK_ROOT=$withval],[SCALAPACK_ROOT=""])
+			  
+	AC_MSG_CHECKING(for scalapack headers and libraries in $SCALAPACK_ROOT)
+	if test -d "$SCALAPACK_ROOT"; then
+
+		dnl defaults
+		HAVE_SCALAPACK=yes
+		if test x$VENDOR = xintel-discover; then
+		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lmkl_scalapack_lp64"
+		else
+		 SCALAPACKLIB=-L"$SCALAPACK_ROOT/ -lscalapack"
+		fi
+
+		AC_DEFINE([_HAVE_SCALAPACK_],[1],[with Scalapack in ISSM src])
+		AC_SUBST([SCALAPACKLIB])
+	else
+		HAVE_SCALAPACK=no
+	fi
+	AC_MSG_RESULT($HAVE_SCALAPACK)
+	dnl }}}
+	dnl blas{{{
+	AC_ARG_WITH([blas-lapack-dir],
+	  AS_HELP_STRING([--with-blas-lapack-dir=DIR],[blas-lapack root directory]),
+	  [BLASLAPACK_ROOT=$withval],[BLASLAPACK_ROOT=""])
+			  
+	AC_MSG_CHECKING(for blas and lapack headers and libraries in $BLASLAPACK_ROOT)
+	if test -d "$BLASLAPACK_ROOT"; then
+
+		dnl defaults
+		HAVE_BLASLAPACK=yes
+		BLASLAPACKINCL=""
+	
+		if test x$VENDOR = xintel-discover; then
+		 BLASLAPACKLIB=-L"$BLASLAPACK_ROOT -lmkl_lapack -lmkl -lguide -lpthread"
+		else
+		dnl: branch on whether we are running on windows or linux.
+		case "${host_os}" in
+			*cygwin*)
+			BLASLAPACKLIB="-L`cygpath -m $BLASLAPACK_ROOT` -Wl,libf2cblas.lib  -Wl,libf2clapack.lib"
+			;;
+			*linux*)
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
+			;;
+			*darwin*)
+			BLASLAPACKLIB=-L"$BLASLAPACK_ROOT/lib -lflapack -lfblas " 
+			;;
+		esac
+		fi
+
+		AC_DEFINE([_HAVE_BLASLAPACK_],[1],[with blas lapack in ISSM src])
+		AC_SUBST([BLASLAPACKLIB])
+		AC_SUBST([BLASLAPACKINCL])
+	else
+		HAVE_BLASLAPACK=no
+	fi
+	AC_MSG_RESULT($HAVE_BLASLAPACK)
+	dnl }}}
+	dnl mkl{{{
+	AC_ARG_WITH([mkl-dir],
+	  AS_HELP_STRING([--with-mkl-dir=DIR],[mkl root directory]),
+	  [MKL_ROOT=$withval],[MKL_ROOT=""])
+			  
+	AC_MSG_CHECKING(for mkl headers and libraries in $MKL_ROOT)
+	if test -d "$MKL_ROOT"; then
+
+		dnl defaults
+		HAVE_MKL=yes
+		MKLINCL=""
+		if test x$VENDOR = xintel-pleiades; then
+		 MKLLIB=-L"$MKL_ROOT -lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core -liomp5 -lpthread"
+		else
+		 MKLLIB=-L"$MKL_ROOT -lmkl -lmkl_lapack -lmkl_scalapack_ilp64 -lmkl_blacs_sgimpt_ilp64 -lguide -lpthread"
+		fi
+		AC_DEFINE([_HAVE_MKL_],[1],[with mkl in ISSM src])
+		AC_SUBST([MKLLIB])
+		AC_SUBST([MKLINCL])
+	else
+		HAVE_MKL=no
+	fi
+	AC_MSG_RESULT($HAVE_MKL)
+	dnl }}}
+	dnl plapack{{{
+	AC_MSG_CHECKING(for plapack)
+	
+	AC_ARG_WITH([plapack-lib],
+	  AS_HELP_STRING([--with-plapack-lib = lib],[plapack library]),
+	  [PLAPACK_LIB=$withval],[PLAPACK_LIB=""])
+	
+	AC_ARG_WITH([plapack-include],
+			  AS_HELP_STRING([--with-plapack-include = include],
+							 [plapack include ]),
+			  [PLAPACK_INCLUDE=$withval],[PLAPACK_INCLUDE=""])
+	  
+	if test -n "$PLAPACK_LIB"; then
+		if test -n "$PLAPACK_INCLUDE"; then
+		
+			dnl defaults
+			HAVE_PLAPACK=yes
+			PLAPACKINCL="$PLAPACK_INCLUDE"
+			PLAPACKLIB="$PLAPACK_LIB"
+
+			AC_DEFINE([_HAVE_PLAPACK_],[1],[with Plapack in ISSM src])
+			AC_SUBST([PLAPACKINCL])
+			AC_SUBST([PLAPACKLIB])
+		else
+			HAVE_PLAPACK=no
+		fi
+	else
+		HAVE_PLAPACK=no
+	fi
+	AC_MSG_RESULT($HAVE_PLAPACK)
+	dnl }}}
+	dnl mumps{{{
+	AC_ARG_WITH([mumps-dir],
+	  AS_HELP_STRING([--with-mumps-dir=DIR],[mumps root directory]),
+	  [MUMPS_ROOT=$withval],[MUMPS_ROOT=""])
+			  
+	AC_MSG_CHECKING(for mumps headers and libraries in $MUMPS_ROOT)
+	if test -d "$MUMPS_ROOT"; then
+
+		dnl defaults
+		HAVE_MUMPS=yes
+		MUMPSINCL=-I"$MUMPS_ROOT/include"
+		if test "$PETSC_MAJOR" = "2" ; then
+		MUMPSLIB=-L"$MUMPS_ROOT/lib -ldmumps -lcmumps  -lpord "
+		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"
+		fi
+
+		AC_DEFINE([_HAVE_MUMPS_],[1],[with Mumps in ISSM src])
+		AC_SUBST([MUMPSINCL])
+		AC_SUBST([MUMPSLIB])
+	else
+		HAVE_MUMPS=no
+	fi
+	AM_CONDITIONAL([MUMPS], [test x$HAVE_MUMPS = xyes])
+	AC_MSG_RESULT($HAVE_MUMPS)
+	dnl }}}
+	dnl blacs{{{
+	AC_ARG_WITH([blacs-dir],
+		AS_HELP_STRING([--with-blacs-dir=DIR],[blacs root directory]),
+			  [BLACS_ROOT=$withval],[BLACS_ROOT=""])
+			  
+	AC_MSG_CHECKING(for blacs headers and libraries in $BLACS_ROOT)
+	if test -d "$BLACS_ROOT"; then
+
+		dnl defaults
+		HAVE_BLACS=yes
+		BLACSINCL=""
+		if test x$VENDOR = xintel-discover; then
+		 BLACSLIB=-L"$BLACS_ROOT/ -lmkl_blacs_intelmpi_lp64"
+		else
+		 BLACSLIB=-L"$BLACS_ROOT/ -lblacs"
+		fi
+        
+		AC_DEFINE([_HAVE_BLACS_],[1],[with Blacs in ISSM src])
+		AC_SUBST([BLACSINCL])
+		AC_SUBST([BLACSLIB])
+	else
+		HAVE_BLACS=no
+	fi
+	AC_MSG_RESULT($HAVE_BLACS)
+	dnl }}}
+	dnl hypre{{{
+	AC_ARG_WITH([hypre-dir],
+	  AS_HELP_STRING([--with-hypre-dir=DIR],[hypre root directory]),
+			  [HYPRE_ROOT=$withval],[HYPRE_ROOT=""])
+			  
+	AC_MSG_CHECKING(for hypre headers and libraries in $HYPRE_ROOT)
+	if test -d "$HYPRE_ROOT"; then
+
+		dnl defaults
+		HAVE_HYPRE=yes
+		HYPREINCL=""
+		HYPRELIB=-L"$HYPRE_ROOT/lib -lHYPRE"
+        
+		AC_DEFINE([_HAVE_HYPRE_],[1],[with Blacs in ISSM src])
+		AC_SUBST([HYPREINCL])
+		AC_SUBST([HYPRELIB])
+	else
+		HAVE_HYPRE=no
+	fi
+	AC_MSG_RESULT($HAVE_HYPRE)
+	dnl }}}
+	dnl prometheus{{{
+		AC_ARG_WITH([prometheus-dir],
+					AS_HELP_STRING([--with-prometheus-dir=DIR],[prometheus root directory]),
+					[PROMETHEUS_ROOT=$withval],[PROMETHEUS_ROOT=""])
+
+		  AC_MSG_CHECKING(for prometheus headers and libraries in $PROMETHEUS_ROOT)
+		  if test -d "$PROMETHEUS_ROOT"; then
+
+			dnl defaults
+			  HAVE_PROMETHEUS=yes
+			  PROMETHEUSINCL=-I"$PROMETHEUS_ROOT/include"
+			  PROMETHEUSLIB=-L"$PROMETHEUS_ROOT/lib -lpromfei -lprometheus -lparmetis"
+
+			  AC_DEFINE([_HAVE_PROMETHEUS_],[1],[with Prometheus in ISSM src])
+			  AC_SUBST([PROMETHEUSINCL])
+			  AC_SUBST([PROMETHEUSLIB])
+		  else
+				HAVE_PROMETHEUS=no
+			fi
+			AC_MSG_RESULT($HAVE_PROMETHEUS)
+		dnl }}}
+dnl spai{{{
+	AC_ARG_WITH([spai-dir],
+				AS_HELP_STRING([--with-spai-dir=DIR],[spai root directory]),
+				[SPAI_ROOT=$withval],[SPAI_ROOT=""])
+
+	  AC_MSG_CHECKING(for spai headers and libraries in $SPAI_ROOT)
+	  if test -d "$SPAI_ROOT"; then
+
+		dnl defaults
+		  HAVE_SPAI=yes
+		  SPAIINCL=-I"$SPAI_ROOT/include"
+		  SPAILIB=-L"$SPAI_ROOT/lib -lspai"
+
+		  AC_DEFINE([_HAVE_SPAI_],[1],[with Spai in ISSM src])
+		  AC_SUBST([SPAIINCL])
+		  AC_SUBST([SPAILIB])
+	  else
+		HAVE_SPAI=no
+		  fi
+		  AC_MSG_RESULT($HAVE_SPAI)
+		  dnl }}}
+dnl superlu{{{ 
+	AC_ARG_WITH([superlu-dir],
+				AS_HELP_STRING([--with-superlu-dir=DIR],[superlu root directory]),
+				[SUPERLU_ROOT=$withval],[SUPERLU_ROOT=""])
+
+	  AC_MSG_CHECKING(for superlu headers and libraries in $SUPERLU_ROOT)
+	  if test -d "$SUPERLU_ROOT"; then
+
+		dnl defaults
+		  HAVE_SUPERLU=yes
+		  SUPERLUINCL=-I"$SUPERLU_ROOT/include"
+		  SUPERLULIB=-L"$SUPERLU_ROOT/lib -lsuperlu_4.3"
+
+		  AC_DEFINE([_HAVE_SUPERLU_],[1],[with Superlu in ISSM src])
+		  AC_SUBST([SUPERLUINCL])
+		  AC_SUBST([SUPERLULIB])
+	  else
+		HAVE_SUPERLU=no
+		  fi
+		  AC_MSG_RESULT($HAVE_SUPERLU)
+		  dnl }}}
+dnl spooles{{{ 
+	AC_ARG_WITH([spooles-dir],
+				AS_HELP_STRING([--with-spooles-dir=DIR],[spooles root directory]),
+				[SPOOLES_ROOT=$withval],[SPOOLES_ROOT=""])
+
+	  AC_MSG_CHECKING(for spooles headers and libraries in $SPOOLES_ROOT)
+	  if test -d "$SPOOLES_ROOT"; then
+
+		dnl defaults
+		  HAVE_SPOOLES=yes
+		  SPOOLESINCL=-I"$SPOOLES_ROOT/include"
+		  SPOOLESLIB=-L"$SPOOLES_ROOT/lib -lspooles"
+
+		  AC_DEFINE([_HAVE_SPOOLES_],[1],[with Spooles in ISSM src])
+		  AC_SUBST([SPOOLESINCL])
+		  AC_SUBST([SPOOLESLIB])
+	  else
+		HAVE_SPOOLES=no
+		  fi
+		  AC_MSG_RESULT($HAVE_SPOOLES)
+		  dnl }}}
+dnl pastix{{{ 
+	AC_ARG_WITH([pastix-dir],
+				AS_HELP_STRING([--with-pastix-dir=DIR],[pastix root directory]),
+				[PASTIX_ROOT=$withval],[PASTIX_ROOT=""])
+
+	  AC_MSG_CHECKING(for pastix headers and libraries in $PASTIX_ROOT)
+	  if test -d "$PASTIX_ROOT"; then
+
+		dnl defaults
+		  HAVE_PASTIX=yes
+		  PASTIXINCL=-I"$PASTIX_ROOT/include"
+		  PASTIXLIB=-L"$PASTIX_ROOT/lib -lpastix_XXbit_mpi_smp_nobubble_int32_simple_real_scotch_i686_pc_linux -lptscotch -lptscotcherr -lpastix"
+
+		  AC_DEFINE([_HAVE_PASTIX_],[1],[with Pastix in ISSM src])
+		  AC_SUBST([PASTIXINCL])
+		  AC_SUBST([PASTIXLIB])
+	  else
+		HAVE_PASTIX=no
+		  fi
+		  AC_MSG_RESULT($HAVE_PASTIX)
+		  dnl }}}
+	dnl ml{{{
+	AC_ARG_WITH([ml-dir],
+	  AS_HELP_STRING([--with-ml-dir=DIR],[ml root directory]),
+			  [ML_ROOT=$withval],[ML_ROOT=""])
+			  
+	AC_MSG_CHECKING(for ml headers and libraries in $ML_ROOT)
+	if test -d "$ML_ROOT"; then
+
+		dnl defaults
+		HAVE_ML=yes
+		MLINCL=-I"$ML_ROOT/include"
+		MLLIB=-L"$ML_ROOT/lib -lml"
+        
+		AC_DEFINE([_HAVE_ML_],[1],[with Blacs in ISSM src])
+		AC_SUBST([MLINCL])
+		AC_SUBST([MLLIB])
+	else
+		HAVE_ML=no
+	fi
+	AC_MSG_RESULT($HAVE_ML)
+	dnl }}}
+	dnl umfpack{{{
+		AC_ARG_WITH([umfpack-dir],
+		  AS_HELP_STRING([--with-umfpack-dir=DIR],[UMFPACK root directory]),
+					[UMFPACK_ROOT=$withval],[UMFPACK_ROOT=""])
+
+		AC_MSG_CHECKING(for UMFPACK headers and libraries in $UMFPACK_ROOT)
+		if test -d "$UMFPACK_ROOT"; then
+
+			dnl defaults
+			HAVE_UMFPACK=yes
+			UMFPACKINCL=""
+			UMFPACKLIB=-L"$UMFPACK_ROOT/lib -lumfpack -lumfpack.5.5.1"
+
+			AC_DEFINE([_HAVE_UMFPACK_],[1],[with UMFPACK in ISSM src])
+			AC_SUBST([UMFPACKINCL])
+			AC_SUBST([UMFPACKLIB])
+		else
+			HAVE_UMFPACK=no
+		fi
+		AC_MSG_RESULT($HAVE_UMFPACK)
+	dnl }}}
+dnl math{{{
+	AC_MSG_CHECKING(for math library)
+	AC_ARG_WITH([math-lib],
+	  AS_HELP_STRING([--with-math-lib = otions],[math options, for ex: "/usr/lib/libm.a]),
+	  [MATH_LIB=$withval],[MATH_LIB=""])
+
+	dnl check that --with-math-lib may have been provided
+	if test -n "$MATH_LIB" ; then
+		HAVE_MATH=yes
+		MATHLIB="$MATH_LIB"
+
+		AC_DEFINE([_HAVE_MATH_],[1],[with MATH in ISSM src])
+		AC_SUBST([MATHLIB])
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+	dnl fortran{{{
+	AC_ARG_WITH([fortran],
+		AS_HELP_STRING([--with-fortran = YES], [do we compile fortran code (default is yes)]),
+		[FORTRAN=$withval],[FORTRAN=yes]) 
+	AC_MSG_CHECKING(for fortran compilation)
+	if test "x$FORTRAN" = "xyes"; then
+		dnl defaults
+		HAVE_FORTRAN=yes
+
+		AC_DEFINE([_HAVE_FORTRAN_],[1],[with fortran capability])
+	else
+		HAVE_FORTRAN=no
+	fi
+	AM_CONDITIONAL([FORTRAN], [test x$FORTRAN = xyes])
+	AC_MSG_RESULT($FORTRAN)
+
+	if test "x$FORTRAN" = "xyes"; then
+		dnl fortran library  option
+		AC_MSG_CHECKING(for fortran library)
+		AC_ARG_WITH([fortran-lib],
+		  AS_HELP_STRING([--with-fortran-lib = options],[fortran options, for ex: "/usr/lib/gfortran.a]),
+			[FORTRAN_LIB=$withval],[FORTRAN_LIB=""])
+
+		dnl check that --with-fortran-lib may have been provided
+		if test -n "$FORTRAN_LIB" ; then
+			dnl check that library provided EXISTS!
+		   FORTRAN_DIR=$(echo $FORTRAN_LIB | sed -e "s/-L//g" | awk '{print $[1]}')
+			if test -d "$FORTRAN_DIR" || test -f "$FORTRAN_DIR"; then
+				FORTRANLIB="$FORTRAN_LIB"
+				AC_DEFINE([_HAVE_FORTRAN_],[1],[with FORTRAN in ISSM src])
+				AC_SUBST([FORTRANLIB])
+			else
+			 if test "x$HAVE_MPI" = "xyes"; then
+				FORTRANLIB=$(mpif77 -print-file-name="libgfortran.a")
+				if test -f "$FORTRANLIB"; then
+					 AC_MSG_ERROR([fortran library provided ($FORTRAN_LIB) does not exist, MPI suggests the following library: $FORTRANLIB]);
+				fi
+			 fi
+				AC_MSG_ERROR([fortran library provided ($FORTRAN_LIB) does not exist!]);
+			fi
+		fi
+		AC_MSG_RESULT(done)
+	fi
+	dnl }}}
+	dnl graphics{{{
+	AC_MSG_CHECKING(for graphics library)
+	AC_ARG_WITH([graphics-lib],
+	  AS_HELP_STRING([--with-graphics-lib = options],[graphics options, for ex: "/usr/X11/lib/libX11.a]),
+	  [GRAPHICS_LIB=$withval],[GRAPHICS_LIB=""])
+
+	dnl check that --with-graphics-lib may have been provided
+	
+	if test -n "$GRAPHICS_LIB" ; then
+		dnl check that library provided EXISTS!
+		GRAPHICS_DIR=$(echo $GRAPHICS_LIB | sed -e "s/-L//g" | awk '{print $[1]}')
+		if test -d "$GRAPHICS_DIR" || test -f "$GRAPHICS_DIR"; then
+			HAVE_GRAPHICS=yes
+			GRAPHICSLIB="$GRAPHICS_LIB"
+			AC_DEFINE([_HAVE_GRAPHICS_],[1],[with GRAPHICS in ISSM src])
+			AC_SUBST([GRAPHICSLIB])
+		else
+			if test -f "$PETSC_ROOT/conf/petscvariables"; then
+				GRAPHICSLIB=$(cat $PETSC_ROOT/conf/petscvariables | grep X_LIB)
+				AC_MSG_ERROR([graphics library provided ($GRAPHICS_LIB) does not exist, PETSc suggests the following library: $GRAPHICSLIB]);
+			fi
+			AC_MSG_ERROR([graphics library provided ($GRAPHICS_LIB$) does not exist!]);
+		fi
+	fi
+	AC_MSG_RESULT(done)
+	dnl }}}
+
+	dnl Capabilities
+	dnl with-kml{{{
+	AC_ARG_WITH([kml],
+		AS_HELP_STRING([--with-kml = YES],[compile with kml capabilities (default is yes)]),
+		[KML=$withval],[KML=yes]) 
+	AC_MSG_CHECKING(for kml capability compilation)
+
+	if test "x$KML" = "xyes"; then
+		HAVE_KML=yes
+		AC_DEFINE([_HAVE_KML_],[1],[with kml capability])
+	else
+		HAVE_KML=no
+	fi
+	AM_CONDITIONAL([KML], [test x$HAVE_KML = xyes])
+	AC_MSG_RESULT($HAVE_KML)
+	dnl }}}
+	dnl with-kriging{{{
+	AC_ARG_WITH([kriging],
+		AS_HELP_STRING([--with-kriging = YES],[compile with kriging capabilities (default is yes)]),
+		[KRIGING=$withval],[KRIGING=yes]) 
+	AC_MSG_CHECKING(for kriging capability compilation)
+
+	if test "x$KRIGING" = "xyes"; then
+		HAVE_KRIGING=yes
+		AC_DEFINE([_HAVE_KRIGING_],[1],[with kriging capability])
+	else
+		HAVE_KRIGING=no
+	fi
+	AM_CONDITIONAL([KRIGING], [test x$HAVE_KRIGING = xyes])
+	AC_MSG_RESULT($HAVE_KRIGING)
+	dnl }}}
+	dnl with-steadystate{{{
+	AC_ARG_WITH([steadystate],
+		AS_HELP_STRING([--with-steadystate = YES],[compile with steadystate capabilities (default is yes)]),
+		[STEADYSTATE=$withval],[STEADYSTATE=yes]) 
+	AC_MSG_CHECKING(for steadystate capability compilation)
+
+	if test "x$STEADYSTATE" = "xyes"; then
+
+		dnl defaults
+		HAVE_STEADYSTATE=yes
+
+		AC_DEFINE([_HAVE_STEADYSTATE_],[1],[with steadystate capability])
+	else
+		HAVE_STEADYSTATE=no
+	fi
+	AM_CONDITIONAL([STEADYSTATE], [test x$HAVE_STEADYSTATE = xyes])
+	AC_MSG_RESULT($HAVE_STEADYSTATE)
+	dnl }}}
+	dnl with-transient{{{
+	AC_ARG_WITH([transient],
+		AS_HELP_STRING([--with-transient = YES], [compile with transient capabilities (default is yes)]),
+		[TRANSIENT=$withval],[TRANSIENT=yes]) 
+	AC_MSG_CHECKING(for transient capability compilation)
+
+	if test "x$TRANSIENT" = "xyes"; then
+
+		dnl defaults
+		HAVE_TRANSIENT=yes
+
+		AC_DEFINE([_HAVE_TRANSIENT_],[1],[with transient capability])
+	else
+		HAVE_TRANSIENT=no
+	fi
+	AM_CONDITIONAL([TRANSIENT], [test x$HAVE_TRANSIENT = xyes])
+	AC_MSG_RESULT($HAVE_TRANSIENT)
+	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)
+
+	if test "x$THERMAL" = "xyes"; then
+
+		dnl defaults
+		HAVE_THERMAL=yes
+
+		AC_DEFINE([_HAVE_THERMAL_],[1],[with thermal capability])
+	else
+		HAVE_THERMAL=no
+	fi
+	AM_CONDITIONAL([THERMAL], [test x$HAVE_THERMAL = xyes])
+	AC_MSG_RESULT($HAVE_THERMAL)
+	dnl }}}
+	dnl with-prognostic{{{
+	AC_ARG_WITH([prognostic],
+		AS_HELP_STRING([--with-prognostic = YES], [compile with prognostic capabilities (default is yes)]),
+		[PROGNOSTIC=$withval],[PROGNOSTIC=yes]) 
+	AC_MSG_CHECKING(for prognostic capability compilation)
+
+	if test "x$PROGNOSTIC" = "xyes"; then
+
+		dnl defaults
+		HAVE_PROGNOSTIC=yes
+
+		AC_DEFINE([_HAVE_PROGNOSTIC_],[1],[with prognostic capability])
+	else
+		HAVE_PROGNOSTIC=no
+	fi
+	AM_CONDITIONAL([PROGNOSTIC], [test x$HAVE_PROGNOSTIC = xyes])
+	AC_MSG_RESULT($HAVE_PROGNOSTIC)
+	dnl }}}
+	dnl with-control{{{
+	AC_ARG_WITH([control],
+		AS_HELP_STRING([--with-control = YES], [compile with control capabilities (default is yes)]),
+		[CONTROL=$withval],[CONTROL=yes]) 
+	AC_MSG_CHECKING(for control capability compilation)
+
+	if test "x$CONTROL" = "xyes"; then
+
+		dnl defaults
+		HAVE_CONTROL=yes
+
+		AC_DEFINE([_HAVE_CONTROL_],[1],[with control capability])
+	else
+		HAVE_CONTROL=no
+	fi
+	AM_CONDITIONAL([CONTROL], [test x$HAVE_CONTROL = xyes])
+	AC_MSG_RESULT($HAVE_CONTROL)
+	dnl }}}
+	dnl with-hydrology{{{
+	AC_ARG_WITH([hydrology],
+		AS_HELP_STRING([--with-hydrology = YES], [compile with hydrology capabilities (default is yes)]),
+		[HYDROLOGY=$withval],[HYDROLOGY=yes]) 
+	AC_MSG_CHECKING(for hydrology capability compilation)
+
+	if test "x$HYDROLOGY" = "xyes"; then
+
+		dnl defaults
+		HAVE_HYDROLOGY=yes
+
+		AC_DEFINE([_HAVE_HYDROLOGY_],[1],[with hydrology capability])
+	else
+		HAVE_HYDROLOGY=no
+	fi
+	AM_CONDITIONAL([HYDROLOGY], [test x$HAVE_HYDROLOGY = xyes])
+	AC_MSG_RESULT($HAVE_HYDROLOGY)
+	dnl }}}
+	dnl with-diagnostic{{{
+	AC_ARG_WITH([diagnostic],
+		AS_HELP_STRING([--with-diagnostic = YES], [compile with diagnostic capabilities (default is yes)]),
+		[DIAGNOSTIC=$withval],[DIAGNOSTIC=yes]) 
+	AC_MSG_CHECKING(for diagnostic capability compilation)
+
+	if test "x$DIAGNOSTIC" = "xyes"; then
+
+		dnl defaults
+		HAVE_DIAGNOSTIC=yes
+
+		AC_DEFINE([_HAVE_DIAGNOSTIC_],[1],[with diagnostic capability])
+	else
+		HAVE_DIAGNOSTIC=no
+	fi
+	AM_CONDITIONAL([DIAGNOSTIC], [test x$HAVE_DIAGNOSTIC = xyes])
+	AC_MSG_RESULT($HAVE_DIAGNOSTIC)
+	dnl }}}
+	dnl with-balanced{{{
+	AC_ARG_WITH([balanced],
+		AS_HELP_STRING([--with-balanced = YES], [compile with balanced capabilities (default is yes)]),
+		[BALANCED=$withval],[BALANCED=yes]) 
+	AC_MSG_CHECKING(for balanced capability compilation)
+
+	if test "x$BALANCED" = "xyes"; then
+
+		dnl defaults
+		HAVE_BALANCED=yes
+
+		AC_DEFINE([_HAVE_BALANCED_],[1],[with balanced capability])
+	else
+		HAVE_BALANCED=no
+	fi
+	AM_CONDITIONAL([BALANCED], [test x$HAVE_BALANCED = xyes])
+	AC_MSG_RESULT($HAVE_BALANCED)
+	dnl }}}
+	dnl with-responses{{{
+	AC_ARG_WITH([responses],
+		AS_HELP_STRING([--with-responses = YES], [compile with responses capabilities (default is yes)]),
+		[RESPONSES=$withval],[RESPONSES=yes]) 
+	AC_MSG_CHECKING(for responses capability compilation)
+
+	if test "x$RESPONSES" = "xyes"; then
+
+		dnl defaults
+		HAVE_RESPONSES=yes
+
+		AC_DEFINE([_HAVE_RESPONSES_],[1],[with responses capability])
+	else
+		HAVE_RESPONSES=no
+	fi
+	AM_CONDITIONAL([RESPONSES], [test x$HAVE_RESPONSES = xyes])
+	AC_MSG_RESULT($HAVE_RESPONSES)
+	dnl }}}
+	dnl with-slope{{{
+	AC_ARG_WITH([slope],
+		AS_HELP_STRING([--with-slope = YES], [compile with slope capabilities (default is yes)]),
+		[SLOPE=$withval],[SLOPE=yes]) 
+	AC_MSG_CHECKING(for slope capability compilation)
+
+	if test "x$SLOPE" = "xyes"; then
+
+		dnl defaults
+		HAVE_SLOPE=yes
+
+		AC_DEFINE([_HAVE_SLOPE_],[1],[with slope capability])
+	else
+		HAVE_SLOPE=no
+	fi
+	AM_CONDITIONAL([SLOPE], [test x$HAVE_SLOPE = xyes])
+	AC_MSG_RESULT($HAVE_SLOPE)
+	dnl }}}
+	dnl with-groundingline{{{
+	AC_ARG_WITH([groundingline],
+		AS_HELP_STRING([--with-groundingline = YES], [compile with groundingline capabilities (default is yes)]),
+		[GROUNDINGLINE=$withval],[GROUNDINGLINE=yes]) 
+	AC_MSG_CHECKING(for groundingline capability compilation)
+
+	if test "x$GROUNDINGLINE" = "xyes"; then
+
+		dnl defaults
+		HAVE_GROUNDINGLINE=yes
+
+		AC_DEFINE([_HAVE_GROUNDINGLINE_],[1],[with groundingline capability])
+	else
+		HAVE_GROUNDINGLINE=no
+	fi
+	AM_CONDITIONAL([GROUNDINGLINE], [test x$HAVE_GROUNDINGLINE = xyes])
+	AC_MSG_RESULT($HAVE_GROUNDINGLINE)
+	dnl }}}
+	dnl with-rifts{{{
+	AC_ARG_WITH([rifts],
+		AS_HELP_STRING([--with-rifts = YES], [compile with rifts capabilities (default is yes)]),
+		[RIFTS=$withval],[RIFTS=yes]) 
+	AC_MSG_CHECKING(for rifts capability compilation)
+
+	if test "x$RIFTS" = "xyes"; then
+
+		dnl defaults
+		HAVE_RIFTS=yes
+
+		AC_DEFINE([_HAVE_RIFTS_],[1],[with rifts capability])
+	else
+		HAVE_RIFTS=no
+	fi
+	AM_CONDITIONAL([RIFTS], [test x$HAVE_RIFTS = xyes])
+	AC_MSG_RESULT($HAVE_RIFTS)
+	dnl }}}
+	dnl math77{{{
+	AC_ARG_WITH([math77-dir],
+		AS_HELP_STRING([--with-math77-dir=DIR], [math77 root directory.]),
+		[MATH77_ROOT=$withval],[MATH77_ROOT=""]) 
+	AC_MSG_CHECKING(for math77)
+
+	if test -d "$MATH77_ROOT"; then
+
+	  HAVE_MATH77=yes
+	  MATH77LIB="-L$MATH77_ROOT/ -lmath77"
+
+	  AC_DEFINE([_HAVE_MATH77_],[1],[with math77 in ISSM src])
+	  AC_SUBST([MATH77LIB])
+	else
+		HAVE_MATH77=no
+	fi
+	AC_MSG_RESULT($HAVE_MATH77)
+	dnl }}}
+	dnl with-gia{{{
+	AC_ARG_WITH([gia],
+		AS_HELP_STRING([--with-gia = YES], [compile with gia capabilities (default is yes)]),
+		[GIA=$withval],[GIA=no]) 
+	AC_MSG_CHECKING(for gia capability compilation)
+
+	if test "x$GIA" = "xyes"; then
+	  
+	  if test "x$HAVE_MATH77" = "xno"; then
+		  HAVE_GIA=no
+		  AC_MSG_ERROR([gia requires compilation of math77 library! Reconfigure with --with-math77 option on]);
+	  else
+		dnl defaults
+		HAVE_GIA=yes
+		AC_DEFINE([_HAVE_GIA_],[1],[with gia capability])
+	  fi
+
+	else
+		HAVE_GIA=no
+	fi
+	AM_CONDITIONAL([GIA], [test x$HAVE_GIA = xyes])
+	AC_MSG_RESULT($HAVE_GIA)
+	dnl }}}
+	dnl with-ios{{{
+	AC_ARG_WITH([ios],
+		AS_HELP_STRING([--with-ios = YES], [compile with iOS capabilities (default is no, alternatives are yes)]),
+		[IOS=$withval],[IOS=no]) 
+	AC_MSG_CHECKING(for iOS compilation)
+
+	if test "x$IOS" = "xyes"; then
+		dnl defaults
+		HAVE_IOS=yes
+
+		AC_DEFINE([_HAVE_IOS_],[1],[with android capability])
+	elif test "x$IOS" = "xno"; then
+		HAVE_IOS=no
+	else
+	  AC_MSG_ERROR([--with-ios should be either no or yes])
+	fi
+	AM_CONDITIONAL([IOS], [test x$HAVE_IOS != xno])
+	AC_MSG_RESULT($HAVE_IOS)
+	dnl }}}
+	dnl with-android{{{
+	AC_ARG_WITH([android],
+		AS_HELP_STRING([--with-android = EXE], [compile with android capabilities (default is no, alternatives are exe and jni)]),
+		[ANDROID=$withval],[ANDROID=no]) 
+	AC_MSG_CHECKING(for android capability compilation)
+
+	if test "x$ANDROID" = "xjni"; then
+
+		dnl defaults
+		HAVE_ANDROID=jni
+		AC_DEFINE([_HAVE_ANDROID_],[1],[with android capability])
+		AC_DEFINE([_HAVE_ANDROID_JNI_],[1],[with android jni])
+	elif test "x$ANDROID" = "xexe"; then
+		dnl defaults
+		HAVE_ANDROID=exe
+
+		AC_DEFINE([_HAVE_ANDROID_],[1],[with android capability])
+	elif test "x$ANDROID" = "xno"; then
+		HAVE_ANDROID=no
+	else
+	  AC_MSG_ERROR([--with-android should be either no, exe or jni])
+	fi
+	AM_CONDITIONAL([ANDROID], [test x$HAVE_ANDROID != xno])
+	AM_CONDITIONAL([ANDROIDJNI], [test x$HAVE_ANDROID = xjni])
+	AM_CONDITIONAL([ANDROIDEXE], [test x$HAVE_ANDROID = xexe])
+	AC_MSG_RESULT($HAVE_ANDROID)
+	dnl }}}
+	dnl with-android-ndk{{{
+	AC_ARG_WITH([android-ndk],
+	  AS_HELP_STRING([--with-android-ndk=DIR], [android-ndk root directory.]),
+	  [ANDROID_NDK_ROOT=$withval],[ANDROID_NDK_ROOT=""]) 
+	AC_MSG_CHECKING(with android ndk)
+	
+	if test -d "$ANDROID_NDK_ROOT"; then
+		dnl defaults
+		HAVE_ANDROID_NDK=yes
+		ANDROID_NDKINCL="-I$ANDROID_NDK_ROOT/arm-linux-android-install/sysroot/usr/include"
+
+		AC_DEFINE([_HAVE_ANDROID_NDK_],[1],[with android ndk in ISSM src])
+		AC_SUBST([ANDROID_NDKINCL])
+	else
+		HAVE_ANDROID_NDK=no
+	fi
+	AC_MSG_RESULT($HAVE_ANDROID_NDK)
+	dnl }}}
+	dnl with-3d{{{
+	AC_ARG_WITH([3d],
+		AS_HELP_STRING([--with-3d = YES], [compile with 3d capabilities (default is yes)]),
+		[THREED=$withval],[THREED=yes]) 
+	AC_MSG_CHECKING(for 3d capability compilation)
+
+	if test "x$THREED" = "xyes"; then
+
+		dnl defaults
+		HAVE_3D=yes
+
+		AC_DEFINE([_HAVE_3D_],[1],[with 3d capability])
+	else
+		HAVE_3D=no
+	fi
+	AM_CONDITIONAL([THREED], [test x$HAVE_3D = xyes])
+	AC_MSG_RESULT($HAVE_3D)
+	dnl }}}
+	dnl checks{{{
+	AC_MSG_CHECKING(consistency between all libraries)
+	
+	dnl check that if petsc is requested , mpi should be specified
+	if test "$HAVE_PETSC" = "yes" ; then
+		if test "$HAVE_MPI" = "NO";  then
+			AC_MSG_ERROR([petsc requires mpi!]);
+		fi
+	fi
+
+	dnl check that we have either python or matlab support if we compile the modules
+	if test "$MODULES_VALUE" = "yes"  && test "$HAVE_MATLAB" = "no" && test "$HAVE_PYTHON" = "no"; then
+		AC_MSG_ERROR([need at least python or matlab support to compile modules (or use --with-modules=no)]);
+	fi
+
+	dnl check that if we have MPI, we have metis
+	if test "$HAVE_METIS" = "yes"  && test "$HAVE_MPI" = "no" ; then
+	AC_MSG_ERROR([need mpi if using the metis partitioner!]);
+	fi
+
+	AC_MSG_RESULT(done)
+	dnl }}}
+
+	dnl other options
+	dnl optimization{{{
+	dnl bypass standard optimization -g -O2 ? 
+	AC_ARG_WITH([cxxoptflags],
+	  AS_HELP_STRING([--with-cxxoptflags = CXXOPTFLAGS], [optimization using CXX flags, ex: --with-cxxoptflags=-march=opteron -O3]),
+	  [CXXOPTFLAGS=$withval],[CXXOPTFLAGS="-g -O2"]) 
+	AC_MSG_CHECKING(for c++ optimization flags)
+	AC_SUBST([CXXOPTFLAGS])
+	AC_MSG_RESULT(done)
+
+	dnl }}}
+	dnl multithreading{{{
+	AC_ARG_WITH([numthreads],
+	  AS_HELP_STRING([--with-numthreads = NUMTHREADS_VALUE],[numthreads, default is 1. ]),
+	  [NUMTHREADS_VALUE=$withval],[NUMTHREADS_VALUE=1])
+	AC_MSG_CHECKING(for number of threads)
+	dnl defaults
+	MULTITHREADING=no
+	MULTITHREADINLIB=""
+	if test "$NUMTHREADS_VALUE" != "1"; then
+		
+		MULTITHREADINGLIB="-lpthread -lrt"
+		case "${host_os}" in
+		*cygwin*)
+		MULTITHREADINGLIB="-lpthread -lrt"
+		;;
+		*linux*)
+		MULTITHREADINGLIB="-lpthread -lrt"
+		;;
+		*darwin*)
+		MULTITHREADINGLIB="-lpthread"
+		;;
+		esac
+
+		AC_DEFINE([_MULTITHREADING_],[1],[with numthreads enabled])
+		AC_DEFINE_UNQUOTED([_NUMTHREADS_],[$NUMTHREADS_VALUE],[number of threads])
+	fi
+	AC_SUBST([MULTITHREADINGLIB])
+	AC_MSG_RESULT($NUMTHREADS_VALUE) 
+	dnl }}}
+	dnl 64bit {{{
+	AC_ARG_WITH([64bit-indices],
+	  AS_HELP_STRING([--with-64bit-indices = bool], [use 64 bit integers, default 0, ex: --with-64bit-indices=1]),
+	  [USE_64BIT_INDICES=$withval],[USE_64BIT_INDICES=0]) 
+	AC_MSG_CHECKING(for 64 bit indices)
+
+	if test "$USE_64BIT_INDICES" == "1"; then
+	AC_DEFINE([ISSM_USE_64BIT_INDICES],[1],[with 64 bits indices])
+	else
+	AC_DEFINE([ISSM_USE_64BIT_INDICES],[0],[with 64 bits indices])
+	fi
+	AC_MSG_RESULT($USE_64BIT_INDICES)
+	dnl }}}
+])
Index: /issm/trunk/packagers/ubuntu/issmpkg/templates/sampleControl
===================================================================
--- /issm/trunk/packagers/ubuntu/issmpkg/templates/sampleControl	(revision 16137)
+++ /issm/trunk/packagers/ubuntu/issmpkg/templates/sampleControl	(revision 16137)
@@ -0,0 +1,6 @@
+Package: issm-python
+Version: 1.1.3
+Architecture: amd64
+Depends: mpich2, petsc3.2-issm, metis4.0-issm, triangle-bin, libtriangle-dev, python2.7-dev, python-scipy, python-netcdf4, netcdf-bin, python-nose, libnetcdfc++4, hdf5-tools
+Maintainer: issm/jpl (issm@jpl.nasa.gov)
+Description: Ice Sheet System Model, ubuntu/debian package
Index: /issm/trunk/packagers/ubuntu/issmpkg/triangle.h.patch
===================================================================
--- /issm/trunk/packagers/ubuntu/issmpkg/triangle.h.patch	(revision 16137)
+++ /issm/trunk/packagers/ubuntu/issmpkg/triangle.h.patch	(revision 16137)
@@ -0,0 +1,12 @@
+250a251,257
+> /*Patch for ISSM*/
+> #ifndef REAL
+> typedef double REAL;
+> typedef void VOID;
+> #endif
+> /*End patch*/
+> 
+283c290
+< void triangulate(char *, struct triangulateio *, struct triangulateio *,
+---
+> extern "C" void triangulate(char *, struct triangulateio *, struct triangulateio *,
Index: sm/trunk/scripts/dailyrun.sh
===================================================================
--- /issm/trunk/scripts/dailyrun.sh	(revision 16136)
+++ 	(revision )
@@ -1,164 +1,0 @@
-#!/bin/bash
-#This bash script calls the dailyrun.m matlab file to run our daily test decks. 
-#It then processes the results and sends an email to the Ice developpers.
-
-#Hard coded options
-NUMCPUS_RUN=7
-NROPTIONS=""
-
-#some functions
-function timer() #{{{1
-{
-	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() #{{{1
-{
-	suffix=`date | awk '{printf("%s-%s-%s  %s",$2,$3,$6,$4);}'`			 
-	echo $suffix;			 
-} #}}}
-function host_name() #{{{1
-{
-	#return host name depending on the OS
-	if [ "$1" = "winxp32" ] 
-	then
-		HOST_NAME=`hostname`;
-	else
-		HOST_NAME=`hostname -s`;
-	fi
-	echo $HOST_NAME;
-} #}}}
-
-#Get configuration
-#Initialize variables {{{1
-TODAY=$(todaydate);
-HOST_NAME=$(host_name $OS);
-START_TIME=$(timer);
-ISSM_RELEASE="N/A"
-USER=$(whoami);
-INIT_PATH=$(pwd);
-#}}}
-
-#Prepare run
-#Windows hack for startup.m {{{1
-#windows environments: ISSM_DIR_WIN variable not correctly picked up when using 
-#the cron job. just get startup to take the ISSM_DIR variable as the pwd:
-if [ "$OS" = "winxp32" ]
-then
-	cat startup.m | sed 's/clear status/clear status; ISSM_DIR=pwd;/g' > startup.m.bak
-	mv startup.m.bak startup.m
-fi
-#}}}
-#create softlink to startup {{{1
-cd $ISSM_DIR/test/NightlyRun/
-ln -s $ISSM_DIR/startup.m .
-#}}}
-#Create dailylog directory and info.log {{{1
-#put installation elapsed time in info.log
-INSTALL_TIME=$(timer)
-ELAPSED_INSTALL=$(timer $START_TIME)
-rm -rf $ISSM_DIR/dailylog
-mkdir  $ISSM_DIR/dailylog
-cat << END > $ISSM_DIR/dailylog/info.log
-today:     $(echo $TODAY)
-user:      $(echo $USER)
-host:      $(echo $HOST_NAME)
-OS:        N/A
-release:   N/A
-init_path: $(echo $INIT_PATH)
-elapsed_install: $(echo $ELAPSED_INSTALL)
-END
-#}}}
-#check NUMCPUS_RUN options {{{1
-if [ "$NUMCPUS_RUN" = "" ]
-then
-	echo "NUMCPUS_RUN option not found, defaulting to NUMCPUS_RUN = 1"
-	NUMCPUS_RUN=1
-fi
-#}}}
-
-#Run tests
-#Launch all tests on different cpus {{{1
-for (( i=1;i<=$NUMCPUS_RUN;i++ ))
-do
-	#Launch matlab and the daily run script
-	cat > $ISSM_DIR/dailylog/matlab_run$i.m << EOF
-	warning off %necessary to avoid a info.log of several Go for parallel runs
-	try,
-	cd $ISSM_DIR/test/NightlyRun
-	startup;
-	$(if [ "$NROPTIONS" = ""  ]
-	then
-		echo "runme('output','daily','rank',$i,'numprocs',$NUMCPUS_RUN);"
-	else
-		echo "runme($NROPTIONS,'output','daily','rank',$i,'numprocs',$NUMCPUS_RUN);"
-	fi
-	)
-	catch me,
-		%An error occured, get report and exit
-		directory=strsplit(pwd,'/');
-		message=getReport(me)
-		fid=fopen([ISSM_DIR '/dailylog/matlaberror.log'], 'at');
-		fprintf(fid,'\nMatlab error occured in: %s\n\n',directory{end});
-		fprintf(fid,'%s',message);
-		fclose(fid);
-	end
-	disp('MATLABEXITEDCORRECTLY');
-	exit
-EOF
-
-	#Start run from dailylog directory
-	cd $ISSM_DIR/dailylog/
-
-	#Start test
-	MATLAB_VERSION="7.6" #7.2,7.4,7.6 and 7.8
-	/usr/local/pkgs/matlab-$MATLAB_VERSION/bin/matlab  -nojvm -nosplash  -r matlab_run$i -logfile matlab_log$i.log &
-done
-
-#wait until matlab closes
-wait
-#}}}
-#concatenate all reports {{{1
-cd $ISSM_DIR/dailylog/
-mv matlab_log1.log  matlab_log.log
-for (( i=2;i<=$NUMCPUS_RUN;i++ ))
-do
-	cat matlab_log.log matlab_log$i.log > matlab_log.log.bak
-	mv matlab_log.log.bak matlab_log.log
-done
-#}}}
-#Complete info.log {{{1
-if [ $(cat matlab_log.log | grep "MATLABEXITEDCORRECTLY" | wc -l) -eq $NUMCPUS_RUN ]
-then
-	MATLABCRASH=0
-else
-	MATLABCRASH=1
-fi
-ELAPSED_RUN=$(timer $INSTALL_TIME)
-ELAPSED_TOTAL=$(timer $START_TIME)
-cat << END >>  $ISSM_DIR/dailylog/info.log
-elapsed_run:   $(echo $ELAPSED_RUN)
-elapsed_total: $(echo $ELAPSED_TOTAL)
-matlab_crash:  $(echo $MATLABCRASH)
-END
-#}}}
-
-#Send Report
-#Build html report {{{1
-cd $ISSM_DIR/dailylog/
-sh ../scripts/report.sh
-ln -s $ISSM_DIR/dailylog/report.html $INIT_PATH
-echo "html report located in $ISSM_DIR/dailylog/report.html and $INIT_PATH/report.html"
-#}}}
Index: sm/trunk/scripts/errlog_process.sh
===================================================================
--- /issm/trunk/scripts/errlog_process.sh	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-#!/bin/bash
-
-#first get rank we want to keep.
-rank=`cat $1 | awk 'NR==1' | sed 's/==/ /'g | awk '{printf("%s\n",$1);}'`
-
-#now only keep lines with this rank
-cat $1 | grep "==$rank==" > $1.bak
-mv $1.bak $1
Index: /issm/trunk/scripts/historyISSM.m
===================================================================
--- /issm/trunk/scripts/historyISSM.m	(revision 16136)
+++ /issm/trunk/scripts/historyISSM.m	(revision 16137)
@@ -2,9 +2,6 @@
 runme('id',[101]);
 md.mesh.numberofelements
-md=mesh(md,'DomainOutline.exp',5000);
-md=setflowequation(md,'macayeal','all');
 md=solve(md,TransientSolutionEnum);
-md=solve(md,DiagnosticSolutionEnum);
-md=loadresultsfromcluster(md);
-plotmodel(md,'data',md.results.DiagnosticSolution.Vel)
+md=solve(md,StressbalanceSolutionEnum);
+plotmodel(md,'data',md.results.StressbalanceSolution.Vel)
 plotmodel(md,'data',)
Index: sm/trunk/scripts/issm_webpdf.sh
===================================================================
--- /issm/trunk/scripts/issm_webpdf.sh	(revision 16136)
+++ 	(revision )
@@ -1,27 +1,0 @@
-#!/bin/bash
-
-# issm_webpdf.sh
-# convert http://issm/ to issm_web.pdf
-
-# Created by gqwang Thu May 12 13:40:08 PDT 2011
-
-PATH=/usr/bin:/bin:/usr/sbin:/sbin
-
-# 1. Download html
-cd /proj/ice/gqwang/
-rm -rf issm.jpl.nasa.gov || exit 1
-wget -r http://issm.jpl.nasa.gov/
-
-# 2. Convert to pdf
-cd issm.jpl.nasa.gov
-a=`find . -name "*.html"`
-for html in $a; do
-   pdf=`echo $html | sed -e '1,1s/\.html/\.pdf/'`
-   echo /usr/bin/wkhtmltopdf $html $pdf
-done
-
-# 3. Merge into one pdf
-
-mkdir pdf
-find . -name "*.pdf" -exec mv {} pdf \;
-gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=issm_web.pdf pdf/*.pdf
Index: /issm/trunk/scripts/report.sh
===================================================================
--- /issm/trunk/scripts/report.sh	(revision 16136)
+++ /issm/trunk/scripts/report.sh	(revision 16137)
@@ -29,4 +29,5 @@
 TODAY=$(       cat info.log | grep "today"           | awk '{printf("%s %s",$2,$3);}')
 USER=$(        cat info.log | grep "user"            | awk '{print $2}')
+VERSION=$(     cat info.log | grep "version"         | awk '{print $2}')
 HOST_NAME=$(   cat info.log | grep "host"            | awk '{print $2}')
 OS=$(          cat info.log | grep "OS"              | awk '{print $2}')
@@ -42,5 +43,5 @@
 
 #Did installation work?
-if [ $(ls -1 $ISSM_DIR/bin | wc -l) -le 20 ]; then
+if [ $(ls -1 $ISSM_DIR/bin | wc -l) -le 1 ]; then
 	IS_INSTALL=0
 else
@@ -68,4 +69,8 @@
 <td $TABLE_FONT>total elapsed time: $EL_TOTAL</td>
 <td $TABLE_FONT>installation elapsed time: $EL_INSTALL</td>
+</tr>
+<tr>
+<td $TABLE_FONT>svn version: $VERSION</td>
+<td $TABLE_FONT></td>
 </tr>
 </table>
Index: /issm/trunk/scripts/tai
===================================================================
--- /issm/trunk/scripts/tai	(revision 16136)
+++ /issm/trunk/scripts/tai	(revision 16137)
@@ -1,5 +1,9 @@
 #!/bin/bash
+if [ -z $EXECUTION_DIR ];
+then
+	EXECUTION_DIR=$ISSM_DIR/execution
+fi
 
-cd $EXECUTION_DIR
-DIR=$(ls -lrtd *"/" | awk '{line= $0} END {print line}' | awk '{printf("%s\n",$9);}')
+DIR=$(ls -rtd1 $EXECUTION_DIR/* | tail -n1)
+echo "Execution idrectory: $DIR"
 tail -f $DIR/*.outlog
Index: /issm/trunk/scripts/vie
===================================================================
--- /issm/trunk/scripts/vie	(revision 16136)
+++ /issm/trunk/scripts/vie	(revision 16137)
@@ -1,10 +1,9 @@
 #!/bin/bash
 
-if [ ! -z $EXECUTION_DIR ];
+if [ -z "$EXECUTION_DIR" ];
 then
 	EXECUTION_DIR=$ISSM_DIR/execution
 fi
 
-cd $EXECUTION_DIR
-DIR=$(ls -lrtd *"/" | awk '{line= $0} END {print line}' | awk '{printf("%s\n",$9);}')
+DIR=$(ls -rtd1 $EXECUTION_DIR/* | tail -n1)
 vim $DIR/*.errlog
Index: /issm/trunk/scripts/vil
===================================================================
--- /issm/trunk/scripts/vil	(revision 16136)
+++ /issm/trunk/scripts/vil	(revision 16137)
@@ -1,10 +1,8 @@
 #!/bin/bash
-
-if [ ! -z $EXECUTION_DIR ];
+if [ -z $EXECUTION_DIR ];
 then
 	EXECUTION_DIR=$ISSM_DIR/execution
 fi
 
-cd $EXECUTION_DIR
-DIR=$(ls -lrtd *"/" | awk '{line= $0} END {print line}' | awk '{printf("%s\n",$9);}')
+DIR=$(ls -rtd1 $EXECUTION_DIR/* | tail -n1)
 vim $DIR/*.outlog
Index: /issm/trunk/src/ad/validation/Update/SquareShelfConstrained.par
===================================================================
--- /issm/trunk/src/ad/validation/Update/SquareShelfConstrained.par	(revision 16136)
+++ /issm/trunk/src/ad/validation/Update/SquareShelfConstrained.par	(revision 16137)
@@ -35,13 +35,13 @@
 
 %Numerical parameters
-md.diagnostic.viscosity_overshoot=0.0;
+md.stressbalance.viscosity_overshoot=0.0;
 md.prognostic.stabilization=1;
 md.thermal.stabilization=1;
 md.verbose=verbose(0);
 md.settings.waitonlock=30;
-md.diagnostic.restol=0.05;
-md.diagnostic.reltol=0.05;
+md.stressbalance.restol=0.05;
+md.stressbalance.reltol=0.05;
 md.steadystate.reltol=0.05;
-md.diagnostic.abstol=NaN;
+md.stressbalance.abstol=NaN;
 md.timestepping.time_step=1;
 md.timestepping.final_time=3;
Index: /issm/trunk/src/ad/validation/Update/update.m
===================================================================
--- /issm/trunk/src/ad/validation/Update/update.m	(revision 16136)
+++ /issm/trunk/src/ad/validation/Update/update.m	(revision 16137)
@@ -4,5 +4,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.cluster.executionpath=[issmtier() '/src/ad/validation/Validation/'];
@@ -12,6 +12,6 @@
 md.verbose=verbose('solution',true);
 
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,MasstransportSolutionEnum);
 
-thickness=md.results.PrognosticSolution.Thickness;
+thickness=md.results.MasstransportSolution.Thickness;
 save ../Validation/Archive.mat thickness;
Index: /issm/trunk/src/ad/validation/Validation/validation.m
===================================================================
--- /issm/trunk/src/ad/validation/Validation/validation.m	(revision 16136)
+++ /issm/trunk/src/ad/validation/Validation/validation.m	(revision 16137)
@@ -22,5 +22,5 @@
 
 	s=load('Archive.mat'); h0=s.thickness;
-	h=md.results.PrognosticSolution.Thickness;
+	h=md.results.MasstransportSolution.Thickness;
 	error_diff=full(max(abs(h-h0))/(max(abs(h0))+eps));
 	if (error_diff>tolerance);
Index: /issm/trunk/src/c/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/CMakeLists.txt	(revision 16136)
+++ /issm/trunk/src/c/CMakeLists.txt	(revision 16137)
@@ -1,15 +1,744 @@
-# Subdirectories {{{
-add_subdirectory(classes)
-add_subdirectory(Container)
-add_subdirectory(EnumDefinitions)
-add_subdirectory(include)
-add_subdirectory(io)
-add_subdirectory(modules)
-add_subdirectory(shared)
-add_subdirectory(solutions)
-add_subdirectory(solvers)
-add_subdirectory(toolkits)
+# config.h {{{
+set(CPP_FLAGS -DHAVE_CONFIG_H)
 # }}}
 # Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c)
-# }}}
+include_directories(AFTER $ENV{ISSM_DIR}/ 
+                          $ENV{ISSM_DIR}/src/c 
+                          $ENV{ISSM_DIR}/src/c/main 
+                          $ENV{ISSM_DIR}/src/c/datastructure 
+                          $ENV{ISSM_DIR}/src/c/classes 
+                          $ENV{ISSM_DIR}/src/c/classes/Options 
+                          $ENV{ISSM_DIR}/src/c/classes/ElementResults 
+                          $ENV{ISSM_DIR}/src/c/classes/ExternalResults 
+                          $ENV{ISSM_DIR}/src/c/classes/Elements 
+                          $ENV{ISSM_DIR}/src/c/classes/Inputs 
+                          $ENV{ISSM_DIR}/src/c/classes/Materials 
+                          $ENV{ISSM_DIR}/src/c/classes/Constraints 
+                          $ENV{ISSM_DIR}/src/c/classes/Loads 
+                          $ENV{ISSM_DIR}/src/c/classes/matrix 
+                          $ENV{ISSM_DIR}/src/c/classes/Params 
+                          $ENV{ISSM_DIR}/src/c/classes/Params 
+                          $ENV{ISSM_DIR}/src/c/shared 
+                          $ENV{ISSM_DIR}/src/c/shared/MemOps 
+                          $ENV{ISSM_DIR}/src/c/shared/Matrix 
+                          $ENV{ISSM_DIR}/src/c/shared/io 
+                          $ENV{ISSM_DIR}/src/c/shared/io/Disk 
+                          $ENV{ISSM_DIR}/src/c/shared/io/Print 
+                          $ENV{ISSM_DIR}/src/c/shared/io/Comm 
+                          $ENV{ISSM_DIR}/src/c/shared/LatLong 
+                          $ENV{ISSM_DIR}/src/c/shared/Enum 
+                          $ENV{ISSM_DIR}/src/c/shared/Numerics 
+                          $ENV{ISSM_DIR}/src/c/shared/Exceptions 
+                          $ENV{ISSM_DIR}/src/c/shared/Sorting 
+                          $ENV{ISSM_DIR}/src/c/shared/Elements 
+                          $ENV{ISSM_DIR}/src/c/shared/String 
+                          $ENV{ISSM_DIR}/src/c/toolkits 
+                          $ENV{ISSM_DIR}/src/c/toolkits/metis 
+                          $ENV{ISSM_DIR}/src/c/toolkits/issm 
+                          $ENV{ISSM_DIR}/src/c/toolkits/adolc 
+                          $ENV{ISSM_DIR}/src/c/toolkits/triangle 
+                          $ENV{ISSM_DIR}/src/c/toolkits/objects 
+                          $ENV{ISSM_DIR}/src/c/modules 
+                          $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx 
+                          $ENV{ISSM_DIR}/src/c/modules/ParseToolkitsOptionsx 
+                          $ENV{ISSM_DIR}/src/c/modules/NodesDofx 
+                          $ENV{ISSM_DIR}/src/c/modules/NodalValuex 
+                          $ENV{ISSM_DIR}/src/c/modules/VerticesDofx 
+                          $ENV{ISSM_DIR}/src/c/modules/VertexCoordinatesx 
+                          $ENV{ISSM_DIR}/src/c/modules/OutputResultsx 
+                          $ENV{ISSM_DIR}/src/c/modules/InputDuplicatex 
+                          $ENV{ISSM_DIR}/src/c/modules/InputScalex 
+                          $ENV{ISSM_DIR}/src/c/modules/SurfaceAreax 
+                          $ENV{ISSM_DIR}/src/c/modules/CreateNodalConstraintsx 
+                          $ENV{ISSM_DIR}/src/c/modules/UpdateDynamicConstraintsx 
+                          $ENV{ISSM_DIR}/src/c/modules/IoModelToConstraintsx 
+                          $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromConstantx 
+                          $ENV{ISSM_DIR}/src/c/modules/GetSolutionFromInputsx 
+                          $ENV{ISSM_DIR}/src/c/modules/GetVectorFromInputsx 
+                          $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromVectorx 
+                          $ENV{ISSM_DIR}/src/c/modules/InputArtificialNoisex 
+                          $ENV{ISSM_DIR}/src/c/modules/ConfigureObjectsx 
+                          $ENV{ISSM_DIR}/src/c/modules/ComputeBasalStressx 
+                          $ENV{ISSM_DIR}/src/c/modules/ComputeStrainRatex 
+                          $ENV{ISSM_DIR}/src/c/modules/SpcNodesx 
+                          $ENV{ISSM_DIR}/src/c/modules/PositiveDegreeDayx 
+                          $ENV{ISSM_DIR}/src/c/modules/Delta18oParameterizationx 
+                          $ENV{ISSM_DIR}/src/c/modules/SmbGradientsx 
+                          $ENV{ISSM_DIR}/src/c/modules/MeshPartitionx 
+                          $ENV{ISSM_DIR}/src/c/modules/Reducevectorgtofx 
+                          $ENV{ISSM_DIR}/src/c/modules/Reduceloadx 
+                          $ENV{ISSM_DIR}/src/c/modules/ConstraintsStatex 
+                          $ENV{ISSM_DIR}/src/c/modules/ResetConstraintsx 
+                          $ENV{ISSM_DIR}/src/c/modules/ResetCoordinateSystemx 
+                          $ENV{ISSM_DIR}/src/c/modules/Solverx 
+                          $ENV{ISSM_DIR}/src/c/modules/VecMergex 
+                          $ENV{ISSM_DIR}/src/c/modules/Mergesolutionfromftogx 
+                          $ENV{ISSM_DIR}/src/c/modules/InputToResultx 
+                          $ENV{ISSM_DIR}/src/c/analyses 
+                          $ENV{ISSM_DIR}/src/c/solutionsequences 
+                          $ENV{ISSM_DIR}/src/c/solutionsequences)
+# }}}
+
+# Core Sources {{{
+set(core_sources   	./datastructures/DataSet.cpp
+					./classes/gauss/GaussTria.cpp
+					./classes/FemModel.cpp
+					./classes/Loads/Friction.cpp
+					./classes/Inputs/TransientInput.cpp
+					./classes/Constraints/SpcTransient.cpp
+					./classes/IndependentObject.cpp
+					./classes/DependentObject.cpp
+					./classes/DofIndexing.cpp
+					./classes/IoModel.cpp
+					./classes/Contours.cpp
+					./classes/Nodes.cpp
+					./classes/Vertices.cpp
+					./classes/Node.cpp
+					./classes/Vertex.cpp
+					./classes/Hook.cpp
+					./classes/Patch.cpp
+					./classes/ElementResults/DoubleElementResult.cpp
+					./classes/ElementResults/TriaP1ElementResult.cpp
+					./classes/ElementResults/BoolElementResult.cpp
+					./classes/ExternalResults/Results.cpp
+					./classes/Elements/Elements.cpp
+					./classes/Elements/ElementHook.cpp
+					./classes/Elements/Tria.cpp
+					./classes/Elements/TriaRef.cpp
+					./classes/Inputs/Inputs.cpp
+					./classes/Inputs/TriaInput.cpp
+					./classes/Inputs/BoolInput.cpp
+					./classes/Inputs/IntInput.cpp
+					./classes/Inputs/DoubleInput.cpp
+					./classes/Inputs/DatasetInput.cpp
+					./classes/Materials/Materials.cpp
+					./classes/Materials/Matice.cpp
+					./classes/Materials/Matdamageice.cpp
+					./classes/Materials/Matpar.cpp
+					./classes/Constraints/Constraints.cpp
+					./classes/Constraints/SpcStatic.cpp
+					./classes/Constraints/SpcDynamic.cpp
+					./classes/Loads/Loads.cpp
+					./classes/Loads/Penpair.cpp
+					./classes/Loads/Pengrid.cpp
+					./classes/Loads/Icefront.cpp
+					./classes/Loads/Numericalflux.cpp
+					./classes/matrix/ElementMatrix.cpp
+					./classes/matrix/ElementVector.cpp
+					./classes/Params/Parameters.cpp
+					./classes/Params/BoolParam.cpp
+					./classes/Params/IntParam.cpp
+					./classes/Params/IntVecParam.cpp
+					./classes/Params/IntMatParam.cpp
+					./classes/Params/DoubleParam.cpp
+					./classes/Params/FileParam.cpp
+					./classes/Params/StringArrayParam.cpp
+					./classes/Params/DoubleMatParam.cpp
+					./classes/Params/DoubleTransientMatParam.cpp
+					./classes/Params/DoubleMatArrayParam.cpp
+					./classes/Params/DoubleVecParam.cpp
+					./classes/Params/StringParam.cpp
+					./classes/Params/MatrixParam.cpp
+					./classes/Params/VectorParam.cpp
+					./classes/Params/TransientParam.cpp
+					./classes/Params/DataSetParam.cpp
+					./classes/Profiler.cpp
+					./shared/Matrix/MatrixUtils.cpp
+					./shared/io/Disk/pfopen.cpp
+					./shared/io/Disk/pfclose.cpp
+					./shared/io/Disk/WriteLockFile.cpp
+					./shared/io/Print/PrintfFunction.cpp
+					./shared/io/Comm/IssmComm.cpp
+					./shared/LatLong/Ll2xyx.cpp
+					./shared/LatLong/Xy2llx.cpp
+					./shared/Enum/EnumToStringx.cpp
+					./shared/Enum/StringToEnumx.cpp
+					./shared/Numerics/Verbosity.cpp
+					./shared/Numerics/GaussPoints.cpp
+					./shared/Numerics/cross.cpp
+					./shared/Numerics/isnan.cpp
+					./shared/Numerics/cubic.cpp
+					./shared/Numerics/extrema.cpp
+					./shared/Numerics/XZvectorsToCoordinateSystem.cpp
+					./shared/Exceptions/Exceptions.cpp
+					./shared/Exceptions/exprintf.cpp
+					./shared/Sorting/binary_search.cpp
+					./shared/Elements/Paterson.cpp
+					./shared/Elements/Arrhenius.cpp
+					./shared/Elements/PrintArrays.cpp
+					./shared/Elements/PddSurfaceMassBalance.cpp
+					./shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp
+					./shared/String/DescriptorIndex.cpp
+					./toolkits/issm/IssmToolkitUtils.cpp
+					./toolkits/issm/IssmSolver.cpp
+					./toolkits/ToolkitOptions.cpp
+					./modules/ModelProcessorx/ModelProcessorx.cpp
+					./modules/ModelProcessorx/DistributeNumDofs.cpp
+					./modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp
+					./modules/ModelProcessorx/NodesPartitioning.cpp
+					./modules/ModelProcessorx/EdgesPartitioning.cpp
+					./modules/ModelProcessorx/SortDataSets.cpp
+					./modules/ModelProcessorx/UpdateCounters.cpp
+					./modules/ModelProcessorx/CreateDataSets.cpp
+					./modules/ModelProcessorx/CreateParameters.cpp
+					./modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp
+					./modules/ModelProcessorx/CreateEdges.cpp
+					./modules/ModelProcessorx/CreateElementToEdgeConnectivity.cpp
+					./modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp
+					./modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp
+					./modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
+					./modules/ModelProcessorx/CreateNodes.cpp
+					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp
+					./modules/NodesDofx/NodesDofx.cpp
+					./modules/NodalValuex/NodalValuex.cpp
+					./modules/VerticesDofx/VerticesDofx.cpp
+					./modules/VertexCoordinatesx/VertexCoordinatesx.cpp
+					./modules/OutputResultsx/OutputResultsx.cpp
+					./modules/InputDuplicatex/InputDuplicatex.cpp
+					./modules/InputScalex/InputScalex.cpp
+					./modules/SurfaceAreax/SurfaceAreax.cpp
+					./modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp
+					./modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp
+					./modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
+					./modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp
+					./modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp
+					./modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp
+					./modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
+					./modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp
+					./modules/InputArtificialNoisex/InputArtificialNoisex.cpp
+					./modules/ConfigureObjectsx/ConfigureObjectsx.cpp
+					./modules/ComputeBasalStressx/ComputeBasalStressx.cpp
+					./modules/ComputeStrainRatex/ComputeStrainRatex.cpp
+					./modules/SpcNodesx/SpcNodesx.cpp
+					./modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp
+					./modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp
+					./modules/SmbGradientsx/SmbGradientsx.cpp
+					./modules/Reducevectorgtofx/Reducevectorgtofx.cpp
+					./modules/Reduceloadx/Reduceloadx.cpp
+					./modules/ConstraintsStatex/ConstraintsStatex.cpp
+					./modules/ResetConstraintsx/ResetConstraintsx.cpp
+					./modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp
+					./modules/Solverx/Solverx.cpp
+					./modules/VecMergex/VecMergex.cpp
+					./modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp
+					./modules/InputToResultx/InputToResultx.cpp
+					./analyses/ProcessArguments.cpp
+					./analyses/ResetBoundaryConditions.cpp
+					./analyses/AnalysisConfiguration.cpp
+					./analyses/WrapperCorePointerFromSolutionEnum.cpp
+					./analyses/CorePointerFromSolutionEnum.cpp
+					./analyses/EnvironmentInit.cpp
+					./analyses/EnvironmentFinalize.cpp
+					./analyses/ad_core.cpp
+					./solutionsequences/solutionsequence_linear.cpp
+					./solutionsequences/solutionsequence_nonlinear.cpp
+					./solutionsequences/solutionsequence_newton.cpp
+					./solutionsequences/convergence.cpp
+					./classes/Options/Options.cpp
+					./classes/Options/OptionUtilities.cpp
+					./classes/RiftStruct.cpp)
+set(issm_sources ${core_sources})
+# }}}
+
+# DAKOTA sources  {{{
+set(dakota_sources 				  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp
+					  				  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp
+					  				  ./modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp
+					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp
+					  				  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
+					  ./analyses/dakota_core.cpp
+					  				  ./analyses/DakotaSpawnCore.cpp)
+#}}}
+#Transient sources  {{{
+set(transient_sources ./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp 
+							./analyses/transient_core.cpp)
+#}}}
+#Steadystate sources  {{{
+set(steadystate_sources ./analyses/steadystate_core.cpp)
+#}}}
+#Prognostic sources  {{{
+set(prognostic_sources ./modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp
+					      ./modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp
+					      ./modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp
+					      ./modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp
+							./analyses/prognostic_core.cpp)
+#}}}
+#Thermal sources  {{{
+set(thermal_sources ./modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp
+					   ./modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp
+					   ./modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp
+					   ./modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp
+					   ./modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp
+					   ./modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp
+					   ./modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp
+					   ./modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp
+					   ./modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp
+					   ./modules/ModelProcessorx/Melting/CreateNodesMelting.cpp
+					   ./modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp
+					   ./modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp
+					   ./modules/ConstraintsStatex/ThermalConstraintsState.cpp
+					   ./modules/ConstraintsStatex/ThermalIsPresent.cpp
+					   ./modules/ResetConstraintsx/ThermalConstraintsReset.cpp 
+					   ./analyses/thermal_core.cpp
+					   ./analyses/enthalpy_core.cpp
+					   ./solutionsequences/solutionsequence_thermal_nonlinear.cpp)
+#}}}
+#Control sources  {{{
+set(control_sources ./modules/ControlInputGetGradientx/ControlInputGetGradientx.cpp
+					  				  ./modules/ControlInputSetGradientx/ControlInputSetGradientx.cpp
+					  				  ./modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp
+					  				  ./modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp
+					  				  ./modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp
+					  				  ./modules/ModelProcessorx/Control/CreateParametersControl.cpp
+					  ./modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
+					  				  ./modules/InputControlUpdatex/InputControlUpdatex.cpp
+					  				  ./modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp
+					  				  ./modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp
+					  				  ./modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp
+					  				  ./modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp
+					  				  ./modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp
+					  				  ./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp
+					  				  ./modules/Orthx/Orthx.cpp
+					  				  ./modules/Gradjx/Gradjx.cpp
+					  ./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp
+					  				  ./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp
+					  				  ./modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp
+					  				  ./modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp
+					  				  				  ./classes/Inputs/ControlInput.cpp
+					  ./shared/Numerics/BrentSearch.cpp
+					  ./shared/Numerics/OptimalSearch.cpp 
+					  ./analyses/control_core.cpp
+					  ./analyses/controltao_core.cpp
+					  ./analyses/objectivefunction.cpp
+					  ./analyses/gradient_core.cpp
+					  ./analyses/adjointdiagnostic_core.cpp
+					  ./analyses/adjointbalancethickness_core.cpp
+					  ./analyses/AdjointCorePointerFromSolutionEnum.cpp
+					  ./solutionsequences/solutionsequence_adjoint_linear.cpp)
+#}}}
+#Hydrology sources  {{{
+set(hydrology_sources  ./modules/ModelProcessorx/HydrologyShreve/UpdateElementsHydrologyShreve.cpp
+					      ./modules/ModelProcessorx/HydrologyShreve/CreateNodesHydrologyShreve.cpp
+					      ./modules/ModelProcessorx/HydrologyShreve/CreateConstraintsHydrologyShreve.cpp
+					      ./modules/ModelProcessorx/HydrologyShreve/CreateLoadsHydrologyShreve.cpp 
+							./modules/ModelProcessorx/HydrologyShreve/CreateParametersHydrologyShreve.cpp 
+							./modules/ModelProcessorx/HydrologyDCInefficient/UpdateElementsHydrologyDCInefficient.cpp
+							./modules/ModelProcessorx/HydrologyDCInefficient/CreateNodesHydrologyDCInefficient.cpp
+							./modules/ModelProcessorx/HydrologyDCInefficient/CreateConstraintsHydrologyDCInefficient.cpp
+							./modules/ModelProcessorx/HydrologyDCInefficient/CreateLoadsHydrologyDCInefficient.cpp 
+							./modules/ModelProcessorx/HydrologyDCInefficient/CreateParametersHydrologyDCInefficient.cpp 
+							./modules/ModelProcessorx/HydrologyDCEfficient/UpdateElementsHydrologyDCEfficient.cpp
+							./modules/ModelProcessorx/HydrologyDCEfficient/CreateNodesHydrologyDCEfficient.cpp
+							./modules/ModelProcessorx/HydrologyDCEfficient/CreateConstraintsHydrologyDCEfficient.cpp
+							./modules/ModelProcessorx/HydrologyDCEfficient/CreateLoadsHydrologyDCEfficient.cpp 
+							./modules/ModelProcessorx/HydrologyDCEfficient/CreateParametersHydrologyDCEfficient.cpp 
+							./analyses/hydrology_core.cpp
+							./solutionsequences/solutionsequence_hydro_nonlinear.cpp)
+#}}}
+#Diagnostic sources  {{{
+set(diagnostic_sources ./modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp
+					      ./modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp 
+					      ./modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp 
+					      ./modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp
+					      ./modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp
+					      ./modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp 
+					      ./modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp 
+					      ./modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp
+					      ./modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp
+					      ./modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp 
+					      ./modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp 
+							./modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp 
+							./analyses/diagnostic_core.cpp
+							./solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp)
+#}}}
+#Balanced sources  {{{
+set(balanced_sources ./modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp
+					    ./modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp
+					    ./modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp
+						 ./modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp
+						 ./analyses/balancethickness_core.cpp 
+						 ./analyses/dummy_core.cpp)
+#}}}
+#Slope sources  {{{
+set(slope_sources  ./modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp
+					  ./modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp 
+					  ./modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp
+					  ./modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp
+					  ./modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp
+					  ./modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp 
+					  ./modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp
+					  ./modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp
+					  ./analyses/surfaceslope_core.cpp
+					  ./analyses/bedslope_core.cpp)
+#}}}
+#Gia sources  {{{
+set(gia_sources  ./analyses/gia_core.cpp
+					./modules/ModelProcessorx/Gia/UpdateElementsGia.cpp
+					./modules/ModelProcessorx/Gia/CreateNodesGia.cpp 
+					./modules/ModelProcessorx/Gia/CreateConstraintsGia.cpp
+					./modules/ModelProcessorx/Gia/CreateLoadsGia.cpp
+					./modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp
+									./modules/GiaDeflectionCorex/distme.f
+					./modules/GiaDeflectionCorex/freed.f
+					./modules/GiaDeflectionCorex/ojrule.f
+					./modules/GiaDeflectionCorex/pwise.f
+					./modules/GiaDeflectionCorex/qwise.f
+					./modules/GiaDeflectionCorex/stot.f
+					./modules/GiaDeflectionCorex/what0.f
+					)
+#}}}
+#Groundingline sources  {{{
+set(groundingline_sources ./modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
+					        )
+#}}}
+#Rifts sources  {{{
+set(rifts_sources ./classes/Loads/Riftfront.cpp
+				    			    ./modules/ConstraintsStatex/RiftConstraintsState.cpp)
+#}}}
+#Android sources  {{{
+set(android_sources )
+#}}}
+#3D sources  {{{
+set(threed_sources 			     ./classes/gauss/GaussPenta.cpp
+				     			     ./classes/ElementResults/PentaP1ElementResult.cpp
+				     			     ./classes/Inputs/PentaInput.cpp
+				     			     ./classes/Elements/Penta.cpp
+				     			     ./classes/Elements/PentaRef.cpp)
+#}}}
+#Bamg sources  {{{
+set(bamg_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/det.h 
+							./bamg/BamgVertex.cpp
+										./bamg/VertexOnEdge.cpp
+							./bamg/VertexOnGeom.cpp
+							./bamg/VertexOnVertex.cpp
+				./bamg/Mesh.cpp
+							./shared/Bamg/Abs.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/BamgConvertMeshx/BamgConvertMeshx.cpp
+							./modules/BamgTriangulatex/BamgTriangulatex.cpp
+				)
+#}}}
+#Kriging sources  {{{
+set(kriging_sources 					./classes/kriging/Observations.cpp
+						./classes/kriging/Variogram.h 
+											./classes/kriging/GaussianVariogram.cpp
+											./classes/kriging/ExponentialVariogram.cpp
+											./classes/kriging/SphericalVariogram.cpp
+											./classes/kriging/PowerVariogram.cpp
+											./classes/kriging/Quadtree.cpp
+											./classes/kriging/Observation.cpp
+						./modules/Krigingx/Krigingx.cpp
+						./modules/Krigingx/Kriging
+#For parallel kriging, only difference is ./modules/Krigingx/pKrigingx.cpp with no multithreading
+set(pkriging_sources 					./classes/kriging/Observations.cpp
+						./classes/kriging/Variogram.h 
+											./classes/kriging/GaussianVariogram.cpp
+											./classes/kriging/ExponentialVariogram.cpp
+											./classes/kriging/SphericalVariogram.cpp
+											./classes/kriging/PowerVariogram.cpp
+											./classes/kriging/Quadtree.cpp
+											./classes/kriging/Observation.cpp
+						./modules/Krigingx/pKrigingx.cpp
+						)
+#}}}
+#Kml sources  {{{
+set(kml_sources 		     ./modules/Exp2Kmlx/Exp2Kmlx.cpp
+			     		     ./modules/Kml2Expx/Kml2Expx.cpp
+			     		     ./modules/Shp2Expx/Shp2Expx.cpp
+			     		     ./modules/Shp2Kmlx/Shp2Kmlx.cpp
+			     		     ./modules/KMLFileReadx/KMLFileReadx.cpp
+			     		     ./modules/KMLMeshWritex/KMLMeshWritex.cpp
+			     		     ./modules/KMLOverlayx/KMLOverlayx.cpp
+			     		     ./kml/KML_Attribute.cpp
+			     		     ./kml/KML_Comment.cpp
+			     		     ./kml/KML_ColorStyle.cpp
+			     		     ./kml/KML_Container.cpp
+			     		     ./kml/KML_Document.cpp
+			     		     ./kml/KML_Feature.cpp
+			     		     ./kml/KML_File.cpp
+			     		     ./kml/KML_Folder.cpp
+			     		     ./kml/KML_Geometry.cpp
+			     		     ./kml/KML_GroundOverlay.cpp
+			     		     ./kml/KML_Icon.cpp
+			     		     ./kml/KML_LatLonBox.cpp
+		  	     		     ./kml/KML_LinearRing.cpp
+			     		     ./kml/KML_LineString.cpp
+			     		     ./kml/KML_LineStyle.cpp
+			     		     ./kml/KML_MultiGeometry.cpp
+			     		     ./kml/KML_Object.cpp
+			     		     ./kml/KML_Overlay.cpp
+			     		     ./kml/KML_Point.cpp
+			     		     ./kml/KML_Placemark.cpp
+			     		     ./kml/KML_Polygon.cpp
+			     		     ./kml/KML_PolyStyle.cpp
+			     		     ./kml/KML_Style.cpp
+			     		     ./kml/KML_StyleSelector.cpp
+			     		     ./kml/KML_SubStyle.cpp
+			     		     ./kml/KML_Unknown.cpp
+			     		     ./kml/KMLFileReadUtils.cpp
+			     )
+#}}}
+#Petsc sources  {{{
+petsc_sources= ./toolkits/petsc
+					./toolkits/petsc/patches
+													./toolkits/petsc/patches/VecToMPISerial.cpp
+					./toolkits/petsc/patches/MatToSerial.cpp
+					./toolkits/petsc/patches/VecMerge.cpp
+					./toolkits/petsc/patches/NewVec.cpp
+					./toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp
+					./toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp
+					./toolkits/petsc/patches/NewMat.cpp
+					./toolkits/petsc/patches/VecFree.cpp
+					./toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp
+					./toolkits/petsc/patches/PetscVectorToDoubleVector.cpp
+					./toolkits/petsc/patches/VecDuplicatePatch.cpp
+					./toolkits/petsc/patches/KSPFree.cpp
+					./toolkits/petsc/patches/MatFree.cpp
+					./toolkits/petsc/patches/MatMultPatch.cpp
+					./toolkits/petsc/patches/ISSMToPetscMatrixType.cpp
+					./toolkits/petsc/patches/ISSMToPetscInsertMode.cpp
+					./toolkits/petsc/patches/ISSMToPetscNormMode.cpp
+													./toolkits/petsc/objects/PetscMat.cpp
+									./toolkits/petsc/objects/PetscVec.cpp
+					./toolkits/petsc/objects/PetscSolver.cpp
+									)
+#}}}
+#Mumps sources  {{{
+set(mumps_sources      ./toolkits/mumps
+									./toolkits/mumps/MpiDenseMumpsSolve.cpp)
+#}}}
+#Gsl sources  {{{
+set(gsl_sources   ./toolkits/gsl/DenseGslSolve.cpp)
+#}}}
+#Mpi sources  {{{
+set(mpi_sources 						./toolkits/mpi/patches/DetermineLocalSize.cpp
+				./toolkits/mpi/patches/DetermineGlobalSize.cpp
+				./toolkits/mpi/patches/DetermineRowRankFromLocalSize.cpp
+				./toolkits/mpi/patches/GetOwnershipBoundariesFromRange.cpp
+							)
+#}}}
+#Metis sources  {{{
+set(metis_sources 				./toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp)
+#}}}
+
+# API Print {{{
+if(NOT PYTHON AND NOT MATLAB)
+    add_library(ISSMOverload STATIC ./shared/String/stricmp.cpp
+            ./shared/String/ApiPrintf.cpp)
+    list(APPEND issm_deps ISSMOverload)
+else(NOT PYTHON AND NOT MATLAB)
+    message(FATAL_ERROR "Python and Matlab are not supported yet.")
+endif(NOT PYTHON AND NOT MATLAB)
+# }}}
+
+# Modules Sources {{{
+set(modules_sources ./shared/Threads/LaunchThread.cpp
+			./shared/Threads/PartitionRange.cpp
+			./shared/Exp/exp.cpp
+			./shared/TriMesh/AssociateSegmentToElement.cpp
+			./shared/TriMesh/GridInsideHole.cpp
+			./shared/TriMesh/OrderSegments.cpp
+			./shared/TriMesh/SplitMeshForRifts.cpp
+			./shared/TriMesh/TriMeshUtils.cpp
+			./modules/Chacox/Chacox.cpp
+			./modules/Chacox/input_parse.cpp
+			./modules/Chacox/chaco_seconds.cpp
+			./modules/Chacox/user_params.cpp
+			./modules/TriaSearchx/TriaSearchx.cpp
+			./modules/TriMeshx/TriMeshx.cpp
+			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp
+			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp
+			./modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp
+			./modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp
+			./modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp
+			./modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
+			./modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp
+			./modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp
+			./modules/HoleFillerx/HoleFillerx.cpp
+			./modules/EdgeDetectionx/EdgeDetectionx.cpp
+			./modules/AverageFilterx/AverageFilterx.cpp
+			./modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp
+			./modules/ContourToMeshx/ContourToMeshx.cpp
+			./modules/ContourToMeshx/ContourToMeshxt.cpp
+			./modules/ContourToNodesx/ContourToNodesx.cpp
+			./modules/Reducevectorgtosx/Reducevectorgtosx.cpp
+			./modules/NodeConnectivityx/NodeConnectivityx.cpp
+			./modules/ElementConnectivityx/ElementConnectivityx.cpp
+			./modules/Scotchx/Scotchx.cpp
+			./modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp)
+# }}}
+
+#{{{ Conditional build-up of sources
+#ISSM sources are a combination of core sources and sources related to specific capabilities.
+
+if(DAKOTA)
+list(APPEND CPP_FLAGS '-D_HAVE_DAKOTA_')
+list(APPEND issm_sources ${dakota_sources})
+endif(DAKOTA)
+
+if(PETSC)
+list(APPEND CPP_FLAGS '-D_HAVE_PETSC_')
+list(APPEND issm_sources ${petsc_sources})
+endif(PETSC)
+
+if(MUMPS)
+list(APPEND CPP_FLAGS '-D_HAVE_MUMPS_')
+list(APPEND issm_sources ${mumps_sources})
+endif(MUMPS)
+
+if(GSL)
+list(APPEND CPP_FLAGS '-D_HAVE_GSL_')
+list(APPEND issm_sources ${gsl_sources})
+list(APPEND issm_deps gsl gslcblas)
+list(APPEND issm_lib_paths ${GSL_LIB_DIR})
+include_directories(AFTER ${GSL_INC_DIR})
+message("GSL_INC: ${GSL_INC_DIR}")
+message("GSL_LIB: ${GSL_LIB_DIR}")
+endif(GSL)
+
+if(TRANSIENT)
+list(APPEND CPP_FLAGS '-D_HAVE_TRANSIENT_')
+list(APPEND issm_sources ${transient_sources})
+endif(TRANSIENT)
+
+if(STEADYSTATE)
+list(APPEND CPP_FLAGS '-D_HAVE_STEADYSTATE_')
+list(APPEND issm_sources ${steadystate_sources})
+endif(STEADYSTATE)
+
+if(PROGNOSTIC)
+list(APPEND CPP_FLAGS '-D_HAVE_PROGNOSTIC_')
+list(APPEND issm_sources ${prognostic_sources})
+endif(PROGNOSTIC)
+
+if(THERMAL)
+list(APPEND CPP_FLAGS '-D_HAVE_THERMAL_')
+list(APPEND issm_sources ${thermal_sources})
+endif(THERMAL)
+
+if(GIA)
+list(APPEND CPP_FLAGS '-D_HAVE_GIA_')
+list(APPEND issm_sources ${gia_sources})
+endif(GIA)
+
+if(CONTROL)
+list(APPEND CPP_FLAGS '-D_HAVE_CONTROL_')
+list(APPEND issm_sources ${control_sources})
+endif(CONTROL)
+
+if(HYDROLOGY)
+list(APPEND CPP_FLAGS '-D_HAVE_HYDROLOGY_')
+list(APPEND issm_sources ${hydrology_sources})
+endif(HYDROLOGY)
+
+if(DIAGNOSTIC)
+list(APPEND CPP_FLAGS '-D_HAVE_DIAGNOSTIC_')
+list(APPEND issm_sources ${diagnostic_sources})
+endif(DIAGNOSTIC)
+
+if(BALANCED)
+list(APPEND CPP_FLAGS '-D_HAVE_BALANCED_')
+list(APPEND issm_sources ${balanced_sources})
+endif(BALANCED)
+
+if(SLOPE)
+list(APPEND CPP_FLAGS '-D_HAVE_SLOPE_')
+list(APPEND issm_sources ${slope_sources})
+endif(SLOPE)
+
+if(GROUNDINGLINE)
+list(APPEND CPP_FLAGS '-D_HAVE_GROUNDINGLINE_')
+list(APPEND issm_sources ${groundingline_sources})
+endif(GROUNDINGLINE)
+
+if(RIFTS)
+list(APPEND CPP_FLAGS '-D_HAVE_RIFTS_')
+list(APPEND issm_sources ${rifts_sources})
+endif(RIFTS)
+
+if(ANDROID)
+list(APPEND CPP_FLAGS '-D_HAVE_ANDROID_')
+list(APPEND issm_sources ${android_sources})
+endif(ANDROID)
+
+if(THREED)
+list(APPEND CPP_FLAGS '-D_HAVE_THREED_')
+list(APPEND issm_sources ${threed_sources})
+endif(THREED)
+
+if(MPI)
+list(APPEND CPP_FLAGS '-D_HAVE_MPI_')
+list(APPEND issm_sources ${mpi_sources})
+endif(MPI)
+
+if(METIS)
+list(APPEND CPP_FLAGS '-D_HAVE_METIS_')
+list(APPEND issm_sources ${metis_sources})
+endif(METIS)
+
+if(KRIGING)
+list(APPEND CPP_FLAGS '-D_HAVE_KRIGING_')
+list(APPEND issm_sources ${pkriging_sources})
+endif(KRIGING)
+#}}}
+
+add_library(ISSMCore STATIC ${issm_sources})
+add_library(ISSMModules STATIC ${modules_sources})
+
+list(INSERT issm_deps 0 ISSMCore ISSMModules)
+add_executable(issm ./main/issm.cpp)
+
+# Definitions {{{
+add_definitions(${CPP_FLAGS})
+# }}}
+# Compilation Flags {{{
+# }}}
+# Linking Flags {{{
+link_directories($ENV{ISSM_DIR}/src/c )
+target_link_libraries(issm ${issm_deps})
+message("ISSM_DEPS: ${issm_deps}")
+# }}}
+
+# Install Targets {{{
+# Install 'issm.exe'
+install(TARGETS issm RUNTIME DESTINATION $ENV{ISSM_DIR}/bin)
+
+# Install 'libISSMCore.a' and 'libISSMOverload.a'
+install(TARGETS ISSMCore
+                ISSMModules
+                ISSMOverload
+        ARCHIVE DESTINATION $ENV{ISSM_DIR}/lib)
+# }}}
+# Optional Install {{{
+#if(${SHARED_LIBS} IS ON)
+#   install(TARGETS ISSMCore
+#                   ISSMOverload
+#           LIBRARY)
+#endif(${SHARED_LIBS} IS ON)
+# }}}
Index: /issm/trunk/src/c/Makefile.am
===================================================================
--- /issm/trunk/src/c/Makefile.am	(revision 16136)
+++ /issm/trunk/src/c/Makefile.am	(revision 16137)
@@ -1,3 +1,4 @@
-AM_CPPFLAGS = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @MPIINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@ @ANDROID_NDKINCL@
+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@
+AUTOMAKE_OPTIONS = subdir-objects
 
 EXEEXT=$(ISSMEXT)
@@ -19,7 +20,5 @@
 #sources
 #Core sources{{{
-core_sources = ./main/issm.h\
-			   ./main/globals.h\
-			   ./datastructures/DataSet.h\
+core_sources = ./datastructures/DataSet.h\
 					./datastructures/DataSet.cpp\
 					./datastructures/Object.h\
@@ -118,6 +117,4 @@
 					./classes/Loads/Pengrid.cpp\
 					./classes/Loads/Pengrid.h\
-					./classes/Loads/Icefront.cpp\
-					./classes/Loads/Icefront.h\
 					./classes/Loads/Numericalflux.cpp\
 					./classes/Loads/Numericalflux.h\
@@ -167,4 +164,5 @@
 					./shared/shared.h\
 					./shared/MemOps/MemOps.h\
+					./shared/MemOps/MemOps.cpp\
 					./shared/Matrix/matrix.h\
 					./shared/Matrix/MatrixUtils.cpp\
@@ -176,6 +174,4 @@
 					./shared/io/Print/PrintfFunction.cpp\
 					./shared/io/Print/Print.h\
-					./shared/io/Comm/Comm.h\
-					./shared/io/Comm/CommDef.h\
 					./shared/io/Comm/IssmComm.h\
 					./shared/io/Comm/IssmComm.cpp\
@@ -209,7 +205,9 @@
 					./shared/Elements/Paterson.cpp\
 					./shared/Elements/Arrhenius.cpp\
+					./shared/Elements/LliboutryDuval.cpp \
 					./shared/Elements/PrintArrays.cpp\
 					./shared/Elements/PddSurfaceMassBalance.cpp\
 					./shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp\
+					./shared/Elements/DrainageFunctionWaterfraction.cpp\
 					./shared/String/sharedstring.h\
 					./shared/String/DescriptorIndex.cpp\
@@ -227,4 +225,11 @@
 					./toolkits/issm/IssmSolver.cpp\
 					./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\
@@ -243,4 +248,6 @@
 					./modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp\
 					./modules/ModelProcessorx/NodesPartitioning.cpp\
+					./modules/ModelProcessorx/EdgesPartitioning.cpp\
+					./modules/ModelProcessorx/FacesPartitioning.cpp\
 					./modules/ModelProcessorx/SortDataSets.cpp\
 					./modules/ModelProcessorx/UpdateCounters.cpp\
@@ -248,7 +255,10 @@
 					./modules/ModelProcessorx/CreateParameters.cpp\
 					./modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp\
+					./modules/ModelProcessorx/CreateFaces.cpp\
+					./modules/ModelProcessorx/CreateEdges.cpp\
 					./modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp\
 					./modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp\
 					./modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp\
+					./modules/ModelProcessorx/CreateNodes.cpp\
 					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.h\
 					./modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp\
@@ -269,4 +279,10 @@
 					./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\
@@ -297,4 +313,6 @@
 					./modules/PositiveDegreeDayx/PositiveDegreeDayx.h\
 					./modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp\
+					./modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.h\
+					./modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.cpp\
 					./modules/Delta18oParameterizationx/Delta18oParameterizationx.h\
 					./modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp\
@@ -363,10 +381,19 @@
 steadystate_sources = ./analyses/steadystate_core.cpp
 #}}}
-#Prognostic sources  {{{
-prognostic_sources = ./modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp\
-					      ./modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp\
-					      ./modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp\
-					      ./modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp\
-							./analyses/prognostic_core.cpp
+#Masstransport sources  {{{
+masstransport_sources = ./modules/ModelProcessorx/Masstransport/UpdateElementsMasstransport.cpp\
+								./modules/ModelProcessorx/Masstransport/CreateNodesMasstransport.cpp\
+								./modules/ModelProcessorx/Masstransport/CreateConstraintsMasstransport.cpp\
+								./modules/ModelProcessorx/Masstransport/CreateLoadsMasstransport.cpp\
+								./modules/ModelProcessorx/FreeSurfaceTop/UpdateElementsFreeSurfaceTop.cpp\
+								./modules/ModelProcessorx/FreeSurfaceTop/CreateNodesFreeSurfaceTop.cpp\
+								./modules/ModelProcessorx/FreeSurfaceTop/CreateConstraintsFreeSurfaceTop.cpp\
+								./modules/ModelProcessorx/FreeSurfaceTop/CreateLoadsFreeSurfaceTop.cpp\
+								./modules/ModelProcessorx/FreeSurfaceBase/UpdateElementsFreeSurfaceBase.cpp\
+								./modules/ModelProcessorx/FreeSurfaceBase/CreateNodesFreeSurfaceBase.cpp\
+								./modules/ModelProcessorx/FreeSurfaceBase/CreateConstraintsFreeSurfaceBase.cpp\
+								./modules/ModelProcessorx/FreeSurfaceBase/CreateLoadsFreeSurfaceBase.cpp\
+								./analyses/masstransport_core.cpp
+
 #}}}
 #Thermal sources  {{{
@@ -437,5 +464,5 @@
 					  ./analyses/objectivefunction.cpp\
 					  ./analyses/gradient_core.cpp\
-					  ./analyses/adjointdiagnostic_core.cpp\
+					  ./analyses/adjointstressbalance_core.cpp\
 					  ./analyses/adjointbalancethickness_core.cpp\
 					  ./analyses/AdjointCorePointerFromSolutionEnum.cpp\
@@ -462,18 +489,18 @@
 							./solutionsequences/solutionsequence_hydro_nonlinear.cpp
 #}}}
-#Diagnostic sources  {{{
-diagnostic_sources = ./modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp\
-					      ./modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp \
-					      ./modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp \
-					      ./modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp\
-					      ./modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp\
-					      ./modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp \
-					      ./modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp \
-					      ./modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp\
-					      ./modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp\
-					      ./modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp \
-					      ./modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp \
-							./modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp \
-							./analyses/diagnostic_core.cpp\
+#Stressbalance sources  {{{
+stressbalance_sources = ./modules/ModelProcessorx/Stressbalance/UpdateElementsStressbalance.cpp\
+					      ./modules/ModelProcessorx/Stressbalance/CreateNodesStressbalance.cpp \
+					      ./modules/ModelProcessorx/Stressbalance/CreateConstraintsStressbalance.cpp \
+					      ./modules/ModelProcessorx/Stressbalance/CreateLoadsStressbalance.cpp\
+					      ./modules/ModelProcessorx/StressbalanceVertical/UpdateElementsStressbalanceVertical.cpp\
+					      ./modules/ModelProcessorx/StressbalanceVertical/CreateNodesStressbalanceVertical.cpp \
+					      ./modules/ModelProcessorx/StressbalanceVertical/CreateConstraintsStressbalanceVertical.cpp \
+					      ./modules/ModelProcessorx/StressbalanceVertical/CreateLoadsStressbalanceVertical.cpp\
+					      ./modules/ModelProcessorx/StressbalanceSIA/UpdateElementsStressbalanceSIA.cpp\
+					      ./modules/ModelProcessorx/StressbalanceSIA/CreateNodesStressbalanceSIA.cpp \
+					      ./modules/ModelProcessorx/StressbalanceSIA/CreateConstraintsStressbalanceSIA.cpp \
+							./modules/ModelProcessorx/StressbalanceSIA/CreateLoadsStressbalanceSIA.cpp \
+							./analyses/stressbalance_core.cpp\
 							./solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp
 #}}}
@@ -483,5 +510,10 @@
 					    ./modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp\
 						 ./modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp\
+						 ./modules/ModelProcessorx/Balancevelocity/UpdateElementsBalancevelocity.cpp\
+						 ./modules/ModelProcessorx/Balancevelocity/CreateNodesBalancevelocity.cpp\
+						 ./modules/ModelProcessorx/Balancevelocity/CreateConstraintsBalancevelocity.cpp\
+						 ./modules/ModelProcessorx/Balancevelocity/CreateLoadsBalancevelocity.cpp\
 						 ./analyses/balancethickness_core.cpp \
+						 ./analyses/balancevelocity_core.cpp \
 						 ./analyses/dummy_core.cpp
 #}}}
@@ -533,6 +565,6 @@
 				     ./classes/ElementResults/PentaP1ElementResult.h\
 				     ./classes/ElementResults/PentaP1ElementResult.cpp\
-				     ./classes/Inputs/PentaP1Input.h\
-				     ./classes/Inputs/PentaP1Input.cpp\
+				     ./classes/Inputs/PentaInput.h\
+				     ./classes/Inputs/PentaInput.cpp\
 				     ./classes/Elements/Penta.h\
 				     ./classes/Elements/Penta.cpp\
@@ -760,11 +792,5 @@
 #}}}
 #Mpi sources  {{{
-mpi_sources= ./toolkits/mpi/mpiincludes.h\
-				./toolkits/mpi/patches/mpipatches.h\
-				./toolkits/mpi/patches/DetermineLocalSize.cpp\
-				./toolkits/mpi/patches/DetermineGlobalSize.cpp\
-				./toolkits/mpi/patches/DetermineRowRankFromLocalSize.cpp\
-				./toolkits/mpi/patches/GetOwnershipBoundariesFromRange.cpp\
-				./toolkits/issm/IssmMpiDenseMat.h\
+mpi_sources= ./toolkits/issm/IssmMpiDenseMat.h\
 				./toolkits/issm/IssmMpiVec.h
 #}}}
@@ -867,6 +893,6 @@
 endif
 
-if PROGNOSTIC
-issm_sources  +=  $(prognostic_sources)
+if MASSTRANSPORT
+issm_sources  +=  $(masstransport_sources)
 endif
 
@@ -887,6 +913,6 @@
 endif
 
-if DIAGNOSTIC
-issm_sources  +=  $(diagnostic_sources)
+if STRESSBALANCE
+issm_sources  +=  $(stressbalance_sources)
 endif
 
@@ -939,5 +965,5 @@
 
 libISSMCore_la_SOURCES  = $(issm_sources)
-libISSMCore_la_LIBADD = $(PETSCLIB) $(TAOLIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(ADOLCLIB)
+libISSMCore_la_LIBADD = $(PETSCLIB) $(TAOLIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB)   $(ADOLCLIB) $(AMPILIB) $(METEOIOLIB) $(SNOWPACKLIB) 
 libISSMCore_la_FFLAGS = $(AM_FFLAGS)
 endif
@@ -987,5 +1013,5 @@
 
 #External packages
-LDADD += $(PETSCLIB) $(TAOLIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(ADOLCLIB)
+LDADD += $(PETSCLIB) $(TAOLIB) $(PLAPACKLIB) $(MUMPSLIB) $(SUPERLULIB) $(SPOOLESLIB) $(SCALAPACKLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(DAKOTALIB) $(METISLIB) $(CHACOLIB) $(SCOTCHLIB) $(BLASLAPACKLIB) $(MKLLIB) $(MPILIB)  $(MATHLIB) $(FORTRANLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(OSLIBS) $(GSLLIB) $(AMPILIB) $(ADOLCLIB) $(METEOIOLIB) $(SNOWPACKLIB)
 
 if FORTRAN
@@ -993,10 +1019,10 @@
 endif
 
-issm_SOURCES = main/issm.cpp
+issm_SOURCES = main/issm.h main/globals.h main/issm.cpp
 issm_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
 
 if KRIGING
 bin_PROGRAMS += kriging
-kriging_SOURCES = main/kriging.cpp
+kriging_SOURCES = main/issm.h main/globals.h main/kriging.cpp
 kriging_CXXFLAGS= -fPIC $(CXXFLAGS) $(CXXOPTFLAGS) $(COPTFLAGS) 
 endif
Index: /issm/trunk/src/c/analyses/AdjointCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AdjointCorePointerFromSolutionEnum.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/AdjointCorePointerFromSolutionEnum.cpp	(revision 16137)
@@ -23,9 +23,9 @@
 	switch(solutiontype){
 
-		case DiagnosticSolutionEnum:
-			adjointcore=&adjointdiagnostic_core;
+		case StressbalanceSolutionEnum:
+			adjointcore=&adjointstressbalance_core;
 			break;
 		case SteadystateSolutionEnum:
-			adjointcore=&adjointdiagnostic_core;
+			adjointcore=&adjointstressbalance_core;
 			break;
 		case BalancethicknessSolutionEnum:
Index: /issm/trunk/src/c/analyses/AnalysisConfiguration.cpp
===================================================================
--- /issm/trunk/src/c/analyses/AnalysisConfiguration.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/AnalysisConfiguration.cpp	(revision 16137)
@@ -25,10 +25,10 @@
 	switch(solutiontype){
 
-		case DiagnosticSolutionEnum:
+		case StressbalanceSolutionEnum:
 			numanalyses=5;
 			analyses=xNew<int>(numanalyses);
-			analyses[0]=DiagnosticHorizAnalysisEnum;
-			analyses[1]=DiagnosticVertAnalysisEnum;
-			analyses[2]=DiagnosticHutterAnalysisEnum;
+			analyses[0]=StressbalanceAnalysisEnum;
+			analyses[1]=StressbalanceVerticalAnalysisEnum;
+			analyses[2]=StressbalanceSIAAnalysisEnum;
 			analyses[3]=SurfaceSlopeAnalysisEnum;
 			analyses[4]=BedSlopeAnalysisEnum;
@@ -38,7 +38,7 @@
 			numanalyses=8;
 			analyses=xNew<int>(numanalyses);
-			analyses[0]=DiagnosticHorizAnalysisEnum;
-			analyses[1]=DiagnosticVertAnalysisEnum;
-			analyses[2]=DiagnosticHutterAnalysisEnum;
+			analyses[0]=StressbalanceAnalysisEnum;
+			analyses[1]=StressbalanceVerticalAnalysisEnum;
+			analyses[2]=StressbalanceSIAAnalysisEnum;
 			analyses[3]=SurfaceSlopeAnalysisEnum;
 			analyses[4]=BedSlopeAnalysisEnum;
@@ -71,8 +71,8 @@
 			break;
 
-		case PrognosticSolutionEnum:
+		case MasstransportSolutionEnum:
 			numanalyses=1;
 			analyses=xNew<int>(numanalyses);
-			analyses[0]=PrognosticAnalysisEnum;
+			analyses[0]=MasstransportAnalysisEnum;
 			break;
 
@@ -87,4 +87,11 @@
 			analyses=xNew<int>(numanalyses);
 			analyses[0]=BalancethicknessAnalysisEnum;
+			break;
+
+		case BalancevelocitySolutionEnum:
+			numanalyses=2;
+			analyses=xNew<int>(numanalyses);
+			analyses[0]=BalancevelocityAnalysisEnum;
+			analyses[1]=SurfaceSlopeAnalysisEnum;
 			break;
 
@@ -108,15 +115,17 @@
 
 		case TransientSolutionEnum:
-			numanalyses=10-1;
+			numanalyses=11;
 			analyses=xNew<int>(numanalyses);
-			analyses[0]=DiagnosticHorizAnalysisEnum;
-			analyses[1]=DiagnosticVertAnalysisEnum;
-			analyses[2]=DiagnosticHutterAnalysisEnum;
-			analyses[3]=SurfaceSlopeAnalysisEnum;
-			analyses[4]=BedSlopeAnalysisEnum;
-			analyses[5]=ThermalAnalysisEnum;
-			analyses[6]=MeltingAnalysisEnum;
-			analyses[7]=EnthalpyAnalysisEnum;
-			analyses[8]=PrognosticAnalysisEnum;
+			analyses[ 0]=StressbalanceAnalysisEnum;
+			analyses[ 1]=StressbalanceVerticalAnalysisEnum;
+			analyses[ 2]=StressbalanceSIAAnalysisEnum;
+			analyses[ 3]=SurfaceSlopeAnalysisEnum;
+			analyses[ 4]=BedSlopeAnalysisEnum;
+			analyses[ 5]=ThermalAnalysisEnum;
+			analyses[ 6]=MeltingAnalysisEnum;
+			analyses[ 7]=EnthalpyAnalysisEnum;
+			analyses[ 8]=MasstransportAnalysisEnum;
+			analyses[ 9]=FreeSurfaceBaseAnalysisEnum;
+			analyses[10]=FreeSurfaceTopAnalysisEnum;
 			break;
 
Index: sm/trunk/src/c/analyses/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/analyses/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,60 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/solutions)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/solutions/ad_core.cpp
-   $ENV{ISSM_DIR}/src/c/solutions/AnalysisConfiguration.cpp
-             $ENV{ISSM_DIR}/src/c/solutions/convergence.cpp
-$ENV{ISSM_DIR}/src/c/solutions/CorePointerFromSolutionEnum.cpp
-     $ENV{ISSM_DIR}/src/c/solutions/EnvironmentFinalize.cpp
-         $ENV{ISSM_DIR}/src/c/solutions/EnvironmentInit.cpp
-        $ENV{ISSM_DIR}/src/c/solutions/ProcessArguments.cpp
- $ENV{ISSM_DIR}/src/c/solutions/ResetBoundaryConditions.cpp
-$ENV{ISSM_DIR}/src/c/solutions/WrapperCorePointerFromSolutionEnum.cpp PARENT_SCOPE)
-# }}}
-# DAKOTA_SOURCES {{{
-set(DAKOTA_SOURCES $ENV{ISSM_DIR}/src/c/solutions/dakota_core.cpp
-               $ENV{ISSM_DIR}/src/c/solutions/DakotaSpawnCore.cpp PARENT_SCOPE)
-# }}}
-# TRANSIENT_SOURCES {{{
-set(TRANSIENT_SOURCES $ENV{ISSM_DIR}/src/c/solutions/transient_core.cpp PARENT_SCOPE)
-# }}}
-# STEADYSTATE_SOURCES {{{
-set(STEADYSTATE_SOURCES $ENV{ISSM_DIR}/src/c/solutions/steadystate_core.cpp PARENT_SCOPE)
-# }}}
-# PROGNOSTIC_SOURCES {{{
-set(PROGNOSTIC_SOURCES $ENV{ISSM_DIR}/src/c/solutions/prognostic_core.cpp PARENT_SCOPE)
-# }}}
-# THERMAL_SOURCES {{{
-set(THERMAL_SOURCES $ENV{ISSM_DIR}/src/c/solutions/enthalpy_core.cpp
-                     $ENV{ISSM_DIR}/src/c/solutions/thermal_core.cpp PARENT_SCOPE)
-# }}}
-# HYDROLOGY_SOURCES {{{
-set(HYDROLOGY_SOURCES $ENV{ISSM_DIR}/src/c/solutions/hydrology_core.cpp
-                 $ENV{ISSM_DIR}/src/c/solutions/hydrology_core_step.cpp PARENT_SCOPE)
-# }}}
-# DIAGNOSTIC_SOURCES {{{
-set(DIAGNOSTIC_SOURCES $ENV{ISSM_DIR}/src/c/solutions/diagnostic_core.cpp PARENT_SCOPE)
-# }}}
-# BALANCED_SOURCES {{{
-set(BALANCED_SOURCES $ENV{ISSM_DIR}/src/c/solutions/balancethickness_core.cpp
-                                $ENV{ISSM_DIR}/src/c/solutions/dummy_core.cpp PARENT_SCOPE)
-# }}}
-# SLOPE_SOURCES {{{
-set(SLOPE_SOURCES $ENV{ISSM_DIR}/src/c/solutions/bedslope_core.cpp
-              $ENV{ISSM_DIR}/src/c/solutions/surfaceslope_core.cpp PARENT_SCOPE)
-# }}}
-# LIBISSM_LA_SOURCES {{{
-set(LIBISSM_LA_SOURCES $ENV{ISSM_DIR}/src/c/solutions/issm.cpp PARENT_SCOPE)
-# }}}
-# ISSM_SOURCES {{{
-set(ISSM_SOURCES $ENV{ISSM_DIR}/src/c/solutions/issm.cpp PARENT_SCOPE)
-# }}}
-# KRIGING_SOURCES {{{
-set(KRIGING_SOURCES $ENV{ISSM_DIR}/src/c/solutions/kriging.cpp PARENT_SCOPE)
-# }}}
-# ISSMROSE_EXE_SOURCES {{{
-set(ISSMROSE_EXE_SOURCES $ENV{ISSM_DIR}/src/c/main/issm.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/analyses/CorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/analyses/CorePointerFromSolutionEnum.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/CorePointerFromSolutionEnum.cpp	(revision 16137)
@@ -23,9 +23,9 @@
 	switch(solutiontype){
 
-		case DiagnosticSolutionEnum:
-			#ifdef _HAVE_DIAGNOSTIC_
-			solutioncore=&diagnostic_core;
+		case StressbalanceSolutionEnum:
+			#ifdef _HAVE_STRESSBALANCE_
+			solutioncore=&stressbalance_core;
 			#else
-			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			_error_("ISSM was not compiled with stressbalance capabilities. Exiting");
 			#endif
 			break;
@@ -65,4 +65,11 @@
 			#endif
 			break;
+		case BalancevelocitySolutionEnum:
+			#ifdef _HAVE_BALANCED_
+			solutioncore=&balancevelocity_core;
+			#else
+			_error_("ISSM was not compiled with balanced capabilities. Exiting");
+			#endif
+			break;
 		case HydrologySolutionEnum:
 			#ifdef _HAVE_HYDROLOGY_
@@ -93,9 +100,9 @@
 			#endif
 			break;
-		case PrognosticSolutionEnum:
-			#ifdef _HAVE_PROGNOSTIC_
-			solutioncore=&prognostic_core;
+		case MasstransportSolutionEnum:
+			#ifdef _HAVE_MASSTRANSPORT_
+			solutioncore=&masstransport_core;
 			#else
-			_error_("ISSM was not compiled with prognostic capabilities. Exiting");
+			_error_("ISSM was not compiled with masstransport capabilities. Exiting");
 			#endif
 			break;
Index: /issm/trunk/src/c/analyses/DakotaSpawnCore.cpp
===================================================================
--- /issm/trunk/src/c/analyses/DakotaSpawnCore.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/DakotaSpawnCore.cpp	(revision 16137)
@@ -49,7 +49,5 @@
 
 	/*If counter==-1 on cpu0, it means that the dakota runs are done. In which case, bail out and return 0: */
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&counter,1,MPI_INT,0,IssmComm::GetComm()); 
-	#endif
+	ISSM_MPI_Bcast(&counter,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 	if(counter==-1)return 0;
 
@@ -68,5 +66,5 @@
 
 	/*Modify core inputs in objects contained in femmodel, to reflect the dakota variables inputs: */
-	InputUpdateFromDakotax(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,d_variables,d_variables_descriptors,d_numvariables);
+	InputUpdateFromDakotax(femmodel,d_variables,d_variables_descriptors,d_numvariables);
 
 	/*Determine solution sequence: */
@@ -116,9 +114,9 @@
 
 	/*numvariables: */
-	MPI_Bcast(&numvariables,1,MPI_INT,0,IssmComm::GetComm()); 
+	ISSM_MPI_Bcast(&numvariables,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	/*variables:*/
 	if(my_rank!=0)variables=xNew<double>(numvariables);
-	MPI_Bcast(variables,numvariables,MPI_DOUBLE,0,IssmComm::GetComm()); 
+	ISSM_MPI_Bcast(variables,numvariables,MPI_DOUBLE,0,IssmComm::GetComm()); 
 
 	/*variables_descriptors: */
@@ -131,12 +129,12 @@
 			string_length=(strlen(string)+1)*sizeof(char);
 		}
-		MPI_Bcast(&string_length,1,MPI_INT,0,IssmComm::GetComm()); 
+		ISSM_MPI_Bcast(&string_length,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 		if(my_rank!=0)string=xNew<char>(string_length);
-		MPI_Bcast(string,string_length,MPI_CHAR,0,IssmComm::GetComm()); 
+		ISSM_MPI_Bcast(string,string_length,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
 		if(my_rank!=0)variables_descriptors[i]=string;
 	}
 
 	/*numresponses: */
-	MPI_Bcast(&numresponses,1,MPI_INT,0,IssmComm::GetComm()); 
+	ISSM_MPI_Bcast(&numresponses,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	/*Assign output pointers:*/
Index: /issm/trunk/src/c/analyses/EnvironmentFinalize.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnvironmentFinalize.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/EnvironmentFinalize.cpp	(revision 16137)
@@ -12,17 +12,14 @@
 void EnvironmentFinalize(void){
 
-	#ifdef _HAVE_MPI_
+	int my_rank;
 
 	/*Make sure we are all here*/
-	MPI_Barrier(MPI_COMM_WORLD);
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD);
 
 	/*Print closing statement*/
-	int my_rank;
-	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
+	ISSM_MPI_Comm_rank(ISSM_MPI_COMM_WORLD,&my_rank);
 	if(!my_rank) printf("closing MPI\n");
 
 	/*Finalize: */
-	MPI_Finalize();
-
-	#endif
+	ISSM_MPI_Finalize();
 }
Index: /issm/trunk/src/c/analyses/EnvironmentInit.cpp
===================================================================
--- /issm/trunk/src/c/analyses/EnvironmentInit.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/EnvironmentInit.cpp	(revision 16137)
@@ -10,13 +10,13 @@
 #include "../toolkits/toolkits.h"
 
-COMM EnvironmentInit(int argc,char** argv){
+ISSM_MPI_Comm EnvironmentInit(int argc,char** argv){
 
 	/*Output*/
-	COMM comm = 0;
+	ISSM_MPI_Comm comm = 0;
 
 	/*Initialize MPI environment: */
 	#if defined(_HAVE_MPI_)
-	MPI_Init(&argc,&argv);
-	comm = MPI_COMM_WORLD;
+	ISSM_MPI_Init(&argc,&argv);
+	comm = ISSM_MPI_COMM_WORLD;
 	#else
 	comm = 1; //bogus number for comm, which does not exist anyway.
@@ -25,7 +25,5 @@
 	/*Print Banner*/
 	int my_rank = 0;
-	#ifdef _HAVE_MPI_
-	MPI_Comm_rank(comm,&my_rank);
-	#endif
+	ISSM_MPI_Comm_rank(comm,&my_rank);
 	if(!my_rank) printf("\n");
 	if(!my_rank) printf("Ice Sheet System Model (%s) version  %s\n",PACKAGE_NAME,PACKAGE_VERSION);
Index: /issm/trunk/src/c/analyses/ResetBoundaryConditions.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ResetBoundaryConditions.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/ResetBoundaryConditions.cpp	(revision 16137)
@@ -22,5 +22,5 @@
 
 	/*retrieve boundary conditions from element inputs :*/
-	GetSolutionFromInputsx( &yg, femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials,  femmodel->parameters);
+	GetSolutionFromInputsx(&yg,femmodel);
 
 	/*update spcs using this new vector of constraints: */
Index: /issm/trunk/src/c/analyses/ad_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/ad_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/ad_core.cpp	(revision 16137)
@@ -24,6 +24,6 @@
 	int     i;
 	int     dummy;
-	int     num_dependents;
-	int     num_independents;
+	int     num_dependents=0;
+	int     num_independents=0;
 	bool    isautodiff       = false;
 	char   *driver           = NULL;
@@ -33,4 +33,6 @@
 	IssmDouble *axp = NULL;
 	double     *xp  = NULL;
+	int my_rank=IssmComm::GetRank();
+
 
 	/*AD mode on?: */
@@ -45,7 +47,9 @@
 
 			/*preliminary checks: */
-			femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
-			femmodel->parameters->FindParam(&num_independents,AutodiffNumIndependentsEnum);
-			if(!(num_dependents*num_independents)) return;
+			if (my_rank==0) {
+				femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
+				femmodel->parameters->FindParam(&num_independents,AutodiffNumIndependentsEnum);
+				if(!(num_dependents*num_independents)) return;
+			}
 
 			if(VerboseAutodiff())_printf0_("   start ad core\n");
@@ -89,5 +93,7 @@
 
 				/*set the forward method function pointer: */
+#ifdef _HAVE_GSL_
 				anEDF_for_solverx_p->fos_forward=EDF_fos_forward_for_solverx;
+#endif
 
 				/*allocate the space for the parameters to invoke the EDF fos_forward:*/
@@ -96,5 +102,5 @@
 
 				/*call driver: */
-				fos_forward(1,num_dependents,num_independents, 0, xp, tangentDir, theOutput, jacTimesTangentDir );
+				fos_forward(my_rank,num_dependents,num_independents, 0, xp, tangentDir, theOutput, jacTimesTangentDir );
 
 				/*add to results*/
@@ -133,5 +139,7 @@
 
 				/*set the forward method function pointers: */
+#ifdef _HAVE_GSL_
 				anEDF_for_solverx_p->fov_forward=EDF_fov_forward_for_solverx;
+#endif
 				// anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
 
@@ -162,5 +170,5 @@
 
 				/*call driver: */
-				fov_forward(1,num_dependents,num_independents, tangentDirNum, xp, seed, theOutput, jacTimesSeed );
+				fov_forward(my_rank,num_dependents,num_independents, tangentDirNum, xp, seed, theOutput, jacTimesSeed );
 				/*Free resources: */
 				xDelete(theOutput);
@@ -183,14 +191,18 @@
 				/*retrieve direction index: */
 				femmodel->parameters->FindParam(&aDepIndex,AutodiffFosReverseIndexEnum);
-
-				if (aDepIndex<0 || aDepIndex>=num_dependents) _error_("index value for AutodiffFosReverseIndexEnum should be in [0,num_dependents-1]");
-
 				aWeightVector=xNewZeroInit<double>(num_dependents);
-				aWeightVector[aDepIndex]=1.0;
-
+				if (my_rank==0) {
+					if (aDepIndex<0 || aDepIndex>=num_dependents) _error_("index value for AutodiffFosReverseIndexEnum should be in [0,num_dependents-1]");
+					aWeightVector[aDepIndex]=1.0;
+				}
 				weightVectorTimesJac=xNew<double>(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
 
 				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
@@ -199,5 +211,6 @@
 
 				/*call driver: */
-				fos_reverse(1,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
+				fos_reverse(my_rank,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
+				if(VerboseAutodiff())_printf_("   done with fos_reverse\n");
 
 				/*add to results*/
@@ -234,5 +247,7 @@
 
 				/*set the forward method function pointers: */
+#ifdef _HAVE_GSL_
 				anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
+#endif
 
 				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
@@ -259,5 +274,5 @@
 
 				/*call driver: */
-				fov_reverse(1,num_dependents,num_independents, weightNum, weights, weightsTimesJac );
+				fov_reverse(my_rank,num_dependents,num_independents, weightNum, weights, weightsTimesJac );
 
 				/*add to results: */
@@ -284,5 +299,5 @@
 
 			/*Print statistics:*/
-			tapestats(1,tape_stats); //reading of tape statistics
+			tapestats(my_rank,tape_stats); //reading of tape statistics
 			if(VerboseAutodiff()){
 				_printf0_("   ADOLC statistics: \n");
Index: /issm/trunk/src/c/analyses/adjointbalancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/adjointbalancethickness_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/adjointbalancethickness_core.cpp	(revision 16137)
@@ -24,5 +24,5 @@
 
 	/*Call SurfaceAreax, because some it might be needed by PVector*/
-	SurfaceAreax(NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	SurfaceAreax(NULL,femmodel);
 
 	/*compute adjoint*/
@@ -34,5 +34,5 @@
 	if(save_results){
 		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,AdjointEnum);
+		InputToResultx(femmodel,AdjointEnum);
 	}
 }
Index: sm/trunk/src/c/analyses/adjointdiagnostic_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/adjointdiagnostic_core.cpp	(revision 16136)
+++ 	(revision )
@@ -1,46 +1,0 @@
-/*!\file:  adjointdiagnostic_core.cpp
- * \brief compute inverse method adjoint state
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void adjointdiagnostic_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool isstokes;
-	bool save_results;
-	bool conserve_loads   = true;
-
-	/*retrieve parameters:*/
-	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-
-	/*Compute velocities*/
-	if(VerboseSolution()) _printf0_("   computing velocities\n");
-	femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
-	solutionsequence_nonlinear(femmodel,conserve_loads); 
-
-	/*Call SurfaceAreax, because some it might be needed by PVector*/
-	SurfaceAreax(NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-
-	/*Compute adjoint*/
-	if(VerboseSolution()) _printf0_("   computing adjoint\n");
-	femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum,AdjointHorizAnalysisEnum);
-	solutionsequence_adjoint_linear(femmodel);
-
-	/*Save results*/
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,AdjointxEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,AdjointyEnum);
-		if (isstokes){
-			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,AdjointzEnum);
-			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,AdjointpEnum);
-		}
-	}
-}
Index: /issm/trunk/src/c/analyses/adjointstressbalance_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/adjointstressbalance_core.cpp	(revision 16137)
+++ /issm/trunk/src/c/analyses/adjointstressbalance_core.cpp	(revision 16137)
@@ -0,0 +1,46 @@
+/*!\file:  adjointstressbalance_core.cpp
+ * \brief compute inverse method adjoint state
+ */ 
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void adjointstressbalance_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool isFS;
+	bool save_results;
+	bool conserve_loads   = true;
+
+	/*retrieve parameters:*/
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	/*Compute velocities*/
+	if(VerboseSolution()) _printf0_("   computing velocities\n");
+	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+	solutionsequence_nonlinear(femmodel,conserve_loads); 
+
+	/*Call SurfaceAreax, because some it might be needed by PVector*/
+	SurfaceAreax(NULL,femmodel);
+
+	/*Compute adjoint*/
+	if(VerboseSolution()) _printf0_("   computing adjoint\n");
+	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum,AdjointHorizAnalysisEnum);
+	solutionsequence_adjoint_linear(femmodel);
+
+	/*Save results*/
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		InputToResultx(femmodel,AdjointxEnum);
+		InputToResultx(femmodel,AdjointyEnum);
+		if (isFS){
+			InputToResultx(femmodel,AdjointzEnum);
+			InputToResultx(femmodel,AdjointpEnum);
+		}
+	}
+}
Index: /issm/trunk/src/c/analyses/analyses.h
===================================================================
--- /issm/trunk/src/c/analyses/analyses.h	(revision 16136)
+++ /issm/trunk/src/c/analyses/analyses.h	(revision 16137)
@@ -13,12 +13,12 @@
 template <class doubletype> class Vector;
 
-#include "../shared/io/Comm/Comm.h"
+#include "../shared/io/Comm/IssmComm.h"
 #include "../shared/Numerics/types.h"
 
 /*cores: */
-void adjointdiagnostic_core(FemModel* femmodel);
+void adjointstressbalance_core(FemModel* femmodel);
 void adjointbalancethickness_core(FemModel* femmodel);
 void gradient_core(FemModel* femmodel,int n=0,bool orthogonalize=false);
-void diagnostic_core(FemModel* femmodel);
+void stressbalance_core(FemModel* femmodel);
 void hydrology_core(FemModel* femmodel);
 void thermal_core(FemModel* femmodel);
@@ -28,6 +28,7 @@
 void control_core(FemModel* femmodel);
 void controltao_core(FemModel* femmodel);
-void prognostic_core(FemModel* femmodel);
+void masstransport_core(FemModel* femmodel);
 void balancethickness_core(FemModel* femmodel);
+void balancevelocity_core(FemModel* femmodel);
 void slopecompute_core(FemModel* femmodel);
 void steadystate_core(FemModel* femmodel);
@@ -46,5 +47,5 @@
 void WriteLockFile(char* filename);
 void ResetBoundaryConditions(FemModel* femmodel, int analysis_type);
-COMM EnvironmentInit(int argc,char** argv);
+ISSM_MPI_Comm EnvironmentInit(int argc,char** argv);
 void EnvironmentFinalize(void);
 void PrintBanner(void);
Index: /issm/trunk/src/c/analyses/balancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/balancethickness_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/balancethickness_core.cpp	(revision 16137)
@@ -26,5 +26,5 @@
 	if(save_results){
 		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ThicknessEnum);
+		InputToResultx(femmodel,ThicknessEnum);
 	}
 
Index: /issm/trunk/src/c/analyses/balancevelocity_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/balancevelocity_core.cpp	(revision 16137)
+++ /issm/trunk/src/c/analyses/balancevelocity_core.cpp	(revision 16137)
@@ -0,0 +1,39 @@
+/*!\file: balancevelocity_core.cpp
+ * \brief: core of the balancevelocity solution 
+ */ 
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void balancevelocity_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool save_results;
+
+
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+
+	if(VerboseSolution()) _printf0_("computing smoothed slopes:\n");
+	femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SmoothedSurfaceSlopeXAnalysisEnum);
+	solutionsequence_linear(femmodel);
+	femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SmoothedSurfaceSlopeYAnalysisEnum);
+	solutionsequence_linear(femmodel);
+	//surfaceslope_core(femmodel);
+
+	if(VerboseSolution()) _printf0_("call computational core:\n");
+	femmodel->SetCurrentConfiguration(BalancevelocityAnalysisEnum);
+	solutionsequence_linear(femmodel);
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		InputToResultx(femmodel,SurfaceSlopeXEnum);
+		InputToResultx(femmodel,SurfaceSlopeYEnum);
+		InputToResultx(femmodel,VelEnum);
+	}
+
+}
Index: /issm/trunk/src/c/analyses/bedslope_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/bedslope_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/bedslope_core.cpp	(revision 16137)
@@ -28,6 +28,6 @@
 	if(save_results){
 		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BedSlopeXEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BedSlopeYEnum);
+		InputToResultx(femmodel,BedSlopeXEnum);
+		InputToResultx(femmodel,BedSlopeYEnum);
 	}
 
Index: /issm/trunk/src/c/analyses/control_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/control_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/control_core.cpp	(revision 16137)
@@ -24,5 +24,5 @@
 	int        dim;
 	int        solution_type;
-	bool       isstokes;
+	bool       isFS;
 	bool       dakota_analysis = false;
 
@@ -34,5 +34,5 @@
 
 	/*intermediary: */
-	IssmDouble search_scalar = 1;
+	IssmDouble search_scalar = 1.;
 	OptArgs    optargs;
 	OptPars    optpars;
@@ -57,5 +57,5 @@
 	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
 	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
 	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
 	femmodel->parameters->SetParam(false,SaveResultsEnum);
@@ -67,5 +67,5 @@
 	/*Launch once a complete solution to set up all inputs*/
 	if(VerboseControl()) _printf0_("   preparing initial solution\n");
-	if(isstokes) solutioncore(femmodel);
+	if(isFS) solutioncore(femmodel);
 
 	/*Initialize responses: */
@@ -90,9 +90,9 @@
 		if(VerboseControl()) _printf0_("   compute adjoint state:\n");
 		adjointcore(femmodel);
-		gradient_core(femmodel,n,search_scalar==0);
+		gradient_core(femmodel,n,search_scalar==0.);
 
 		/*Return gradient if asked: */
 		if (cm_gradient){
-			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,GradientEnum);
+			InputToResultx(femmodel,GradientEnum);
 			goto cleanup_and_return;
 		}
@@ -112,7 +112,7 @@
 	solutioncore(femmodel);
 
-	/*some results not computed by steadystate_core or diagnostic_core: */
+	/*some results not computed by steadystate_core or stressbalance_core: */
 	if(!dakota_analysis){ //do not save this if we are running the control core from a qmu run!
-		for(i=0;i<num_controls;i++) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,control_type[i]);
+		for(i=0;i<num_controls;i++) InputToResultx(femmodel,control_type[i]);
 
 		#ifdef _HAVE_ADOLC_
Index: /issm/trunk/src/c/analyses/controltao_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/controltao_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/controltao_core.cpp	(revision 16137)
@@ -32,4 +32,5 @@
 	int                *control_list = NULL;
 	Vector<IssmDouble> *X            = NULL;
+	Vector<IssmDouble> *G            = NULL;
 	Vector<IssmDouble> *XL           = NULL;
 	Vector<IssmDouble> *XU           = NULL;
@@ -83,7 +84,10 @@
 	TaoView(tao,PETSC_VIEWER_STDOUT_WORLD);
 	TaoGetSolutionVector(tao,&X->pvector->vector);
+	G=new Vector<IssmDouble>(0); VecFree(&G->pvector->vector);
+	TaoGetGradientVector(tao,&G->pvector->vector);
 	SetControlInputsFromVectorx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,X);
+	ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
 	for(int i=0;i<num_controls;i++){
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,control_list[i]);
+		InputToResultx(femmodel,control_list[i]);
 	}
 	femmodel->results->AddObject(new GenericExternalResult<double*>(femmodel->results->Size()+1,JEnum,user.J,maxiter+3,1,1,0));
Index: /issm/trunk/src/c/analyses/dakota_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/dakota_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/dakota_core.cpp	(revision 16137)
@@ -14,5 +14,5 @@
  *
  * Now, how does CPU 0 drive all other CPUS to carry out sensitivity analysese? By synchronizing its call to 
- * our ISSM cores (diagnostic_core, thermal_core, transient_core, etc ...) on CPU 0 with all other CPUS. 
+ * our ISSM cores (stressbalance_core, thermal_core, transient_core, etc ...) on CPU 0 with all other CPUS. 
  * This explains the structure of qmu.cpp, where cpu 0 runs Dakota, the Dakota pluggin fires up DakotaSpawnCore.cpp, 
  * while the other CPUS are waiting for a broadcast from CPU0, once they get it, they also fire up 
@@ -177,6 +177,9 @@
 		// Instantiate/initialize the parallel library and problem description
 		// database objects.
-		Dakota::ParallelLibrary parallel_lib("serial"); //use our own ISSM Dakota library mode constructor, which only fires up Dakota on CPU 0. 
+		char* dakotamode=xNew<char>(strlen("serial")+1);
+		xMemCpy<char>(dakotamode,"serial",strlen("serial")+1);
+		Dakota::ParallelLibrary parallel_lib(dakotamode); //use our own ISSM Dakota library mode constructor, which only fires up Dakota on CPU 0. 
 		Dakota::ProblemDescDB problem_db(parallel_lib); 
+		xDelete<char>(dakotamode);
 
 		// Manage input file parsing, output redirection, and restart processing
Index: sm/trunk/src/c/analyses/diagnostic_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/diagnostic_core.cpp	(revision 16136)
+++ 	(revision )
@@ -1,108 +1,0 @@
-/*!\file: diagnostic_core.cpp
- * \brief: core of the diagnostic solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void diagnostic_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool  dakota_analysis   = false;
-	int   dim               = -1;
-	bool  ishutter          = false;
-	bool  ismacayealpattyn  = false;
-	bool  isl1l2            = false;
-	bool  isstokes          = false;
-	bool  conserve_loads    = true;
-	bool  modify_loads      = true;
-	bool  save_results;
-	int   newton;
-	int   solution_type;
-	int   numoutputs        = 0;
-	int  *requested_outputs = NULL;
-
-	/* recover parameters:*/
-	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
-	femmodel->parameters->FindParam(&ishutter,FlowequationIshutterEnum);
-	femmodel->parameters->FindParam(&ismacayealpattyn,FlowequationIsmacayealpattynEnum);
-	femmodel->parameters->FindParam(&isl1l2,FlowequationIsl1l2Enum);
-	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
-	femmodel->parameters->FindParam(&newton,DiagnosticIsnewtonEnum);
-	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-	femmodel->parameters->FindParam(&numoutputs,DiagnosticNumRequestedOutputsEnum);
-	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,DiagnosticRequestedOutputsEnum);
-
-	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
-	if(dakota_analysis && solution_type==DiagnosticSolutionEnum){
-		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVxEnum,VxEnum);
-		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVyEnum,VyEnum);
-		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVzEnum,VzEnum);
-		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuPressureEnum,PressureEnum);
-	}
-
-	/*Compute slopes: */
-	if(ishutter) surfaceslope_core(femmodel);
-	if(isstokes){
-		bedslope_core(femmodel);
-		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
-		ResetCoordinateSystemx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-	}
-
-	if(ishutter){
-
-		if(VerboseSolution()) _printf0_("   computing hutter velocities\n");
-
-		//Take the last velocity into account so that the velocity on the MacAyeal domain is not zero
-		if (ismacayealpattyn) ResetBoundaryConditions(femmodel,DiagnosticHutterAnalysisEnum);
-
-		femmodel->SetCurrentConfiguration(DiagnosticHutterAnalysisEnum);
-		solutionsequence_linear(femmodel);
-
-		if (ismacayealpattyn) ResetBoundaryConditions(femmodel,DiagnosticHorizAnalysisEnum);
-	}
-
-	if ((ismacayealpattyn || isl1l2) ^ isstokes){ // ^ = xor
-
-		if(VerboseSolution()) _printf0_("   computing velocities\n");
-		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
-		if(newton>0)
-		 solutionsequence_newton(femmodel);
-		else
-		 solutionsequence_nonlinear(femmodel,conserve_loads); 
-	}
-
-	if (ismacayealpattyn && isstokes){
-
-		if(VerboseSolution()) _printf0_("   computing coupling macayealpattyn and stokes velocities and pressure \n");
-		solutionsequence_stokescoupling_nonlinear(femmodel,conserve_loads);
-	}
-
-	if (dim==3 & (ishutter || ismacayealpattyn)){
-
-		if(VerboseSolution()) _printf0_("   computing vertical velocities\n");
-		femmodel->SetCurrentConfiguration(DiagnosticVertAnalysisEnum);
-		solutionsequence_linear(femmodel);
-	}
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VxEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VyEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VelEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,PressureEnum);
-		if(dim==3) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VzEnum);
-		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
-	}
-
-	if(solution_type==DiagnosticSolutionEnum)femmodel->RequestedDependentsx();
-
-	/*Free ressources:*/
-	xDelete<int>(requested_outputs);
-}
Index: /issm/trunk/src/c/analyses/enthalpy_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/enthalpy_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/enthalpy_core.cpp	(revision 16137)
@@ -27,7 +27,7 @@
 	if(save_results){
 		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,TemperatureEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EnthalpyEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,WaterfractionEnum);
+		InputToResultx(femmodel,TemperatureEnum);
+		InputToResultx(femmodel,EnthalpyEnum);
+		InputToResultx(femmodel,WaterfractionEnum);
 	}
 }
Index: /issm/trunk/src/c/analyses/gia_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/gia_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/gia_core.cpp	(revision 16137)
@@ -46,11 +46,11 @@
 	dwdtg->Assemble();
 
-	InputUpdateFromVectorx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,wg,GiaWEnum,VertexSIdEnum);
-	InputUpdateFromVectorx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,dwdtg,GiadWdtEnum,VertexSIdEnum);
+	InputUpdateFromVectorx(femmodel,wg,GiaWEnum,VertexSIdEnum);
+	InputUpdateFromVectorx(femmodel,dwdtg,GiadWdtEnum,VertexSIdEnum);
 
 	if(save_results){
 		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,GiaWEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,GiadWdtEnum);
+		InputToResultx(femmodel,GiaWEnum);
+		InputToResultx(femmodel,GiadWdtEnum);
 	}
 
Index: /issm/trunk/src/c/analyses/hydrology_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/hydrology_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/hydrology_core.cpp	(revision 16137)
@@ -68,7 +68,7 @@
 			if(save_results && ((i+1)%output_frequency==0 || (i+1)==nsteps)){
 				if(VerboseSolution()) _printf0_("   saving results \n");
-				InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,WatercolumnEnum);
-				InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologyWaterVxEnum);
-				InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologyWaterVyEnum);
+				InputToResultx(femmodel,WatercolumnEnum);
+				InputToResultx(femmodel,HydrologyWaterVxEnum);
+				InputToResultx(femmodel,HydrologyWaterVyEnum);
 
 				/*unload results*/
@@ -89,9 +89,9 @@
 			if(save_results && ((i+1)%output_frequency==0 || (i+1)==nsteps)){
 				if(VerboseSolution()) _printf0_("   saving results \n");
-				InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SedimentHeadEnum);
-				InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SedimentHeadResidualEnum);
+				InputToResultx(femmodel,SedimentHeadEnum);
+				InputToResultx(femmodel,SedimentHeadResidualEnum);
 				if(isefficientlayer){
-					InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EplHeadEnum);
-					InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologydcMaskEplactiveEnum);
+					InputToResultx(femmodel,EplHeadEnum);
+					InputToResultx(femmodel,HydrologydcMaskEplactiveEnum);
 				}
 				/*unload results*/
Index: /issm/trunk/src/c/analyses/masstransport_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/masstransport_core.cpp	(revision 16137)
+++ /issm/trunk/src/c/analyses/masstransport_core.cpp	(revision 16137)
@@ -0,0 +1,72 @@
+/*!\file: masstransport_core.cpp
+ * \brief: core of the masstransport solution 
+ */ 
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void masstransport_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool  save_results;
+	bool  issmbgradients,ispdd,isdelta18o,isFS,isfreesurface;
+	int   solution_type;
+	int  *requested_outputs = NULL;
+	int   numoutputs        = 0;
+
+	/*activate configuration*/
+	femmodel->SetCurrentConfiguration(MasstransportAnalysisEnum);
+
+	/*recover parameters: */
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&issmbgradients,SurfaceforcingsIssmbgradientsEnum);
+	femmodel->parameters->FindParam(&ispdd,SurfaceforcingsIspddEnum);
+	femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&isfreesurface,MasstransportIsfreesurfaceEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&numoutputs,MasstransportNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,MasstransportRequestedOutputsEnum);
+
+	if(issmbgradients){
+	  if(VerboseSolution())_printf_("	call smb gradients module\n\n");
+	  SmbGradientsx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+	if(ispdd){
+		if(isdelta18o){
+			if(VerboseSolution()) _printf0_("   call Delta18oParametrization module\n");
+			Delta18oParameterizationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		} 
+		if(VerboseSolution()) _printf0_("   call positive degree day module\n");
+		PositiveDegreeDayx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+
+	if(isFS && isfreesurface){
+		if(VerboseSolution()) _printf0_("   call free surface computational core\n");
+		femmodel->SetCurrentConfiguration(FreeSurfaceBaseAnalysisEnum);
+		solutionsequence_linear(femmodel);
+		femmodel->SetCurrentConfiguration(FreeSurfaceTopAnalysisEnum);
+		solutionsequence_linear(femmodel);
+	}
+	else{
+		if(VerboseSolution()) _printf0_("   call computational core\n");
+		solutionsequence_linear(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		InputToResultx(femmodel,ThicknessEnum);
+		InputToResultx(femmodel,BedEnum);
+		InputToResultx(femmodel,SurfaceEnum);
+		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
+	}
+
+	if(solution_type==MasstransportSolutionEnum)femmodel->RequestedDependentsx();
+
+	/*Free ressources:*/
+	xDelete<int>(requested_outputs);
+}
Index: /issm/trunk/src/c/analyses/objectivefunction.cpp
===================================================================
--- /issm/trunk/src/c/analyses/objectivefunction.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/objectivefunction.cpp	(revision 16137)
@@ -24,5 +24,5 @@
 	/*parameters: */
 	int        solution_type,analysis_type;
-	bool       isstokes       = false;
+	bool       isFS       = false;
 	bool       conserve_loads = true;
 	FemModel  *femmodel       = NULL;
@@ -32,11 +32,11 @@
 
 	/*Recover parameters: */
-	femmodel->parameters->FindParam(&isstokes,FlowequationIsstokesEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
 	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
 
 	/*set analysis type to compute velocity: */
-	if (solution_type==SteadystateSolutionEnum || solution_type==DiagnosticSolutionEnum){
-		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
+	if (solution_type==SteadystateSolutionEnum || solution_type==StressbalanceSolutionEnum){
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
 	}
 	else if (solution_type==BalancethicknessSolutionEnum){
@@ -53,9 +53,9 @@
 	InputControlUpdatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,search_scalar,false);
 
-	/*Run diagnostic with updated inputs: */
+	/*Run stressbalance with updated inputs: */
 	if (solution_type==SteadystateSolutionEnum){
-		diagnostic_core(femmodel);	//We need a 3D velocity!! (vz is required for the next thermal run)
+		stressbalance_core(femmodel);	//We need a 3D velocity!! (vz is required for the next thermal run)
 	}
-	else if (solution_type==DiagnosticSolutionEnum){
+	else if (solution_type==StressbalanceSolutionEnum){
 		solutionsequence_nonlinear(femmodel,conserve_loads); 
 	}
Index: sm/trunk/src/c/analyses/prognostic_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/prognostic_core.cpp	(revision 16136)
+++ 	(revision )
@@ -1,58 +1,0 @@
-/*!\file: prognostic_core.cpp
- * \brief: core of the prognostic solution 
- */ 
-
-#include "./analyses.h"
-#include "../toolkits/toolkits.h"
-#include "../classes/classes.h"
-#include "../shared/shared.h"
-#include "../modules/modules.h"
-#include "../solutionsequences/solutionsequences.h"
-
-void prognostic_core(FemModel* femmodel){
-
-	/*parameters: */
-	bool save_results;
-	bool issmbgradients,ispdd,isdelta18o;
-	int  solution_type;
-	int  *requested_outputs = NULL;
-	int  numoutputs=0;
-
-	/*activate formulation: */
-	femmodel->SetCurrentConfiguration(PrognosticAnalysisEnum);
-
-	/*recover parameters: */
-	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
-	femmodel->parameters->FindParam(&issmbgradients,SurfaceforcingsIssmbgradientsEnum);
-	femmodel->parameters->FindParam(&ispdd,SurfaceforcingsIspddEnum);
-	femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
-	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
-	femmodel->parameters->FindParam(&numoutputs,PrognosticNumRequestedOutputsEnum);
-	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,PrognosticRequestedOutputsEnum);
-
-	if(issmbgradients){
-	  if(VerboseSolution())_printf_("	call smb gradients module\n\n");
-	  SmbGradientsx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-	}
-	if(ispdd){
-		if(isdelta18o){
-			if(VerboseSolution()) _printf0_("   call Delta18oParametrization module\n");
-			Delta18oParameterizationx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-		} 
-		if(VerboseSolution()) _printf0_("   call positive degree day module\n");
-		PositiveDegreeDayx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-	}
-	if(VerboseSolution()) _printf0_("   call computational core\n");
-	solutionsequence_linear(femmodel);
-
-	if(save_results){
-		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ThicknessEnum);
-		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
-	}
-
-	if(solution_type==PrognosticSolutionEnum)femmodel->RequestedDependentsx();
-
-	/*Free ressources:*/
-	xDelete<int>(requested_outputs);
-}
Index: /issm/trunk/src/c/analyses/steadystate_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/steadystate_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/steadystate_core.cpp	(revision 16137)
@@ -53,9 +53,9 @@
 			thermal_core(femmodel);
 			femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
-			GetSolutionFromInputsx(&tg,femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+			GetSolutionFromInputsx(&tg,femmodel);
 		}
 		else{
 			enthalpy_core(femmodel);
-			GetSolutionFromInputsx(&tg,femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+			GetSolutionFromInputsx(&tg,femmodel);
 		}
 		#else
@@ -64,6 +64,6 @@
 
 		if(VerboseSolution()) _printf0_("   computing new velocity\n");
-		diagnostic_core(femmodel);
-		GetSolutionFromInputsx(&ug,femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+		stressbalance_core(femmodel);
+		GetSolutionFromInputsx(&ug,femmodel);
 
 		if(step>1){
@@ -84,17 +84,21 @@
 	if(save_results){
 		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VxEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VyEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VzEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VelEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,PressureEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,TemperatureEnum);
-		if(isenthalpy) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,WaterfractionEnum);
-		if(isenthalpy) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EnthalpyEnum);
-		if(!isenthalpy) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BasalforcingsMeltingRateEnum);
+		InputToResultx(femmodel,VxEnum);
+		InputToResultx(femmodel,VyEnum);
+		InputToResultx(femmodel,VzEnum);
+		InputToResultx(femmodel,VelEnum);
+		InputToResultx(femmodel,PressureEnum);
+		InputToResultx(femmodel,TemperatureEnum);
+		if(isenthalpy)  InputToResultx(femmodel,WaterfractionEnum);
+		if(isenthalpy)  InputToResultx(femmodel,EnthalpyEnum);
+        	if(isenthalpy)  InputToResultx(femmodel,WatercolumnEnum);
+		//if(!isenthalpy) InputToResultx(femmodel,BasalforcingsMeltingRateEnum);
+        	InputToResultx(femmodel,BasalforcingsMeltingRateEnum);
 		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
 	}
 
 	/*Free ressources:*/
+	delete tg_old;
+	delete ug_old;
 	delete tg;
 	delete ug;
Index: /issm/trunk/src/c/analyses/stressbalance_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/stressbalance_core.cpp	(revision 16137)
+++ /issm/trunk/src/c/analyses/stressbalance_core.cpp	(revision 16137)
@@ -0,0 +1,100 @@
+/*!\file: stressbalance_core.cpp
+ * \brief: core of the stressbalance solution 
+ */ 
+
+#include "./analyses.h"
+#include "../toolkits/toolkits.h"
+#include "../classes/classes.h"
+#include "../shared/shared.h"
+#include "../modules/modules.h"
+#include "../solutionsequences/solutionsequences.h"
+
+void stressbalance_core(FemModel* femmodel){
+
+	/*parameters: */
+	bool  dakota_analysis;
+	int   dim;
+	bool  isSIA,isSSA,isL1L2,isHO,isFS;
+	bool  conserve_loads    = true;
+	bool  save_results;
+	int   newton;
+	int   solution_type;
+	int   numoutputs        = 0;
+	int  *requested_outputs = NULL;
+
+	/* recover parameters:*/
+	femmodel->parameters->FindParam(&dim,MeshDimensionEnum);
+	femmodel->parameters->FindParam(&isSIA,FlowequationIsSIAEnum);
+	femmodel->parameters->FindParam(&isSSA,FlowequationIsSSAEnum);
+	femmodel->parameters->FindParam(&isL1L2,FlowequationIsL1L2Enum);
+	femmodel->parameters->FindParam(&isHO,FlowequationIsHOEnum);
+	femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
+	femmodel->parameters->FindParam(&newton,StressbalanceIsnewtonEnum);
+	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&numoutputs,StressbalanceNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,StressbalanceRequestedOutputsEnum);
+
+	/*for qmu analysis, reinitialize velocity so that fake sensitivities do not show up as a result of a different restart of the convergence at each trial.*/
+	if(dakota_analysis && solution_type==StressbalanceSolutionEnum){
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVxEnum,VxEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVyEnum,VyEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVzEnum,VzEnum);
+		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuPressureEnum,PressureEnum);
+	}
+
+	/*Compute slopes: */
+	if(isSIA) surfaceslope_core(femmodel);
+	if(isFS){
+		bedslope_core(femmodel);
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+		ResetCoordinateSystemx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	}
+
+	if(isSIA){
+		if(VerboseSolution()) _printf0_("   computing SIA velocities\n");
+
+		/*Take the last velocity into account so that the velocity on the SSA domain is not zero*/
+		if(isSSA || isL1L2 || isHO ) ResetBoundaryConditions(femmodel,StressbalanceSIAAnalysisEnum);
+		femmodel->SetCurrentConfiguration(StressbalanceSIAAnalysisEnum);
+		solutionsequence_linear(femmodel);
+		if(isSSA || isL1L2 || isHO) ResetBoundaryConditions(femmodel,StressbalanceAnalysisEnum);
+	}
+
+	if ((isSSA || isHO || isL1L2) ^ isFS){ // ^ = xor
+		if(VerboseSolution()) _printf0_("   computing velocities\n");
+
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+		if(newton>0)
+		 solutionsequence_newton(femmodel);
+		else
+		 solutionsequence_nonlinear(femmodel,conserve_loads); 
+	}
+
+	if ((isSSA || isL1L2 || isHO) && isFS){
+		if(VerboseSolution()) _printf0_("   computing coupling betweem lower order models and full-FS\n");
+		solutionsequence_FScoupling_nonlinear(femmodel,conserve_loads);
+	}
+
+	if (dim==3 & (isSIA || isSSA || isL1L2 || isHO)){
+		if(VerboseSolution()) _printf0_("   computing vertical velocities\n");
+		femmodel->SetCurrentConfiguration(StressbalanceVerticalAnalysisEnum);
+		solutionsequence_linear(femmodel);
+	}
+
+	if(save_results){
+		if(VerboseSolution()) _printf0_("   saving results\n");
+		InputToResultx(femmodel,VxEnum);
+		InputToResultx(femmodel,VyEnum);
+		InputToResultx(femmodel,VelEnum);
+		InputToResultx(femmodel,PressureEnum);
+		if(dim==3) InputToResultx(femmodel,VzEnum);
+		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
+	}
+
+	if(solution_type==StressbalanceSolutionEnum)femmodel->RequestedDependentsx();
+
+	/*Free ressources:*/
+	xDelete<int>(requested_outputs);
+}
Index: /issm/trunk/src/c/analyses/surfaceslope_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/surfaceslope_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/surfaceslope_core.cpp	(revision 16137)
@@ -28,6 +28,6 @@
 	if(save_results){
 		if(VerboseSolution()) _printf0_("saving results:\n");
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceSlopeXEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceSlopeYEnum);
+		InputToResultx(femmodel,SurfaceSlopeXEnum);
+		InputToResultx(femmodel,SurfaceSlopeYEnum);
 	}
 
Index: /issm/trunk/src/c/analyses/thermal_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/thermal_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/thermal_core.cpp	(revision 16137)
@@ -24,6 +24,9 @@
 	if(dakota_analysis && solution_type!=TransientSolutionEnum){
 		femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
-		ResetConstraintsx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		ResetConstraintsx(femmodel);
 	}
+
+	if(VerboseSolution()) _printf0_("   setting basal Dirichlet boundary conditions\n");
+	femmodel->UpdateThermalBasalConstraintsx();
 
 	if(VerboseSolution()) _printf0_("   computing temperatures\n");
@@ -37,6 +40,6 @@
 	if(save_results){
 		if(VerboseSolution()) _printf0_("   saving results\n");
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,TemperatureEnum);
-		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BasalforcingsMeltingRateEnum);
+		InputToResultx(femmodel,TemperatureEnum);
+		InputToResultx(femmodel,BasalforcingsMeltingRateEnum);
 	}
 }
Index: /issm/trunk/src/c/analyses/transient_core.cpp
===================================================================
--- /issm/trunk/src/c/analyses/transient_core.cpp	(revision 16136)
+++ /issm/trunk/src/c/analyses/transient_core.cpp	(revision 16137)
@@ -21,5 +21,5 @@
 	/*parameters: */
 	IssmDouble starttime,finaltime,dt,yts;
-	bool   isdiagnostic,isprognostic,isthermal,isgroundingline,isenthalpy,isdelta18o,isgia;
+	bool   isstressbalance,ismasstransport,isthermal,isgroundingline,isenthalpy,isdelta18o,isgia;
 	bool   save_results,dakota_analysis;
 	bool   time_adapt=false;
@@ -42,6 +42,6 @@
 	femmodel->parameters->FindParam(&output_frequency,SettingsOutputFrequencyEnum);
 	femmodel->parameters->FindParam(&time_adapt,TimesteppingTimeAdaptEnum);
-	femmodel->parameters->FindParam(&isdiagnostic,TransientIsdiagnosticEnum);
-	femmodel->parameters->FindParam(&isprognostic,TransientIsprognosticEnum);
+	femmodel->parameters->FindParam(&isstressbalance,TransientIsstressbalanceEnum);
+	femmodel->parameters->FindParam(&ismasstransport,TransientIsmasstransportEnum);
 	femmodel->parameters->FindParam(&isthermal,TransientIsthermalEnum);
 	femmodel->parameters->FindParam(&isgia,TransientIsgiaEnum);
@@ -69,5 +69,5 @@
 		if(isthermal && dim==3){
 			//Update Vertex Position after updating Thickness and Bed
-			femmodel->SetCurrentConfiguration(PrognosticAnalysisEnum);
+			femmodel->SetCurrentConfiguration(MasstransportAnalysisEnum);
 			femmodel->UpdateVertexPositionsx();
 			InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,QmuVxMeshEnum,VxMeshEnum);
@@ -79,5 +79,5 @@
 			//Reset Thermal Constraints
 			femmodel->SetCurrentConfiguration(ThermalAnalysisEnum);
-			ResetConstraintsx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+			ResetConstraintsx(femmodel);
 		}
 	}
@@ -111,4 +111,5 @@
 			else{
 				enthalpy_core(femmodel);
+                		PostprocessingEnthalpyx(femmodel);
 			}
 			#else
@@ -117,16 +118,16 @@
 		}
 
-		if(isdiagnostic){
+		if(isstressbalance){
 			if(VerboseSolution()) _printf0_("   computing new velocity\n");
-			#ifdef _HAVE_DIAGNOSTIC_
-			diagnostic_core(femmodel);
+			#ifdef _HAVE_STRESSBALANCE_
+			stressbalance_core(femmodel);
 			#else
-			_error_("ISSM was not compiled with diagnostic capabilities. Exiting");
+			_error_("ISSM was not compiled with stressbalance capabilities. Exiting");
 			#endif
 		}
 
-		if(isprognostic){
+		if(ismasstransport){
 			if(VerboseSolution()) _printf0_("   computing new thickness\n");
-			prognostic_core(femmodel);
+			masstransport_core(femmodel);
 			if(VerboseSolution()) _printf0_("   updating vertices positions\n");
 			femmodel->UpdateVertexPositionsx();
@@ -140,4 +141,9 @@
 			_error_("ISSM was not compiled with grounding line migration capabilities. Exiting");
 			#endif
+			if(save_results){
+				InputToResultx(femmodel,SurfaceEnum);
+				InputToResultx(femmodel,BedEnum);
+				InputToResultx(femmodel,MaskGroundediceLevelsetEnum);
+			}
 		}
 		if(isgia){
@@ -154,19 +160,13 @@
 		if(save_results){
 			if(VerboseSolution()) _printf0_("   saving transient results\n");
-			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceEnum);
-			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BedEnum);
-			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceforcingsMassBalanceEnum);
-			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,MaskElementonfloatingiceEnum);
+			InputToResultx(femmodel,SurfaceforcingsMassBalanceEnum);
 			femmodel->RequestedOutputsx(requested_outputs,numoutputs);
-
 			if(isdelta18o){
-				InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceforcingsMonthlytemperaturesEnum);
-				InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceforcingsPrecipitationEnum);
-				InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BasalFrictionEnum);
+				InputToResultx(femmodel,SurfaceforcingsMonthlytemperaturesEnum);
+				InputToResultx(femmodel,SurfaceforcingsPrecipitationEnum);
 			}
 			if(isgroundingline && (groundingline_migration==SubelementMigrationEnum || groundingline_migration==SubelementMigration2Enum)){
-				InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,GLlevelsetEnum);
+				InputToResultx(femmodel,MaskGroundediceLevelsetEnum);
 			}
-
 			if(VerboseSolution()) _printf0_("   saving temporary results\n");
 			OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
Index: sm/trunk/src/c/bamg/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/bamg/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,31 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/bamg)
-# }}}
-# BAMG_SOURCES {{{
-set(BAMG_SOURCES $ENV{ISSM_DIR}/src/c/classes/bamg/AdjacentTriangle.cpp
-                         $ENV{ISSM_DIR}/src/c/classes/bamg/BamgGeom.cpp
-                         $ENV{ISSM_DIR}/src/c/classes/bamg/BamgMesh.cpp
-                         $ENV{ISSM_DIR}/src/c/classes/bamg/BamgOpts.cpp
-                     $ENV{ISSM_DIR}/src/c/classes/bamg/BamgQuadtree.cpp
-                       $ENV{ISSM_DIR}/src/c/classes/bamg/BamgVertex.cpp
-                      $ENV{ISSM_DIR}/src/c/classes/bamg/CrackedEdge.cpp
-                            $ENV{ISSM_DIR}/src/c/classes/bamg/Curve.cpp
-                        $ENV{ISSM_DIR}/src/c/classes/bamg/Direction.cpp
-                             $ENV{ISSM_DIR}/src/c/classes/bamg/Edge.cpp
-                      $ENV{ISSM_DIR}/src/c/classes/bamg/EigenMetric.cpp
-                         $ENV{ISSM_DIR}/src/c/classes/bamg/GeomEdge.cpp
-                         $ENV{ISSM_DIR}/src/c/classes/bamg/Geometry.cpp
-                    $ENV{ISSM_DIR}/src/c/classes/bamg/GeomSubDomain.cpp
-                       $ENV{ISSM_DIR}/src/c/classes/bamg/GeomVertex.cpp
-      $ENV{ISSM_DIR}/src/c/classes/bamg/ListofIntersectionTriangles.cpp
-                             $ENV{ISSM_DIR}/src/c/classes/bamg/Mesh.cpp
-                           $ENV{ISSM_DIR}/src/c/classes/bamg/Metric.cpp
-                          $ENV{ISSM_DIR}/src/c/classes/bamg/SetOfE4.cpp
-                        $ENV{ISSM_DIR}/src/c/classes/bamg/SubDomain.cpp
-                         $ENV{ISSM_DIR}/src/c/classes/bamg/Triangle.cpp
-                     $ENV{ISSM_DIR}/src/c/classes/bamg/VertexOnEdge.cpp
-                     $ENV{ISSM_DIR}/src/c/classes/bamg/VertexOnGeom.cpp
-                   $ENV{ISSM_DIR}/src/c/classes/bamg/VertexOnVertex.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/classes/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,20 +1,0 @@
-# Subdirectories {{{
-add_subdirectory(bamg)
-add_subdirectory(dakota)
-add_subdirectory(gauss)
-add_subdirectory(kriging)
-add_subdirectory(matrix)
-add_subdirectory(objects)
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/classes/DofIndexing.cpp
-                    $ENV{ISSM_DIR}/src/c/classes/FemModel.cpp
-                        $ENV{ISSM_DIR}/src/c/classes/Hook.cpp
-                     $ENV{ISSM_DIR}/src/c/classes/IoModel.cpp
-                    $ENV{ISSM_DIR}/src/c/classes/IssmComm.cpp
-                       $ENV{ISSM_DIR}/src/c/classes/Patch.cpp
-                  $ENV{ISSM_DIR}/src/c/classes/RiftStruct.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/classes/Constraints/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Constraints/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,10 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/objects/Constraints)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/Constraints/SpcDynamic.cpp
-                  $ENV{ISSM_DIR}/src/c/classes/objects/Constraints/SpcStatic.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/Constraints/SpcTransient.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/classes/Constraints/Constraints.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/Constraints.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Constraints/Constraints.cpp	(revision 16137)
@@ -29,10 +29,6 @@
 
 	/*figure out total number of constraints combining all the cpus (no clones here)*/
-	#ifdef _HAVE_MPI_
-		MPI_Reduce(&localconstraints,&numberofconstraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-		MPI_Bcast(&numberofconstraints,1,MPI_INT,0,IssmComm::GetComm());
-	#else
-		numberofconstraints=localconstraints;
-	#endif
+	ISSM_MPI_Reduce(&localconstraints,&numberofconstraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&numberofconstraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 
 	return numberofconstraints;
Index: /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Constraints/SpcStatic.cpp	(revision 16137)
@@ -22,9 +22,9 @@
 SpcStatic::SpcStatic(int spc_sid,int spc_nodeid, int spc_dof,IssmDouble spc_value,int spc_analysis_type){
 
-	sid=spc_sid;
-	nodeid=spc_nodeid;
-	dof=spc_dof;
-	value=spc_value;
-	analysis_type=spc_analysis_type;
+	sid           = spc_sid;
+	nodeid        = spc_nodeid;
+	dof           = spc_dof;
+	value         = spc_value;
+	analysis_type = spc_analysis_type;
 
 	return;
Index: /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp
===================================================================
--- /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Constraints/SpcTransient.cpp	(revision 16137)
@@ -101,10 +101,10 @@
 void SpcTransient::ConstrainNode(Nodes* nodes,Parameters* parameters){
 
-	Node* node=NULL;
-	IssmDouble time=0;
-	int    i;
-	IssmDouble alpha=-1;
-	IssmDouble value;
-	bool   found=false;
+	Node       *node  = NULL;
+	IssmDouble  time  = 0.;
+	int         i;
+	IssmDouble  alpha = -1.;
+	IssmDouble  value;
+	bool        found = false;
 
 	/*Chase through nodes and find the node to which this SpcTransient applys: */
@@ -140,4 +140,5 @@
 		/*Apply or relax constraint: */
 		if(xIsNan<IssmDouble>(value)){
+			printf("-------------- file: SpcTransient.cpp line: %i\n",__LINE__); 
 			node->RelaxConstraint(dof);
 		}
Index: /issm/trunk/src/c/classes/DofIndexing.cpp
===================================================================
--- /issm/trunk/src/c/classes/DofIndexing.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/DofIndexing.cpp	(revision 16137)
@@ -167,4 +167,6 @@
 	_printf_("DofIndexing:\n");
 	_printf_("   gsize:  " << gsize << "\n");
+	_printf_("   fsize:  " << fsize << "\n");
+	_printf_("   ssize:  " << ssize << "\n");
 	_printf_("   clone:  " << clone << "\n");
 	_printf_("   active: " << active << "\n");
Index: /issm/trunk/src/c/classes/ElementResults/BoolElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/BoolElementResult.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/ElementResults/BoolElementResult.cpp	(revision 16137)
@@ -75,21 +75,4 @@
 }
 /*}}}*/
-/*FUNCTION BoolElementResult::SpawnTriaElementResult{{{*/
-ElementResult* BoolElementResult::SpawnTriaElementResult(int* indices){
-
-	/*output*/
-	BoolElementResult* outresult=new BoolElementResult();
-
-	/*copy fields: */
-	outresult->enum_type=this->enum_type;
-	outresult->value=this->value;
-	outresult->time=this->time;
-	outresult->step=this->step;
-
-	/*Assign output*/
-	return outresult;
-
-}
-/*}}}*/
 /*FUNCTION BoolElementResult::NumberOfNodalValues{{{*/
 int BoolElementResult::NumberOfNodalValues(void){
Index: /issm/trunk/src/c/classes/ElementResults/BoolElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/BoolElementResult.h	(revision 16136)
+++ /issm/trunk/src/c/classes/ElementResults/BoolElementResult.h	(revision 16137)
@@ -34,5 +34,4 @@
 		/*}}}*/
 		/*ElementResult virtual functions definitions: {{{*/
-		ElementResult* SpawnTriaElementResult(int* indices);
 		IssmDouble  GetTime(void){return time;};
 		int     GetStep(void){return step;};
Index: sm/trunk/src/c/classes/ElementResults/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,13 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/objects/ElementResults)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/ElementResults/BoolElementResult.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/ElementResults/DoubleElementResult.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp PARENT_SCOPE)
-# }}}
-# THREED_SOURCES {{{
-set(THREED_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/classes/ElementResults/DoubleElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/DoubleElementResult.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/ElementResults/DoubleElementResult.cpp	(revision 16137)
@@ -75,21 +75,4 @@
 }
 /*}}}*/
-/*FUNCTION DoubleElementResult::SpawnTriaElementResult{{{*/
-ElementResult* DoubleElementResult::SpawnTriaElementResult(int* indices){
-
-	/*output*/
-	DoubleElementResult* outresult=new DoubleElementResult();
-
-	/*copy fields: */
-	outresult->enum_type=this->enum_type;
-	outresult->value=this->value;
-	outresult->time=this->time;
-	outresult->step=this->step;
-
-	/*Assign output*/
-	return outresult;
-
-}
-/*}}}*/
 /*FUNCTION DoubleElementResult::NumberOfNodalValues{{{*/
 int DoubleElementResult::NumberOfNodalValues(void){
Index: /issm/trunk/src/c/classes/ElementResults/DoubleElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/DoubleElementResult.h	(revision 16136)
+++ /issm/trunk/src/c/classes/ElementResults/DoubleElementResult.h	(revision 16137)
@@ -14,35 +14,33 @@
 
 	private: 
-		int    enum_type;
+		int        enum_type;
 		IssmDouble value;
-		int    step;
+		int        step;
 		IssmDouble time;
 
 	public:
 
-		/*DoubleElementResult constructors, destructors: {{{*/
+		/*DoubleElementResult constructors, destructors:*/
 		DoubleElementResult();
 		DoubleElementResult(int enum_type,IssmDouble value,int step,IssmDouble time);
 		~DoubleElementResult();
-		/*}}}*/
-		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   ObjectEnum();
+
+		/*Object virtual functions definitions:*/
+		void    Echo();
+		void    DeepEcho();
+		int     Id(); 
+		int     ObjectEnum();
 		Object* copy();
-		/*}}}*/
+
 		/*ElementResult virtual functions definitions: {{{*/
-		ElementResult* SpawnTriaElementResult(int* indices);
 		IssmDouble  GetTime(void){return time;};
 		int     GetStep(void){return step;};
 		int     NumberOfNodalValues(void);
 		void    PatchFill(int row, Patch* patch);
-		/*}}}*/
-		/*DoubleElementResult management: {{{*/
-		int   InstanceEnum();
+
+		/*DoubleElementResult management*/
+		int  InstanceEnum();
 		void GetVectorFromResults(Vector<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdofs);
 		void GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof);
-		/*}}}*/
 };
 #endif  /* _DOUBLEELEMENTRESULT_H */
Index: /issm/trunk/src/c/classes/ElementResults/ElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/ElementResult.h	(revision 16136)
+++ /issm/trunk/src/c/classes/ElementResults/ElementResult.h	(revision 16137)
@@ -15,13 +15,12 @@
 	public: 
 
-		virtual        ~ElementResult(){};
-		virtual         ElementResult* SpawnTriaElementResult(int* indices)=0;
-		virtual IssmDouble  GetTime(void)=0;
-		virtual int     GetStep(void)=0;
-		virtual int     NumberOfNodalValues(void)=0;
-		virtual void    PatchFill(int row, Patch* patch)=0;
-		virtual int     InstanceEnum()=0;
-		virtual void    GetVectorFromResults(Vector<IssmDouble>* vector,int* doflist,int* connectivitylist,int numdof)=0;
-		virtual void    GetElementVectorFromResults(Vector<IssmDouble>* vector,int dof)=0;
+		virtual ~ElementResult(){};
+		virtual IssmDouble GetTime(void) = 0;
+		virtual int        GetStep(void) = 0;
+		virtual int        NumberOfNodalValues(void) = 0;
+		virtual void       PatchFill(int row, Patch *patch)=0;
+		virtual int        InstanceEnum() = 0;
+		virtual void       GetVectorFromResults(Vector <IssmDouble> *vector,int*doflist,int*connectivitylist,int numdof)=0;
+		virtual void       GetElementVectorFromResults(Vector <IssmDouble> *vector,int dof)=0;
 
 };
Index: /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.cpp	(revision 16137)
@@ -78,29 +78,4 @@
 }
 /*}}}*/
-/*FUNCTION PentaP1ElementResult::SpawnTriaElementResult{{{*/
-ElementResult* PentaP1ElementResult::SpawnTriaElementResult(int* indices){
-
-	/*output*/
-	TriaP1ElementResult* outresult=NULL;
-	IssmDouble newvalues[3];
-
-	/*Loop over the new indices*/
-	for(int i=0;i<3;i++){
-
-		/*Check index value*/
-		_assert_(indices[i]>=0 && indices[i]<6);
-
-		/*Assign value to new result*/
-		newvalues[i]=this->values[indices[i]];
-	}
-
-	/*Create new Tria result*/
-	outresult=new TriaP1ElementResult(this->enum_type,&newvalues[0],this->step,this->time);
-
-	/*Assign output*/
-	return outresult;
-
-}
-/*}}}*/
 /*FUNCTION PentaP1ElementResult::NumberOfNodalValues{{{*/
 int PentaP1ElementResult::NumberOfNodalValues(void){
Index: /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.h	(revision 16136)
+++ /issm/trunk/src/c/classes/ElementResults/PentaP1ElementResult.h	(revision 16137)
@@ -33,5 +33,4 @@
 		/*}}}*/
 		/*ElementResult virtual functions definitions: {{{*/
-		ElementResult* SpawnTriaElementResult(int* indices);
 		IssmDouble  GetTime(void){return time;};
 		int     GetStep(void){return step;};
Index: /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.cpp	(revision 16137)
@@ -77,18 +77,4 @@
 }
 /*}}}*/
-/*FUNCTION TriaP1ElementResult::SpawnTriaElementResult{{{*/
-ElementResult* TriaP1ElementResult::SpawnTriaElementResult(int* indices){
-
-	/*output*/
-	TriaP1ElementResult* outresult=NULL;
-
-	/*Create new Tria result (copy of current result)*/
-	outresult=new TriaP1ElementResult(this->enum_type,&this->values[0],this->step,this->time);
-
-	/*Assign output*/
-	return outresult;
-
-}
-/*}}}*/
 /*FUNCTION TriaP1ElementResult::NumberOfNodalValues{{{*/
 int TriaP1ElementResult::NumberOfNodalValues(void){
Index: /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.h	(revision 16136)
+++ /issm/trunk/src/c/classes/ElementResults/TriaP1ElementResult.h	(revision 16137)
@@ -32,5 +32,4 @@
 		/*}}}*/
 		/*ElementResult virtual functions definitions: {{{*/
-		ElementResult* SpawnTriaElementResult(int* indices);
 		IssmDouble  GetTime(void){return time;};
 		int     GetStep(void){return step;};
Index: sm/trunk/src/c/classes/Elements/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Elements/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,15 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/objects/Elements)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/Elements/Tria.cpp
-             $ENV{ISSM_DIR}/src/c/classes/objects/Elements/TriaHook.cpp
-              $ENV{ISSM_DIR}/src/c/classes/objects/Elements/TriaRef.cpp PARENT_SCOPE)
-# }}}
-# THREED_SOURCES {{{
-set(THREED_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/Elements/Penta.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/Elements/PentaHook.cpp
-                $ENV{ISSM_DIR}/src/c/classes/objects/Elements/PentaRef.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/classes/Elements/Element.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Element.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Elements/Element.h	(revision 16137)
@@ -36,5 +36,5 @@
 		virtual void   Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
 		virtual void   SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters)=0;
-		virtual void   SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum)=0;
+		virtual void   SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum)=0;
 		virtual void   CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>*  Kfs)=0;
 		virtual void   CreateDVector(Vector<IssmDouble>* df)=0;
@@ -45,8 +45,8 @@
 		virtual int    GetNumberOfNodes(void)=0;
 		virtual void   GetNodesSidList(int* sidlist)=0;
+		virtual void   GetNodesLidList(int* sidlist)=0;
 
 		virtual int    Sid()=0;
 		virtual bool   IsFloating()=0; 
-		virtual bool   IsNodeOnShelf()=0; 
 		virtual bool   IsNodeOnShelfFromFlags(IssmDouble* flags)=0; 
 		virtual bool   IsOnBed()=0;
@@ -63,5 +63,5 @@
 		virtual void   ListResultsInfo(int** results_enums,int** results_size,IssmDouble** results_times,int** results_steps,int* num_results)=0;
 		virtual void   DeleteResults(void)=0;
-		virtual void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type)=0;
+		virtual void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finite_element)=0;
 		virtual void   InputToResult(int enum_type,int step,IssmDouble time)=0;
 		virtual void   InputDuplicate(int original_enum,int new_enum)=0;
@@ -75,10 +75,8 @@
 		virtual void   GetVectorFromResults(Vector<IssmDouble>* vector,int id,int enum_in,int interp)=0;
 		virtual void   InputArtificialNoise(int enum_type,IssmDouble min,IssmDouble max)=0;
-		virtual int*   GetHorizontalNeighboorSids(void)=0;
 		virtual IssmDouble TimeAdapt()=0;
 		virtual void   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm)=0;
 		virtual void   Delta18oParameterization(void)=0;
 		virtual void   SmbGradients()=0;
-		virtual void UpdateConstraints(void)=0; 
 		virtual void   ResetCoordinateSystem()=0;
 
@@ -128,4 +126,10 @@
 		#endif
 
+		#ifdef _HAVE_THERMAL_
+		virtual void UpdateThermalBasalConstraints(void)=0;
+		virtual void ComputeBasalMeltingrate(void)=0;
+       	virtual void DrainWaterfraction(void)=0;
+		#endif
+
 		#ifdef _HAVE_HYDROLOGY_
 		virtual void GetHydrologyDCInefficientHmax(IssmDouble* ph_max, Node* innode)=0;
@@ -134,7 +138,7 @@
 		virtual void HydrologyEPLGetActive(Vector<IssmDouble>* active)=0;
 		#endif
-		
+
 		#ifdef _HAVE_GROUNDINGLINE_
-		virtual void   MigrateGroundingLine(IssmDouble* old_floating_ice,IssmDouble* sheet_ungrounding)=0;
+		virtual void   MigrateGroundingLine(IssmDouble* sheet_ungrounding)=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;
Index: /issm/trunk/src/c/classes/Elements/ElementHook.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Elements/ElementHook.cpp	(revision 16137)
@@ -49,5 +49,5 @@
 
 	/*retrieve material_id: */
-	iomodel->Constant(&matpar_id,MeshNumberofelementsEnum); matpar_id++;
+	matpar_id = iomodel->numberofelements+1;
 
 	/*retrieve material_id*/
@@ -57,5 +57,5 @@
 	int* vertex_ids = xNew<int>(numvertices);
 	for(int i=0;i<numvertices;i++){ 
-		vertex_ids[i]=reCast<int>(iomodel->Data(MeshElementsEnum)[(element_id-1)*numvertices+i]);
+		vertex_ids[i]=reCast<int>(iomodel->elements[(element_id-1)*numvertices+i]);
 	}
 
@@ -89,13 +89,28 @@
 /*}}}*/
 /*FUNCTION ElementHook::SpawnTriaHook{{{*/
-void ElementHook::SpawnTriaHook(ElementHook* triahook,int* indices){
+void ElementHook::SpawnTriaHook(ElementHook* triahook,int location){
 
-	int i;
-	int zero=0;
+	/*Create arrow of indices depending on location (0=base 1=surface)*/
+	int indices[3];
+	switch(location){
+		case 0:
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			break;
+		case 1:
+			indices[0] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			break;
+		default:
+			_error_("case "<<location<<" not supported");
+	}
 
 	triahook->numanalyses=this->numanalyses;
+
+	/*Spawn nodes hook*/
 	triahook->hnodes=new Hook*[this->numanalyses];
-
-	for(i=0;i<this->numanalyses;i++){
+	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){
@@ -103,9 +118,9 @@
 		}
 		else{
-			/*Else, spawn Hook*/
 			triahook->hnodes[i]=this->hnodes[i]->Spawn(indices,3);
 		}
 	}
-	// do not spawn hmaterial. material will be taken care of by Penta
+
+	/*do not spawn hmaterial. material will be taken care of by Penta*/
 	triahook->hmaterial=NULL;
 	triahook->hvertices=(Hook*)this->hvertices->Spawn(indices,3);
Index: /issm/trunk/src/c/classes/Elements/ElementHook.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/ElementHook.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Elements/ElementHook.h	(revision 16137)
@@ -25,5 +25,5 @@
 
 		void SetHookNodes(int* node_ids,int numnodes,int analysis_counter);
-		void SpawnTriaHook(ElementHook* triahook,int* indices);    //3d only
+		void SpawnTriaHook(ElementHook* triahook,int location); //3d 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 16136)
+++ /issm/trunk/src/c/classes/Elements/Elements.cpp	(revision 16137)
@@ -114,13 +114,11 @@
 
 	/*Synchronize across cluster, so as to not end up with different sizes for each patch on each cpu: */
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&numvertices,&max_numvertices,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&max_numvertices,1,MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Reduce (&numvertices,&max_numvertices,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&max_numvertices,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 	numvertices=max_numvertices;
 
-	MPI_Reduce (&numnodes,&max_numnodes,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&max_numnodes,1,MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Reduce (&numnodes,&max_numnodes,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&max_numnodes,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 	numnodes=max_numnodes;
-	#endif
 
 	/*Ok, initialize Patch object: */
@@ -186,11 +184,7 @@
 
 		/*Get rank of first cpu that has results*/
-		#ifdef _HAVE_MPI_
 		if(this->Size()) rank=my_rank;
 		else rank=num_procs;
-		MPI_Allreduce (&rank,&minrank,1,MPI_INT,MPI_MIN,IssmComm::GetComm());
-		#else
-		minrank=my_rank;
-		#endif
+		ISSM_MPI_Allreduce (&rank,&minrank,1,ISSM_MPI_INT,ISSM_MPI_MIN,IssmComm::GetComm());
 
 		/*see what the first element of this partition has in stock (this is common to all partitions)*/
@@ -200,11 +194,8 @@
 			element->ListResultsInfo(&resultsenums,&resultssizes,&resultstimes,&resultssteps,&numberofresults);
 		}
-		#ifdef _HAVE_MPI_
-		MPI_Bcast(&numberofresults,1,MPI_DOUBLE,minrank,IssmComm::GetComm());
-		#endif
+		ISSM_MPI_Bcast(&numberofresults,1,ISSM_MPI_INT,minrank,IssmComm::GetComm());
 
 		/*Get out if there is no results. Otherwise broadcast info*/
 		if(!numberofresults) return;
-		#ifdef _HAVE_MPI_
 		if(my_rank!=minrank){
 			resultsenums=xNew<int>(numberofresults);
@@ -213,9 +204,8 @@
 			resultssteps=xNew<int>(numberofresults);
 		}
-		MPI_Bcast(resultsenums,numberofresults,MPI_INT,minrank,IssmComm::GetComm());
-		MPI_Bcast(resultssizes,numberofresults,MPI_INT,minrank,IssmComm::GetComm());
-		MPI_Bcast(resultstimes,numberofresults,MPI_DOUBLE,minrank,IssmComm::GetComm());
-		MPI_Bcast(resultssteps,numberofresults,MPI_INT,minrank,IssmComm::GetComm());
-		#endif
+		ISSM_MPI_Bcast(resultsenums,numberofresults,ISSM_MPI_INT,minrank,IssmComm::GetComm());
+		ISSM_MPI_Bcast(resultssizes,numberofresults,ISSM_MPI_INT,minrank,IssmComm::GetComm());
+		ISSM_MPI_Bcast(resultstimes,numberofresults,ISSM_MPI_DOUBLE,minrank,IssmComm::GetComm());
+		ISSM_MPI_Bcast(resultssteps,numberofresults,ISSM_MPI_INT,minrank,IssmComm::GetComm());
 
 		/*Loop over all results and get nodal vector*/
@@ -299,8 +289,6 @@
 
 	/*Grab max of all cpus: */
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
+	ISSM_MPI_Allreduce((void*)&max,(void*)&allmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
 	max=allmax;
-	#endif
 
 	return max;
@@ -314,9 +302,5 @@
 
 	local_nelem=this->Size();
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)&local_nelem,(void*)&numberofelements,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
-	#else
-	numberofelements=local_nelem;
-	#endif
+	ISSM_MPI_Allreduce ( (void*)&local_nelem,(void*)&numberofelements,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
 
 	return numberofelements;
Index: /issm/trunk/src/c/classes/Elements/Penta.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Elements/Penta.cpp	(revision 16137)
@@ -31,5 +31,4 @@
 	this->parameters        = NULL;
 	this->results           = NULL;
-	for(int i=0;i<3;i++)this->horizontalneighborsids[i]=UNDEF;
 }
 /*}}}*/
@@ -66,8 +65,4 @@
 	else                                    penta_elements_ids[0]=reCast<int,IssmDouble>((iomodel->Data(MeshLowerelementsEnum)[index]));
 	this->InitHookNeighbors(penta_elements_ids);
-
-	/*Build horizontalneighborsids list: */
-	_assert_(iomodel->Data(MeshElementconnectivityEnum));
-	for(i=0;i<3;i++) this->horizontalneighborsids[i]=reCast<int,IssmDouble>(iomodel->Data(MeshElementconnectivityEnum)[3*index+i])-1;
 
 	//this->parameters: we still can't point to it, it may not even exist. Configure will handle this.
@@ -134,7 +129,4 @@
 	penta->verticalneighbors=(Penta**)penta->hneighbors->deliverp();
 
-	/*neighbors: */
-	for(i=0;i<3;i++)penta->horizontalneighborsids[i]=this->horizontalneighborsids[i];
-
 	return penta;
 }
@@ -182,5 +174,5 @@
 	if (!IsOnBed() || IsFloating()){
 		//empty friction: 
-		this->inputs->AddInput(new PentaP1Input(BasalFrictionEnum,&basalfriction[0]));
+		this->inputs->AddInput(new PentaInput(BasalFrictionEnum,&basalfriction[0],P1Enum));
 		return;
 	}
@@ -192,5 +184,5 @@
 
 	/*Build friction element, needed later: */
-	friction=new Friction("3d",inputs,matpar,DiagnosticHorizAnalysisEnum);
+	friction=new Friction("3d",inputs,matpar,StressbalanceAnalysisEnum);
 
 	/* Start looping on the number of gauss 2d (nodes on the bedrock) */
@@ -209,5 +201,5 @@
 
 	/*Create PentaVertex input, which will hold the basal friction:*/
-	this->inputs->AddInput(new PentaP1Input(BasalFrictionEnum,&basalfriction[0]));
+	this->inputs->AddInput(new PentaInput(BasalFrictionEnum,&basalfriction[0],P1Enum));
 
 	/*Clean up and return*/
@@ -225,5 +217,5 @@
 	IssmDouble  xyz_list[NUMVERTICES][3];
 	IssmDouble  xyz_list_tria[3][3];
-	IssmDouble  rho_ice,gravity,stokesreconditioning;
+	IssmDouble  rho_ice,gravity,FSreconditioning;
 	IssmDouble  pressure,viscosity,Jdet2d;
 	IssmDouble  bed_normal[3];
@@ -241,9 +233,9 @@
 
 	/*Check analysis_types*/
-	if (analysis_type!=DiagnosticHorizAnalysisEnum) _error_("Not supported yet!");
-	if (approximation!=StokesApproximationEnum) _error_("Not supported yet!");
+	if (analysis_type!=StressbalanceAnalysisEnum) _error_("Not supported yet!");
+	if (approximation!=FSApproximationEnum) _error_("Not supported yet!");
 
 	/*retrieve some parameters: */
-	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
 
 	if(!IsOnBed()){
@@ -275,11 +267,11 @@
 		/*Compute strain rate viscosity and pressure: */
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
 		pressure_input->GetInputValue(&pressure,gauss);
 
 		/*Compute Stress*/
-		sigma_xx=2*viscosity*epsilon[0]-pressure*stokesreconditioning; // sigma = nu eps - pressure
-		sigma_yy=2*viscosity*epsilon[1]-pressure*stokesreconditioning;
-		sigma_zz=2*viscosity*epsilon[2]-pressure*stokesreconditioning;
+		sigma_xx=2*viscosity*epsilon[0]-pressure*FSreconditioning; // sigma = nu eps - pressure
+		sigma_yy=2*viscosity*epsilon[1]-pressure*FSreconditioning;
+		sigma_zz=2*viscosity*epsilon[2]-pressure*FSreconditioning;
 		sigma_xy=2*viscosity*epsilon[3];
 		sigma_xz=2*viscosity*epsilon[4];
@@ -354,10 +346,10 @@
 
 	/*Add Stress tensor components into inputs*/
-	this->inputs->AddInput(new PentaP1Input(StressTensorxxEnum,&sigma_xx[0]));
-	this->inputs->AddInput(new PentaP1Input(StressTensorxyEnum,&sigma_xy[0]));
-	this->inputs->AddInput(new PentaP1Input(StressTensorxzEnum,&sigma_xz[0]));
-	this->inputs->AddInput(new PentaP1Input(StressTensoryyEnum,&sigma_yy[0]));
-	this->inputs->AddInput(new PentaP1Input(StressTensoryzEnum,&sigma_yz[0]));
-	this->inputs->AddInput(new PentaP1Input(StressTensorzzEnum,&sigma_zz[0]));
+	this->inputs->AddInput(new PentaInput(StressTensorxxEnum,&sigma_xx[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensorxyEnum,&sigma_xy[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensorxzEnum,&sigma_xz[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensoryyEnum,&sigma_yy[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensoryzEnum,&sigma_yz[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(StressTensorzzEnum,&sigma_zz[0],P1Enum));
 
 	/*Clean up and return*/
@@ -365,5 +357,5 @@
 }
 /*}}}*/
-		/*FUNCTION Penta::Configure {{{*/
+/*FUNCTION Penta::Configure {{{*/
 void  Penta::Configure(Elements* elementsin, Loads* loadsin, Nodes* nodesin,Vertices* verticesin, Materials* materialsin, Parameters* parametersin){
 
@@ -399,6 +391,48 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrix {{{*/
+/*FUNCTION Penta::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs) {{{*/
 void  Penta::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
+
+	/*Skip if water element*/
+	if(NoIceInElement()) return;
+
+	/*Create element stiffness matrix*/
+	ElementMatrix* Ke=CreateKMatrix();
+
+	if(Ke){
+		int analysis_type;
+		parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+		if(analysis_type==StressbalanceAnalysisEnum){
+			int approximation;
+			inputs->GetInputValue(&approximation,ApproximationEnum);
+			if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+				//Do nothing condensatino already done for Stokes part
+			}
+			else{
+				/*Condense if requested*/
+				if(this->element_type==MINIcondensedEnum){
+					int indices[3]={18,19,20};
+					Ke->StaticCondensation(3,&indices[0]);
+				}
+				else if(this->element_type==P1bubblecondensedEnum){
+					int size   = nodes[6]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+					int offset = 0;
+					for(int i=0;i<6;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+					int* indices=xNew<int>(size);
+					for(int i=0;i<size;i++) indices[i] = offset+i;
+					Ke->StaticCondensation(size,indices);
+					xDelete<int>(indices);
+				}
+			}
+		}
+
+		/*Add to global matrix*/
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrix(void){{{*/
+ElementMatrix* Penta::CreateKMatrix(void){
 
 	/*retrieve parameters: */
@@ -412,50 +446,56 @@
 
 	/*Skip if water element*/
-	if(IsOnWater()) return;
+	if(NoIceInElement()) return NULL;
 
 	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-		#ifdef _HAVE_DIAGNOSTIC_
-		case DiagnosticHorizAnalysisEnum:
-			Ke=CreateKMatrixDiagnosticHoriz();
+		#ifdef _HAVE_STRESSBALANCE_
+		case StressbalanceAnalysisEnum:
+			return CreateKMatrixStressbalanceHoriz();
 			break;
 		case AdjointHorizAnalysisEnum:
-			Ke=CreateKMatrixAdjointHoriz();
+			return CreateKMatrixAdjointHoriz();
 			break;
-		case DiagnosticHutterAnalysisEnum:
-			Ke=CreateKMatrixDiagnosticHutter();
+		case StressbalanceSIAAnalysisEnum:
+			return CreateKMatrixStressbalanceSIA();
 			break;
-		case DiagnosticVertAnalysisEnum:
-			Ke=CreateKMatrixDiagnosticVert();
+		case StressbalanceVerticalAnalysisEnum:
+			return CreateKMatrixStressbalanceVert();
 			break;
 		#endif
 		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
-			Ke=CreateBasalMassMatrix();
+			return CreateBasalMassMatrix();
 			break;
-		case PrognosticAnalysisEnum:
-			Ke=CreateKMatrixPrognostic();
+		case MasstransportAnalysisEnum:
+			return CreateKMatrixMasstransport();
+			break;
+		case FreeSurfaceTopAnalysisEnum:
+			return CreateKMatrixFreeSurfaceTop();
+			break;
+		case FreeSurfaceBaseAnalysisEnum:
+			return CreateKMatrixFreeSurfaceBase();
 			break;
 		#ifdef _HAVE_BALANCED_
 		case BalancethicknessAnalysisEnum:
-			Ke=CreateKMatrixBalancethickness();
+			return CreateKMatrixBalancethickness();
 			break;
 		#endif
 		#ifdef _HAVE_THERMAL_
 		case ThermalAnalysisEnum:
-			Ke=CreateKMatrixThermal();
+			return CreateKMatrixThermal();
 			break;
 		case EnthalpyAnalysisEnum:
-			Ke=CreateKMatrixEnthalpy();
+			return CreateKMatrixEnthalpy();
 			break;
 		case MeltingAnalysisEnum:
-			Ke=CreateKMatrixMelting();
+			return CreateKMatrixMelting();
 			break;
 		#endif
 		#ifdef _HAVE_HYDROLOGY_
 	  case HydrologyDCInefficientAnalysisEnum:
-			Ke=CreateKMatrixHydrologyDCInefficient();
+			return CreateKMatrixHydrologyDCInefficient();
 			break;
 	  case HydrologyDCEfficientAnalysisEnum:
-			Ke=CreateKMatrixHydrologyDCEfficient();
+			return CreateKMatrixHydrologyDCEfficient();
 			break;
 		#endif
@@ -464,13 +504,10 @@
 	}
 
-	/*Add to global matrix*/
-	if(Ke){
-		Ke->AddToGlobal(Kff,Kfs);
-		delete Ke;
-	}
-}
-/*}}}*/
-/*FUNCTION Penta::CreateKMatrixPrognostic {{{*/
-ElementMatrix* Penta::CreateKMatrixPrognostic(void){
+	/*Make compiler happy*/
+	return NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixMasstransport {{{*/
+ElementMatrix* Penta::CreateKMatrixMasstransport(void){
 
 	if (!IsOnBed()) return NULL;
@@ -480,6 +517,6 @@
 	this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
 
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-	ElementMatrix* Ke=tria->CreateKMatrixPrognostic();
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	ElementMatrix* Ke=tria->CreateKMatrixMasstransport();
 	delete tria->material; delete tria;
 
@@ -492,4 +529,30 @@
 }
 /*}}}*/
+/*FUNCTION Penta::CreateKMatrixFreeSurfaceTop {{{*/
+ElementMatrix* Penta::CreateKMatrixFreeSurfaceTop(void){
+
+	if(!IsOnSurface()) return NULL;
+
+	Tria* tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
+	ElementMatrix* Ke=tria->CreateKMatrixFreeSurfaceTop();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixFreeSurfaceBase {{{*/
+ElementMatrix* Penta::CreateKMatrixFreeSurfaceBase(void){
+
+	if(!IsOnBed()) return NULL;
+
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	ElementMatrix* Ke=tria->CreateKMatrixFreeSurfaceBase();
+	delete tria->material; delete tria;
+
+	/*clean up and return*/
+	return Ke;
+}
+/*}}}*/
 /*FUNCTION Penta::CreateBasalMassMatrix{{{*/
 ElementMatrix* Penta::CreateBasalMassMatrix(void){
@@ -497,5 +560,5 @@
 	if (!IsOnBed()) return NULL;
 
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	ElementMatrix* Ke=tria->CreateMassMatrix();
 	delete tria->material; delete tria;
@@ -519,7 +582,7 @@
 
 	switch(analysis_type){
-		#ifdef _HAVE_DIAGNOSTIC_
-		case DiagnosticHorizAnalysisEnum:
-			De=CreateDVectorDiagnosticHoriz();
+		#ifdef _HAVE_STRESSBALANCE_
+		case StressbalanceAnalysisEnum:
+			De=CreateDVectorStressbalanceHoriz();
 			break;
 		#endif
@@ -533,9 +596,61 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVector {{{*/
+/*FUNCTION Penta::CreatePVector(Vector<IssmDouble>* pf) {{{*/
 void  Penta::CreatePVector(Vector<IssmDouble>* pf){
 
-	/*retrive parameters: */
-	ElementVector* pe=NULL;
+	/*Skip if water element*/
+	if(NoIceInElement()) return;
+
+	/*Create element load vector*/
+	ElementVector* pe = CreatePVector();
+
+	if(pe){
+		int analysis_type;
+		parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+		if(analysis_type==StressbalanceAnalysisEnum){
+			/*StaticCondensation if requested*/
+			if(this->element_type==MINIcondensedEnum){
+				int approximation;
+				inputs->GetInputValue(&approximation,ApproximationEnum);
+				if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+					//Do nothing, condensation already done in PVectorCoupling
+				}
+				else{
+					int indices[3]={18,19,20};
+
+					this->element_type=MINIEnum;
+					ElementMatrix* Ke = CreateKMatrixStressbalanceFS();
+					this->element_type=MINIcondensedEnum;
+
+					pe->StaticCondensation(Ke,3,&indices[0]);
+					delete Ke;
+				}
+			}
+			else if(this->element_type==P1bubblecondensedEnum){
+				int size   = nodes[6]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+				int offset = 0;
+				for(int i=0;i<6;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+				int* indices=xNew<int>(size);
+				for(int i=0;i<size;i++) indices[i] = offset+i;
+
+				this->element_type=P1bubbleEnum;
+				ElementMatrix* Ke = CreateKMatrix();
+				this->element_type=P1bubblecondensedEnum;
+				pe->StaticCondensation(Ke,size,indices);
+				xDelete<int>(indices);
+				delete Ke;
+			}
+		}
+
+		/*Add to global Vector*/
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVector(void) {{{*/
+ElementVector* Penta::CreatePVector(void){
+
+	/*retrieve parameters: */
 	int analysis_type;
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
@@ -546,52 +661,58 @@
 
 	/*Skip if water element*/
-	if(IsOnWater()) return;
+	if(NoIceInElement()) return NULL;
 
 	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-		#ifdef _HAVE_DIAGNOSTIC_
-		case DiagnosticHorizAnalysisEnum:
-			pe=CreatePVectorDiagnosticHoriz();
+		#ifdef _HAVE_STRESSBALANCE_
+		case StressbalanceAnalysisEnum:
+			return CreatePVectorStressbalanceHoriz();
 			break;
-		case DiagnosticHutterAnalysisEnum:
-			pe=CreatePVectorDiagnosticHutter();
+		case StressbalanceSIAAnalysisEnum:
+			return CreatePVectorStressbalanceSIA();
 			break;
-		case DiagnosticVertAnalysisEnum:
-			pe=CreatePVectorDiagnosticVert();
+		case StressbalanceVerticalAnalysisEnum:
+			return CreatePVectorStressbalanceVert();
 			break;
 		#endif
 	 	#ifdef _HAVE_CONTROL_
 		case AdjointHorizAnalysisEnum:
-			pe=CreatePVectorAdjointHoriz();
+			return CreatePVectorAdjointHoriz();
 			break;
 		#endif
 		#ifdef _HAVE_THERMAL_
 		case ThermalAnalysisEnum:
-			pe=CreatePVectorThermal();
+			return CreatePVectorThermal();
 			break;
 		case EnthalpyAnalysisEnum:
-			pe=CreatePVectorEnthalpy();
+			return CreatePVectorEnthalpy();
 			break;
 		case MeltingAnalysisEnum:
-			pe=CreatePVectorMelting();
+			return CreatePVectorMelting();
 			break;
 		#endif
 		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
-			pe=CreatePVectorSlope();
+			return CreatePVectorSlope();
 			break;
-		case PrognosticAnalysisEnum:
-			pe=CreatePVectorPrognostic();
+		case MasstransportAnalysisEnum:
+			return CreatePVectorMasstransport();
+			break;
+		case FreeSurfaceTopAnalysisEnum:
+			return CreatePVectorFreeSurfaceTop();
+			break;
+		case FreeSurfaceBaseAnalysisEnum:
+			return CreatePVectorFreeSurfaceBase();
 			break;
 		#ifdef _HAVE_BALANCED_
 		case BalancethicknessAnalysisEnum:
-			pe=CreatePVectorBalancethickness();
+			return CreatePVectorBalancethickness();
 			break;
 		#endif
 		#ifdef _HAVE_HYDROLOGY_
 	  case HydrologyDCInefficientAnalysisEnum:
-			pe=CreatePVectorHydrologyDCInefficient();
+			return CreatePVectorHydrologyDCInefficient();
 			break;
 	  case HydrologyDCEfficientAnalysisEnum:
-			pe=CreatePVectorHydrologyDCEfficient();
+			return CreatePVectorHydrologyDCEfficient();
 			break;
 		#endif
@@ -600,13 +721,10 @@
 	}
 
-	/*Add to global Vector*/
-	if(pe){
-		pe->AddToGlobal(pf);
-		delete pe;
-	}
-}
-/*}}}*/
-/*FUNCTION Penta::CreatePVectorPrognostic {{{*/
-ElementVector* Penta::CreatePVectorPrognostic(void){
+	/*make compiler happy*/
+	return NULL;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorMasstransport {{{*/
+ElementVector* Penta::CreatePVectorMasstransport(void){
 
 	if (!IsOnBed()) return NULL;
@@ -617,6 +735,6 @@
 
 	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-	ElementVector* pe=tria->CreatePVectorPrognostic();
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	ElementVector* pe=tria->CreatePVectorMasstransport();
 	delete tria->material; delete tria;
 
@@ -629,4 +747,32 @@
 }
 /*}}}*/
+/*FUNCTION Penta::CreatePVectorFreeSurfaceTop {{{*/
+ElementVector* Penta::CreatePVectorFreeSurfaceTop(void){
+
+	if(!IsOnSurface()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
+	ElementVector* pe=tria->CreatePVectorFreeSurfaceTop();
+	delete tria->material; delete tria;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorFreeSurfaceBase {{{*/
+ElementVector* Penta::CreatePVectorFreeSurfaceBase(void){
+
+	if(!IsOnBed()) return NULL;
+
+	/*Call Tria function*/
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	ElementVector* pe=tria->CreatePVectorFreeSurfaceBase();
+	delete tria->material; delete tria;
+
+	/*Clean up and return*/
+	return pe;
+}
+/*}}}*/
 /*FUNCTION Penta::CreatePVectorSlope {{{*/
 ElementVector* Penta::CreatePVectorSlope(void){
@@ -635,5 +781,5 @@
 
 	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	ElementVector* pe=tria->CreatePVectorSlope();
 	delete tria->material; delete tria;
@@ -656,11 +802,11 @@
 
 	/*Skip if water element*/
-	if(IsOnWater()) return;
+	if(NoIceInElement()) return;
 
 	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-#ifdef _HAVE_DIAGNOSTIC_
-		case DiagnosticHorizAnalysisEnum:
-			Ke=CreateJacobianDiagnosticHoriz();
+#ifdef _HAVE_STRESSBALANCE_
+		case StressbalanceAnalysisEnum:
+			Ke=CreateJacobianStressbalanceHoriz();
 			break;
 #endif
@@ -671,4 +817,19 @@
 	/*Add to global matrix*/
 	if(Ke){
+		/*Condense if requested*/
+		if(this->element_type==MINIcondensedEnum){
+			int indices[3]={18,19,20};
+			Ke->StaticCondensation(3,&indices[0]);
+		}
+		else if(this->element_type==P1bubblecondensedEnum){
+			int size   = nodes[6]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int offset = 0;
+			for(int i=0;i<6;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int* indices=xNew<int>(size);
+			for(int i=0;i<size;i++) indices[i] = offset+i;
+			Ke->StaticCondensation(size,indices);
+			xDelete<int>(indices);
+		}
+
 		Ke->AddToGlobal(Jff);
 		delete Ke;
@@ -696,6 +857,4 @@
 	_printf_("   results\n");
 	results->DeepEcho();
-	_printf_("neighboor sids: \n");
-	_printf_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2] << "\n");
 }
 /*}}}*/
@@ -763,9 +922,9 @@
 	for (int imonth=0;imonth<12;imonth++) {
 		for(i=0;i<NUMVERTICES;i++) tmp[i]=monthlytemperatures[i][imonth];
-		PentaP1Input* newmonthinput1 = new PentaP1Input(SurfaceforcingsMonthlytemperaturesEnum,&tmp[0]);
+		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];
-		PentaP1Input* newmonthinput2 = new PentaP1Input(SurfaceforcingsPrecipitationEnum,&tmp[0]);
+		PentaInput* newmonthinput2 = new PentaInput(SurfaceforcingsPrecipitationEnum,&tmp[0],P1Enum);
 		NewPrecipitationInput->AddTimeInput(newmonthinput2,time+imonth/12.*yts);
 	}
@@ -792,4 +951,40 @@
 	return PentaEnum;
 
+}
+/*}}}*/
+/*FUNCTION Penta::GetAreaCoordinates{{{*/
+void Penta::GetAreaCoordinates(IssmDouble* area_coordinates,IssmDouble xyz_zero[4][3],IssmDouble xyz_list[6][3],int numpoints){
+	/*Computeportion of the element that is grounded*/ 
+
+	int         i,j,k;
+	IssmDouble  area_init,area_portion;
+	IssmDouble  xyz_bis[3][3];
+
+	area_init=fabs(xyz_list[1][0]*xyz_list[2][1] - xyz_list[1][1]*xyz_list[2][0] + xyz_list[0][0]*xyz_list[1][1] - xyz_list[0][1]*xyz_list[1][0] + xyz_list[2][0]*xyz_list[0][1] - xyz_list[2][1]*xyz_list[0][0])/2.;
+
+	/*Initialize xyz_list with original xyz_list of triangle coordinates*/
+	for(j=0;j<3;j++){ 
+		for(k=0;k<3;k++){
+			xyz_bis[j][k]=xyz_list[j][k];
+		}
+	}
+	for(i=0;i<numpoints;i++){
+		for(j=0;j<3;j++){ 
+			for(k=0;k<3;k++){
+				/*Change appropriate line*/
+				xyz_bis[j][k]=xyz_zero[i][k];
+			}
+
+			/*Compute area fraction*/
+			area_portion=fabs(xyz_bis[1][0]*xyz_bis[2][1] - xyz_bis[1][1]*xyz_bis[2][0] + xyz_bis[0][0]*xyz_bis[1][1] - xyz_bis[0][1]*xyz_bis[1][0] + xyz_bis[2][0]*xyz_bis[0][1] - xyz_bis[2][1]*xyz_bis[0][0])/2.;
+			*(area_coordinates+3*i+j)=area_portion/area_init;
+
+			/*Reinitialize xyz_list*/
+			for(k=0;k<3;k++){
+				/*Reinitialize xyz_list with original coordinates*/
+				xyz_bis[j][k]=xyz_list[j][k];
+			}
+		}
+	}
 }
 /*}}}*/
@@ -818,17 +1013,17 @@
 void  Penta::GetDofList(int** pdoflist,int approximation_enum,int setenum){
 
-	int  i,count=0;
-	int  numberofdofs=0;
-	int* doflist=NULL;
-
-	/*First, figure out size of doflist: */
-	for(i=0;i<6;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
-
-	/*Allocate: */
-	doflist=xNew<int>(numberofdofs);
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*First, figure out size of doflist and create it: */
+	int numberofdofs=0;
+	for(int i=0;i<numnodes;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+
+	/*Allocate output*/
+	int* doflist=xNew<int>(numberofdofs);
 
 	/*Populate: */
-	count=0;
-	for(i=0;i<6;i++){
+	int count=0;
+	for(int i=0;i<numnodes;i++){
 		nodes[i]->GetDofList(doflist+count,approximation_enum,setenum);
 		count+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
@@ -837,4 +1032,107 @@
 	/*Assign output pointers:*/
 	*pdoflist=doflist;
+}
+/*}}}*/
+/*FUNCTION Penta::GetDofListVelocity{{{*/
+void  Penta::GetDofListVelocity(int** pdoflist,int setenum){
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodesVelocity();
+
+	/*First, figure out size of doflist and create it: */
+	int numberofdofs=0;
+	for(int i=0;i<numnodes;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(FSvelocityEnum,setenum);
+
+	/*Allocate output*/
+	int* doflist=xNew<int>(numberofdofs);
+
+	/*Populate: */
+	int count=0;
+	for(int i=0;i<numnodes;i++){
+		nodes[i]->GetDofList(doflist+count,FSvelocityEnum,setenum);
+		count+=nodes[i]->GetNumberOfDofs(FSvelocityEnum,setenum);
+	}
+
+	/*Assign output pointers:*/
+	*pdoflist=doflist;
+}
+/*}}}*/
+/*FUNCTION Penta::GetDofListPressure{{{*/
+void  Penta::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;
+}
+/*}}}*/
+/*FUNCTION Penta::GetGroundedPart{{{*/
+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;
 }
 /*}}}*/
@@ -846,14 +1144,14 @@
 	const IssmPDouble  epsilon= 1.e-15;
 	IssmDouble         phi,s1,s2,area_init,area_grounded;
-	IssmDouble         gl[3];
-	IssmDouble         xyz_bis[3][3];
+	IssmDouble         gl[NUMVERTICES];
+	IssmDouble         xyz_bis[NUMVERTICES2D][3];
 
 	/*Recover parameters and values*/
-	GetInputListOnVertices(&gl[0],GLlevelsetEnum);
+	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;
+	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*/
@@ -870,7 +1168,7 @@
 		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);
+			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*/
@@ -879,12 +1177,12 @@
 
 			/*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));
+			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));
+			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
@@ -930,11 +1228,11 @@
 
 		/*Compute fraction of grounded element*/
-		GetJacobianDeterminant(&area_init, xyz_list,NULL);
-		GetJacobianDeterminant(&area_grounded, &xyz_bis[0][0],NULL);
+		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");
+	if(phi>1. || phi<0.) _error_("Error. Problem with portion of grounded element: value should be between 0 and 1");
 
 	return phi;
@@ -957,5 +1255,5 @@
 /*FUNCTION Penta::GetConnectivityList {{{*/
 void  Penta::GetConnectivityList(int* connectivity){
-	for(int i=0;i<NUMVERTICES;i++) connectivity[i]=nodes[i]->GetConnectivity();
+	for(int i=0;i<NUMVERTICES;i++) connectivity[i]=vertices[i]->Connectivity();
 }
 /*}}}*/
@@ -994,12 +1292,4 @@
 }
 /*}}}*/
-/*FUNCTION Penta::GetHorizontalNeighboorSids {{{*/
-int* Penta::GetHorizontalNeighboorSids(){
-
-	/*return PentaRef field*/
-	return &this->horizontalneighborsids[0];
-
-}
-/*}}}*/
 /*FUNCTION Penta::GetLowerElement{{{*/
 Penta* Penta::GetLowerElement(void){
@@ -1016,7 +1306,8 @@
 
 	_assert_(nodes);
-	for(int i=0;i<NUMVERTICES;i++){
-		if(node==nodes[i])
-		 return i;
+	int numnodes = this->NumberofNodes();
+
+	for(int i=0;i<numnodes;i++){
+		if(node==nodes[i]) return i;
 	}
 	_error_("Node provided not found among element nodes");
@@ -1029,23 +1320,26 @@
 	_assert_(sidlist);
 	_assert_(nodes);
-
-	for(int i=0;i<NUMVERTICES;i++){
+	int numnodes = this->NumberofNodes();
+
+	for(int i=0;i<numnodes;i++){
 		sidlist[i]=nodes[i]->Sid();
 	}
 }
 /*}}}*/
-/*FUNCTION Penta::GetNumberOfNodes{{{*/
+/*FUNCTION Penta::GetNodesLidList{{{*/
+void Penta::GetNodesLidList(int* lidlist){
+
+	_assert_(lidlist);
+	_assert_(nodes);
+	int numnodes = this->NumberofNodes();
+
+	for(int i=0;i<numnodes;i++){
+		lidlist[i]=nodes[i]->Lid();
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::GetNumberOfNodes;{{{*/
 int Penta::GetNumberOfNodes(void){
-
-	if(this->nodes==NULL) return 0;
-
-	switch(this->element_type){
-		case P1Enum:
-			return 6;
-		case P1DGEnum:
-			return 6;
-		default:
-			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
-	}
+	return this->NumberofNodes();
 }
 /*}}}*/
@@ -1092,4 +1386,45 @@
 		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
 	}
+}
+/*}}}*/
+/*FUNCTION Penta::GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue) {{{*/
+void Penta::GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){
+
+	_assert_(pvalue);
+
+	Input *input    = inputs->GetInput(enumtype);
+	int    numnodes = this->NumberofNodes();
+
+	/* Start looping on the number of vertices: */
+	if(input){
+		GaussPenta* gauss=new GaussPenta();
+		for(int iv=0;iv<this->NumberofNodes();iv++){
+			gauss->GaussNode(this->element_type,iv);
+			input->GetInputValue(&pvalue[iv],gauss);
+		}
+		delete gauss;
+	}
+	else{
+		for(int iv=0;iv<numnodes;iv++) pvalue[iv]=defaultvalue;
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::GetInputListOnNodes(IssmDouble* pvalue,int enumtype) {{{*/
+void Penta::GetInputListOnNodes(IssmDouble* pvalue,int enumtype){
+
+	_assert_(pvalue);
+
+	/*Recover input*/
+	Input* input=inputs->GetInput(enumtype);
+	if (!input) _error_("Input " << EnumToStringx(enumtype) << " not found in element");
+	int    numnodes = this->NumberofNodes();
+
+	/* Start looping on the number of vertices: */
+	GaussPenta* gauss=new GaussPenta();
+	for (int iv=0;iv<this->NumberofNodes();iv++){
+		gauss->GaussNode(this->element_type,iv);
+		input->GetInputValue(&pvalue[iv],gauss);
+	}
+	delete gauss;
 }
 /*}}}*/
@@ -1145,4 +1480,25 @@
 }
 /*}}}*/
+/*FUNCTION Penta::GetQuadNormal {{{*/
+void Penta:: GetQuadNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]){
+
+	/*Build unit outward pointing vector*/
+	IssmDouble AB[3];
+	IssmDouble AC[3];
+	IssmDouble norm;
+
+	AB[0]=xyz_list[1][0] - xyz_list[0][0];
+	AB[1]=xyz_list[1][1] - xyz_list[0][1];
+	AB[2]=xyz_list[1][2] - xyz_list[0][2];
+	AC[0]=xyz_list[2][0] - xyz_list[0][0];
+	AC[1]=xyz_list[2][1] - xyz_list[0][1];
+	AC[2]=xyz_list[2][2] - xyz_list[0][2];
+
+	cross(normal,AB,AC);
+	norm=sqrt(pow(normal[0],2.0)+pow(normal[1],2.0)+pow(normal[2],2.0));
+
+	for(int i=0;i<3;i++) normal[i]=normal[i]/norm;
+}
+/*}}}*/
 /*FUNCTION Penta::GetSolutionFromInputs{{{*/
 void  Penta::GetSolutionFromInputs(Vector<IssmDouble>* solution){
@@ -1155,23 +1511,23 @@
 	/*Just branch to the correct InputUpdateFromSolution generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-	#ifdef _HAVE_DIAGNOSTIC_
-	case DiagnosticHorizAnalysisEnum:
+	#ifdef _HAVE_STRESSBALANCE_
+	case StressbalanceAnalysisEnum:
 		int approximation;
 		inputs->GetInputValue(&approximation,ApproximationEnum);
-		if(approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
-			GetSolutionFromInputsDiagnosticStokes(solution);
-		}
-		else if (approximation==MacAyealApproximationEnum || approximation==PattynApproximationEnum || approximation==HutterApproximationEnum){
-			GetSolutionFromInputsDiagnosticHoriz(solution);
-		}
-		else if (approximation==MacAyealPattynApproximationEnum || approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
+		if(approximation==FSApproximationEnum || approximation==NoneApproximationEnum){
+			GetSolutionFromInputsStressbalanceFS(solution);
+		}
+		else if (approximation==SSAApproximationEnum || approximation==HOApproximationEnum || approximation==SIAApproximationEnum){
+			GetSolutionFromInputsStressbalanceHoriz(solution);
+		}
+		else if (approximation==SSAHOApproximationEnum || approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
 			return; //the elements around will create the solution
 		}
 		break;
-	case DiagnosticHutterAnalysisEnum:
-		GetSolutionFromInputsDiagnosticHutter(solution);
+	case StressbalanceSIAAnalysisEnum:
+		GetSolutionFromInputsStressbalanceSIA(solution);
 		break;
-	case DiagnosticVertAnalysisEnum:
-		//GetSolutionFromInputsDiagnosticVert(solution);
+	case StressbalanceVerticalAnalysisEnum:
+		//GetSolutionFromInputsStressbalanceVert(solution);
 		GetSolutionFromInputsOneDof(solution, VzEnum);
 		break;
@@ -1218,7 +1574,7 @@
 }
 /*}}}*/
-/*FUNCTION Penta::GetStrainRate3dPattyn{{{*/
-void Penta::GetStrainRate3dPattyn(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input){
-	/*Compute the 3d Blatter/PattynStrain Rate (5 components):
+/*FUNCTION Penta::GetStrainRate3dHO{{{*/
+void Penta::GetStrainRate3dHO(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input){
+	/*Compute the 3d Blatter/HOStrain Rate (5 components):
 	 *
 	 * epsilon=[exx eyy exy exz eyz]
@@ -1240,6 +1596,6 @@
 
 	/*Get strain rate assuming that epsilon has been allocated*/
-	vx_input->GetVxStrainRate3dPattyn(epsilonvx,xyz_list,gauss);
-	vy_input->GetVyStrainRate3dPattyn(epsilonvy,xyz_list,gauss);
+	vx_input->GetVxStrainRate3dHO(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate3dHO(epsilonvy,xyz_list,gauss);
 
 	/*Sum all contributions*/
@@ -1254,5 +1610,4 @@
 	 */
 
-	int i;
 	IssmDouble epsilonvx[6];
 	IssmDouble epsilonvy[6];
@@ -1270,5 +1625,5 @@
 
 	/*Sum all contributions*/
-	for(i=0;i<6;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i]+epsilonvz[i];
+	for(int i=0;i<6;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i]+epsilonvz[i];
 }
 /*}}}*/
@@ -1340,4 +1695,156 @@
 }
 /*}}}*/
+/*FUNCTION Penta::GetZeroLevelsetCoordinates{{{*/
+void Penta::GetZeroLevelsetCoordinates(IssmDouble* xyz_zero,IssmDouble xyz_list[6][3],int levelsetenum){
+	/*Computeportion of the element that is grounded*/ 
+
+	int         normal_orientation;
+	IssmDouble  s1,s2;
+	IssmDouble  levelset[NUMVERTICES];
+
+	/*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;
+		/*New point 1*/
+		xyz_zero[3*normal_orientation+0]=xyz_list[2][0]+s1*(xyz_list[1][0]-xyz_list[2][0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[2][1]+s1*(xyz_list[1][1]-xyz_list[2][1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[2][2]+s1*(xyz_list[1][2]-xyz_list[2][2]);
+
+		/*New point 0*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[2][0]+s2*(xyz_list[0][0]-xyz_list[2][0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[2][1]+s2*(xyz_list[0][1]-xyz_list[2][1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[2][2]+s2*(xyz_list[0][2]-xyz_list[2][2]);
+
+		/*New point 3*/
+		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[5][0]+s1*(xyz_list[4][0]-xyz_list[5][0]);
+		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[5][1]+s1*(xyz_list[4][1]-xyz_list[5][1]);
+		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[5][2]+s1*(xyz_list[4][2]-xyz_list[5][2]);
+
+		/*New point 4*/
+		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[5][0]+s2*(xyz_list[3][0]-xyz_list[5][0]);
+		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[5][1]+s2*(xyz_list[3][1]-xyz_list[5][1]);
+		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[5][2]+s2*(xyz_list[3][2]-xyz_list[5][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][0]+s1*(xyz_list[2][0]-xyz_list[0][0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[0][1]+s1*(xyz_list[2][1]-xyz_list[0][1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[0][2]+s1*(xyz_list[2][2]-xyz_list[0][2]);
+
+		/*New point 2*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[0][0]+s2*(xyz_list[1][0]-xyz_list[0][0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[0][1]+s2*(xyz_list[1][1]-xyz_list[0][1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[0][2]+s2*(xyz_list[1][2]-xyz_list[0][2]);
+
+		/*New point 3*/
+		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[3][0]+s1*(xyz_list[5][0]-xyz_list[3][0]);
+		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[3][1]+s1*(xyz_list[5][1]-xyz_list[3][1]);
+		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[3][2]+s1*(xyz_list[5][2]-xyz_list[3][2]);
+
+		/*New point 4*/
+		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[3][0]+s2*(xyz_list[4][0]-xyz_list[3][0]);
+		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[3][1]+s2*(xyz_list[4][1]-xyz_list[3][1]);
+		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[3][2]+s2*(xyz_list[4][2]-xyz_list[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][0]+s1*(xyz_list[0][0]-xyz_list[1][0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[1][1]+s1*(xyz_list[0][1]-xyz_list[1][1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[1][2]+s1*(xyz_list[0][2]-xyz_list[1][2]);
+
+		/*New point 2*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[1][0]+s2*(xyz_list[2][0]-xyz_list[1][0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[1][1]+s2*(xyz_list[2][1]-xyz_list[1][1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[1][2]+s2*(xyz_list[2][2]-xyz_list[1][2]);
+
+		/*New point 3*/
+		xyz_zero[3*(2+1-normal_orientation)+0]=xyz_list[4][0]+s1*(xyz_list[3][0]-xyz_list[4][0]);
+		xyz_zero[3*(2+1-normal_orientation)+1]=xyz_list[4][1]+s1*(xyz_list[3][1]-xyz_list[4][1]);
+		xyz_zero[3*(2+1-normal_orientation)+2]=xyz_list[4][2]+s1*(xyz_list[3][2]-xyz_list[4][2]);
+
+		/*New point 4*/
+		xyz_zero[3*(2+normal_orientation)+0]=xyz_list[4][0]+s2*(xyz_list[5][0]-xyz_list[4][0]);
+		xyz_zero[3*(2+normal_orientation)+1]=xyz_list[4][1]+s2*(xyz_list[5][1]-xyz_list[4][1]);
+		xyz_zero[3*(2+normal_orientation)+2]=xyz_list[4][2]+s2*(xyz_list[5][2]-xyz_list[4][2]);
+	}
+	else if(levelset[0]==0 && levelset[1]==0){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[0][0];
+		xyz_zero[3*0+1]=xyz_list[0][1];
+		xyz_zero[3*0+2]=xyz_list[0][2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[1][0];
+		xyz_zero[3*1+1]=xyz_list[1][1];
+		xyz_zero[3*1+2]=xyz_list[1][2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[4][0];
+		xyz_zero[3*2+1]=xyz_list[4][1];
+		xyz_zero[3*2+2]=xyz_list[4][2];
+
+		/*New point 4*/
+		xyz_zero[3*3+0]=xyz_list[3][0];
+		xyz_zero[3*3+1]=xyz_list[3][1];
+		xyz_zero[3*3+2]=xyz_list[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][0];
+		xyz_zero[3*0+1]=xyz_list[2][1];
+		xyz_zero[3*0+2]=xyz_list[2][2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[0][0];
+		xyz_zero[3*1+1]=xyz_list[0][1];
+		xyz_zero[3*1+2]=xyz_list[0][2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[3][0];
+		xyz_zero[3*2+1]=xyz_list[3][1];
+		xyz_zero[3*2+2]=xyz_list[3][2];
+
+		/*New point 4*/
+		xyz_zero[3*3+0]=xyz_list[5][0];
+		xyz_zero[3*3+1]=xyz_list[5][1];
+		xyz_zero[3*3+2]=xyz_list[5][2];
+	}
+	else if(levelset[1]==0 && levelset[2]==0){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[1][0];
+		xyz_zero[3*0+1]=xyz_list[1][1];
+		xyz_zero[3*0+2]=xyz_list[1][2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[2][0];
+		xyz_zero[3*1+1]=xyz_list[2][1];
+		xyz_zero[3*1+2]=xyz_list[2][2];
+
+		/*New point 3*/
+		xyz_zero[3*2+0]=xyz_list[5][0];
+		xyz_zero[3*2+1]=xyz_list[5][1];
+		xyz_zero[3*2+2]=xyz_list[5][2];
+
+		/*New point 4*/
+		xyz_zero[3*3+0]=xyz_list[4][0];
+		xyz_zero[3*3+1]=xyz_list[4][1];
+		xyz_zero[3*3+2]=xyz_list[4][2];
+	}
+	else _error_("Case not covered");
+}
+/*}}}*/
 /*FUNCTION Penta::Sid {{{*/
 int    Penta::Sid(){
@@ -1388,19 +1895,10 @@
 
 	/*Intermediaries*/
-	int    i,t;
-	int    penta_vertex_ids[6];
-	int    row;
-	IssmDouble nodeinputs[6];
-	IssmDouble time;
-	TransientInput* transientinput=NULL;
-
-	int    numberofvertices;
-	int    numberofelements;
-	IssmDouble yts;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->Constant(&yts,ConstantsYtsEnum);
+	int             i,t;
+	int             penta_vertex_ids[6];
+	int             row;
+	IssmDouble      nodeinputs[6];
+	IssmDouble      time;
+	TransientInput *transientinput      = NULL;
 
 	/*Branch on type of vector: nodal or elementary: */
@@ -1409,10 +1907,10 @@
 		/*Recover vertices ids needed to initialize inputs*/
 		for(i=0;i<6;i++){ 
-			_assert_(iomodel->Data(MeshElementsEnum));
-			penta_vertex_ids[i]=reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
+			_assert_(iomodel->elements);
+			penta_vertex_ids[i]=iomodel->elements[6*index+i]; //ids for vertices are in the elements array from Matlab
 		}
 
 		/*Are we in transient or static? */
-		if(M==numberofvertices){
+		if(M==iomodel->numberofvertices){
 
 			/*create input values: */
@@ -1420,7 +1918,7 @@
 
 			/*create static input: */
-			this->inputs->AddInput(new PentaP1Input(vector_enum,nodeinputs));
-		}
-		else if(M==numberofvertices+1){
+			this->inputs->AddInput(new PentaInput(vector_enum,nodeinputs,P1Enum));
+		}
+		else if(M==iomodel->numberofvertices+1){
 			/*create transient input: */
 			for(t=0;t<N;t++){ //N is the number of times
@@ -1433,16 +1931,16 @@
 
 				/*time? :*/
-				time=(IssmDouble)vector[(M-1)*N+t]*yts;
+				time=(IssmDouble)vector[(M-1)*N+t];
 
 				if(t==0)transientinput=new TransientInput(vector_enum);
-				transientinput->AddTimeInput(new PentaP1Input(vector_enum,nodeinputs),time);
+				transientinput->AddTimeInput(new PentaInput(vector_enum,nodeinputs,P1Enum),time);
 			}
 			this->inputs->AddInput(transientinput);
 		}
-		else _error_("nodal vector is either numberofnodes (" << numberofvertices << "), or numberofnodes+1 long. Field provided is " << M << " long. Enum " << EnumToStringx(vector_enum));
+		else _error_("nodal vector is either numberofvertices (" << iomodel->numberofvertices << "), or numberofvertices+1 long. Field provided is " << M << " long. Enum " << EnumToStringx(vector_enum));
 	}
 	else if(vector_type==2){ //element vector
 		/*Are we in transient or static? */
-		if(M==numberofelements){
+		if(M==iomodel->numberofelements){
 
 			/*static mode: create an input out of the element value: */
@@ -1490,5 +1988,5 @@
 
 	/*OK, we are on bed. Initialize global inputs as 0*/
-	total_thickness_input =new PentaP1Input(ThicknessEnum,zeros_list);
+	total_thickness_input =new PentaInput(ThicknessEnum,zeros_list,P1Enum);
 
 	/*Now follow all the upper element from the base to the surface to integrate the input*/
@@ -1508,8 +2006,8 @@
 		/*If first time, initialize total_integrated_input*/
 		if (step==0){
-			if (original_input->ObjectEnum()==PentaP1InputEnum)
-			 total_integrated_input=new PentaP1Input(average_enum_type,zeros_list);
+			if (original_input->ObjectEnum()==PentaInputEnum)
+			 total_integrated_input=new PentaInput(average_enum_type,zeros_list,P1Enum);
 			else if (original_input->ObjectEnum()==ControlInputEnum)
-			 total_integrated_input=new PentaP1Input(average_enum_type,zeros_list);
+			 total_integrated_input=new PentaInput(average_enum_type,zeros_list,P1Enum);
 			else if (original_input->ObjectEnum()==DoubleInputEnum)
 			 total_integrated_input=new DoubleInput(average_enum_type,0.0);
@@ -1524,5 +2022,5 @@
 			Helem_list[i+3]=Helem_list[i];
 		}
-		element_thickness_input=new PentaP1Input(ThicknessEnum,Helem_list);
+		element_thickness_input=new PentaInput(ThicknessEnum,Helem_list,P1Enum);
 
 		/*Step3: Vertically integrate A COPY of the original*/
@@ -1586,20 +2084,13 @@
 
 	/*Step1: Get and Extrude original input: */
-	if (object_type==ElementEnum){
+	if(object_type==ElementEnum){
 		num_inputs=1;
 		base_inputs=xNew<Input*>(num_inputs);
 		base_inputs[0]=(Input*)this->inputs->GetInput(enum_type);
 	}
-	else if (object_type==MaterialsEnum){
+	else if(object_type==MaterialsEnum){
 		num_inputs=1;
 		base_inputs=xNew<Input*>(num_inputs);
 		base_inputs[0]=(Input*)material->inputs->GetInput(enum_type);
-	}
-	else if (object_type==NodeEnum){
-		num_inputs=3; //only the three upper nodes
-		base_inputs=xNew<Input*>(num_inputs);
-		for(i=0;i<num_inputs;i++){
-			base_inputs[i]=(Input*)this->nodes[i]->inputs->GetInput(enum_type);
-		}
 	}
 	else{
@@ -1630,7 +2121,4 @@
 				penta->material->inputs->AddInput((Input*)copy);
 			}
-			else if(object_type==NodeEnum){
-				penta->nodes[i+3]->inputs->AddInput((Input*)copy); //change only the three upper nodes
-			}
 			else{
 				_error_("object of type " << EnumToStringx(object_type) << " not supported yet");
@@ -1675,8 +2163,8 @@
 	/*If we don't find it, no big deal, just don't do the transfer. Otherwise, build a new Result 
 	 * object out of the input, with the additional step and time information: */
-	this->results->AddObject((Object*)input->SpawnResult(step,time));
+	this->results->AddResult(input->SpawnResult(step,time));
 	#ifdef _HAVE_CONTROL_
 	if(input->ObjectEnum()==ControlInputEnum){
-		if(((ControlInput*)input)->gradient!=NULL) this->results->AddObject((Object*)((ControlInput*)input)->SpawnGradient(step,time));
+		if(((ControlInput*)input)->gradient!=NULL) this->results->AddResult(((ControlInput*)input)->SpawnGradient(step,time));
 	}
 	#endif
@@ -1734,10 +2222,10 @@
 	/*Checks if debuging*/
 	/*{{{*/
-	_assert_(iomodel->Data(MeshElementsEnum));
+	_assert_(iomodel->elements);
 	/*}}}*/
 
 	/*Recover vertices ids needed to initialize inputs*/
 	for(i=0;i<6;i++){ 
-		penta_vertex_ids[i]=reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
+		penta_vertex_ids[i]=iomodel->elements[6*index+i]; //ids for vertices are in the elements array from Matlab
 	}
 
@@ -1752,5 +2240,5 @@
 						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(BalancethicknessThickeningRateEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 					}
 					break;
@@ -1760,5 +2248,5 @@
 						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(VxEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(VxEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 					}
 					break;
@@ -1768,5 +2256,5 @@
 						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
 						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i]/yts;
-						this->inputs->AddInput(new ControlInput(VyEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(VyEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 					}
 					break;
@@ -1776,5 +2264,5 @@
 						for(j=0;j<6;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
 						for(j=0;j<6;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(penta_vertex_ids[j]-1)*num_control_type+i];
-						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+						this->inputs->AddInput(new ControlInput(FrictionCoefficientEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 					}
 					break;
@@ -1791,27 +2279,27 @@
 	//Need to know the type of approximation for this element
 	if(iomodel->Data(FlowequationElementEquationEnum)){
-		if (iomodel->Data(FlowequationElementEquationEnum)[index]==MacAyealApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==PattynApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,PattynApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==MacAyealPattynApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealPattynApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==HutterApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,HutterApproximationEnum));
+		if (iomodel->Data(FlowequationElementEquationEnum)[index]==SSAApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,SSAApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==HOApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,HOApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==SSAHOApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,SSAHOApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==SIAApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,SIAApproximationEnum));
 		}
 		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==L1L2ApproximationEnum){
 			this->inputs->AddInput(new IntInput(ApproximationEnum,L1L2ApproximationEnum));
 		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==StokesApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,StokesApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==MacAyealStokesApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,MacAyealStokesApproximationEnum));
-		}
-		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==PattynStokesApproximationEnum){
-			this->inputs->AddInput(new IntInput(ApproximationEnum,PattynStokesApproximationEnum));
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==FSApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,FSApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==SSAFSApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,SSAFSApproximationEnum));
+		}
+		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==HOFSApproximationEnum){
+			this->inputs->AddInput(new IntInput(ApproximationEnum,HOFSApproximationEnum));
 		}
 		else if (iomodel->Data(FlowequationElementEquationEnum)[index]==NoneApproximationEnum){
@@ -1830,5 +2318,5 @@
 		for(i=0;i<num_cm_responses;i++){
 			for(j=0;j<6;j++)nodeinputs[j]=iomodel->Data(InversionCostFunctionsCoefficientsEnum)[(penta_vertex_ids[j]-1)*num_cm_responses+i];
-			datasetinput->inputs->AddObject(new PentaP1Input(InversionCostFunctionsCoefficientsEnum,nodeinputs));
+			datasetinput->inputs->AddObject(new PentaInput(InversionCostFunctionsCoefficientsEnum,nodeinputs,P1Enum));
 		}
 
@@ -1848,13 +2336,13 @@
 	/*Just branch to the correct InputUpdateFromSolution generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-	#ifdef _HAVE_DIAGNOSTIC_
-	case DiagnosticHorizAnalysisEnum:
-		InputUpdateFromSolutionDiagnosticHoriz( solution);
+	#ifdef _HAVE_STRESSBALANCE_
+	case StressbalanceAnalysisEnum:
+		InputUpdateFromSolutionStressbalanceHoriz( solution);
 		break;
-	case DiagnosticHutterAnalysisEnum:
-		InputUpdateFromSolutionDiagnosticHutter( solution);
+	case StressbalanceSIAAnalysisEnum:
+		InputUpdateFromSolutionStressbalanceSIA( solution);
 		break;
-	case DiagnosticVertAnalysisEnum:
-		InputUpdateFromSolutionDiagnosticVert( solution);
+	case StressbalanceVerticalAnalysisEnum:
+		InputUpdateFromSolutionStressbalanceVert( solution);
 		break;
 	#endif
@@ -1863,6 +2351,6 @@
 		int approximation;
 		inputs->GetInputValue(&approximation,ApproximationEnum);
-		if(approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
-			InputUpdateFromSolutionAdjointStokes( solution);
+		if(approximation==FSApproximationEnum || approximation==NoneApproximationEnum){
+			InputUpdateFromSolutionAdjointFS( solution);
 		}
 		else{
@@ -1894,6 +2382,12 @@
 		InputUpdateFromSolutionOneDofCollapsed(solution,SurfaceSlopeYEnum);
 		break;
-	case PrognosticAnalysisEnum:
-		InputUpdateFromSolutionPrognostic(solution);
+	case MasstransportAnalysisEnum:
+		InputUpdateFromSolutionMasstransport(solution);
+		break;
+	case FreeSurfaceTopAnalysisEnum:
+		InputUpdateFromSolutionFreeSurfaceTop(solution);
+		break;
+	case FreeSurfaceBaseAnalysisEnum:
+		InputUpdateFromSolutionFreeSurfaceBase(solution);
 		break;
 	#ifdef _HAVE_BALANCED_
@@ -1915,6 +2409,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionPrognostic{{{*/
-void  Penta::InputUpdateFromSolutionPrognostic(IssmDouble* solution){
+/*FUNCTION Penta::InputUpdateFromSolutionMasstransport{{{*/
+void  Penta::InputUpdateFromSolutionMasstransport(IssmDouble* solution){
 
 	const int  numdof   = NDOF1*NUMVERTICES;
@@ -1930,4 +2424,5 @@
 	IssmDouble oldsurface[NUMVERTICES];
 	IssmDouble oldthickness[NUMVERTICES];
+	IssmDouble phi[NUMVERTICES];
 	Penta  *penta   = NULL;
 
@@ -1939,5 +2434,5 @@
 
 	/*Use the dof list to index into the solution vector and extrude it */
-	this->parameters->FindParam(&minthickness,PrognosticMinThicknessEnum);
+	this->parameters->FindParam(&minthickness,MasstransportMinThicknessEnum);
 	for(i=0;i<numdof2d;i++){
 		newthickness[i]=solution[doflist[i]];
@@ -1952,7 +2447,8 @@
 	GetInputListOnVertices(&oldsurface[0],SurfaceEnum);
 	GetInputListOnVertices(&oldthickness[0],ThicknessEnum);
-
-	/*Fing PrognosticHydrostaticAdjustment to figure out how to update the geometry:*/
-	this->parameters->FindParam(&hydroadjustment,PrognosticHydrostaticAdjustmentEnum);
+	GetInputListOnVertices(&phi[0],MaskGroundediceLevelsetEnum);
+
+	/*Fing MasstransportHydrostaticAdjustment to figure out how to update the geometry:*/
+	this->parameters->FindParam(&hydroadjustment,MasstransportHydrostaticAdjustmentEnum);
 
 	/*recover material parameters: */
@@ -1962,5 +2458,5 @@
 	for(i=0;i<numdof;i++) {
 		/*If shelf: hydrostatic equilibrium*/
-		if (this->nodes[i]->IsGrounded()){
+		if (phi[i]>0.){
 			newsurface[i]=oldbed[i]+newthickness[i]; //surface = oldbed + newthickness
 			newbed[i]=oldbed[i];               //same bed: do nothing
@@ -1983,10 +2479,112 @@
 	for(;;){
 		/*Add input to the element: */
-		penta->inputs->AddInput(new PentaP1Input(ThicknessEnum,newthickness));
-		penta->inputs->AddInput(new PentaP1Input(SurfaceEnum,newsurface));
-		penta->inputs->AddInput(new PentaP1Input(BedEnum,newbed));
+		penta->inputs->AddInput(new PentaInput(ThicknessEnum,newthickness,P1Enum));
+		penta->inputs->AddInput(new PentaInput(SurfaceEnum,newsurface,P1Enum));
+		penta->inputs->AddInput(new PentaInput(BedEnum,newbed,P1Enum));
 
 		/*Stop if we have reached the surface*/
 		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionFreeSurfaceTop{{{*/
+void  Penta::InputUpdateFromSolutionFreeSurfaceTop(IssmDouble* solution){
+
+	const int  numdof   = NDOF1*NUMVERTICES;
+	const int  numdof2d = NDOF1*NUMVERTICES2D;
+
+	int    i;
+	int*   doflist = NULL;
+	IssmDouble newthickness[numdof];
+	IssmDouble newbed[numdof];
+	IssmDouble newsurface[numdof];
+
+	/*If not on bed, return*/
+	if (!IsOnSurface()) return;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector and extrude it */
+	for(i=0;i<numdof2d;i++){
+		newsurface[i+numdof2d]=solution[doflist[i+numdof2d]];
+		if(xIsNan<IssmDouble>(newsurface[i+numdof2d])) _error_("NaN found in solution vector");
+		newsurface[i]=newsurface[i+numdof2d];
+	}
+
+	/*Get previous bed and thickness*/
+	GetInputListOnVertices(&newbed[0],BedEnum);
+
+	for(i=0;i<numdof;i++) {
+		newthickness[i]=newsurface[i]-newbed[i];
+		_assert_(newthickness[i]>0.);
+	}
+
+	/*Start looping over all elements above current element and update all inputs*/
+	Penta* penta=this;
+	for(;;){
+		/*Add input to the element: */
+		penta->inputs->AddInput(new PentaInput(ThicknessEnum,newthickness,P1Enum));
+		penta->inputs->AddInput(new PentaInput(SurfaceEnum,newsurface,P1Enum));
+
+		/*Stop if we have reached the surface*/
+		if(penta->IsOnBed()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetLowerElement(); _assert_(penta->Id()!=this->id);
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionFreeSurfaceBase{{{*/
+void  Penta::InputUpdateFromSolutionFreeSurfaceBase(IssmDouble* solution){
+
+	const int  numdof   = NDOF1*NUMVERTICES;
+	const int  numdof2d = NDOF1*NUMVERTICES2D;
+
+	int    i;
+	int*   doflist = NULL;
+	IssmDouble newthickness[numdof];
+	IssmDouble newbed[numdof];
+	IssmDouble newsurface[numdof];
+
+	/*If not on bed, return*/
+	if (!IsOnBed()) return;
+
+	/*Get dof list: */
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+
+	/*Use the dof list to index into the solution vector and extrude it */
+	for(i=0;i<numdof2d;i++){
+		newbed[i]=solution[doflist[i]];
+		if(xIsNan<IssmDouble>(newbed[i])) _error_("NaN found in solution vector");
+		newbed[i+numdof2d]=newbed[i];
+	}
+
+	/*Get previous bed and thickness*/
+	GetInputListOnVertices(&newsurface[0],SurfaceEnum);
+
+	for(i=0;i<numdof;i++) {
+		newthickness[i]=newsurface[i]-newbed[i];
+		_assert_(newthickness[i]>0.);
+	}
+
+	/*Start looping over all elements above current element and update all inputs*/
+	Penta* penta=this;
+	for(;;){
+		/*Add input to the element: */
+		penta->inputs->AddInput(new PentaInput(ThicknessEnum,newthickness,P1Enum));
+		penta->inputs->AddInput(new PentaInput(BedEnum,newbed,P1Enum));
+
+		/*Stop if we have reached the surface*/
+		if(penta->IsOnSurface()) break;
 
 		/* get upper Penta*/
@@ -2016,5 +2614,5 @@
 
 	/*Add input to the element: */
-	this->inputs->AddInput(new PentaP1Input(enum_type,values));
+	this->inputs->AddInput(new PentaInput(enum_type,values,P1Enum));
 
 	/*Free ressources:*/
@@ -2049,5 +2647,5 @@
 	for(;;){
 		/*Add input to the element: */
-		penta->inputs->AddInput(new PentaP1Input(enum_type,values));
+		penta->inputs->AddInput(new PentaInput(enum_type,values,P1Enum));
 
 		/*Stop if we have reached the surface*/
@@ -2079,8 +2677,8 @@
 			/*update input*/
 			if (name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
-				material->inputs->AddInput(new PentaP1Input(name,values));
+				material->inputs->AddInput(new PentaInput(name,values,P1Enum));
 			}
 			else{
-				this->inputs->AddInput(new PentaP1Input(name,values));
+				this->inputs->AddInput(new PentaInput(name,values,P1Enum));
 			}
 			return;
@@ -2092,8 +2690,8 @@
 			/*update input*/
 			if (name==MaterialsRheologyZEnum || name==MaterialsRheologyZbarEnum){
-				material->inputs->AddInput(new PentaP1Input(name,values));
+				material->inputs->AddInput(new PentaInput(name,values,P1Enum));
 			}
 			else{
-				this->inputs->AddInput(new PentaP1Input(name,values));
+				this->inputs->AddInput(new PentaInput(name,values,P1Enum));
 			}
 			return;
@@ -2109,5 +2707,5 @@
 			}
 			/*Add input to the element: */
-			this->inputs->AddInput(new PentaP1Input(name,values));
+			this->inputs->AddInput(new PentaInput(name,values,P1Enum));
 
 			/*Free ressources:*/
@@ -2121,23 +2719,13 @@
 			}
 			/*Add input to the element: */
-			this->inputs->AddInput(new PentaP1Input(name,values));
-			
+			this->inputs->AddInput(new PentaInput(name,values,P1Enum));
+
 			/*Free ressources:*/
 			xDelete<int>(doflist);
 			return;
-			
+
 	  default:
 			_error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
 	}
-}
-/*}}}*/
-/*FUNCTION Penta::InputUpdateFromVector(int* vector, int name, int type);{{{*/
-void  Penta::InputUpdateFromVector(int* vector, int name, int type){
-	_error_("not supported yet!");
-}
-/*}}}*/
-/*FUNCTION Penta::InputUpdateFromVector(bool* vector, int name, int type);{{{*/
-void  Penta::InputUpdateFromVector(bool* vector, int name, int type){
-	_error_("not supported yet!");
 }
 /*}}}*/
@@ -2177,5 +2765,6 @@
 				name==WaterfractionEnum||
 				name==FrictionCoefficientEnum ||
-				name==GLlevelsetEnum ||
+				name==MaskGroundediceLevelsetEnum ||
+				name==MaskIceLevelsetEnum ||
 				name==GradientEnum ||
 				name==OldGradientEnum  ||
@@ -2201,5 +2790,5 @@
 				name==HydrologydcMaskEplactiveEnum ||
 				name==WaterTransferEnum
-				
+
 				) {
 		return true;
@@ -2211,32 +2800,29 @@
 bool   Penta::IsFloating(){
 
-	bool onshelf;
-	inputs->GetInputValue(&onshelf,MaskElementonfloatingiceEnum);
-	return onshelf;
-}
-/*}}}*/
-/*FUNCTION Penta::IsNodeOnShelf {{{*/
-bool   Penta::IsNodeOnShelf(){
+	bool shelf;
+	int  migration_style;
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+
+	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==AgressiveMigrationEnum || migration_style==SoftMigrationEnum){ //Floating if all nodes are floating
+		if(this->inputs->Min(MaskGroundediceLevelsetEnum) > 0.) shelf=false;
+		else shelf=true;
+	}
+	else _error_("migration_style not implemented yet");
+
+	return shelf;
+}
+/*}}}*/
+/*FUNCTION Penta::IsNodeOnShelfFromFlags {{{*/
+bool   Penta::IsNodeOnShelfFromFlags(IssmDouble* flags){
 
 	int  i;
 	bool shelf=false;
 
-	for(i=0;i<6;i++){
-		if (nodes[i]->IsFloating()){
-			shelf=true;
-			break;
-		}
-	}
-	return shelf;
-}
-/*}}}*/
-/*FUNCTION Penta::IsNodeOnShelfFromFlags {{{*/
-bool   Penta::IsNodeOnShelfFromFlags(IssmDouble* flags){
-
-	int  i;
-	bool shelf=false;
-
 	for(i=0;i<NUMVERTICES;i++){
-		if (reCast<bool,IssmDouble>(flags[nodes[i]->Sid()])){
+		if (flags[vertices[i]->Pid()]<0.){
 			shelf=true;
 			break;
@@ -2254,10 +2840,16 @@
 }
 /*}}}*/
-/*FUNCTION Penta::IsOnWater {{{*/
-bool   Penta::IsOnWater(){
-
-	bool onwater;
-	inputs->GetInputValue(&onwater,MaskElementonwaterEnum);
-	return onwater;
+/*FUNCTION Penta::NoIceInElement {{{*/
+bool   Penta::NoIceInElement(){
+
+	/*Get levelset*/
+	IssmDouble ls[NUMVERTICES];
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/*If the level set is >0, ice is present in this element*/
+	if(ls[0]>0. || ls[1]>0. || ls[2]>0.) return false;
+
+	/*If the level set is awlays <=0, there is no ice here*/
+	return true;
 }
 /*}}}*/
@@ -2328,5 +2920,5 @@
 
 		/*Compute the length of this edge and compare it to the minimal length*/
-		length=pow(pow(xyz_list[node0][0]-xyz_list[node1][0],2.0)+pow(xyz_list[node0][1]-xyz_list[node1][1],2.0)+pow(xyz_list[node0][2]-xyz_list[node1][2],2.0),0.5);
+		length=sqrt(pow(xyz_list[node0][0]-xyz_list[node1][0],2)+pow(xyz_list[node0][1]-xyz_list[node1][1],2)+pow(xyz_list[node0][2]-xyz_list[node1][2],2));
 		if(length<minlength || minlength<0) minlength=length;
 	}
@@ -2459,9 +3051,8 @@
      agd[iv]=PddSurfaceMassBlance(&monthlytemperatures[iv][0], &monthlyprec[iv][0], pdds, pds, 
 				  signorm, yts, h[iv], s[iv], rho_ice, rho_water, desfac, s0p);
-     //printf("mass balance %f \n",agd[iv]);
    }
 
    /*Update inputs*/    
-   this->inputs->AddInput(new PentaP1Input(SurfaceforcingsMassBalanceEnum,&agd[0]));
+   this->inputs->AddInput(new PentaInput(SurfaceforcingsMassBalanceEnum,&agd[0],P1Enum));
    //this->inputs->AddInput(new PentaVertexInput(ThermalSpcTemperatureEnum,&Tsurf[0]));
    this->InputExtrude(SurfaceforcingsMassBalanceEnum,ElementEnum);
@@ -2471,6 +3062,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::ReduceMatrixStokes {{{*/
-void Penta::ReduceMatrixStokes(IssmDouble* Ke_reduced, IssmDouble* Ke_temp){
+/*FUNCTION Penta::ReduceMatrixFS {{{*/
+void Penta::ReduceMatrixFS(IssmDouble* Ke_reduced, IssmDouble* Ke_temp){
 
 	int    i,j;
@@ -2513,6 +3104,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::ReduceVectorStokes {{{*/
-void Penta::ReduceVectorStokes(IssmDouble* Pe_reduced, IssmDouble* Ke_temp, IssmDouble* Pe_temp){
+/*FUNCTION Penta::ReduceVectorFS {{{*/
+void Penta::ReduceVectorFS(IssmDouble* Pe_reduced, IssmDouble* Ke_temp, IssmDouble* Pe_temp){
 
 	int    i,j;
@@ -2601,27 +3192,40 @@
 void  Penta::ResetCoordinateSystem(void){
 
-	int    approximation;
-	IssmDouble slopex[NUMVERTICES];
-	IssmDouble slopey[NUMVERTICES];
+	int        approximation;
+	int        numindices;
+	int       *indices = NULL;
+	IssmDouble slopex,slopey;
 	IssmDouble xz_plane[6];
 
-	/*For Stokes only: we want the CS to be tangential to the bedrock*/
+	/*For FS only: we want the CS to be tangential to the bedrock*/
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(IsFloating() || !IsOnBed() || (approximation!=StokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum &&  approximation!=PattynStokesApproximationEnum)) return;
-
-	/*Get slope on each node*/
-	GetInputListOnVertices(&slopex[0],BedSlopeXEnum);
-	GetInputListOnVertices(&slopey[0],BedSlopeYEnum);
-
-	/*Loop over basal nodes (first 3) and update their CS*/
-	for(int i=0;i<NUMVERTICES2D;i++){
-
-		/*New X axis             New Z axis*/
-		xz_plane[0]=1.;          xz_plane[3]=-slopex[i];  
-		xz_plane[1]=0.;          xz_plane[4]=-slopey[i];  
-		xz_plane[2]=slopex[i];   xz_plane[5]=1.;          
-
-		XZvectorsToCoordinateSystem(&this->nodes[i]->coord_system[0][0],&xz_plane[0]);
-	}
+	if(IsFloating() || !IsOnBed() || (approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum &&  approximation!=HOFSApproximationEnum)) return;
+
+	/*Get number of nodes for velocity only and base*/
+	BasalNodeIndices(&numindices,&indices,this->VelocityInterpolation());
+
+	/*Get inputs*/
+	Input* slopex_input=inputs->GetInput(BedSlopeXEnum); _assert_(slopex_input);
+	Input* slopey_input=inputs->GetInput(BedSlopeYEnum); _assert_(slopey_input);
+
+	/*Loop over basal nodes and update their CS*/
+	GaussPenta* gauss = new GaussPenta();
+	for(int i=0;i<numindices;i++){//FIXME
+		gauss->GaussNode(this->VelocityInterpolation(),indices[i]);
+
+		slopex_input->GetInputValue(&slopex,gauss);
+		slopey_input->GetInputValue(&slopey,gauss);
+
+		/*New X axis          New Z axis*/
+		xz_plane[0]=1.;       xz_plane[3]=-slopex;  
+		xz_plane[1]=0.;       xz_plane[4]=-slopey;  
+		xz_plane[2]=slopex;   xz_plane[5]=1.;          
+
+		XZvectorsToCoordinateSystem(&this->nodes[indices[i]]->coord_system[0][0],&xz_plane[0]);
+	}
+
+	/*cleanup*/
+	xDelete<int>(indices);
+	delete gauss;
 }
 /*}}}*/
@@ -2649,5 +3253,8 @@
 /*}}}*/
 /*FUNCTION Penta::SetwiseNodeConnectivity{{{*/
-void Penta::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+void Penta::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){
+
+	/*Intermediaries*/
+	const int numnodes = this->NumberofNodes();
 
 	/*Output */
@@ -2656,10 +3263,14 @@
 
 	/*Loop over all nodes*/
-	for(int i=0;i<6;i++){
-
-		if(!flags[this->nodes[i]->Sid()]){
+	for(int i=0;i<numnodes;i++){
+
+		if(!flags[this->nodes[i]->Lid()]){
 
 			/*flag current node so that no other element processes it*/
-			flags[this->nodes[i]->Sid()]=true;
+			flags[this->nodes[i]->Lid()]=true;
+
+			int counter=0;
+			while(flagsindices[counter]>=0) counter++;
+			flagsindices[counter]=this->nodes[i]->Lid();
 
 			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
@@ -2698,7 +3309,7 @@
 	int analysis_type,approximation,numlayers;
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	if(analysis_type==DiagnosticHorizAnalysisEnum){
+	if(analysis_type==StressbalanceAnalysisEnum){
 		inputs->GetInputValue(&approximation,ApproximationEnum);
-		if(approximation==MacAyealPattynApproximationEnum || approximation==MacAyealStokesApproximationEnum){
+		if(approximation==SSAHOApproximationEnum || approximation==SSAFSApproximationEnum){
 			parameters->FindParam(&numlayers,MeshNumberoflayersEnum);
 			o_nz += numlayers*3;
@@ -2713,32 +3324,18 @@
 /*}}}*/
 /*FUNCTION Penta::SpawnTria {{{*/
-Tria*  Penta::SpawnTria(int g0, int g1, int g2){
-
-	int   analysis_counter;
-	int   indices[3];
-	int   zero=0;
-	Tria*       tria            = NULL;
-	Inputs*     tria_inputs     = NULL;
-	Results*    tria_results    = NULL;
-	Parameters* tria_parameters = NULL;
+Tria*  Penta::SpawnTria(int location){
+
+	int analysis_counter;
 
 	/*go into parameters and get the analysis_counter: */
 	this->parameters->FindParam(&analysis_counter,AnalysisCounterEnum);
 
-	indices[0]=g0;
-	indices[1]=g1;
-	indices[2]=g2;
-
-	tria_parameters=this->parameters;
-	tria_inputs=(Inputs*)this->inputs->SpawnTriaInputs(indices);
-	tria_results=(Results*)this->results->SpawnTriaResults(indices);
-
-	tria=new Tria();
+	/*Create Tria*/
+	Tria* tria=new Tria();
 	tria->id=this->id;
-	tria->inputs=tria_inputs;
-	tria->results=tria_results;
-	tria->parameters=tria_parameters;
+	tria->inputs=(Inputs*)this->inputs->SpawnTriaInputs(location);
+	tria->parameters=this->parameters;
 	tria->element_type=P1Enum; //Only P1 CG for now (TO BE CHANGED)
-	this->SpawnTriaHook(dynamic_cast<ElementHook*>(tria),&indices[0]);
+	this->SpawnTriaHook(dynamic_cast<ElementHook*>(tria),location);
 
 	/*Spawn material*/
@@ -2746,5 +3343,5 @@
 	tria->material=(Material*)this->material->copy();
 	delete tria->material->inputs;
-	tria->material->inputs=(Inputs*)this->material->inputs->SpawnTriaInputs(indices);
+	tria->material->inputs=(Inputs*)this->material->inputs->SpawnTriaInputs(location);
 
 	/*recover nodes, material and matpar: */
@@ -2753,4 +3350,5 @@
 	tria->matpar=(Matpar*)tria->hmatpar->delivers();
 
+	/*Return new Tria*/
 	return tria;
 }
@@ -2799,5 +3397,5 @@
 	}  //end of the loop over the vertices
 	  /*Update inputs*/
-	  this->inputs->AddInput(new PentaP1Input(SurfaceforcingsMassBalanceEnum,&smb[0]));
+	  this->inputs->AddInput(new PentaInput(SurfaceforcingsMassBalanceEnum,&smb[0],P1Enum));
 }
 /*}}}*/
@@ -2813,17 +3411,17 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/*Bail out if this element if:
-	 * -> Non MacAyeal not on the surface
-	 * -> MacAyeal (2d model) and not on bed) */
-	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+	 * -> Non SSA not on the surface
+	 * -> SSA (2d model) and not on bed) */
+	if ((approximation!=SSAApproximationEnum && !IsOnSurface()) || (approximation==SSAApproximationEnum && !IsOnBed())){
 		return 0;
 	}
-	else if (approximation==MacAyealApproximationEnum){
+	else if (approximation==SSAApproximationEnum){
 
 		/*This element should be collapsed into a tria element at its base. Create this tria element, 
 		 * and compute SurfaceArea*/
-		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 		S=tria->SurfaceArea();
 		delete tria->material; delete tria;
@@ -2832,5 +3430,5 @@
 	else{
 
-		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
 		S=tria->SurfaceArea();
 		delete tria->material; delete tria;
@@ -2907,24 +3505,22 @@
 	return dt;
 }/*}}}*/
-/*FUNCTION Penta::Update(int index,IoModel* iomodel,int analysis_counter,int analysis_type) {{{*/
-void Penta::Update(int index,IoModel* iomodel,int analysis_counter,int analysis_type){ 
+/*FUNCTION Penta::Update {{{*/
+void Penta::Update(int index,IoModel* iomodel,int analysis_counter,int analysis_type,int finiteelement_type){ 
 
 	/*Intermediaries*/
 	int        i;
-	int        penta_type;
-	int        penta_node_ids[6];
 	int        penta_vertex_ids[6];
 	IssmDouble nodeinputs[6];
 	IssmDouble yts;
-	int        stabilization;
 	bool       dakota_analysis;
-	bool       isstokes;
+	bool       isFS;
 	IssmDouble beta,heatcapacity,referencetemperature,meltingpoint,latentheat;
+	int        numnodes;
+	int*       penta_node_ids = NULL;
 
 	/*Fetch parameters: */
 	iomodel->Constant(&yts,ConstantsYtsEnum);
-	iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
 	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
-	iomodel->Constant(&isstokes,FlowequationIsstokesEnum);
+	iomodel->Constant(&isFS,FlowequationIsFSEnum);
 	iomodel->Constant(&beta,MaterialsBetaEnum);
 	iomodel->Constant(&heatcapacity,MaterialsHeatcapacityEnum);
@@ -2935,30 +3531,152 @@
 	/*Checks if debuging*/
 	/*{{{*/
-	_assert_(iomodel->Data(MeshElementsEnum));
+	_assert_(iomodel->elements);
 	/*}}}*/
 
 	/*Recover element type*/
-	if ((analysis_type==PrognosticAnalysisEnum || analysis_type==BalancethicknessAnalysisEnum) && stabilization==3){
-		/*P1 Discontinuous Galerkin*/
-		penta_type=P1DGEnum;
-	}
-	else{
-		/*P1 Continuous Galerkin*/
-		penta_type=P1Enum;
-	}
-	this->SetElementType(penta_type,analysis_counter);
+	this->SetElementType(finiteelement_type,analysis_counter);
 
 	/*Recover vertices ids needed to initialize inputs*/
-	for(i=0;i<6;i++) penta_vertex_ids[i]=reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
+	for(i=0;i<6;i++) penta_vertex_ids[i]=iomodel->elements[6*index+i]; //ids for vertices are in the elements array from Matlab
 
 	/*Recover nodes ids needed to initialize the node hook.*/
-	for(i=0;i<6;i++){ 
-		//go recover node ids, needed to initialize the node hook.
-		//WARNING: We assume P1 elements here!!!!!
-		penta_node_ids[i]=iomodel->nodecounter+reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[6*index+i]); //ids for vertices are in the elements array from Matlab
+	switch(finiteelement_type){
+		case P1Enum:
+			numnodes         = 6;
+			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];
+			break;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			numnodes         = 7;
+			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+index+1;
+			break;
+		case P1xP2Enum:
+			numnodes         = 9;
+			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;
+			break;
+		case P2xP1Enum:
+			numnodes         = 12;
+			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+3]+1;
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+4]+1;
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+5]+1;
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+6]+1;
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+7]+1;
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elementtoedgeconnectivity[9*index+8]+1;
+			break;
+		case P2Enum:
+			numnodes         = 15;
+			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;
+			break;
+		case P1P1Enum: case P1P1GLSEnum:
+			numnodes         = 12;
+			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->elements[6*index+0];
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[6*index+1];
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[6*index+2];
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[6*index+3];
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[6*index+4];
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->elements[6*index+5];
+			break;
+		case MINIEnum: case MINIcondensedEnum:
+			numnodes         = 13;
+			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+index+1;
+
+			penta_node_ids[ 7]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+0];
+			penta_node_ids[ 8]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+1];
+			penta_node_ids[ 9]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+2];
+			penta_node_ids[10]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+3];
+			penta_node_ids[11]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+4];
+			penta_node_ids[12]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+iomodel->elements[6*index+5];
+			break;
+		case TaylorHoodEnum:
+			numnodes         = 21;
+			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->elements[6*index+0];
+			penta_node_ids[16]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[6*index+1];
+			penta_node_ids[17]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[6*index+2];
+			penta_node_ids[18]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[6*index+3];
+			penta_node_ids[19]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[6*index+4];
+			penta_node_ids[20]=iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+iomodel->elements[6*index+5];
+			break;
+		default:
+			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
 	}
 
 	/*hooks: */
-	this->SetHookNodes(penta_node_ids,6,analysis_counter); this->nodes=NULL; //set hook to nodes, for this analysis type
+	this->SetHookNodes(penta_node_ids,numnodes,analysis_counter); this->nodes=NULL;
+	xDelete<int>(penta_node_ids);
 
 	/*Fill with IoModel*/
@@ -2968,59 +3686,59 @@
 	switch(analysis_type){
 
-		case DiagnosticHorizAnalysisEnum:
+		case StressbalanceAnalysisEnum:
 
 			/*default vx,vy and vz: either observation or 0 */
 			if(!iomodel->Data(VxEnum)){
 				for(i=0;i<6;i++)nodeinputs[i]=0;
-				this->inputs->AddInput(new PentaP1Input(VxEnum,nodeinputs));
-				if(dakota_analysis) this->inputs->AddInput(new PentaP1Input(QmuVxEnum,nodeinputs));
+				this->inputs->AddInput(new PentaInput(VxEnum,nodeinputs,P1Enum));
+				if(dakota_analysis) this->inputs->AddInput(new PentaInput(QmuVxEnum,nodeinputs,P1Enum));
 			}
 			if(!iomodel->Data(VyEnum)){
 				for(i=0;i<6;i++)nodeinputs[i]=0;
-				this->inputs->AddInput(new PentaP1Input(VyEnum,nodeinputs));
-				if(dakota_analysis) this->inputs->AddInput(new PentaP1Input(QmuVyEnum,nodeinputs));
+				this->inputs->AddInput(new PentaInput(VyEnum,nodeinputs,P1Enum));
+				if(dakota_analysis) this->inputs->AddInput(new PentaInput(QmuVyEnum,nodeinputs,P1Enum));
 			}
 			if(!iomodel->Data(VzEnum)){
 				for(i=0;i<6;i++)nodeinputs[i]=0;
-				this->inputs->AddInput(new PentaP1Input(VzEnum,nodeinputs));
-				if(dakota_analysis) this->inputs->AddInput(new PentaP1Input(QmuVzEnum,nodeinputs));
+				this->inputs->AddInput(new PentaInput(VzEnum,nodeinputs,P1Enum));
+				if(dakota_analysis) this->inputs->AddInput(new PentaInput(QmuVzEnum,nodeinputs,P1Enum));
 			}
 			if(!iomodel->Data(PressureEnum)){
 				for(i=0;i<6;i++)nodeinputs[i]=0;
 				if(dakota_analysis){
-					this->inputs->AddInput(new PentaP1Input(PressureEnum,nodeinputs));
-					this->inputs->AddInput(new PentaP1Input(QmuPressureEnum,nodeinputs));
+					this->inputs->AddInput(new PentaInput(PressureEnum,nodeinputs,P1Enum));
+					this->inputs->AddInput(new PentaInput(QmuPressureEnum,nodeinputs,P1Enum));
 				}
-				if(isstokes){
-					this->inputs->AddInput(new PentaP1Input(PressureEnum,nodeinputs));
-					this->inputs->AddInput(new PentaP1Input(PressurePicardEnum,nodeinputs));
+				if(isFS){
+					this->inputs->AddInput(new PentaInput(PressureEnum,nodeinputs,P1Enum));
+					this->inputs->AddInput(new PentaInput(PressurePicardEnum,nodeinputs,P1Enum));
 				}
 			}
-			if(*(iomodel->Data(FlowequationElementEquationEnum)+index)==PattynStokesApproximationEnum){
-				/*Create VzPattyn and VzStokes Enums*/
-				if(iomodel->Data(VzEnum) && iomodel->Data(FlowequationBorderstokesEnum)){
-					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*iomodel->Data(FlowequationBorderstokesEnum)[penta_vertex_ids[i]-1];
-					this->inputs->AddInput(new PentaP1Input(VzStokesEnum,nodeinputs));
-					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*(1-iomodel->Data(FlowequationBorderstokesEnum)[penta_vertex_ids[i]-1]);
-					this->inputs->AddInput(new PentaP1Input(VzPattynEnum,nodeinputs));
+			if(*(iomodel->Data(FlowequationElementEquationEnum)+index)==HOFSApproximationEnum){
+				/*Create VzHO and VzFS Enums*/
+				if(iomodel->Data(VzEnum) && iomodel->Data(FlowequationBorderFSEnum)){
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*iomodel->Data(FlowequationBorderFSEnum)[penta_vertex_ids[i]-1];
+					this->inputs->AddInput(new PentaInput(VzFSEnum,nodeinputs,P1Enum));
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*(1-iomodel->Data(FlowequationBorderFSEnum)[penta_vertex_ids[i]-1]);
+					this->inputs->AddInput(new PentaInput(VzHOEnum,nodeinputs,P1Enum));
 				}
 				else{
 					for(i=0;i<6;i++)nodeinputs[i]=0;
-					this->inputs->AddInput(new PentaP1Input(VzStokesEnum,nodeinputs));
-					this->inputs->AddInput(new PentaP1Input(VzPattynEnum,nodeinputs));
+					this->inputs->AddInput(new PentaInput(VzFSEnum,nodeinputs,P1Enum));
+					this->inputs->AddInput(new PentaInput(VzHOEnum,nodeinputs,P1Enum));
 				}
 			}
-			if(*(iomodel->Data(FlowequationElementEquationEnum)+index)==MacAyealStokesApproximationEnum){
-				/*Create VzMacAyeal and VzStokes Enums*/
-				if(iomodel->Data(VzEnum) && iomodel->Data(FlowequationBorderstokesEnum)){
-					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*iomodel->Data(FlowequationBorderstokesEnum)[penta_vertex_ids[i]-1];
-					this->inputs->AddInput(new PentaP1Input(VzStokesEnum,nodeinputs));
-					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*(1-iomodel->Data(FlowequationBorderstokesEnum)[penta_vertex_ids[i]-1]);
-					this->inputs->AddInput(new PentaP1Input(VzMacAyealEnum,nodeinputs));
+			if(*(iomodel->Data(FlowequationElementEquationEnum)+index)==SSAFSApproximationEnum){
+				/*Create VzSSA and VzFS Enums*/
+				if(iomodel->Data(VzEnum) && iomodel->Data(FlowequationBorderFSEnum)){
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*iomodel->Data(FlowequationBorderFSEnum)[penta_vertex_ids[i]-1];
+					this->inputs->AddInput(new PentaInput(VzFSEnum,nodeinputs,P1Enum));
+					for(i=0;i<6;i++) nodeinputs[i]=iomodel->Data(VzEnum)[penta_vertex_ids[i]-1]*(1-iomodel->Data(FlowequationBorderFSEnum)[penta_vertex_ids[i]-1]);
+					this->inputs->AddInput(new PentaInput(VzSSAEnum,nodeinputs,P1Enum));
 				}
 				else{
 					for(i=0;i<6;i++)nodeinputs[i]=0;
-					this->inputs->AddInput(new PentaP1Input(VzStokesEnum,nodeinputs));
-					this->inputs->AddInput(new PentaP1Input(VzMacAyealEnum,nodeinputs));
+					this->inputs->AddInput(new PentaInput(VzFSEnum,nodeinputs,P1Enum));
+					this->inputs->AddInput(new PentaInput(VzSSAEnum,nodeinputs,P1Enum));
 				}
 			}
@@ -3030,11 +3748,11 @@
 			/*Initialize mesh velocity*/
 			for(i=0;i<6;i++)nodeinputs[i]=0;
-			this->inputs->AddInput(new PentaP1Input(VxMeshEnum,nodeinputs));
-			this->inputs->AddInput(new PentaP1Input(VyMeshEnum,nodeinputs));
-			this->inputs->AddInput(new PentaP1Input(VzMeshEnum,nodeinputs));
+			this->inputs->AddInput(new PentaInput(VxMeshEnum,nodeinputs,P1Enum));
+			this->inputs->AddInput(new PentaInput(VyMeshEnum,nodeinputs,P1Enum));
+			this->inputs->AddInput(new PentaInput(VzMeshEnum,nodeinputs,P1Enum));
 			if(dakota_analysis){
-				this->inputs->AddInput(new PentaP1Input(QmuVxMeshEnum,nodeinputs));
-				this->inputs->AddInput(new PentaP1Input(QmuVyMeshEnum,nodeinputs));
-				this->inputs->AddInput(new PentaP1Input(QmuVzMeshEnum,nodeinputs));
+				this->inputs->AddInput(new PentaInput(QmuVxMeshEnum,nodeinputs,P1Enum));
+				this->inputs->AddInput(new PentaInput(QmuVyMeshEnum,nodeinputs,P1Enum));
+				this->inputs->AddInput(new PentaInput(QmuVzMeshEnum,nodeinputs,P1Enum));
 			}
 			break;
@@ -3043,7 +3761,7 @@
 			/*Initialize mesh velocity*/
 			for(i=0;i<6;i++)nodeinputs[i]=0;
-			this->inputs->AddInput(new PentaP1Input(VxMeshEnum,nodeinputs));
-			this->inputs->AddInput(new PentaP1Input(VyMeshEnum,nodeinputs));
-			this->inputs->AddInput(new PentaP1Input(VzMeshEnum,nodeinputs));
+			this->inputs->AddInput(new PentaInput(VxMeshEnum,nodeinputs,P1Enum));
+			this->inputs->AddInput(new PentaInput(VyMeshEnum,nodeinputs,P1Enum));
+			this->inputs->AddInput(new PentaInput(VzMeshEnum,nodeinputs,P1Enum));
 			if (iomodel->Data(TemperatureEnum) && iomodel->Data(WaterfractionEnum) && iomodel->Data(PressureEnum)) {
 				for(i=0;i<6;i++){
@@ -3055,5 +3773,5 @@
 						+latentheat*iomodel->Data(WaterfractionEnum)[penta_vertex_ids[i]-1];
 				}
-				this->inputs->AddInput(new PentaP1Input(EnthalpyEnum,nodeinputs));
+				this->inputs->AddInput(new PentaInput(EnthalpyEnum,nodeinputs,P1Enum));
 			}
 			else _error_("temperature and waterfraction required for the enthalpy solution");
@@ -3064,11 +3782,4 @@
 			break;
 	}
-}
-/*}}}*/
-/*FUNCTION Penta::UpdateConstraints{{{*/
-void Penta::UpdateConstraints(void){
-
-	/*Do nothing for now*/
-
 }
 /*}}}*/
@@ -3106,5 +3817,5 @@
 
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
 		GetPhi(&phi, &epsilon[0], viscosity);
 
@@ -3113,5 +3824,5 @@
 
 	/*Create PentaVertex input, which will hold the basal friction:*/
-	this->inputs->AddInput(new PentaP1Input(ViscousHeatingEnum,&viscousheating[0]));
+	this->inputs->AddInput(new PentaInput(ViscousHeatingEnum,&viscousheating[0],P1Enum));
 
 	/*Clean up and return*/
@@ -3133,5 +3844,5 @@
 	IssmDouble xyz_list[NUMVERTICES][3];
 
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
@@ -3201,5 +3912,5 @@
 
 	/*Spawn Tria element from the base of the Penta: */
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	mass_flux=tria->MassFlux(segment);
 	delete tria->material; delete tria;
@@ -3325,5 +4036,5 @@
 	rho_ice=matpar->GetRhoIce();
 
-	if(IsOnWater() || !IsOnSurface()) return 0.;
+	if(NoIceInElement() || !IsOnSurface()) return 0.;
 
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
@@ -3484,6 +4195,6 @@
 			/*Build K: */
 			GetElementSizes(&hx,&hy,&hz);
-			vel=sqrt(pow(vx,2.)+pow(vy,2.)+pow(vz,2.))+1.e-14;
-			h=sqrt( pow(hx*vx/vel,2.) + pow(hy*vy/vel,2.) + pow(hz*vz/vel,2.));
+			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;
@@ -3584,5 +4295,5 @@
 	if (!IsOnBed()) return NULL;
 
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	ElementMatrix* Ke=tria->CreateKMatrixMelting();
 
@@ -3713,6 +4424,6 @@
 			/*Build K: */
 			GetElementSizes(&hx,&hy,&hz);
-			vel=sqrt(pow(vx,2.)+pow(vy,2.)+pow(vz,2.))+1.e-14;
-			h=sqrt( pow(hx*vx/vel,2.) + pow(hy*vy/vel,2.) + pow(hz*vz/vel,2.));
+			vel=sqrt(vx*vx + vy*vy + vz*vz)+1.e-14;
+			h=sqrt( pow(hx*vx/vel,2) + pow(hy*vy/vel,2) + pow(hz*vz/vel,2));
 
 			K[0][0]=h/(2*vel)*fabs(vx*vx);  K[0][1]=h/(2*vel)*fabs(vx*vy); K[0][2]=h/(2*vel)*fabs(vx*vz);
@@ -3884,5 +4595,5 @@
 
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
 		GetPhi(&phi, &epsilon[0], viscosity);
 
@@ -3995,4 +4706,5 @@
 	IssmDouble scalar,enthalpy,enthalpyup;
 	IssmDouble pressure,pressureup;
+	IssmDouble watercolumn;
 	IssmDouble basis[NUMVERTICES];
 	Friction*  friction=NULL;
@@ -4008,5 +4720,5 @@
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 	rho_ice=matpar->GetRhoIce();
@@ -4019,6 +4731,7 @@
 	Input* pressure_input=inputs->GetInput(PressureEnum);             _assert_(pressure_input);
 	Input* geothermalflux_input=inputs->GetInput(BasalforcingsGeothermalfluxEnum); _assert_(geothermalflux_input);
-
-	/*Build frictoin element, needed later: */
+	Input* watercolumn_input=inputs->GetInput(WatercolumnEnum); _assert_(watercolumn_input);
+
+	/*Build friction element, needed later: */
 	friction=new Friction("3d",inputs,matpar,analysis_type);
 
@@ -4036,27 +4749,31 @@
 		enthalpy_input->GetInputValue(&enthalpy,gauss);
 		pressure_input->GetInputValue(&pressure,gauss);
-//		if(enthalpy>matpar->PureIceEnthalpy(pressure)){
-//			enthalpy_input->GetInputValue(&enthalpyup,gaussup);
-//			pressure_input->GetInputValue(&pressureup,gaussup);
-//			if(enthalpyup>matpar->PureIceEnthalpy(pressureup)){
-//				//do nothing, don't add heatflux
-//			}
-//			else{
-//				//need to change spcenthalpy according to Aschwanden 
-//				//NEED TO UPDATE
-//			}
-//		}
-//		else{
-			geothermalflux_input->GetInputValue(&geothermalflux_value,gauss);
-			friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
-			vx_input->GetInputValue(&vx,gauss);
-			vy_input->GetInputValue(&vy,gauss);
-			basalfriction=alpha2*(pow(vx,2.0)+pow(vy,2.0));
-
-			scalar=gauss->weight*Jdet2d*(basalfriction+geothermalflux_value)/(rho_ice);
-			if(reCast<bool,IssmDouble>(dt)) scalar=dt*scalar;
-
-			for(i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
-//		}
+		if(enthalpy>=matpar->PureIceEnthalpy(pressure)){
+			enthalpy_input->GetInputValue(&enthalpyup,gaussup);
+			pressure_input->GetInputValue(&pressureup,gaussup);
+			if(enthalpyup>=matpar->PureIceEnthalpy(pressureup)){
+				// temperate ice has positive thickness: grad enthalpy*n=0.
+			}
+			else{
+				// only base temperate, set Dirichlet BCs in Penta::UpdateThermalBasalConstraints()
+			}
+		}
+		else{
+			watercolumn_input->GetInputValue(&watercolumn,gauss);
+			if(watercolumn==0.){
+				/*add geothermal heat flux and basal friction*/
+				geothermalflux_input->GetInputValue(&geothermalflux_value,gauss);
+				friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
+				vx_input->GetInputValue(&vx,gauss);
+				vy_input->GetInputValue(&vy,gauss);
+				basalfriction=alpha2*(pow(vx,2.0)+pow(vy,2.0));
+
+				scalar=gauss->weight*Jdet2d*(basalfriction+geothermalflux_value)/(rho_ice);
+				if(reCast<bool,IssmDouble>(dt)) scalar=dt*scalar;
+
+				for(i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
+			}
+			else{  /*do nothing (water layer acts as insulation)*/  }
+		}
 	}
 
@@ -4140,5 +4857,5 @@
 
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
 		GetPhi(&phi, &epsilon[0], viscosity);
 
@@ -4260,5 +4977,5 @@
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 	rho_ice=matpar->GetRhoIce();
@@ -4336,9 +5053,8 @@
 	const int    numdof=NDOF1*NUMVERTICES;
 
-	int          i;
-	int*         doflist=NULL;
-	IssmDouble       values[numdof];
-	IssmDouble       enthalpy;
-	GaussPenta   *gauss=NULL;
+	int*        doflist=NULL;
+	IssmDouble  values[numdof];
+	IssmDouble  enthalpy;
+	GaussPenta *gauss=NULL;
 
 	/*Get dof list: */
@@ -4347,5 +5063,5 @@
 
 	gauss=new GaussPenta();
-	for(i=0;i<NUMVERTICES;i++){
+	for(int i=0;i<NUMVERTICES;i++){
 		/*Recover temperature*/
 		gauss->GaussVertex(i);
@@ -4398,5 +5114,5 @@
 	this->inputs->GetInputValue(&converged,ConvergedEnum);
 	if(converged){
-		this->inputs->AddInput(new PentaP1Input(TemperatureEnum,values));
+		this->inputs->AddInput(new PentaInput(TemperatureEnum,values,P1Enum));
 
 		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
@@ -4410,5 +5126,5 @@
 				B_average=Paterson((values[0]+values[1]+values[2]+values[3]+values[4]+values[5])/6.0);
 				for(i=0;i<numdof;i++) B[i]=B_average;
-				this->material->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				this->material->inputs->AddInput(new PentaInput(MaterialsRheologyBEnum,B,P1Enum));
 				break;
 			case ArrheniusEnum:
@@ -4418,5 +5134,5 @@
 							material->GetN());
 				for(i=0;i<numdof;i++) B[i]=B_average;
-				this->material->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				this->material->inputs->AddInput(new PentaInput(MaterialsRheologyBEnum,B,P1Enum));
 				break;
 			default:
@@ -4426,5 +5142,5 @@
 	}
 	else{
-		this->inputs->AddInput(new PentaP1Input(TemperaturePicardEnum,values));
+		this->inputs->AddInput(new PentaInput(TemperaturePicardEnum,values,P1Enum));
 	}
 
@@ -4438,6 +5154,6 @@
 	const int    numdof=NDOF1*NUMVERTICES;
 
-	bool   converged=false;
-	int    i,rheology_law;
+	bool       converged=false;
+	int        i,rheology_law;
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble values[numdof];
@@ -4447,5 +5163,5 @@
 	IssmDouble B[numdof];
 	IssmDouble B_average,s_average;
-	int*   doflist=NULL;
+	int*       doflist=NULL;
 
 	/*Get dof list: */
@@ -4474,7 +5190,7 @@
 		}
 
-		this->inputs->AddInput(new PentaP1Input(EnthalpyEnum,values));
-		this->inputs->AddInput(new PentaP1Input(WaterfractionEnum,waterfraction));
-		this->inputs->AddInput(new PentaP1Input(TemperatureEnum,temperatures));
+		this->inputs->AddInput(new PentaInput(EnthalpyEnum,values,P1Enum));
+		this->inputs->AddInput(new PentaInput(WaterfractionEnum,waterfraction,P1Enum));
+		this->inputs->AddInput(new PentaInput(TemperatureEnum,temperatures,P1Enum));
 
 		/*Update Rheology only if converged (we must make sure that the temperature is below melting point
@@ -4488,5 +5204,5 @@
 				B_average=Paterson((temperatures[0]+temperatures[1]+temperatures[2]+temperatures[3]+temperatures[4]+temperatures[5])/6.0);
 				for(i=0;i<numdof;i++) B[i]=B_average;
-				this->material->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				this->material->inputs->AddInput(new PentaInput(MaterialsRheologyBEnum,B,P1Enum));
 				break;
 			case ArrheniusEnum:
@@ -4496,17 +5212,236 @@
 							material->GetN());
 				for(i=0;i<numdof;i++) B[i]=B_average;
-				this->material->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,B));
+				this->material->inputs->AddInput(new PentaInput(MaterialsRheologyBEnum,B,P1Enum));
+				break;
+			case LliboutryDuvalEnum:
+				B_average=LliboutryDuval((values[0]+values[1]+values[2]+values[3]+values[4]+values[5])/6.0,
+							(pressure[0]+pressure[1]+pressure[2]+pressure[3]+pressure[4]+pressure[5])/6.0,
+							material->GetN());
+				for(i=0;i<numdof;i++) B[i]=B_average;
+				this->material->inputs->AddInput(new PentaInput(MaterialsRheologyBEnum,B,P1Enum));
 				break;
 			default:
 				_error_("Rheology law " << EnumToStringx(rheology_law) << " not supported yet");
-
 		}
 	}
 	else{
-		this->inputs->AddInput(new PentaP1Input(EnthalpyPicardEnum,values));
+		this->inputs->AddInput(new PentaInput(EnthalpyPicardEnum,values,P1Enum));
 	}
 
 	/*Free ressources:*/
 	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::UpdateThermalBasalConstraints{{{*/
+void  Penta::UpdateThermalBasalConstraints(void){
+
+	/*Intermediary*/
+	bool        isenthalpy,isdynamicbasalspc,istemperatelayer;
+	int         numindices, numindicesup;
+	IssmDouble  h_pmp,pressure, pressureup;
+    IssmDouble  enthalpy, enthalpyup;
+	int        *indices = NULL, *indicesup = NULL;
+
+	/* Only update Constraints at the base of grounded ice*/
+	if(!IsOnBed() || IsFloating()) return;
+
+	/*Check wether dynamic basal boundary conditions are activated */
+	parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
+	if(!isenthalpy) return;
+	//parameters->FindParam(&isdynamicbasalspc,ThermalIsdynamicbasalspcEnum);
+	isdynamicbasalspc = true;
+	if(!isdynamicbasalspc) return;
+
+	/*Fetch indices of basal & surface nodes for this finite element*/
+	BasalNodeIndices(&numindices,&indices,this->element_type);
+    SurfaceNodeIndices(&numindicesup,&indicesup,this->element_type);
+    _assert_(numindices==numindicesup);
+
+	/*Get parameters and inputs: */
+	Input* pressure_input=inputs->GetInput(PressureEnum); _assert_(pressure_input);
+    Input* enthalpy_input=inputs->GetInput(EnthalpyEnum); _assert_(enthalpy_input);
+
+	/*if there is a temperate layer of positive thickness, set enthalpy=h_pmp at that node*/
+	GaussPenta* gauss=new GaussPenta();
+    GaussPenta* gaussup=new GaussPenta();
+	for(int i=0;i<numindices;i++){
+		gauss->GaussNode(this->element_type,indices[i]);
+        gaussup->GaussNode(this->element_type,indicesup[i]); // TODO: check: are the nodes corresponding?
+
+		/*Check wether there is a temperate layer at the base or not -> TODO: Johannes:) */
+        /*check if node is temperate, if not, return*/
+        enthalpy_input->GetInputValue(&enthalpy, gauss);
+		pressure_input->GetInputValue(&pressure, gauss);
+        if (enthalpy<matpar->PureIceEnthalpy(pressure)){
+          // TODO: reset, if necessary, all spcs to non-valid 
+          continue;
+        }
+        /*check if upper node is temperate. if yes, then we have a temperate layer of positive thickness. if not, continue.*/
+        enthalpy_input->GetInputValue(&enthalpyup, gaussup);
+		pressure_input->GetInputValue(&pressureup, gaussup);    
+        istemperatelayer = false;
+        if (enthalpyup>=matpar->PureIceEnthalpy(pressureup))
+          istemperatelayer=true;
+
+		/*Add Dirichlet constraint to this node if there is no layer of temperate ice with positive thickness*/
+		if(!istemperatelayer){
+			/*Calculate enthalpy at pressure melting point */
+			h_pmp=matpar->PureIceEnthalpy(pressure);
+
+			/*Apply Dirichlet condition (dof = 0 here, since there is only one degree of freedom per node)*/
+			nodes[indices[i]]->ApplyConstraint(1,h_pmp);
+		}
+        else {
+          /*remove spc*/
+          nodes[indices[i]]->DofInFSet(0);
+        }
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(indices);
+    xDelete<int>(indicesup);
+}
+/*}}}*/
+/*FUNCTION Penta::ComputeBasalMeltingrate{{{*/
+void Penta::ComputeBasalMeltingrate(void){
+	/*Calculate the basal melt rates of the enthalpy model after Aschwanden 2012*/
+
+	/* Intermediaries */
+	bool        isenthalpy, checkpositivethickness, istemperatelayer;
+	int         i,j,analysis_type;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble  heatflux,kappa;
+	IssmDouble  vec_heatflux[3];
+	IssmDouble  normal_base[3], d1enthalpy[3];
+	IssmDouble  basalmeltingrate[NUMVERTICES], watercolumn[NUMVERTICES];
+	IssmDouble  enthalpy[NUMVERTICES],pressure[NUMVERTICES];
+	IssmDouble  temperature, waterfraction;
+	IssmDouble  latentheat, rho_ice;
+	IssmDouble  basalfriction, alpha2;
+	IssmDouble  vx[NUMVERTICES],vy[NUMVERTICES],vz[NUMVERTICES];
+	IssmDouble  geothermalflux[NUMVERTICES];
+	IssmDouble  dt,meltingrate_enthalpy;
+	Friction   *friction  = NULL;
+
+	/* Only compute melt rates at the base of grounded ice*/
+	if(!IsOnBed() || IsFloating()) return;
+
+	/*Check wether enthalpy is activated*/
+	parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
+	if(!isenthalpy) return;
+
+	/*Fetch parameters and inputs */
+	latentheat=matpar->GetLatentHeat();
+	rho_ice=this->matpar->GetRhoIce();
+	GetInputListOnVertices(&vx[0],VxEnum);
+	GetInputListOnVertices(&vy[0],VyEnum);
+	GetInputListOnVertices(&vz[0],VzEnum);
+	GetInputListOnVertices(&enthalpy[0],EnthalpyEnum);
+	GetInputListOnVertices(&pressure[0],PressureEnum);
+	GetInputListOnVertices(&watercolumn[0],WatercolumnEnum);
+	GetInputListOnVertices(&basalmeltingrate[0],BasalforcingsMeltingRateEnum);
+	GetInputListOnVertices(&geothermalflux[0],BasalforcingsGeothermalfluxEnum);
+	Input* enthalpy_input=inputs->GetInput(EnthalpyEnum); _assert_(enthalpy_input);
+
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*Build friction element, needed later: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	friction=new Friction("3d",inputs,matpar,analysis_type);
+
+	/*Ok, get meltingrates now from basal conditions*/
+	GaussPenta* gauss=new GaussPenta();
+	for(int iv=0;iv<3;iv++){
+
+		gauss->GaussVertex(iv);
+		checkpositivethickness=true;
+
+		/*Calculate basal meltingrate after Fig.5 of A.Aschwanden 2012*/
+		meltingrate_enthalpy=0.;
+		if((watercolumn[iv]>0.) && (enthalpy[iv]<matpar->PureIceEnthalpy(pressure[iv]))){
+			/*ensure that no ice is at T<Tm(p), if water layer present*/
+			enthalpy[iv]=matpar->PureIceEnthalpy(pressure[iv]); 
+			//meltingrate_enthalpy=0.;
+		}
+		else if(enthalpy[iv]<matpar->PureIceEnthalpy(pressure[iv])){
+			/*cold base: set q*n=q_geo*n+frictionheating as Neumann BC in Penta::CreatePVectorEnthalpySheet*/
+			meltingrate_enthalpy=0.;
+			checkpositivethickness=false;
+		}
+		else {/*do nothing, go to next check*/}
+
+		if(checkpositivethickness){
+			/*ok, from here on all basal ice is temperate. Check for positive thickness of layer of temperate ice. */
+			istemperatelayer=false;
+			if(enthalpy[iv+3]>=matpar->PureIceEnthalpy(pressure[iv+3])) istemperatelayer=true;
+			if(istemperatelayer) for(i=0;i<3;i++) vec_heatflux[i]=0.;
+			else{
+				enthalpy_input->GetInputDerivativeValue(&d1enthalpy[0],&xyz_list[0][0],gauss);
+				kappa=matpar->GetEnthalpyDiffusionParameter(enthalpy[iv],pressure[iv]);
+				for(i=0;i<3;i++) vec_heatflux[i]=-kappa*d1enthalpy[i];
+			}
+
+			/*geothermal heatflux*/
+			BedNormal(&normal_base[0],xyz_list_tria);
+			heatflux=0.;
+			for(i=0;i<3;i++) heatflux+=(vec_heatflux[i])*normal_base[i];
+
+			/*basal friction*/
+			friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
+			basalfriction=alpha2*(pow(vx[iv],2.0)+pow(vy[iv],2.0)+pow(vz[iv],2.0));
+
+			matpar->EnthalpyToThermal(&temperature, &waterfraction, enthalpy[iv],pressure[iv]);
+			meltingrate_enthalpy=(basalfriction-(heatflux-geothermalflux[iv]))/((1-waterfraction)*latentheat*rho_ice); // m/yr water equivalent 
+		}
+
+		/*Update water column, basal meltingrate*/
+		basalmeltingrate[iv]+=meltingrate_enthalpy;
+		this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+		if(reCast<bool,IssmDouble>(dt))
+		 watercolumn[iv]+=dt*meltingrate_enthalpy; 
+		else
+		 watercolumn[iv]+=meltingrate_enthalpy;
+	}  
+	/*feed updated variables back into model*/
+	this->inputs->AddInput(new PentaInput(EnthalpyEnum,enthalpy,P1Enum));
+	this->inputs->AddInput(new PentaInput(WatercolumnEnum,watercolumn,P1Enum));
+	this->inputs->AddInput(new PentaInput(BasalforcingsMeltingRateEnum,basalmeltingrate,P1Enum));
+
+	/*Clean up and return*/
+	delete gauss;
+	delete friction;
+}
+/*}}}*/
+/*FUNCTION Penta::DrainWaterfraction{{{*/
+void Penta::DrainWaterfraction(void){
+    
+    /*Intermediaries*/
+	bool isenthalpy;
+	IssmDouble waterfraction[NUMVERTICES], temperature[NUMVERTICES];
+	IssmDouble enthalpy[NUMVERTICES], pressure[NUMVERTICES]; 
+	IssmDouble latentheat, dt;
+
+	/*Check wether enthalpy is activated*/
+	parameters->FindParam(&isenthalpy,ThermalIsenthalpyEnum);
+	if(!isenthalpy) return;       
+
+	GetInputListOnVertices(&enthalpy[0],EnthalpyEnum);
+	GetInputListOnVertices(&pressure[0],PressureEnum);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	latentheat=matpar->GetLatentHeat();
+
+	for(int iv=0;iv<NUMVERTICES;iv++){ 
+		matpar->EnthalpyToThermal(&temperature[iv],&waterfraction[iv], enthalpy[iv],pressure[iv]); 
+
+		/*drain water fraction & update enthalpy*/
+		waterfraction[iv]-=DrainageFunctionWaterfraction(waterfraction[iv], dt);
+		matpar->ThermalToEnthalpy(&enthalpy[iv], temperature[iv], waterfraction[iv], pressure[iv]);        
+	}
+	/*feed updated results back into model*/
+	this->inputs->AddInput(new PentaInput(EnthalpyEnum,enthalpy,P1Enum));
+	this->inputs->AddInput(new PentaInput(WaterfractionEnum,waterfraction,P1Enum));
+	// this->inputs->AddInput(new PentaInput(TemperatureEnum,temperature,P1Enum));    // temperature should not change during drainage...
 }
 /*}}}*/
@@ -4580,5 +5515,5 @@
 	GradientIndexing(&vertexpidlist[0],control_index);
 	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
-	grad_input=new PentaP1Input(GradientEnum,grad_list);
+	grad_input=new PentaInput(GradientEnum,grad_list,P1Enum);
 	((ControlInput*)input)->SetGradient(grad_input);
 
@@ -4591,10 +5526,10 @@
 
 	switch(approximation){
-		case MacAyealApproximationEnum:
-			return CreateKMatrixAdjointMacAyeal2d();
-		case PattynApproximationEnum:
-			return CreateKMatrixAdjointPattyn();
-		case StokesApproximationEnum:
-			return CreateKMatrixAdjointStokes();
+		case SSAApproximationEnum:
+			return CreateKMatrixAdjointSSA2d();
+		case HOApproximationEnum:
+			return CreateKMatrixAdjointHO();
+		case FSApproximationEnum:
+			return CreateKMatrixAdjointFS();
 		case NoneApproximationEnum:
 			return NULL;
@@ -4604,6 +5539,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixAdjointMacAyeal2d{{{*/
-ElementMatrix* Penta::CreateKMatrixAdjointMacAyeal2d(void){
+/*FUNCTION Penta::CreateKMatrixAdjointSSA2d{{{*/
+ElementMatrix* Penta::CreateKMatrixAdjointSSA2d(void){
 
 	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
@@ -4626,6 +5561,6 @@
 
 	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-	ElementMatrix* Ke=tria->CreateKMatrixAdjointMacAyeal();
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	ElementMatrix* Ke=tria->CreateKMatrixAdjointSSA();
 	delete tria->material; delete tria;
 
@@ -4638,6 +5573,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixAdjointPattyn{{{*/
-ElementMatrix* Penta::CreateKMatrixAdjointPattyn(void){
+/*FUNCTION Penta::CreateKMatrixAdjointHO{{{*/
+ElementMatrix* Penta::CreateKMatrixAdjointHO(void){
 
 	/*Intermediaries */
@@ -4655,7 +5590,7 @@
 	GaussPenta *gauss=NULL;
 
-	/*Initialize Jacobian with regular Pattyn (first part of the Gateau derivative)*/
+	/*Initialize Jacobian with regular HO (first part of the Gateau derivative)*/
 	parameters->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
-	ElementMatrix* Ke=CreateKMatrixDiagnosticPattyn();
+	ElementMatrix* Ke=CreateKMatrixStressbalanceHO();
 	if(incomplete_adjoint) return Ke;
 
@@ -4674,5 +5609,5 @@
 		GetNodalFunctionsP1Derivatives(&dphi[0][0],&xyz_list[0][0],gauss);
 
-		this->GetStrainRate3dPattyn(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->GetStrainRate3dHO(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
 		material->GetViscosityDerivativeEpsSquare(&mu_prime,&epsilon[0]);
 		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
@@ -4703,9 +5638,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixAdjointStokes{{{*/
-ElementMatrix* Penta::CreateKMatrixAdjointStokes(void){
-
-	/*Constants*/
-	const int    numdof=NDOF4*NUMVERTICES;
+/*FUNCTION Penta::CreateKMatrixAdjointFS{{{*/
+ElementMatrix* Penta::CreateKMatrixAdjointFS(void){
 
 	/*Intermediaries */
@@ -4723,8 +5655,13 @@
 	GaussPenta *gauss=NULL;
 
-	/*Initialize Jacobian with regular Stokes (first part of the Gateau derivative)*/
+	/*Initialize Jacobian with regular FS (first part of the Gateau derivative)*/
 	parameters->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
-	ElementMatrix* Ke=CreateKMatrixDiagnosticStokes();
+	ElementMatrix* Ke=CreateKMatrixStressbalanceFS();
 	if(incomplete_adjoint) return Ke;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int numdof    = vnumnodes*NDOF3 + pnumnodes*NDOF1;
 
 	/*Retrieve all inputs and parameters*/
@@ -4743,5 +5680,5 @@
 		GetNodalFunctionsP1Derivatives(&dphi[0][0],&xyz_list[0][0],gauss);
 
-		this->GetStrainRate3dPattyn(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->GetStrainRate3dHO(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
 		material->GetViscosityDerivativeEpsSquare(&mu_prime,&epsilon[0]);
 		eps1[0]=epsilon[0];   eps2[0]=epsilon[2];   eps3[0]=epsilon[3];
@@ -4774,5 +5711,5 @@
 
 	/*Transform Coordinate System*/
-	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZEnum);
 
 	/*Clean up and return*/
@@ -4788,12 +5725,12 @@
 
 	switch(approximation){
-		case MacAyealApproximationEnum:
-			return CreatePVectorAdjointMacAyeal();
-		case PattynApproximationEnum:
-			return CreatePVectorAdjointPattyn();
+		case SSAApproximationEnum:
+			return CreatePVectorAdjointSSA();
+		case HOApproximationEnum:
+			return CreatePVectorAdjointHO();
 		case NoneApproximationEnum:
 			return NULL;
-		case StokesApproximationEnum:
-			return CreatePVectorAdjointStokes();
+		case FSApproximationEnum:
+			return CreatePVectorAdjointFS();
 		default:
 			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
@@ -4801,11 +5738,11 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorAdjointMacAyeal{{{*/
-ElementVector* Penta::CreatePVectorAdjointMacAyeal(){
+/*FUNCTION Penta::CreatePVectorAdjointSSA{{{*/
+ElementVector* Penta::CreatePVectorAdjointSSA(){
 
 	if (!IsOnBed()) return NULL;
 
 	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	ElementVector* pe=tria->CreatePVectorAdjointHoriz();
 	delete tria->material; delete tria;
@@ -4815,29 +5752,391 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorAdjointPattyn{{{*/
-ElementVector* Penta::CreatePVectorAdjointPattyn(void){
-
+/*FUNCTION Penta::CreatePVectorAdjointHO{{{*/
+ElementVector* Penta::CreatePVectorAdjointHO(void){
+
+
+	/*Nothing to be done if not on surface*/
 	if (!IsOnSurface()) return NULL;
 
-	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
-	ElementVector* pe=tria->CreatePVectorAdjointHoriz();
-	delete tria->material; delete tria;
-
-	/*clean up and return*/
+	/*Intermediaries */
+	int        i,j,resp;
+	int       *responses=NULL;
+	int        num_responses;
+	IssmDouble Jdet2d;
+	IssmDouble obs_velocity_mag,velocity_mag;
+	IssmDouble dux,duy;
+	IssmDouble epsvel=2.220446049250313e-16;
+	IssmDouble meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	IssmDouble scalex=0.,scaley=0.,scale=0.,S=0.;
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
+	Input* vx_input     =inputs->GetInput(VxEnum);        _assert_(vx_input);
+	Input* vy_input     =inputs->GetInput(VyEnum);        _assert_(vy_input);
+	Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
+	Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);
+
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*Get Surface if required by one response*/
+	for(resp=0;resp<num_responses;resp++){
+		if(responses[resp]==SurfaceAverageVelMisfitEnum){
+			inputs->GetInputValue(&S,SurfaceAreaEnum); break;
+		}
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	GaussPenta* gauss=new GaussPenta(3,4,5,4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetTriaJacobianDeterminant(&Jdet2d,&xyz_list_tria[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+		GetNodalFunctions(basis, gauss);
+
+		/*Loop over all requested responses*/
+		for(resp=0;resp<num_responses;resp++){
+
+			weights_input->GetInputValue(&weight,gauss,resp);
+
+			switch(responses[resp]){
+				case SurfaceAbsVelMisfitEnum:
+					/*
+					 *      1  [           2              2 ]
+					 * J = --- | (u - u   )  +  (v - v   )  |
+					 *      2  [       obs            obs   ]
+					 *
+					 *        dJ
+					 * DU = - -- = (u   - u )
+					 *        du     obs
+					 */
+					for(i=0;i<numnodes;i++){
+						dux=vxobs-vx;
+						duy=vyobs-vy;
+						pe->values[i*NDOF2+0]+=dux*weight*Jdet2d*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet2d*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceRelVelMisfitEnum:
+					/*
+					 *      1  [     \bar{v}^2             2   \bar{v}^2              2 ]
+					 * J = --- | -------------  (u - u   ) + -------------  (v - v   )  |
+					 *      2  [  (u   + eps)^2       obs    (v   + eps)^2       obs    ]
+					 *              obs                        obs                      
+					 *
+					 *        dJ     \bar{v}^2
+					 * DU = - -- = ------------- (u   - u )
+					 *        du   (u   + eps)^2    obs
+					 *               obs
+					 */
+					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*NDOF2+0]+=dux*weight*Jdet2d*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet2d*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceLogVelMisfitEnum:
+					/*
+					 *                 [        vel + eps     ] 2
+					 * J = 4 \bar{v}^2 | log ( -----------  ) |  
+					 *                 [       vel   + eps    ]
+					 *                            obs
+					 *
+					 *        dJ                 2 * log(...)
+					 * DU = - -- = - 4 \bar{v}^2 -------------  u
+					 *        du                 vel^2 + eps
+					 *            
+					 */
+					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*NDOF2+0]+=dux*weight*Jdet2d*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet2d*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceAverageVelMisfitEnum:
+					/*
+					 *      1                    2              2
+					 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
+					 *      S                obs            obs
+					 *
+					 *        dJ      1       1 
+					 * DU = - -- = - --- ----------- * 2 (u - u   )
+					 *        du      S  2 sqrt(...)           obs
+					 */
+					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*NDOF2+0]+=dux*weight*Jdet2d*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet2d*gauss->weight*basis[i]; 
+					}
+					break;
+				case SurfaceLogVxVyMisfitEnum:
+					/*
+					 *      1            [        |u| + eps     2          |v| + eps     2  ]
+					 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
+					 *      2            [       |u    |+ eps              |v    |+ eps     ]
+					 *                              obs                       obs
+					 *        dJ                              1      u                             1
+					 * DU = - -- = - \bar{v}^2 log(u...) --------- ----  ~ - \bar{v}^2 log(u...) ------
+					 *        du                         |u| + eps  |u|                           u + eps
+					 */
+					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*NDOF2+0]+=dux*weight*Jdet2d*gauss->weight*basis[i]; 
+						pe->values[i*NDOF2+1]+=duy*weight*Jdet2d*gauss->weight*basis[i]; 
+					}
+					break;
+				case DragCoefficientAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAlongGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAcrossGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<int>(responses);
+	delete gauss;
 	return pe;
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorAdjointStokes{{{*/
-ElementVector* Penta::CreatePVectorAdjointStokes(void){
-
-	if (!IsOnSurface()) return NULL;
-
-	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
-	ElementVector* pe=tria->CreatePVectorAdjointStokes();
-	delete tria->material; delete tria;
-
-	/*clean up and return*/
+/*FUNCTION Penta::CreatePVectorAdjointFS{{{*/
+ElementVector* Penta::CreatePVectorAdjointFS(void){
+
+	if(!IsOnSurface()) return NULL;
+
+	/*Intermediaries */
+	int         i,j,resp;
+	int        *responses= NULL;
+	int         num_responses;
+	IssmDouble  Jdet2d;
+	IssmDouble  obs_velocity_mag,velocity_mag;
+	IssmDouble  dux,duy;
+	IssmDouble  epsvel  = 2.220446049250313e-16;
+	IssmDouble  meanvel = 3.170979198376458e-05;  /*1000 m/yr */
+	IssmDouble  scalex  = 0,scaley=0,scale=0,S=0;
+	IssmDouble  vx,vy,vxobs,vyobs,weight;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble	xyz_list_tria[NUMVERTICES2D][3];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	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*/
+	ElementVector* pe     = new ElementVector(nodes,vnumnodes+pnumnodes,this->parameters,FSApproximationEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+	Input* weights_input = inputs->GetInput(InversionCostFunctionsCoefficientsEnum); _assert_(weights_input);
+	Input* vx_input      = inputs->GetInput(VxEnum);                                 _assert_(vx_input);
+	Input* vy_input      = inputs->GetInput(VyEnum);                                 _assert_(vy_input);
+	Input* vxobs_input   = inputs->GetInput(InversionVxObsEnum);                     _assert_(vxobs_input);
+	Input* vyobs_input   = inputs->GetInput(InversionVyObsEnum);                     _assert_(vyobs_input);
+
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+
+	/*Get Surface if required by one response*/
+	for(resp=0;resp<num_responses;resp++){
+		if(responses[resp]==SurfaceAverageVelMisfitEnum){
+			inputs->GetInputValue(&S,SurfaceAreaEnum); break;
+		}
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	GaussPenta* gauss=new GaussPenta(3,4,5,4);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		/* Get Jacobian determinant: */
+		GetTriaJacobianDeterminant(&Jdet2d,&xyz_list_tria[0][0],gauss);
+
+		/*Get all parameters at gaussian point*/
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+		vxobs_input->GetInputValue(&vxobs,gauss);
+		vyobs_input->GetInputValue(&vyobs,gauss);
+		GetNodalFunctionsVelocity(vbasis,gauss);
+
+		/*Loop over all requested responses*/
+		for(resp=0;resp<num_responses;resp++){
+
+			weights_input->GetInputValue(&weight,gauss,resp);
+
+			switch(responses[resp]){
+
+				case SurfaceAbsVelMisfitEnum:
+					/*
+					 *      1  [           2              2 ]
+					 * J = --- | (u - u   )  +  (v - v   )  |
+					 *      2  [       obs            obs   ]
+					 *
+					 *        dJ
+					 * DU = - -- = (u   - u )
+					 *        du     obs
+					 */
+					for(i=0;i<vnumnodes;i++){
+						dux=vxobs-vx;
+						duy=vyobs-vy;
+						pe->values[i*NDOF3+0]+=dux*weight*Jdet2d*gauss->weight*vbasis[i]; 
+						pe->values[i*NDOF3+1]+=duy*weight*Jdet2d*gauss->weight*vbasis[i]; 
+					}
+					break;
+				case SurfaceRelVelMisfitEnum:
+					/*
+					 *      1  [     \bar{v}^2             2   \bar{v}^2              2 ]
+					 * J = --- | -------------  (u - u   ) + -------------  (v - v   )  |
+					 *      2  [  (u   + eps)^2       obs    (v   + eps)^2       obs    ]
+					 *              obs                        obs                      
+					 *
+					 *        dJ     \bar{v}^2
+					 * DU = - -- = ------------- (u   - u )
+					 *        du   (u   + eps)^2    obs
+					 *               obs
+					 */
+					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*NDOF3+0]+=dux*weight*Jdet2d*gauss->weight*vbasis[i]; 
+						pe->values[i*NDOF3+1]+=duy*weight*Jdet2d*gauss->weight*vbasis[i]; 
+					}
+					break;
+				case SurfaceLogVelMisfitEnum:
+					/*
+					 *                 [        vel + eps     ] 2
+					 * J = 4 \bar{v}^2 | log ( -----------  ) |  
+					 *                 [       vel   + eps    ]
+					 *                            obs
+					 *
+					 *        dJ                 2 * log(...)
+					 * DU = - -- = - 4 \bar{v}^2 -------------  u
+					 *        du                 vel^2 + eps
+					 *            
+					 */
+					for(i=0;i<vnumnodes;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*NDOF3+0]+=dux*weight*Jdet2d*gauss->weight*vbasis[i]; 
+						pe->values[i*NDOF3+1]+=duy*weight*Jdet2d*gauss->weight*vbasis[i]; 
+					}
+					break;
+				case SurfaceAverageVelMisfitEnum:
+					/*
+					 *      1                    2              2
+					 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
+					 *      S                obs            obs
+					 *
+					 *        dJ      1       1 
+					 * DU = - -- = - --- ----------- * 2 (u - u   )
+					 *        du      S  2 sqrt(...)           obs
+					 */
+					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*NDOF3+0]+=dux*weight*Jdet2d*gauss->weight*vbasis[i]; 
+						pe->values[i*NDOF3+1]+=duy*weight*Jdet2d*gauss->weight*vbasis[i]; 
+					}
+					break;
+				case SurfaceLogVxVyMisfitEnum:
+					/*
+					 *      1            [        |u| + eps     2          |v| + eps     2  ]
+					 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
+					 *      2            [       |u    |+ eps              |v    |+ eps     ]
+					 *                              obs                       obs
+					 *        dJ                              1      u                             1
+					 * DU = - -- = - \bar{v}^2 log(u...) --------- ----  ~ - \bar{v}^2 log(u...) ------
+					 *        du                         |u| + eps  |u|                           u + eps
+					 */
+					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*NDOF3+0]+=dux*weight*Jdet2d*gauss->weight*vbasis[i]; 
+						pe->values[i*NDOF3+1]+=duy*weight*Jdet2d*gauss->weight*vbasis[i]; 
+					}
+					break;
+				case DragCoefficientAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAcrossGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case ThicknessAlongGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				case RheologyBbarAbsGradientEnum:
+					/*Nothing in P vector*/
+					break;
+				default:
+					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<int>(responses);
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
+	delete gauss;
 	return pe;
 }
@@ -4865,5 +6164,5 @@
 
 	/*If on water, skip grad (=0): */
-	if(IsOnWater())return;
+	if(NoIceInElement())return;
 
 	/*First deal with ∂/∂alpha(KU-F)*/
@@ -4873,12 +6172,12 @@
 			inputs->GetInputValue(&approximation,ApproximationEnum);
 			switch(approximation){
-				case MacAyealApproximationEnum:
-					GradjDragMacAyeal(gradient,control_index);
+				case SSAApproximationEnum:
+					GradjDragSSA(gradient,control_index);
 					break;
-				case PattynApproximationEnum:
-					GradjDragPattyn(gradient,control_index);
+				case HOApproximationEnum:
+					GradjDragHO(gradient,control_index);
 					break;
-				case StokesApproximationEnum:
-					GradjDragStokes(gradient,control_index);
+				case FSApproximationEnum:
+					GradjDragFS(gradient,control_index);
 					break;
 				case NoneApproximationEnum:
@@ -4893,12 +6192,12 @@
 			inputs->GetInputValue(&approximation,ApproximationEnum);
 			switch(approximation){
-				case MacAyealApproximationEnum:
-					GradjBbarMacAyeal(gradient,control_index);
+				case SSAApproximationEnum:
+					GradjBbarSSA(gradient,control_index);
 					break;
-				case PattynApproximationEnum:
-					GradjBbarPattyn(gradient,control_index);
+				case HOApproximationEnum:
+					GradjBbarHO(gradient,control_index);
 					break;
-				case StokesApproximationEnum:
-					GradjBbarStokes(gradient,control_index);
+				case FSApproximationEnum:
+					GradjBbarFS(gradient,control_index);
 					break;
 				case NoneApproximationEnum:
@@ -4931,14 +6230,16 @@
 			break;
 		case DragCoefficientAbsGradientEnum:
-			if (!IsOnBed()) return;
-			tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-			tria->GradjDragGradient(gradient,resp,control_index);
-			delete tria->material; delete tria;
+			if(IsOnBed()){
+				tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+				tria->GradjDragGradient(gradient,resp,control_index);
+				delete tria->material; delete tria;
+			}
 			break;
 		case RheologyBbarAbsGradientEnum:
-			if (!IsOnBed()) return;
-			tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-			tria->GradjBGradient(gradient,resp,control_index);
-			delete tria->material; delete tria;
+			if(IsOnBed()){
+				tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+				tria->GradjBGradient(gradient,resp,control_index);
+				delete tria->material; delete tria;
+			}
 			break;
 		default:
@@ -4948,6 +6249,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::GradjDragMacAyeal {{{*/
-void  Penta::GradjDragMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+/*FUNCTION Penta::GradjDragSSA {{{*/
+void  Penta::GradjDragSSA(Vector<IssmDouble>* gradient,int control_index){
 
 	/*Gradient is 0 if on shelf or not on bed*/
@@ -4955,11 +6256,11 @@
 
 	/*Spawn tria*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-	tria->GradjDragMacAyeal(gradient,control_index);
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	tria->GradjDragSSA(gradient,control_index);
 	delete tria->material; delete tria;
 
 } /*}}}*/
-/*FUNCTION Penta::GradjDragPattyn {{{*/
-void  Penta::GradjDragPattyn(Vector<IssmDouble>* gradient,int control_index){
+/*FUNCTION Penta::GradjDragHO {{{*/
+void  Penta::GradjDragHO(Vector<IssmDouble>* gradient,int control_index){
 
 	int        i,j;
@@ -4984,5 +6285,5 @@
 	GradientIndexing(&vertexpidlist[0],control_index);
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
 	Input* adjointx_input=inputs->GetInput(AdjointxEnum);               _assert_(adjointx_input);
 	Input* adjointy_input=inputs->GetInput(AdjointyEnum);               _assert_(adjointy_input);
@@ -5001,5 +6302,5 @@
 
 		GetTriaJacobianDeterminant(&Jdet, &xyz_list_tria[0][0],gauss);
-		GetNodalFunctionsP1(basis, gauss);
+		GetNodalFunctionsP1(basis,gauss);
 
 		/*Build alpha_complement_list: */
@@ -5015,5 +6316,5 @@
 		/*Build gradje_g_gaussian vector (actually -dJ/ddrag): */
 		for (i=0;i<NUMVERTICES;i++){
-			grade_g_gaussian[i]=-2*drag*alpha_complement*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i]; /*basis are 0 for the 3 upper nodes*/
+			grade_g_gaussian[i]=-2*drag*alpha_complement*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
 		}
 
@@ -5031,6 +6332,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::GradjDragStokes {{{*/
-void  Penta::GradjDragStokes(Vector<IssmDouble>* gradient,int control_index){
+/*FUNCTION Penta::GradjDragFS {{{*/
+void  Penta::GradjDragFS(Vector<IssmDouble>* gradient,int control_index){
 
 	int        i,j;
@@ -5056,5 +6357,5 @@
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
 	GradientIndexing(&vertexpidlist[0],control_index);
 	Input* drag_input    =inputs->GetInput(FrictionCoefficientEnum); _assert_(drag_input);
@@ -5123,6 +6424,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::GradjBbarMacAyeal {{{*/
-void  Penta::GradjBbarMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+/*FUNCTION Penta::GradjBbarSSA {{{*/
+void  Penta::GradjBbarSSA(Vector<IssmDouble>* gradient,int control_index){
 
 	/*This element should be collapsed into a tria element at its base*/
@@ -5133,6 +6434,6 @@
 
 	/*Collapse element to the base*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
-	tria->GradjBMacAyeal(gradient,control_index);
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	tria->GradjBSSA(gradient,control_index);
 	delete tria->material; delete tria;
 
@@ -5141,6 +6442,6 @@
 
 } /*}}}*/
-/*FUNCTION Penta::GradjBbarPattyn {{{*/
-void  Penta::GradjBbarPattyn(Vector<IssmDouble>* gradient,int control_index){
+/*FUNCTION Penta::GradjBbarHO {{{*/
+void  Penta::GradjBbarHO(Vector<IssmDouble>* gradient,int control_index){
 
 	/*Gradient is computed on bed only (Bbar)*/
@@ -5151,6 +6452,6 @@
 
 	/*Collapse element to the base*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2);
-	tria->GradjBMacAyeal(gradient,control_index);    //We use MacAyeal as an estimate for now
+	Tria* tria=(Tria*)SpawnTria(0);
+	tria->GradjBSSA(gradient,control_index);    //We use SSA as an estimate for now
 	delete tria->material; delete tria;
 
@@ -5158,6 +6459,6 @@
 	this->material->inputs->DeleteInput(MaterialsRheologyBbarEnum);
 } /*}}}*/
-/*FUNCTION Penta::GradjBbarStokes {{{*/
-void  Penta::GradjBbarStokes(Vector<IssmDouble>* gradient,int control_index){
+/*FUNCTION Penta::GradjBbarFS {{{*/
+void  Penta::GradjBbarFS(Vector<IssmDouble>* gradient,int control_index){
 
 	/*Gradient is computed on bed only (Bbar)*/
@@ -5168,6 +6469,6 @@
 
 	/*Collapse element to the base*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2);
-	tria->GradjBMacAyeal(gradient,control_index);    //We use MacAyeal as an estimate for now
+	Tria* tria=(Tria*)SpawnTria(0);
+	tria->GradjBSSA(gradient,control_index);    //We use SSA as an estimate for now
 	delete tria->material; delete tria;
 
@@ -5220,45 +6521,67 @@
 }
 /*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionAdjointStokes {{{*/
-void  Penta::InputUpdateFromSolutionAdjointStokes(IssmDouble* solution){
-
-	const int    numdof=NDOF4*NUMVERTICES;
-
-	int    i;
-	IssmDouble values[numdof];
-	IssmDouble lambdax[NUMVERTICES];
-	IssmDouble lambday[NUMVERTICES];
-	IssmDouble lambdaz[NUMVERTICES];
-	IssmDouble lambdap[NUMVERTICES];
-	int*   doflist=NULL;
+/*FUNCTION Penta::InputUpdateFromSolutionAdjointFS {{{*/
+void  Penta::InputUpdateFromSolutionAdjointFS(IssmDouble* solution){
+
+	int          i;
+	int*         vdoflist=NULL;
+	int*         pdoflist=NULL;
+	IssmDouble   FSreconditioning;
+	GaussPenta  *gauss;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int vnumdof   = vnumnodes*NDOF3;
+	int pnumdof   = pnumnodes*NDOF1;
+
+	/*Initialize values*/
+	IssmDouble* vvalues = xNew<IssmDouble>(vnumdof);
+	IssmDouble* pvalues = xNew<IssmDouble>(pnumdof);
+	IssmDouble* lambdax = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* lambday = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* lambdaz = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* lambdap = xNew<IssmDouble>(pnumnodes);
 
 	/*Get dof list: */
-	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	GetDofListVelocity(&vdoflist,GsetEnum);
+	GetDofListPressure(&pdoflist,GsetEnum);
 
 	/*Use the dof list to index into the solution vector: */
-	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
-
-	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
-	for(i=0;i<NUMVERTICES;i++){
-		lambdax[i]=values[i*NDOF4+0];
-		lambday[i]=values[i*NDOF4+1];
-		lambdaz[i]=values[i*NDOF4+2];
-		lambdap[i]=values[i*NDOF4+3];
-
-		/*Check solution*/
-		if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(lambdaz[i])) _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(lambdap[i])) _error_("NaN found in solution vector");
-	}
+	for(i=0;i<vnumdof;i++) vvalues[i]=solution[vdoflist[i]];
+	for(i=0;i<pnumdof;i++) pvalues[i]=solution[pdoflist[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&vvalues[0],nodes,vnumnodes,XYZEnum);
+
+	/*fill in all arrays: */
+	for(i=0;i<vnumnodes;i++){
+		lambdax[i] = vvalues[i*NDOF3+0]; if(xIsNan<IssmDouble>(lambdax[i])) _error_("NaN found in solution vector");
+		lambday[i] = vvalues[i*NDOF3+1]; if(xIsNan<IssmDouble>(lambday[i])) _error_("NaN found in solution vector");
+		lambdaz[i] = vvalues[i*NDOF3+2]; if(xIsNan<IssmDouble>(lambdaz[i])) _error_("NaN found in solution vector");
+	}
+	for(i=0;i<pnumnodes;i++){
+		lambdap[i] = pvalues[i]; if(xIsNan<IssmDouble>(lambdap[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Recondition pressure and compute vel: */
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	for(i=0;i<pnumnodes;i++) lambdap[i]=lambdap[i]*FSreconditioning;
 
 	/*Add vx and vy as inputs to the tria element: */
-	this->inputs->AddInput(new PentaP1Input(AdjointxEnum,lambdax));
-	this->inputs->AddInput(new PentaP1Input(AdjointyEnum,lambday));
-	this->inputs->AddInput(new PentaP1Input(AdjointzEnum,lambdaz));
-	this->inputs->AddInput(new PentaP1Input(AdjointpEnum,lambdap));
+	this->inputs->AddInput(new PentaInput(AdjointxEnum,lambdax,P1Enum));
+	this->inputs->AddInput(new PentaInput(AdjointyEnum,lambday,P1Enum));
+	this->inputs->AddInput(new PentaInput(AdjointzEnum,lambdaz,P1Enum));
+	this->inputs->AddInput(new PentaInput(AdjointpEnum,lambdap,P1Enum));
 
 	/*Free ressources:*/
-	xDelete<int>(doflist);
+	xDelete<int>(vdoflist);
+	xDelete<int>(pdoflist);
+	xDelete<IssmDouble>(lambdap);
+	xDelete<IssmDouble>(lambdaz);
+	xDelete<IssmDouble>(lambday);
+	xDelete<IssmDouble>(lambdax);
+	xDelete<IssmDouble>(vvalues);
+	xDelete<IssmDouble>(pvalues);
 }
 /*}}}*/
@@ -5291,6 +6614,6 @@
 
 	/*Add vx and vy as inputs to the tria element: */
-	this->inputs->AddInput(new PentaP1Input(AdjointxEnum,lambdax));
-	this->inputs->AddInput(new PentaP1Input(AdjointyEnum,lambday));
+	this->inputs->AddInput(new PentaInput(AdjointxEnum,lambdax,P1Enum));
+	this->inputs->AddInput(new PentaInput(AdjointyEnum,lambday,P1Enum));
 
 	/*Free ressources:*/
@@ -5309,17 +6632,17 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/*Bail out if this element if:
-	 * -> Non MacAyeal and not on the surface
-	 * -> MacAyeal (2d model) and not on bed) */
-	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+	 * -> Non SSA and not on the surface
+	 * -> SSA (2d model) and not on bed) */
+	if ((approximation!=SSAApproximationEnum && !IsOnSurface()) || (approximation==SSAApproximationEnum && !IsOnBed())){
 		return 0;
 	}
-	else if (approximation==MacAyealApproximationEnum){
+	else if (approximation==SSAApproximationEnum){
 
 		/*This element should be collapsed into a tria element at its base. Create this tria element, 
 		 * and compute SurfaceAverageVelMisfit*/
-		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 		J=tria->SurfaceAverageVelMisfit(weight_index);
 		delete tria->material; delete tria;
@@ -5328,5 +6651,5 @@
 	else{
 
-		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
 		J=tria->SurfaceAverageVelMisfit(weight_index);
 		delete tria->material; delete tria;
@@ -5346,17 +6669,17 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/*Bail out if this element if:
-	 * -> Non MacAyeal and not on the surface
-	 * -> MacAyeal (2d model) and not on bed) */
-	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+	 * -> Non SSA and not on the surface
+	 * -> SSA (2d model) and not on bed) */
+	if ((approximation!=SSAApproximationEnum && !IsOnSurface()) || (approximation==SSAApproximationEnum && !IsOnBed())){
 		return 0;
 	}
-	else if (approximation==MacAyealApproximationEnum){
+	else if (approximation==SSAApproximationEnum){
 
 		/*This element should be collapsed into a tria element at its base. Create this tria element, 
 		 * and compute SurfaceAbsVelMisfit*/
-		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 		J=tria->SurfaceAbsVelMisfit(weight_index);
 		delete tria->material; delete tria;
@@ -5365,5 +6688,5 @@
 	else{
 
-		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
 		J=tria->SurfaceAbsVelMisfit(weight_index);
 		delete tria->material; delete tria;
@@ -5383,17 +6706,17 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/*Bail out if this element if:
-	 * -> Non MacAyeal and not on the surface
-	 * -> MacAyeal (2d model) and not on bed) */
-	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+	 * -> Non SSA and not on the surface
+	 * -> SSA (2d model) and not on bed) */
+	if ((approximation!=SSAApproximationEnum && !IsOnSurface()) || (approximation==SSAApproximationEnum && !IsOnBed())){
 		return 0;
 	}
-	else if (approximation==MacAyealApproximationEnum){
+	else if (approximation==SSAApproximationEnum){
 
 		/*This element should be collapsed into a tria element at its base. Create this tria element, 
 		 * and compute SurfaceLogVelMisfit*/
-		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 		J=tria->SurfaceLogVelMisfit(weight_index);
 		delete tria->material; delete tria;
@@ -5402,5 +6725,5 @@
 	else{
 
-		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
 		J=tria->SurfaceLogVelMisfit(weight_index);
 		delete tria->material; delete tria;
@@ -5422,17 +6745,17 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/*Bail out if this element if:
-	 * -> Non MacAyeal and not on the surface
-	 * -> MacAyeal (2d model) and not on bed) */
-	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+	 * -> Non SSA and not on the surface
+	 * -> SSA (2d model) and not on bed) */
+	if ((approximation!=SSAApproximationEnum && !IsOnSurface()) || (approximation==SSAApproximationEnum && !IsOnBed())){
 		return 0;
 	}
-	else if (approximation==MacAyealApproximationEnum){
+	else if (approximation==SSAApproximationEnum){
 
 		/*This element should be collapsed into a tria element at its base. Create this tria element, 
 		 * and compute SurfaceLogVxVyMisfit*/
-		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 		J=tria->SurfaceLogVxVyMisfit(weight_index);
 		delete tria->material; delete tria;
@@ -5441,5 +6764,5 @@
 	else{
 
-		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
 		J=tria->SurfaceLogVxVyMisfit(weight_index);
 		delete tria->material; delete tria;
@@ -5459,17 +6782,17 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/*Bail out if this element if:
-	 * -> Non MacAyeal and not on the surface
-	 * -> MacAyeal (2d model) and not on bed) */
-	if ((approximation!=MacAyealApproximationEnum && !IsOnSurface()) || (approximation==MacAyealApproximationEnum && !IsOnBed())){
+	 * -> Non SSA and not on the surface
+	 * -> SSA (2d model) and not on bed) */
+	if ((approximation!=SSAApproximationEnum && !IsOnSurface()) || (approximation==SSAApproximationEnum && !IsOnBed())){
 		return 0;
 	}
-	else if (approximation==MacAyealApproximationEnum){
+	else if (approximation==SSAApproximationEnum){
 
 		/*This element should be collapsed into a tria element at its base. Create this tria element, 
 		 * and compute SurfaceRelVelMisfit*/
-		tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria (lower face).
+		tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 		J=tria->SurfaceRelVelMisfit(weight_index);
 		delete tria->material; delete tria;
@@ -5478,5 +6801,5 @@
 	else{
 
-		tria=(Tria*)SpawnTria(3,4,5); //nodes 3, 4 and 5 make the new tria (upper face).
+		tria=(Tria*)SpawnTria(1); //lower face is 0, upper face is 1.
 		J=tria->SurfaceRelVelMisfit(weight_index);
 		delete tria->material; delete tria;
@@ -5502,8 +6825,8 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 	_error_("Not implemented yet");
 
-	tria=(Tria*)SpawnTria(0,1,2);
+	tria=(Tria*)SpawnTria(0);
 	J=tria->ThicknessAbsMisfit(weight_index);
 	delete tria->material; delete tria;
@@ -5518,7 +6841,7 @@
 
 	/*If on water, on shelf or not on bed, skip: */
-	if(IsOnWater()|| IsFloating() || !IsOnBed()) return 0;
-
-	tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria
+	if(NoIceInElement()|| IsFloating() || !IsOnBed()) return 0;
+
+	tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1
 	J=tria->DragCoefficientAbsGradient(weight_index);
 	delete tria->material; delete tria;
@@ -5533,7 +6856,7 @@
 
 	/*If on water, on shelf or not on bed, skip: */
-	if(IsOnWater() || !IsOnBed()) return 0;
-
-	tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria
+	if(NoIceInElement() || !IsOnBed()) return 0;
+
+	tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1
 	J=tria->RheologyBbarAbsGradient(weight_index);
 	delete tria->material; delete tria;
@@ -5582,5 +6905,5 @@
 		values[i]=vector[vertexpidlist[i]];
 	}
-	new_input = new PentaP1Input(control_enum,values);
+	new_input = new PentaInput(control_enum,values,P1Enum);
 
 	if(control_enum==MaterialsRheologyBbarEnum){
@@ -5613,5 +6936,5 @@
 		case VertexEnum:
 
-			/*New PentaP1Input*/
+			/*New PentaInput*/
 			IssmDouble values[6];
 
@@ -5624,5 +6947,5 @@
 			switch(name){
 				case ThicknessEnum:
-					/*Update thickness + surface: assume bed is constant. On ice shelves, takes hydrostatic equilibrium {{{*/
+					/*Update thickness + surface: assume bed is constant. On ice shelves, takes hydrostatic equilibrium*/
 					IssmDouble  thickness[6];
 					IssmDouble  thickness_init[6];
@@ -5686,12 +7009,11 @@
 
 					/*Add new inputs: */
-					this->inputs->AddInput(new PentaP1Input(ThicknessEnum,thickness));
-					this->inputs->AddInput(new PentaP1Input(BedEnum,bed));
-					this->inputs->AddInput(new PentaP1Input(SurfaceEnum,surface));
-
-					/*}}}*/
+					this->inputs->AddInput(new PentaInput(ThicknessEnum,thickness,P1Enum));
+					this->inputs->AddInput(new PentaInput(BedEnum,bed,P1Enum));
+					this->inputs->AddInput(new PentaInput(SurfaceEnum,surface,P1Enum));
+
 					break;
 				default:
-					this->inputs->AddInput(new PentaP1Input(name,values));
+					this->inputs->AddInput(new PentaInput(name,values,P1Enum));
 			}
 			break;
@@ -5703,23 +7025,11 @@
 }
 /*}}}*/
-/*FUNCTION Penta::InputUpdateFromVectorDakota(int* vector, int name, int type);{{{*/
-void  Penta::InputUpdateFromVectorDakota(int* vector, int name, int type){
-	_error_("not supported yet!");
-}
-/*}}}*/
-/*FUNCTION Penta::InputUpdateFromVectorDakota(bool* vector, int name, int type);{{{*/
-void  Penta::InputUpdateFromVectorDakota(bool* vector, int name, int type){
-	_error_("not supported yet!");
-}
-/*}}}*/
 /*FUNCTION Penta::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type);{{{*/
 void  Penta::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){
 
-	int i,j,t;
-	TransientInput* transientinput=NULL;
-	IssmDouble values[6];
-	IssmDouble time;
-	int row;
-	IssmDouble yts;
+	int             i,t,row;
+	IssmDouble      time;
+	TransientInput *transientinput = NULL;
+	IssmDouble      values[6];
 
 	/*Check that name is an element input*/
@@ -5729,9 +7039,5 @@
 
 		case VertexEnum:
-
 			/*Create transient input: */
-
-			parameters->FindParam(&yts,ConstantsYtsEnum);
-
 			for(t=0;t<ncols;t++){ //ncols is the number of times
 
@@ -5739,12 +7045,12 @@
 				for(i=0;i<6;i++){
 					row=this->vertices[i]->Sid();
-					values[i]=(IssmDouble)matrix[ncols*row+t];
+					values[i]=matrix[ncols*row+t];
 				}
 
-				/*time? :*/
-				time=(IssmDouble)matrix[(nrows-1)*ncols+t]*yts;
+				/*time:*/
+				time=matrix[(nrows-1)*ncols+t];
 
 				if(t==0) transientinput=new TransientInput(name);
-				transientinput->AddTimeInput(new PentaP1Input(name,values),time);
+				transientinput->AddTimeInput(new PentaInput(name,values,P1Enum),time);
 				transientinput->Configure(parameters);
 			}
@@ -5760,7 +7066,7 @@
 #endif
 
-#ifdef _HAVE_DIAGNOSTIC_
-/*FUNCTION Penta::CreateDVectorDiagnosticHoriz {{{*/
-ElementVector* Penta::CreateDVectorDiagnosticHoriz(void){
+#ifdef _HAVE_STRESSBALANCE_
+/*FUNCTION Penta::CreateDVectorStressbalanceHoriz {{{*/
+ElementVector* Penta::CreateDVectorStressbalanceHoriz(void){
 
 	int approximation;
@@ -5768,31 +7074,35 @@
 
 	switch(approximation){
-		case StokesApproximationEnum:
-			return CreateDVectorDiagnosticStokes();
+		case FSApproximationEnum:
+			return CreateDVectorStressbalanceFS();
 		default:
-			return NULL; //no need for doftypes outside of stokes approximation
-	}
-}
-/*}}}*/
-/*FUNCTION Penta::CreateDVectorDiagnosticStokes{{{*/
-ElementVector* Penta::CreateDVectorDiagnosticStokes(void){
+			return NULL; //no need for doftypes outside of FS approximation
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::CreateDVectorStressbalanceFS{{{*/
+ElementVector* Penta::CreateDVectorStressbalanceFS(void){
 
 	/*output: */
 	ElementVector* De=NULL;
-	/*intermediary: */
+
+	/*Initialize Element vector and return if necessary*/
 	int approximation;
-	int i;
-
-	/*Initialize Element vector and return if necessary*/
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=StokesApproximationEnum) return NULL;
-
-	De=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
-
-	for (i=0;i<NUMVERTICES;i++){
-		De->values[i*4+0]=VelocityEnum;
-		De->values[i*4+1]=VelocityEnum;
-		De->values[i*4+2]=VelocityEnum;
-		De->values[i*4+3]=PressureEnum;
+	if(approximation!=FSApproximationEnum) return NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	De=new ElementVector(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
+
+	for(int i=0;i<vnumnodes;i++){
+		De->values[i*3+0]=VelocityEnum;
+		De->values[i*3+1]=VelocityEnum;
+		De->values[i*3+2]=VelocityEnum;
+	}
+	for(int i=0;i<pnumnodes;i++){
+		De->values[vnumnodes*3+i]=PressureEnum;
 	}
 
@@ -5800,10 +7110,10 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattyn{{{*/
-ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattyn(void){
+/*FUNCTION Penta::CreateKMatrixCouplingSSAHO{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingSSAHO(void){
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixCouplingMacAyealPattynViscous();
-	ElementMatrix* Ke2=CreateKMatrixCouplingMacAyealPattynFriction();
+	ElementMatrix* Ke1=CreateKMatrixCouplingSSAHOViscous();
+	ElementMatrix* Ke2=CreateKMatrixCouplingSSAHOFriction();
 	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
 
@@ -5814,6 +7124,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattynViscous{{{*/
-ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattynViscous(void){
+/*FUNCTION Penta::CreateKMatrixCouplingSSAHOViscous{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingSSAHOViscous(void){
 
 	/*Constants*/
@@ -5840,9 +7150,9 @@
 	int         cs_list[numnodes];
 
-	/*Find penta on bed as pattyn must be coupled to the dofs on the bed: */
+	/*Find penta on bed as HO must be coupled to the dofs on the bed: */
 	Penta* pentabase=GetBasalElement();
-	Tria*  tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-
-	/*Prepare node list*/
+	Tria*  tria=pentabase->SpawnTria(0); //lower face is 0, upper face is 1.
+
+	/*prepare node list*/
 	for(i=0;i<NUMVERTICES;i++){
 		node_list[i+0*NUMVERTICES] = pentabase->nodes[i];
@@ -5853,6 +7163,6 @@
 
 	/*Initialize Element matrix*/
-	ElementMatrix* Ke1=new ElementMatrix(pentabase->nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
-	ElementMatrix* Ke2=new ElementMatrix(this->nodes     ,NUMVERTICES,this->parameters,PattynApproximationEnum);
+	ElementMatrix* Ke1=new ElementMatrix(pentabase->nodes,NUMVERTICES,this->parameters,SSAApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(this->nodes     ,NUMVERTICES,this->parameters,HOApproximationEnum);
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
 	delete Ke1; delete Ke2;
@@ -5860,5 +7170,5 @@
 	/* Get node coordinates and dof list: */
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+	this->parameters->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
 	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
 	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
@@ -5875,9 +7185,9 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetBMacAyealPattyn(&B[0][0], &xyz_list[0][0], gauss);
-		tria->GetBprimeMacAyeal(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
-
-		this->GetStrainRate3dPattyn(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
-		this->GetStrainRate3dPattyn(&oldepsilon[0],&xyz_list[0][0],gauss,vxold_input,vyold_input);
+		GetBSSAHO(&B[0][0], &xyz_list[0][0], gauss);
+		tria->GetBprimeSSA(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
+
+		this->GetStrainRate3dHO(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->GetStrainRate3dHO(&oldepsilon[0],&xyz_list[0][0],gauss,vxold_input,vyold_input);
 		material->GetViscosity3d(&viscosity, &epsilon[0]);
 		material->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
@@ -5907,6 +7217,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattynFriction{{{*/
-ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattynFriction(void){
+/*FUNCTION Penta::CreateKMatrixCouplingSSAHOFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingSSAHOFriction(void){
 
 	/*Constants*/
@@ -5932,6 +7242,6 @@
 	/*Initialize Element matrix and return if necessary*/
 	if(IsFloating() || !IsOnBed()) return NULL;
-	ElementMatrix* Ke1=new ElementMatrix(nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
-	ElementMatrix* Ke2=new ElementMatrix(nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+	ElementMatrix* Ke1=new ElementMatrix(nodes,NUMVERTICES,this->parameters,SSAApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(nodes,NUMVERTICES,this->parameters,HOApproximationEnum);
 	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
 	delete Ke1; delete Ke2;
@@ -5947,5 +7257,5 @@
 	/*retrieve inputs :*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 	Input* vx_input=inputs->GetInput(VxEnum);           _assert_(vx_input);
@@ -5966,5 +7276,5 @@
 
 		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
-		GetBPattynFriction(&L[0][0],gauss);
+		GetBHOFriction(&L[0][0],gauss);
 
 		DL_scalar=alpha2*gauss->weight*Jdet2d;
@@ -5992,10 +7302,10 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixCouplingMacAyealStokes{{{*/
-ElementMatrix* Penta::CreateKMatrixCouplingMacAyealStokes(void){
+/*FUNCTION Penta::CreateKMatrixCouplingSSAFS{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingSSAFS(void){
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixCouplingMacAyealStokesViscous();
-	ElementMatrix* Ke2=CreateKMatrixCouplingMacAyealStokesFriction();
+	ElementMatrix* Ke1=CreateKMatrixCouplingSSAFSViscous();
+	ElementMatrix* Ke2=CreateKMatrixCouplingSSAFSFriction();
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
 
@@ -6006,23 +7316,22 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixCouplingMacAyealStokesViscous{{{*/
-ElementMatrix* Penta::CreateKMatrixCouplingMacAyealStokesViscous(void){
+/*FUNCTION Penta::CreateKMatrixCouplingSSAFSViscous{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingSSAFSViscous(void){
 
 	/*Constants*/
-	const int numnodes    = 2 *NUMVERTICES;
 	const int numdofm     = NDOF2 *NUMVERTICES2D;
-	const int numdofs     = NDOF4 *NUMVERTICES;
+	const int numdofs     = NDOF4 *NUMVERTICES + NDOF3;
 	const int numdoftotal = 2 *numdofm+numdofs;
 
 	/*Intermediaries */
-	int         i,j;
+	int        i,j;
 	IssmDouble Jdet;
-	IssmDouble viscosity,stokesreconditioning; //viscosity
+	IssmDouble viscosity,FSreconditioning; //viscosity
 	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble B[4][numdofs+3];
+	IssmDouble B[4][numdofs];
 	IssmDouble Bprime[4][numdofm];
 	IssmDouble B2[3][numdofm];
-	IssmDouble Bprime2[3][numdofs+3];
+	IssmDouble Bprime2[3][numdofs];
 	IssmDouble D[4][4]={0.0};            // material matrix, simple scalar matrix.
 	IssmDouble D2[3][3]={0.0};            // material matrix, simple scalar matrix.
@@ -6030,32 +7339,42 @@
 	IssmDouble Ke_gg[numdofs][numdofm]={0.0}; //local element stiffness matrix 
 	IssmDouble Ke_gg2[numdofm][numdofs]={0.0}; //local element stiffness matrix 
-	IssmDouble Ke_gg_gaussian[numdofs+3][numdofm]; //stiffness matrix evaluated at the gaussian point.
-	IssmDouble Ke_gg_gaussian2[numdofm][numdofs+3]; //stiffness matrix evaluated at the gaussian point.
+	IssmDouble Ke_gg_gaussian[numdofs][numdofm]; //stiffness matrix evaluated at the gaussian point.
+	IssmDouble Ke_gg_gaussian2[numdofm][numdofs]; //stiffness matrix evaluated at the gaussian point.
 	GaussPenta *gauss=NULL;
 	GaussTria  *gauss_tria=NULL;
-	Node       *node_list[numnodes];
-	int         cs_list[numnodes];
-
-	/*Find penta on bed as stokes must be coupled to the dofs on the bed: */
+	Node       *node_list[20];
+
+	/*Find penta on bed as FS must be coupled to the dofs on the bed: */
 	Penta* pentabase=GetBasalElement();
-	Tria* tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=pentabase->SpawnTria(0); //lower face is 0, upper face is 1.
+
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int numnodes  = 2*vnumnodes-1+pnumnodes;
 
 	/*Prepare node list*/
-	for(i=0;i<NUMVERTICES;i++){
-		node_list[i+0*NUMVERTICES] = pentabase->nodes[i];
-		node_list[i+1*NUMVERTICES] = this->nodes[i];
-		cs_list[i+0*NUMVERTICES] = XYEnum;
-		cs_list[i+1*NUMVERTICES] = XYZPEnum;
+	int* cs_list = xNew<int>(2*vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes-1;i++){
+		node_list[i] = pentabase->nodes[i];
+		cs_list[i] = XYEnum;
+	}
+	for(i=0;i<vnumnodes;i++){
+		node_list[i+vnumnodes-1] = this->nodes[i];
+		cs_list[i+vnumnodes-1] = XYZEnum;
+	}
+	for(i=0;i<pnumnodes;i++){
+		node_list[2*vnumnodes-1+i] = this->nodes[vnumnodes+i];
+		cs_list[2*vnumnodes-1+i] = PressureEnum;
 	}
 
 	/*Initialize Element matrix and return if necessary*/
-	ElementMatrix* Ke1=new ElementMatrix(pentabase->nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
-	ElementMatrix* Ke2=new ElementMatrix(this->nodes     ,NUMVERTICES,this->parameters,StokesApproximationEnum);
-	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
+	ElementMatrix* Ke1=new ElementMatrix(pentabase->nodes,NUMVERTICES,    this->parameters,SSAApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(this->nodes     ,2*NUMVERTICES+1,this->parameters,FSvelocityEnum);
+	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
 	delete Ke1; delete Ke2;
 
 	/* Get node coordinates and dof list: */
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
 	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
 	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
@@ -6071,18 +7390,18 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetBMacAyealStokes(&B[0][0], &xyz_list[0][0], gauss);
-		tria->GetBprimeMacAyealStokes(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
-		tria->GetBMacAyealStokes(&B2[0][0], &xyz_list[0][0], gauss_tria);
-		GetBprimeMacAyealStokes(&Bprime2[0][0], &xyz_list[0][0], gauss);
+		GetBSSAFS(&B[0][0], &xyz_list[0][0], gauss);
+		tria->GetBprimeSSAFS(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
+		tria->GetBSSAFS(&B2[0][0], &xyz_list[0][0], gauss_tria);
+		GetBprimeSSAFS(&Bprime2[0][0], &xyz_list[0][0], gauss);
 
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity, &epsilon[0]);
+		material->GetViscosity3dFS(&viscosity, &epsilon[0]);
 
 		D_scalar=2*viscosity*gauss->weight*Jdet;
 		for (i=0;i<3;i++) D[i][i]=D_scalar;
-		D[3][3]=-gauss->weight*Jdet*stokesreconditioning;
+		D[3][3]=-gauss->weight*Jdet*FSreconditioning;
 		for (i=0;i<3;i++) D2[i][i]=D_scalar;
 
-		TripleMultiply( &B[0][0],4,numdofs+3,1,
+		TripleMultiply( &B[0][0],4,numdofs,1,
 					&D[0][0],4,4,0,
 					&Bprime[0][0],4,numdofm,0,
@@ -6091,12 +7410,12 @@
 		TripleMultiply( &B2[0][0],3,numdofm,1,
 					&D2[0][0],3,3,0,
-					&Bprime2[0][0],3,numdofs+3,0,
+					&Bprime2[0][0],3,numdofs,0,
 					&Ke_gg_gaussian2[0][0],0);
 
-		for( i=0; i<numdofs; i++) for(j=0;j<numdofm; j++) Ke_gg[i][j]+=Ke_gg_gaussian[i][j];
-		for( i=0; i<numdofm; i++) for(j=0;j<numdofs; j++) Ke_gg2[i][j]+=Ke_gg_gaussian2[i][j];
+		for( i=0; i<numdofs; i++) for(j=0;j<numdofm; j++)      Ke_gg[i][j]+=Ke_gg_gaussian[i][j];
+		for( i=0; i<numdofm; i++)      for(j=0;j<numdofs; j++) Ke_gg2[i][j]+=Ke_gg_gaussian2[i][j];
 	} 
-	for(i=0;i<numdofs;i++) for(j=0;j<numdofm;j++) Ke->values[(i+2*numdofm)*numdoftotal+j]+=Ke_gg[i][j];
-	for(i=0;i<numdofm;i++) for(j=0;j<numdofs;j++) Ke->values[i*numdoftotal+(j+2*numdofm)]+=Ke_gg2[i][j];
+	for(i=0;i<numdofs;i++) for(j=0;j<numdofm;j++)      Ke->values[(i+2*numdofm)*numdoftotal+j]+=Ke_gg[i][j];
+	for(i=0;i<numdofm;i++)      for(j=0;j<numdofs;j++) Ke->values[i*numdoftotal+(j+2*numdofm)]+=Ke_gg2[i][j];
 
 	/*Transform Coordinate System*/
@@ -6104,4 +7423,5 @@
 
 	/*Clean-up and return*/
+	xDelete<int>(cs_list);
 	delete tria->material; delete tria;
 	delete gauss;
@@ -6110,19 +7430,17 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixCouplingMacAyealStokesFriction {{{*/
-ElementMatrix* Penta::CreateKMatrixCouplingMacAyealStokesFriction(void){
-
+/*FUNCTION Penta::CreateKMatrixCouplingSSAFSFriction {{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingSSAFSFriction(void){
 	/*Constants*/
-	const int numnodes  = 2 *NUMVERTICES;
-	const int numdof    = NUMVERTICES *NDOF4;
+	const int numdofs   = (NUMVERTICES+1)*NDOF3 + NUMVERTICES*NDOF1;
 	const int numdofm   = NUMVERTICES *NDOF2;
-	const int numdof2d  = NUMVERTICES2D *NDOF4;
+	const int numdof2d  = NUMVERTICES2D *NDOF3;
 	const int numdof2dm = NUMVERTICES2D *NDOF2;
-	const int numdoftot = numdof+numdofm;
+	const int numdoftot = NUMVERTICES*2 + (NUMVERTICES+1)*3 +NUMVERTICES; // HO + FS vel + FS Pressure
 
 	/*Intermediaries */
 	int        i,j;
 	int        analysis_type,approximation;
-	IssmDouble stokesreconditioning;
+	IssmDouble FSreconditioning;
 	IssmDouble viscosity,alpha2_gauss,Jdet2d;
 	IssmDouble bed_normal[3];
@@ -6130,37 +7448,48 @@
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
-	IssmDouble LMacAyealStokes[8][numdof2dm];
-	IssmDouble LprimeMacAyealStokes[8][numdof2d];
-	IssmDouble DLMacAyealStokes[8][8]={0.0};
-	IssmDouble LStokesMacAyeal[4][numdof2d];
-	IssmDouble LprimeStokesMacAyeal[4][numdof2dm];
-	IssmDouble DLStokesMacAyeal[4][4]={0.0};
-	IssmDouble Ke_drag_gaussian[numdof2dm][numdof2d];
+	IssmDouble LSSAFS[8][numdof2dm];
+	IssmDouble LprimeSSAFS[8][numdofs];
+	IssmDouble DLSSAFS[8][8]={0.0};
+	IssmDouble LFSSSA[4][numdof2d];
+	IssmDouble LprimeFSSSA[4][numdof2dm];
+	IssmDouble DLFSSSA[4][4]={0.0};
+	IssmDouble Ke_drag_gaussian[numdof2dm][numdofs];
 	IssmDouble Ke_drag_gaussian2[numdof2d][numdof2dm];
 	Friction*  friction=NULL;
 	GaussPenta *gauss=NULL;
-	Node       *node_list[numnodes];
-	int         cs_list[numnodes];
-
-	/*If on water or not Stokes, skip stiffness: */
+	Node       *node_list[20];
+
+	/*If on water or not FS, skip stiffness: */
 	inputs->GetInputValue(&approximation,ApproximationEnum);
 	if(IsFloating() || !IsOnBed()) return NULL;
-	ElementMatrix* Ke1=new ElementMatrix(this->nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
-	ElementMatrix* Ke2=new ElementMatrix(this->nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int numnodes  = 2*vnumnodes-1+pnumnodes;
+
+	/*Prepare node list*/
+	int* cs_list = xNew<int>(2*vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes-1;i++){
+		node_list[i] = this->nodes[i];
+		cs_list[i] = XYEnum;
+	}
+	for(i=0;i<vnumnodes;i++){
+		node_list[i+vnumnodes-1] = this->nodes[i];
+		cs_list[i+vnumnodes-1] = XYZEnum;
+	}
+	for(i=0;i<pnumnodes;i++){
+		node_list[2*vnumnodes-1+i] = this->nodes[vnumnodes+i];
+		cs_list[2*vnumnodes-1+i] = PressureEnum;
+	}
+
+	ElementMatrix* Ke1=new ElementMatrix(this->nodes,NUMVERTICES,        this->parameters,SSAApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(this->nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
 	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
 	delete Ke1; delete Ke2;
-
-	/*Prepare node list*/
-	for(i=0;i<NUMVERTICES;i++){
-		node_list[i+0*NUMVERTICES] = this->nodes[i];
-		node_list[i+1*NUMVERTICES] = this->nodes[i];
-		cs_list[i+0*NUMVERTICES] = XYEnum;
-		cs_list[i+1*NUMVERTICES] = XYZPEnum;
-	}
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
 	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
 	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
@@ -6178,40 +7507,39 @@
 
 		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
-		GetLMacAyealStokes(&LMacAyealStokes[0][0], gauss);
-		GetLprimeMacAyealStokes(&LprimeMacAyealStokes[0][0], &xyz_list[0][0], gauss);
-		GetLStokesMacAyeal(&LStokesMacAyeal[0][0], gauss);
-		GetLprimeStokesMacAyeal(&LprimeStokesMacAyeal[0][0], &xyz_list[0][0], gauss);
+		GetLSSAFS(&LSSAFS[0][0], gauss);
+		GetLprimeSSAFS(&LprimeSSAFS[0][0], &xyz_list[0][0], gauss);
+		GetLFSSSA(&LFSSSA[0][0], gauss);
+		GetLprimeFSSSA(&LprimeFSSSA[0][0], &xyz_list[0][0], gauss);
 
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
 
 		BedNormal(&bed_normal[0],xyz_list_tria);
 		friction->GetAlpha2(&alpha2_gauss, gauss,VxEnum,VyEnum,VzEnum);
 
-		DLMacAyealStokes[0][0]=alpha2_gauss*gauss->weight*Jdet2d;
-		DLMacAyealStokes[1][1]=alpha2_gauss*gauss->weight*Jdet2d;
-		DLMacAyealStokes[2][2]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[0]*bed_normal[2];
-		DLMacAyealStokes[3][3]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[1]*bed_normal[2];
-		DLMacAyealStokes[4][4]=-2*viscosity*gauss->weight*Jdet2d*bed_normal[0];
-		DLMacAyealStokes[5][5]=-2*viscosity*gauss->weight*Jdet2d*bed_normal[1];
-		DLMacAyealStokes[6][6]=stokesreconditioning*gauss->weight*Jdet2d*bed_normal[0];
-		DLMacAyealStokes[7][7]=stokesreconditioning*gauss->weight*Jdet2d*bed_normal[1];
-
-		DLStokesMacAyeal[0][0]=alpha2_gauss*gauss->weight*Jdet2d;
-		DLStokesMacAyeal[1][1]=alpha2_gauss*gauss->weight*Jdet2d;
-		DLStokesMacAyeal[2][2]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[0]*bed_normal[2];
-		DLStokesMacAyeal[3][3]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[1]*bed_normal[2];
-
-		TripleMultiply( &LMacAyealStokes[0][0],8,numdof2dm,1,
-					&DLMacAyealStokes[0][0],8,8,0,
-					&LprimeMacAyealStokes[0][0],8,numdof2d,0,
+		DLSSAFS[0][0]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLSSAFS[1][1]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLSSAFS[2][2]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[0]*bed_normal[2];
+		DLSSAFS[3][3]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[1]*bed_normal[2];
+		DLSSAFS[4][4]=-2*viscosity*gauss->weight*Jdet2d*bed_normal[0];
+		DLSSAFS[5][5]=-2*viscosity*gauss->weight*Jdet2d*bed_normal[1];
+		DLSSAFS[6][6]=FSreconditioning*gauss->weight*Jdet2d*bed_normal[0];
+		DLSSAFS[7][7]=FSreconditioning*gauss->weight*Jdet2d*bed_normal[1];
+
+		DLFSSSA[0][0]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLFSSSA[1][1]=alpha2_gauss*gauss->weight*Jdet2d;
+		DLFSSSA[2][2]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[0]*bed_normal[2];
+		DLFSSSA[3][3]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[1]*bed_normal[2];
+
+		TripleMultiply( &LSSAFS[0][0],8,numdof2dm,1,
+					&DLSSAFS[0][0],8,8,0,
+					&LprimeSSAFS[0][0],8,numdofs,0,
 					&Ke_drag_gaussian[0][0],0);
 
-		TripleMultiply( &LStokesMacAyeal[0][0],4,numdof2d,1,
-					&DLStokesMacAyeal[0][0],4,4,0,
-					&LprimeStokesMacAyeal[0][0],4,numdof2dm,0,
+		TripleMultiply( &LFSSSA[0][0],4,numdof2d,1,
+					&DLFSSSA[0][0],4,4,0,
+					&LprimeFSSSA[0][0],4,numdof2dm,0,
 					&Ke_drag_gaussian2[0][0],0);
-
-		for(i=0;i<numdof2dm;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdoftot+j+numdofm]+=Ke_drag_gaussian[i][j];
+		for(i=0;i<numdof2dm;i++) for(j=0;j<numdofs;j++) Ke->values[i*numdoftot+j+numdofm]+=Ke_drag_gaussian[i][j];
 		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2dm;j++) Ke->values[(i+numdofm)*numdoftot+j]+=Ke_drag_gaussian2[i][j];
 	}
@@ -6221,4 +7549,5 @@
 
 	/*Clean up and return*/
+	xDelete<int>(cs_list);
 	delete gauss;
 	delete friction;
@@ -6226,45 +7555,61 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixCouplingPattynStokes{{{*/
-ElementMatrix* Penta::CreateKMatrixCouplingPattynStokes(void){
+/*FUNCTION Penta::CreateKMatrixCouplingHOFS{{{*/
+ElementMatrix* Penta::CreateKMatrixCouplingHOFS(void){
 
 	/*Constants*/
-	const int numnodes  = 2 *NUMVERTICES;
-	const int numdofp     = NDOF2 *NUMVERTICES;
-	const int numdofs     = NDOF4 *NUMVERTICES;
-	const int numdoftotal = (NDOF2+NDOF4) *NUMVERTICES;
+	const int numnodes       = 3 *NUMVERTICES+1;
+	const int numdofp        = NDOF2 *NUMVERTICES;
+	const int numdofs        = NDOF4 * 6 + NDOF3;
+	const int numdoftotal    = (NDOF2+NDOF4) *NUMVERTICES + NDOF3;
 
 	/*Intermediaries*/
-	Node     *node_list[numnodes];
-	int       cs_list[numnodes];
-	int       i,j;
-
-	/*Prepare node list*/
+	int   i,j,init;
+	Node  *node_list[NUMVERTICES*3+1];
+	int   cs_list[NUMVERTICES*3+1];
+	int   cs_list2[NUMVERTICES*2+1];
+
+	/*Some parameters needed*/
+	init=this->element_type;
+
+	/*prepare node list*/
+	for(i=0;i<NUMVERTICES+1;i++){
+		node_list[i+NUMVERTICES] = this->nodes[i];
+		cs_list[i+NUMVERTICES]   = XYZEnum;
+		cs_list2[i]              = XYZEnum;
+	}
 	for(i=0;i<NUMVERTICES;i++){
-		node_list[i+0*NUMVERTICES] = this->nodes[i];
-		node_list[i+1*NUMVERTICES] = this->nodes[i];
-		cs_list[i+0*NUMVERTICES] = XYEnum;
-		cs_list[i+1*NUMVERTICES] = XYZPEnum;
+		node_list[i]                 = this->nodes[i];
+		node_list[i+2*NUMVERTICES+1] = this->nodes[i+NUMVERTICES+1];
+		cs_list[i]                   = XYEnum;
+		cs_list[i+2*NUMVERTICES+1]   = PressureEnum;
+		cs_list2[i+NUMVERTICES+1]    = PressureEnum;
 	}
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=new ElementMatrix(this->nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
-	ElementMatrix* Ke2=new ElementMatrix(this->nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	ElementMatrix* Ke1=new ElementMatrix(this->nodes,NUMVERTICES,this->parameters,HOApproximationEnum);
+	ElementMatrix* Ke2=new ElementMatrix(this->nodes,2*NUMVERTICES+1,this->parameters,FSvelocityEnum);
 	ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
-	delete Ke1;
-	delete Ke2;
-	Ke1=CreateKMatrixDiagnosticPattyn(); TransformInvStiffnessMatrixCoord(Ke1,this->nodes,NUMVERTICES,XYEnum);
-	Ke2=CreateKMatrixDiagnosticStokes(); TransformInvStiffnessMatrixCoord(Ke2,this->nodes,NUMVERTICES,XYZPEnum);
+	delete Ke1; delete Ke2;
+	
+	/*Compute HO Matrix with P1 element type\n");*/
+	this->element_type=P1Enum;
+	Ke1=CreateKMatrixStressbalanceHO(); TransformInvStiffnessMatrixCoord(Ke1,this->nodes,NUMVERTICES,XYEnum);
+	this->element_type=init;
+	/*Compute FS Matrix and condense it \n");*/
+	Ke2=CreateKMatrixStressbalanceFS(); TransformInvStiffnessMatrixCoord(Ke2,this->nodes,2*NUMVERTICES+1,cs_list2);
+	int indices[3]={18,19,20};
+	Ke2->StaticCondensation(3,&indices[0]);
 
 	for(i=0;i<numdofs;i++) for(j=0;j<NUMVERTICES;j++){
-		Ke->values[(i+numdofp)*numdoftotal+NDOF2*j+0]+=Ke2->values[i*numdofs+NDOF4*j+0];
-		Ke->values[(i+numdofp)*numdoftotal+NDOF2*j+1]+=Ke2->values[i*numdofs+NDOF4*j+1];
+		Ke->values[(i+numdofp)*numdoftotal+NDOF2*j+0]+=Ke2->values[i*numdofs+NDOF3*j+0];
+		Ke->values[(i+numdofp)*numdoftotal+NDOF2*j+1]+=Ke2->values[i*numdofs+NDOF3*j+1];
 	}
 	for(i=0;i<numdofp;i++) for(j=0;j<NUMVERTICES;j++){
-		Ke->values[i*numdoftotal+numdofp+NDOF4*j+0]+=Ke1->values[i*numdofp+NDOF2*j+0];
-		Ke->values[i*numdoftotal+numdofp+NDOF4*j+1]+=Ke1->values[i*numdofp+NDOF2*j+1];
-	}
-
-	/*Transform Coordinate System*/
+		Ke->values[i*numdoftotal+numdofp+NDOF3*j+0]+=Ke1->values[i*numdofp+NDOF2*j+0];
+		Ke->values[i*numdoftotal+numdofp+NDOF3*j+1]+=Ke1->values[i*numdofp+NDOF2*j+1];
+	}
+
+	/*Transform Coordinate System*/ //Do not transform, already done in the matrices
 	TransformStiffnessMatrixCoord(Ke,node_list,numnodes,cs_list);
 
@@ -6274,30 +7619,29 @@
 	return Ke;
 }
-/*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticHoriz {{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticHoriz(void){
+//*}}}*/
+/*FUNCTION Penta::CreateKMatrixStressbalanceHoriz {{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceHoriz(void){
 
 	int approximation;
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-
 	switch(approximation){
-		case MacAyealApproximationEnum:
-			return CreateKMatrixDiagnosticMacAyeal2d();
+		case SSAApproximationEnum:
+			return CreateKMatrixStressbalanceSSA2d();
 		case L1L2ApproximationEnum:
-			return CreateKMatrixDiagnosticL1L2();
-		case PattynApproximationEnum:
-			return CreateKMatrixDiagnosticPattyn();
-		case StokesApproximationEnum:
-			return CreateKMatrixDiagnosticStokes();
-		case HutterApproximationEnum:
+			return CreateKMatrixStressbalanceL1L2();
+		case HOApproximationEnum:
+			return CreateKMatrixStressbalanceHO();
+		case FSApproximationEnum:
+			return CreateKMatrixStressbalanceFS();
+		case SIAApproximationEnum:
 			return NULL;
 		case NoneApproximationEnum:
 			return NULL;
-		case MacAyealPattynApproximationEnum:
-			return CreateKMatrixDiagnosticMacAyealPattyn();
-		case MacAyealStokesApproximationEnum:
-			return CreateKMatrixDiagnosticMacAyealStokes();
-		case PattynStokesApproximationEnum:
-			return CreateKMatrixDiagnosticPattynStokes();
+		case SSAHOApproximationEnum:
+			return CreateKMatrixStressbalanceSSAHO();
+		case SSAFSApproximationEnum:
+			return CreateKMatrixStressbalanceSSAFS();
+		case HOFSApproximationEnum:
+			return CreateKMatrixStressbalanceHOFS();
 		default:
 			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
@@ -6305,61 +7649,61 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticHutter{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticHutter(void){
-
-	/*Constants*/
-	const int numdof=NDOF2*NUMVERTICES;
+/*FUNCTION Penta::CreateKMatrixStressbalanceSIA{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceSIA(void){
 
 	/*Intermediaries*/
-	int         connectivity[2];
-	int         i,i0,i1,j0,j1;
-	IssmDouble  one0,one1;
+	IssmDouble connectivity[2];
+	IssmDouble one0,one1;
+	int        i,i0,i1,j0,j1;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes(); _assert_(numnodes==6); 
+	int numdof   = numnodes*NDOF2;
 
 	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
-
-	/*Spawn 3 beam elements: */
+	ElementMatrix* Ke=new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+
+	/*3 vertical edges*/
 	for(i=0;i<3;i++){
+
 		/*2 dofs of first node*/
-		i0=2*i;
-		i1=2*i+1;
+		i0=2*i;     i1=2*i+1;
 		/*2 dofs of second node*/
-		j0=2*(i+3);
-		j1=2*(i+3)+1;
+		j0=2*(i+3); j1=2*(i+3)+1;
 
 		/*Find connectivity for the two nodes*/
-		connectivity[0]=nodes[i]->GetConnectivity();
-		connectivity[1]=nodes[i+3]->GetConnectivity();
-		one0=1/(IssmDouble)connectivity[0];
-		one1=1/(IssmDouble)connectivity[1];
+		connectivity[0]=(IssmDouble)vertices[i]->Connectivity();
+		connectivity[1]=(IssmDouble)vertices[i+3]->Connectivity();
+		one0=1./connectivity[0];
+		one1=1./connectivity[1];
 
 		/*Create matrix for these two nodes*/
 		if (IsOnBed() && IsOnSurface()){
-			Ke->values[i0*numdof+i0]=one0;
-			Ke->values[i1*numdof+i1]=one0;
-			Ke->values[j0*numdof+i0]=-one1;
-			Ke->values[j0*numdof+j0]=one1;
-			Ke->values[j1*numdof+i1]=-one1;
-			Ke->values[j1*numdof+j1]=one1;
+			Ke->values[i0*numdof+i0] = +one0;
+			Ke->values[i1*numdof+i1] = +one0;
+			Ke->values[j0*numdof+i0] = -one1;
+			Ke->values[j0*numdof+j0] = +one1;
+			Ke->values[j1*numdof+i1] = -one1;
+			Ke->values[j1*numdof+j1] = +one1;
 		}
 		else if (IsOnBed()){
-			Ke->values[i0*numdof+i0]=one0;
-			Ke->values[i1*numdof+i1]=one0;
-			Ke->values[j0*numdof+i0]=-2*one1;
-			Ke->values[j0*numdof+j0]=2*one1;
-			Ke->values[j1*numdof+i1]=-2*one1;
-			Ke->values[j1*numdof+j1]=2*one1;
+			Ke->values[i0*numdof+i0] = one0;
+			Ke->values[i1*numdof+i1] = one0;
+			Ke->values[j0*numdof+i0] = -2.*one1;
+			Ke->values[j0*numdof+j0] = +2.*one1;
+			Ke->values[j1*numdof+i1] = -2.*one1;
+			Ke->values[j1*numdof+j1] = +2.*one1;
 		}
 		else if (IsOnSurface()){
-			Ke->values[j0*numdof+i0]=-one1;
-			Ke->values[j0*numdof+j0]=one1;
-			Ke->values[j1*numdof+i1]=-one1;
-			Ke->values[j1*numdof+j1]=one1;
+			Ke->values[j0*numdof+i0] = -one1;
+			Ke->values[j0*numdof+j0] = +one1;
+			Ke->values[j1*numdof+i1] = -one1;
+			Ke->values[j1*numdof+j1] = +one1;
 		}
 		else{ //node is on two horizontal layers and beams include the values only once, so the have to use half of the connectivity
-			Ke->values[j0*numdof+i0]=-2*one1;
-			Ke->values[j0*numdof+j0]=2*one1;
-			Ke->values[j1*numdof+i1]=-2*one1;
-			Ke->values[j1*numdof+j1]=2*one1;
+			Ke->values[j0*numdof+i0] = -2.*one1;
+			Ke->values[j0*numdof+j0] = +2.*one1;
+			Ke->values[j1*numdof+i1] = -2.*one1;
+			Ke->values[j1*numdof+j1] = +2.*one1;
 		}
 	}
@@ -6368,6 +7712,6 @@
 	return Ke;
 }/*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal2d{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal2d(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceSSA2d{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceSSA2d(void){
 
 	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
@@ -6390,6 +7734,6 @@
 
 	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyeal();
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	ElementMatrix* Ke=tria->CreateKMatrixStressbalanceSSA();
 	delete tria->material; delete tria;
 
@@ -6402,10 +7746,10 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3d{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3d(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceSSA3d{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceSSA3d(void){
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3dViscous();
-	ElementMatrix* Ke2=CreateKMatrixDiagnosticMacAyeal3dFriction();
+	ElementMatrix* Ke1=CreateKMatrixStressbalanceSSA3dViscous();
+	ElementMatrix* Ke2=CreateKMatrixStressbalanceSSA3dFriction();
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
 
@@ -6416,6 +7760,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3dViscous{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3dViscous(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceSSA3dViscous{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceSSA3dViscous(void){
 
 	/*Constants*/
@@ -6427,5 +7771,5 @@
 	IssmDouble  viscosity , oldviscosity, newviscosity, viscosity_overshoot;
 	IssmDouble  epsilon[5],oldepsilon[5];       /* epsilon=[exx,eyy,exy,exz,eyz];*/
-	IssmDouble  epsilons[6];                    //6 for stokes
+	IssmDouble  epsilons[6];                    //6 for FS
 	IssmDouble  xyz_list[NUMVERTICES][3];
 	IssmDouble  B[3][numdof2d];
@@ -6439,15 +7783,15 @@
 	GaussTria  *gauss_tria = NULL;
 
-	/*Find penta on bed as this is a macayeal elements: */
+	/*Find penta on bed as this is a SSA elements: */
 	pentabase=GetBasalElement();
-	tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	tria=pentabase->SpawnTria(0); //lower face is 0, upper face is 1.
 
 	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(tria->nodes,NUMVERTICES2D,this->parameters,MacAyealApproximationEnum);
+	ElementMatrix* Ke=new ElementMatrix(tria->nodes,NUMVERTICES2D,this->parameters,SSAApproximationEnum);
 	inputs->GetInputValue(&approximation,ApproximationEnum);
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+	this->parameters->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
 	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
 	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
@@ -6465,10 +7809,10 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		tria->GetBMacAyeal(&B[0][0], &xyz_list[0][0], gauss_tria);
-		tria->GetBprimeMacAyeal(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
-
-		if(approximation==MacAyealPattynApproximationEnum){
-			this->GetStrainRate3dPattyn(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
-			this->GetStrainRate3dPattyn(&oldepsilon[0],&xyz_list[0][0],gauss,vxold_input,vyold_input);
+		tria->GetBSSA(&B[0][0], &xyz_list[0][0], gauss_tria);
+		tria->GetBprimeSSA(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
+
+		if(approximation==SSAHOApproximationEnum){
+			this->GetStrainRate3dHO(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+			this->GetStrainRate3dHO(&oldepsilon[0],&xyz_list[0][0],gauss,vxold_input,vyold_input);
 			material->GetViscosity3d(&viscosity, &epsilon[0]);
 			material->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
@@ -6476,7 +7820,7 @@
 			newviscosity=viscosity+viscosity_overshoot*(viscosity-oldviscosity);
 		}
-		else if (approximation==MacAyealStokesApproximationEnum){
+		else if (approximation==SSAFSApproximationEnum){
 			this->GetStrainRate3d(&epsilons[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-			material->GetViscosity3dStokes(&newviscosity,&epsilons[0]);
+			material->GetViscosity3dFS(&newviscosity,&epsilons[0]);
 		}
 		else _error_("approximation " << approximation << " (" << EnumToStringx(approximation) << ") not supported yet");
@@ -6504,6 +7848,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyeal3dFriction{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyeal3dFriction(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceSSA3dFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceSSA3dFriction(void){
 
 	/*Initialize Element matrix and return if necessary*/
@@ -6513,6 +7857,6 @@
 	 * the tria functionality to build a friction stiffness matrix on these 3
 	 * nodes: */
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyealFriction();
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	ElementMatrix* Ke=tria->CreateKMatrixStressbalanceSSAFriction();
 	delete tria->material; delete tria;
 
@@ -6521,11 +7865,11 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyealPattyn{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyealPattyn(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceSSAHO{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceSSAHO(void){
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3d();
-	ElementMatrix* Ke2=CreateKMatrixDiagnosticPattyn();
-	ElementMatrix* Ke3=CreateKMatrixCouplingMacAyealPattyn();
+	ElementMatrix* Ke1=CreateKMatrixStressbalanceSSA3d();
+	ElementMatrix* Ke2=CreateKMatrixStressbalanceHO();
+	ElementMatrix* Ke3=CreateKMatrixCouplingSSAHO();
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
 
@@ -6537,11 +7881,16 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticMacAyealStokes{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticMacAyealStokes(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceSSAFS{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceSSAFS(void){
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyeal3d();
-	ElementMatrix* Ke2=CreateKMatrixDiagnosticStokes();
-	ElementMatrix* Ke3=CreateKMatrixCouplingMacAyealStokes();
+	ElementMatrix* Ke1=CreateKMatrixStressbalanceFS();
+	int indices[3]={18,19,20};
+	Ke1->StaticCondensation(3,&indices[0]);
+	int init = this->element_type;
+	this->element_type=P1Enum; //P1 needed for HO 
+	ElementMatrix* Ke2=CreateKMatrixStressbalanceSSA3d();
+	this->element_type=init;
+	ElementMatrix* Ke3=CreateKMatrixCouplingSSAFS();
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
 
@@ -6553,10 +7902,10 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceL1L2{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceL1L2(void){
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixDiagnosticL1L2Viscous();
-	ElementMatrix* Ke2=CreateKMatrixDiagnosticL1L2Friction();
+	ElementMatrix* Ke1=CreateKMatrixStressbalanceL1L2Viscous();
+	ElementMatrix* Ke2=CreateKMatrixStressbalanceL1L2Friction();
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
 
@@ -6567,6 +7916,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2Viscous{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2Viscous(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceL1L2Viscous{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceL1L2Viscous(void){
 
 	/*Constants*/
@@ -6587,7 +7936,7 @@
 	GaussTria  *gauss_tria = NULL;
 
-	/*Find penta on bed as this is a macayeal elements: */
+	/*Find penta on bed as this is a SSA elements: */
 	pentabase=GetBasalElement();
-	tria=pentabase->SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	tria=pentabase->SpawnTria(0); //lower face is 0, upper face is 1.
 
 	/*Initialize Element matrix*/
@@ -6609,6 +7958,6 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		tria->GetBMacAyeal(&B[0][0], &xyz_list[0][0], gauss_tria);
-		tria->GetBprimeMacAyeal(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
+		tria->GetBSSA(&B[0][0], &xyz_list[0][0], gauss_tria);
+		tria->GetBprimeSSA(&Bprime[0][0], &xyz_list[0][0], gauss_tria);
 
 		/*Get viscosity for L1L2 model*/
@@ -6635,6 +7984,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticL1L2Friction{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticL1L2Friction(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceL1L2Friction{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceL1L2Friction(void){
 
 	/*Initialize Element matrix and return if necessary*/
@@ -6644,6 +7993,6 @@
 	 * the tria functionality to build a friction stiffness matrix on these 3
 	 * nodes: */
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-	ElementMatrix* Ke=tria->CreateKMatrixDiagnosticMacAyealFriction();
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	ElementMatrix* Ke=tria->CreateKMatrixStressbalanceSSAFriction();
 	delete tria->material; delete tria;
 
@@ -6652,10 +8001,10 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticPattyn{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticPattyn(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceHO{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceHO(void){
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixDiagnosticPattynViscous();
-	ElementMatrix* Ke2=CreateKMatrixDiagnosticPattynFriction();
+	ElementMatrix* Ke1=CreateKMatrixStressbalanceHOViscous();
+	ElementMatrix* Ke2=CreateKMatrixStressbalanceHOFriction();
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
 
@@ -6667,31 +8016,31 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticPattynViscous{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticPattynViscous(void){
-
-	/*Constants*/
-	const int    numdof=NDOF2*NUMVERTICES;
+/*FUNCTION Penta::CreateKMatrixStressbalanceHOViscous{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceHOViscous(void){
 
 	/*Intermediaries */
-	int        i,j;
-	int        approximation;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble Jdet;
-	IssmDouble viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
-	IssmDouble epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
-	IssmDouble D_scalar;
-	IssmDouble D[5][5]={0.0};            // material matrix, simple scalar matrix.
-	IssmDouble B[5][numdof];
-	IssmDouble Bprime[5][numdof];
-	Tria*      tria=NULL;
+	int         i,j;
+	int         approximation;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  Jdet;
+	IssmDouble  viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
+	IssmDouble  epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble  D_scalar;
 	GaussPenta *gauss=NULL;
 
-	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+	int numdof   = numnodes*NDOF2;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,HOApproximationEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(5*numdof);
+	IssmDouble*    Bprime = xNew<IssmDouble>(5*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(5*5);
 
 	/*Retrieve all inputs and parameters*/
 	inputs->GetInputValue(&approximation,ApproximationEnum);
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+	this->parameters->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
 	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
 	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
@@ -6706,9 +8055,9 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetBPattyn(&B[0][0], &xyz_list[0][0], gauss);
-		GetBprimePattyn(&Bprime[0][0], &xyz_list[0][0], gauss);
-
-		this->GetStrainRate3dPattyn(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
-		this->GetStrainRate3dPattyn(&oldepsilon[0],&xyz_list[0][0],gauss,vxold_input,vyold_input);
+		GetBHO(&B[0], &xyz_list[0][0], gauss);
+		GetBprimeHO(&Bprime[0], &xyz_list[0][0], gauss);
+
+		this->GetStrainRate3dHO(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->GetStrainRate3dHO(&oldepsilon[0],&xyz_list[0][0],gauss,vxold_input,vyold_input);
 		material->GetViscosity3d(&viscosity, &epsilon[0]);
 		material->GetViscosity3d(&oldviscosity, &oldepsilon[0]);
@@ -6716,47 +8065,56 @@
 
 		D_scalar=2*newviscosity*gauss->weight*Jdet;
-		for (i=0;i<5;i++) D[i][i]=D_scalar;
-
-		TripleMultiply( &B[0][0],5,numdof,1,
-					&D[0][0],5,5,0,
-					&Bprime[0][0],5,numdof,0,
+		for (i=0;i<5;i++) D[i*5+i]=D_scalar;
+
+		TripleMultiply(B,5,numdof,1,
+					D,5,5,0,
+					Bprime,5,numdof,0,
 					&Ke->values[0],1);
 	}
 
 	/*Transform Coordinate System*/
-	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+	TransformStiffnessMatrixCoord(Ke,nodes,numnodes,XYEnum);
 
 	/*Clean up and return*/
 	delete gauss;
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(B);
 	return Ke;
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticPattynFriction{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticPattynFriction(void){
-
-	/*Constants*/
-	const int numdof   = NDOF2*NUMVERTICES;
+/*FUNCTION Penta::CreateKMatrixStressbalanceHOFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceHOFriction(void){
 
 	/*Intermediaries */
-	int       i,j;
-	int       analysis_type,migration_style;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
-	IssmDouble alpha2,Jdet;
-	IssmDouble phi=1.0;
-	IssmDouble L[2][numdof];
-	IssmDouble DL[2][2]={{ 0,0 },{0,0}}; //for basal drag
-	IssmDouble DL_scalar;
-	Friction  *friction = NULL;
-	GaussPenta *gauss=NULL;
+	bool       mainlyfloating;
+	int         i,j;
+	int         analysis_type,migration_style;
+	int         point1;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble  alpha2,Jdet;
+	IssmDouble fraction1,fraction2;
+	IssmDouble gllevelset;
+	IssmDouble  phi=1.0;
+	IssmDouble  DL_scalar;
+	Friction   *friction = NULL;
+	GaussPenta *gauss    = NULL;
 
 	/*Initialize Element matrix and return if necessary*/
 	if(IsFloating() || !IsOnBed()) return NULL;
 
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+	int numdof   = numnodes*NDOF2;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,HOApproximationEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(2*2);
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
+	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
 	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
@@ -6765,4 +8123,5 @@
 	Input* vy_input=inputs->GetInput(VyEnum);           _assert_(vy_input);
 	Input* vz_input=inputs->GetInput(VzEnum);           _assert_(vz_input);
+	Input* gllevelset_input=NULL;
 
 	/*build friction object, used later on: */
@@ -6770,43 +8129,62 @@
 
 	/*Recover portion of element that is grounded*/
-	if(migration_style==SubelementMigrationEnum) phi=this->GetGroundedPortion(&xyz_list[0][0]);
+	if(migration_style==SubelementMigrationEnum) phi=this->GetGroundedPortion(&xyz_list_tria[0][0]);
+	if(migration_style==SubelementMigration2Enum){
+		gllevelset_input=inputs->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
+		this->GetGroundedPart(&point1,&fraction1,&fraction2,&mainlyfloating);
+		//gauss=new GaussPenta(point1,fraction1,fraction2,mainlyfloating,2);
+		gauss=new GaussPenta(0,1,2,2);
+	}
+	else{
+		gauss=new GaussPenta(0,1,2,2);
+	}
 
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussPenta(0,1,2,2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
 
-		GetTriaJacobianDeterminant(&Jdet, &xyz_list_tria[0][0],gauss);
-		GetBPattynFriction(&L[0][0],gauss);
+		GetTriaJacobianDeterminant(&Jdet,&xyz_list_tria[0][0],gauss);
+		GetBHOFriction(&B[0],gauss);
 
 		friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum); 
 		if(migration_style==SubelementMigrationEnum) alpha2=phi*alpha2;
+		if(migration_style==SubelementMigration2Enum){
+			gllevelset_input->GetInputValue(&gllevelset, gauss);
+			if(gllevelset<0) alpha2=0;
+		}
 
 		DL_scalar=alpha2*gauss->weight*Jdet;
-		for (i=0;i<2;i++) DL[i][i]=DL_scalar;
-
-		TripleMultiply( &L[0][0],2,numdof,1,
-					&DL[0][0],2,2,0,
-					&L[0][0],2,numdof,0,
+		for (i=0;i<2;i++) D[i*2+i]=DL_scalar;
+
+		TripleMultiply(B,2,numdof,1,
+					D,2,2,0,
+					B,2,numdof,0,
 					&Ke->values[0],1);
 	}
 
 	/*Transform Coordinate System*/
-	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+	TransformStiffnessMatrixCoord(Ke,nodes,numnodes,XYEnum);
 
 	/*Clean up and return*/
 	delete gauss;
+	xDelete<IssmDouble>(D);
+	xDelete<IssmDouble>(B);
 	delete friction;
 	return Ke;
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticPattynStokes{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticPattynStokes(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceHOFS{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceHOFS(void){
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixDiagnosticPattyn();
-	ElementMatrix* Ke2=CreateKMatrixDiagnosticStokes();
-	ElementMatrix* Ke3=CreateKMatrixCouplingPattynStokes();
+	ElementMatrix* Ke1=CreateKMatrixStressbalanceFS();
+	int indices[3]={18,19,20};
+	Ke1->StaticCondensation(3,&indices[0]);
+	int init = this->element_type;
+	this->element_type=P1Enum; //P1 needed for HO 
+	ElementMatrix* Ke2=CreateKMatrixStressbalanceHO();
+	this->element_type=init;
+	ElementMatrix* Ke3=CreateKMatrixCouplingHOFS();
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2,Ke3);
 
@@ -6818,11 +8196,15 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticStokes{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticStokes(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceFS{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceFS(void){
+
+	ElementMatrix* Ke1 = NULL;
+	ElementMatrix* Ke2 = NULL;
+	ElementMatrix* Ke  = NULL;
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixDiagnosticStokesViscous();
-	ElementMatrix* Ke2=CreateKMatrixDiagnosticStokesFriction();
-	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
+	Ke1=CreateKMatrixStressbalanceFSViscous();
+	Ke2=CreateKMatrixStressbalanceFSFriction();
+	Ke =new ElementMatrix(Ke1,Ke2);
 
 	/*clean-up and return*/
@@ -6830,33 +8212,61 @@
 	delete Ke2;
 	return Ke;
-}
-/*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticStokesViscous {{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticStokesViscous(void){
+
+}
+/*}}}*/
+/*FUNCTION Penta::KMatrixGLSstabilization{{{*/
+void Penta::KMatrixGLSstabilization(ElementMatrix* Ke){
+
+	int        numdof  = NUMVERTICES*NDOF4;
 
 	/*Intermediaries */
-	int        i,approximation;
-	IssmDouble Jdet,viscosity,stokesreconditioning;
+	int        i,j,approximation;
+	IssmDouble Jdet,viscosity,FSreconditioning,diameter,rigidity;
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
-	IssmDouble B[8][27];
-	IssmDouble B_prime[8][27];
-	IssmDouble D_scalar;
+	IssmDouble B[8][24];
+	IssmDouble B_prime[8][24];
+	IssmDouble B_stab[3][NUMVERTICES];
+	IssmDouble D_scalar,D_scalar_stab;
 	IssmDouble D[8][8]={0.0};
-	IssmDouble Ke_temp[27][27]={0.0}; //for the six nodes and the bubble 
+	IssmDouble D_stab[3][3]={0.0};
+	IssmDouble Ke_temp[24][24]={0.0}; //for the six nodes
+	IssmDouble Ke_temp_stab[6][6]={0.0}; //for the six nodes
 	GaussPenta *gauss=NULL;
 
-	/*If on water or not Stokes, skip stiffness: */
-	inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=StokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum && approximation!=PattynStokesApproximationEnum) return NULL;
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	/*Stabilization*/
+	bool       stabilization = true;
+	IssmDouble dbasis[3][6];
+	IssmDouble dmu[3];
+	IssmDouble mu;
+	IssmDouble dnodalbasis[6][6][3];
+	IssmDouble SU[6][4][4];
+	IssmDouble SW[6][4][4];
+	int p,q,ii;
+	int c=3; //index of pressure
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
 	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);
 
+	/*Find minimal length and B*/
+	rigidity=material->GetB();
+	diameter=MinEdgeLength(xyz_list);
+
+		gauss=new GaussPenta();
+		for(int iv=0;iv<6;iv++){
+			gauss->GaussVertex(iv);
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+			for(i=0;i<6;i++){
+				for(j=0;j<3;j++){
+					dnodalbasis[i][iv][j] = dbasis[j][i];
+				}
+			}
+		}
+		delete gauss;
+
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(5,5);
@@ -6866,61 +8276,164 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetBStokes(&B[0][0],&xyz_list[0][0],gauss); 
-		GetBprimeStokes(&B_prime[0][0],&xyz_list[0][0],gauss); 
 
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
 
 		D_scalar=gauss->weight*Jdet;
-		for (i=0;i<6;i++) D[i][i]=D_scalar*2*viscosity;
-		for (i=6;i<8;i++) D[i][i]=-D_scalar*stokesreconditioning;
-
-		TripleMultiply( &B[0][0],8,27,1,
-					&D[0][0],8,8,0,
-					&B_prime[0][0],8,27,0,
-					&Ke_temp[0][0],1);
-	}
-
-	/*Condensation*/
-	ReduceMatrixStokes(Ke->values, &Ke_temp[0][0]);
+
+
+		/*Add stabilization*/
+		GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+		dmu[0]=0.; dmu[1]=0.; dmu[2]=0.;
+		mu = 2.*viscosity;
+		for(p=0;p<6;p++) for(i=0;i<4;i++) for(j=0;j<4;j++){
+			SU[p][i][j]=0.;
+			SW[p][i][j]=0.;
+		}
+		for(p=0;p<6;p++){
+			for(i=0;i<3;i++){
+				SU[p][i][c] += dbasis[i][p];
+				SW[p][c][i] += dbasis[i][p];
+				for(j=0;j<3;j++){
+					SU[p][i][i] += -dmu[j]*dbasis[j][p];
+					SU[p][i][j] += -dmu[i]*dbasis[i][p];
+					for(ii=0;ii<6;ii++){
+						SU[p][i][i] += -mu*dnodalbasis[p][ii][j]*dbasis[j][ii];
+						SU[p][i][j] += -mu*dnodalbasis[p][ii][i]*dbasis[j][ii];
+					}
+					SW[p][i][i] += -dmu[j]*dbasis[j][p];
+					SW[p][j][i] += -dmu[j]*dbasis[i][p];
+					for(ii=0;ii<6;ii++){
+						SW[p][i][i] += -mu*dnodalbasis[p][ii][j]*dbasis[j][ii];
+						SW[p][j][i] += -mu*dnodalbasis[p][ii][i]*dbasis[j][ii];
+					}
+				}
+			}
+		}
+		IssmDouble tau = 1./3.*pow(diameter,2)/(8.*2.*viscosity);
+		for(p=0;p<6;p++){
+			for(q=0;q<6;q++){
+				for(i=0;i<4;i++){
+					for(j=0;j<4;j++){
+						Ke->values[(p*4+i)*numdof+q*4+j] += gauss->weight*Jdet*tau*SW[p][i][0]*SU[q][0][j];
+						Ke->values[(p*4+i)*numdof+q*4+j] += gauss->weight*Jdet*tau*SW[p][i][1]*SU[q][1][j];
+						Ke->values[(p*4+i)*numdof+q*4+j] += gauss->weight*Jdet*tau*SW[p][i][2]*SU[q][2][j];
+					}
+				}
+			}
+		}
+	}
+
+	/*Clean up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::CreateKMatrixStressbalanceFSViscous {{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceFSViscous(void){
+
+	/*Intermediaries */
+	int        i,j,approximation;
+	IssmDouble Jdet,viscosity,FSreconditioning,D_scalar;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	GaussPenta *gauss=NULL;
+
+	/*If on water or not FS, skip stiffness: */
+	inputs->GetInputValue(&approximation,ApproximationEnum);
+	if(approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum && approximation!=HOFSApproximationEnum) return NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int numdof    = vnumnodes*NDOF3 + pnumnodes*NDOF1;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	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     = new ElementMatrix(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(8*numdof);
+	IssmDouble*    Bprime = xNew<IssmDouble>(8*numdof);
+	IssmDouble*    D      = xNewZeroInit<IssmDouble>(8*8);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	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 gaussian points: */
+	gauss=new GaussPenta(5,5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetBFS(B,&xyz_list[0][0],gauss); 
+		GetBprimeFS(Bprime,&xyz_list[0][0],gauss); 
+
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
+
+		D_scalar=gauss->weight*Jdet;
+		for(i=0;i<6;i++) D[i*8+i] = +D_scalar*2.*viscosity;
+		for(i=6;i<8;i++) D[i*8+i] = -D_scalar*FSreconditioning;
+
+		TripleMultiply(B,8,numdof,1,
+					D,8,8,0,
+					Bprime,8,numdof,0,
+					Ke->values,1);
+	}
 
 	/*Transform Coordinate System*/
-	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+	TransformStiffnessMatrixCoord(Ke,nodes,(vnumnodes+pnumnodes),cs_list);
 
 	/*Clean up and return*/
 	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(D);
 	return Ke;
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticStokesFriction{{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticStokesFriction(void){
-
-	/*Constants*/
-	const int numdof=NUMVERTICES*NDOF4;
-	const int numdof2d=NUMVERTICES2D*NDOF4;
+/*FUNCTION Penta::CreateKMatrixStressbalanceFSFriction{{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceFSFriction(void){
 
 	/*Intermediaries */
-	int        i,j;
-	int        analysis_type,approximation;
-	IssmDouble alpha2,Jdet2d;
-	IssmDouble stokesreconditioning,viscosity;
-	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
-	IssmDouble LStokes[2][numdof2d];
-	IssmDouble DLStokes[2][2]={0.0};
-	IssmDouble Ke_drag_gaussian[numdof2d][numdof2d];
-	Friction*  friction=NULL;
-	GaussPenta *gauss=NULL;
-
-	/*If on water or not Stokes, skip stiffness: */
+	int         i,j;
+	int         analysis_type,approximation;
+	IssmDouble  alpha2,Jdet2d;
+	IssmDouble  FSreconditioning,viscosity;
+	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  xyz_list_tria[NUMVERTICES2D][3];
+	Friction   *friction = NULL;
+	GaussPenta *gauss    = NULL;
+
+	/*Initialize Element matrix and return if necessary*/
+	if(IsFloating() || !IsOnBed()) return NULL;
+
+	/*If on water or not FS, skip stiffness: */
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(IsFloating() || !IsOnBed() || (approximation!=StokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum &&  approximation!=PattynStokesApproximationEnum)) return NULL;
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	if(approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum && approximation!=HOFSApproximationEnum) return NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int  numdof   = vnumnodes*NDOF3 + pnumnodes*NDOF1;
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke        = new ElementMatrix(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
+	IssmDouble*    BFriction = xNew<IssmDouble>(2*numdof);
+	IssmDouble*    D         = xNewZeroInit<IssmDouble>(2*2);
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
 	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
 	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
@@ -6938,37 +8451,37 @@
 
 		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0],gauss);
-		GetLStokes(&LStokes[0][0], gauss);
+		GetLFS(BFriction,gauss);
 
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
-
-		friction->GetAlpha2(&alpha2, gauss,VxEnum,VyEnum,VzEnum);
-
-		DLStokes[0][0] = +alpha2*gauss->weight*Jdet2d; //taub_x = -alpha2 vx
-		DLStokes[1][1] = +alpha2*gauss->weight*Jdet2d; //taub_y = -alpha2 vy
-
-		TripleMultiply( &LStokes[0][0],2,numdof2d,1,
-					&DLStokes[0][0],2,2,0,
-					&LStokes[0][0],2,numdof2d,0,
-					&Ke_drag_gaussian[0][0],0);
-
-		for(i=0;i<numdof2d;i++) for(j=0;j<numdof2d;j++) Ke->values[i*numdof+j]+=Ke_drag_gaussian[i][j];
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
+
+		friction->GetAlpha2(&alpha2,gauss,VxEnum,VyEnum,VzEnum);
+
+		D[0*2+0] = +alpha2*gauss->weight*Jdet2d; //taub_x = -alpha2 vx
+		D[1*2+1] = +alpha2*gauss->weight*Jdet2d; //taub_y = -alpha2 vy
+
+		TripleMultiply(BFriction,2,numdof,1,
+					D,2,2,0,
+					BFriction,2,numdof,0,
+					Ke->values,1);
 	}
 
 	/*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
-	//TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+	//TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZEnum);
 
 	/*Clean up and return*/
 	delete gauss;
 	delete friction;
+	xDelete<IssmDouble>(BFriction);
+	xDelete<IssmDouble>(D);
 	return Ke;
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticVert {{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticVert(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceVert {{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceVert(void){
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixDiagnosticVertVolume();
-	ElementMatrix* Ke2=CreateKMatrixDiagnosticVertSurface();
+	ElementMatrix* Ke1=CreateKMatrixStressbalanceVertVolume();
+	ElementMatrix* Ke2=CreateKMatrixStressbalanceVertSurface();
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
 
@@ -6980,9 +8493,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticVertVolume {{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticVertVolume(void){
-
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
+/*FUNCTION Penta::CreateKMatrixStressbalanceVertVolume {{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceVertVolume(void){
 
 	/*Intermediaries */
@@ -7023,6 +8533,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateKMatrixDiagnosticVertSurface {{{*/
-ElementMatrix* Penta::CreateKMatrixDiagnosticVertSurface(void){
+/*FUNCTION Penta::CreateKMatrixStressbalanceVertSurface {{{*/
+ElementMatrix* Penta::CreateKMatrixStressbalanceVertSurface(void){
 
 	if (!IsOnSurface()) return NULL;
@@ -7070,10 +8580,10 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorCouplingMacAyealStokes {{{*/
-ElementVector* Penta::CreatePVectorCouplingMacAyealStokes(void){
+/*FUNCTION Penta::CreatePVectorCouplingSSAFS {{{*/
+ElementVector* Penta::CreatePVectorCouplingSSAFS(void){
 
 	/*compute all load vectors for this element*/
-	ElementVector* pe1=CreatePVectorCouplingMacAyealStokesViscous();
-	ElementVector* pe2=CreatePVectorCouplingMacAyealStokesFriction();
+	ElementVector* pe1=CreatePVectorCouplingSSAFSViscous();
+	ElementVector* pe2=CreatePVectorCouplingSSAFSFriction();
 	ElementVector* pe =new ElementVector(pe1,pe2);
 
@@ -7084,9 +8594,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorCouplingMacAyealStokesViscous {{{*/
-ElementVector* Penta::CreatePVectorCouplingMacAyealStokesViscous(void){
-
-	/*Constants*/
-	const int   numdof=NUMVERTICES*NDOF4;
+/*FUNCTION Penta::CreatePVectorCouplingSSAFSViscous {{{*/
+ElementVector* Penta::CreatePVectorCouplingSSAFSViscous(void){
 
 	/*Intermediaries */
@@ -7094,5 +8601,5 @@
 	int         approximation;
 	IssmDouble  viscosity,Jdet;
-	IssmDouble  stokesreconditioning;
+	IssmDouble  FSreconditioning;
 	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
 	IssmDouble  dw[3];
@@ -7104,14 +8611,21 @@
 	/*Initialize Element vector and return if necessary*/
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=MacAyealStokesApproximationEnum) return NULL;
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	if(approximation!=SSAFSApproximationEnum) return NULL;
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+	ElementVector* pe=new ElementVector(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
 	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);
-	Input* vzmacayeal_input=inputs->GetInput(VzMacAyealEnum);   _assert_(vzmacayeal_input);
+	Input* vzSSA_input=inputs->GetInput(VzSSAEnum);   _assert_(vzSSA_input);
 
 	/* Start  looping on the number of gaussian points: */
@@ -7125,30 +8639,28 @@
 		GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
 
-		vzmacayeal_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
+		vzSSA_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
 
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
 
 		for(i=0;i<NUMVERTICES;i++){
-			pe->values[i*NDOF4+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
-			pe->values[i*NDOF4+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
-			pe->values[i*NDOF4+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
-			pe->values[i*NDOF4+3]+=Jdet*gauss->weight*stokesreconditioning*dw[2]*basis[i];
+			pe->values[i*NDOF3+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
+			pe->values[i*NDOF3+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
+			pe->values[i*NDOF3+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
+			pe->values[NDOF3*vnumnodes+i]+=Jdet*gauss->weight*FSreconditioning*dw[2]*basis[i];
 		}
 	}
 
 	/*Transform coordinate system*/
-	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+	TransformLoadVectorCoord(pe,nodes,vnumnodes+pnumnodes,cs_list);
 
 	/*Clean up and return*/
+	xDelete<int>(cs_list);
 	delete gauss;
 	return pe;
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorCouplingMacAyealStokesFriction{{{*/
-ElementVector* Penta::CreatePVectorCouplingMacAyealStokesFriction(void){
-
-	/*Constants*/
-	const int numdof=NUMVERTICES*NDOF4;
+/*FUNCTION Penta::CreatePVectorCouplingSSAFSFriction{{{*/
+ElementVector* Penta::CreatePVectorCouplingSSAFSFriction(void){
 
 	/*Intermediaries*/
@@ -7156,5 +8668,5 @@
 	int         approximation,analysis_type;
 	IssmDouble  Jdet,Jdet2d;
-	IssmDouble  stokesreconditioning;
+	IssmDouble  FSreconditioning;
 	IssmDouble	bed_normal[3];
 	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
@@ -7171,15 +8683,22 @@
 	if(!IsOnBed() || IsFloating()) return NULL;
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=MacAyealStokesApproximationEnum) return NULL;
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	if(approximation!=SSAFSApproximationEnum) return NULL;
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+	ElementVector* pe=new ElementVector(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
-	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);
-	Input* vzmacayeal_input=inputs->GetInput(VzMacAyealEnum);   _assert_(vzmacayeal_input);
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	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);
+	Input* vzSSA_input=inputs->GetInput(VzSSAEnum);  _assert_(vzSSA_input);
 
 	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
@@ -7197,23 +8716,24 @@
 		GetNodalFunctionsP1(basis, gauss);
 
-		vzmacayeal_input->GetInputValue(&w, gauss);
-		vzmacayeal_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
+		vzSSA_input->GetInputValue(&w, gauss);
+		vzSSA_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
 
 		BedNormal(&bed_normal[0],xyz_list_tria);
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
 		friction->GetAlpha2(&alpha2_gauss, gauss,VxEnum,VyEnum,VzEnum);
 
 		for(i=0;i<NUMVERTICES2D;i++){
-			pe->values[i*NDOF4+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*NDOF4+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*NDOF4+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
+			pe->values[i*NDOF3+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*NDOF3+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*NDOF3+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*/
-	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+	TransformLoadVectorCoord(pe,nodes,(vnumnodes+pnumnodes),cs_list);
 
 	/*Clean up and return*/
+	xDelete<int>(cs_list);
 	delete gauss;
 	delete friction;
@@ -7221,10 +8741,10 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorCouplingPattynStokes {{{*/
-ElementVector* Penta::CreatePVectorCouplingPattynStokes(void){
+/*FUNCTION Penta::CreatePVectorCouplingHOFS {{{*/
+ElementVector* Penta::CreatePVectorCouplingHOFS(void){
 
 	/*compute all load vectors for this element*/
-	ElementVector* pe1=CreatePVectorCouplingPattynStokesViscous();
-	ElementVector* pe2=CreatePVectorCouplingPattynStokesFriction();
+	ElementVector* pe1=CreatePVectorCouplingHOFSViscous();
+	ElementVector* pe2=CreatePVectorCouplingHOFSFriction();
 	ElementVector* pe =new ElementVector(pe1,pe2);
 
@@ -7235,9 +8755,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorCouplingPattynStokesViscous {{{*/
-ElementVector* Penta::CreatePVectorCouplingPattynStokesViscous(void){
-
-	/*Constants*/
-	const int   numdof=NUMVERTICES*NDOF4;
+/*FUNCTION Penta::CreatePVectorCouplingHOFSViscous {{{*/
+ElementVector* Penta::CreatePVectorCouplingHOFSViscous(void){
 
 	/*Intermediaries */
@@ -7245,5 +8762,5 @@
 	int         approximation;
 	IssmDouble  viscosity,Jdet;
-	IssmDouble  stokesreconditioning;
+	IssmDouble  FSreconditioning;
 	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
 	IssmDouble  dw[3];
@@ -7255,14 +8772,23 @@
 	/*Initialize Element vector and return if necessary*/
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=PattynStokesApproximationEnum) return NULL;
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	if(approximation!=HOFSApproximationEnum) return NULL;
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	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*/
+	ElementVector* pe=new ElementVector(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
-	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);
-	Input* vzpattyn_input=inputs->GetInput(VzPattynEnum);   _assert_(vzpattyn_input);
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	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);
+	Input* vzHO_input=inputs->GetInput(VzHOEnum);   _assert_(vzHO_input);
 
 	/* Start  looping on the number of gaussian points: */
@@ -7276,30 +8802,28 @@
 		GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0], gauss);
 
-		vzpattyn_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
+		vzHO_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
 
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
 
 		for(i=0;i<NUMVERTICES;i++){
-			pe->values[i*NDOF4+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
-			pe->values[i*NDOF4+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
-			pe->values[i*NDOF4+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
-			pe->values[i*NDOF4+3]+=Jdet*gauss->weight*stokesreconditioning*dw[2]*basis[i];
+			pe->values[i*NDOF3+0]+=-Jdet*gauss->weight*viscosity*dw[0]*dbasis[2][i];
+			pe->values[i*NDOF3+1]+=-Jdet*gauss->weight*viscosity*dw[1]*dbasis[2][i];
+			pe->values[i*NDOF3+2]+=-Jdet*gauss->weight*viscosity*(dw[0]*dbasis[0][i]+dw[1]*dbasis[1][i]+2*dw[2]*dbasis[2][i]);
+			pe->values[NDOF3*vnumnodes+i]+=Jdet*gauss->weight*FSreconditioning*dw[2]*basis[i];
 		}
 	}
 
 	/*Transform coordinate system*/
-	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+	TransformLoadVectorCoord(pe,nodes,vnumnodes+pnumnodes,cs_list);
 
 	/*Clean up and return*/
+	xDelete<int>(cs_list);
 	delete gauss;
 	return pe;
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorCouplingPattynStokesFriction{{{*/
-ElementVector* Penta::CreatePVectorCouplingPattynStokesFriction(void){
-
-	/*Constants*/
-	const int numdof=NUMVERTICES*NDOF4;
+/*FUNCTION Penta::CreatePVectorCouplingHOFSFriction{{{*/
+ElementVector* Penta::CreatePVectorCouplingHOFSFriction(void){
 
 	/*Intermediaries*/
@@ -7307,5 +8831,5 @@
 	int         approximation,analysis_type;
 	IssmDouble  Jdet,Jdet2d;
-	IssmDouble  stokesreconditioning;
+	IssmDouble  FSreconditioning;
 	IssmDouble	bed_normal[3];
 	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
@@ -7322,15 +8846,25 @@
 	if(!IsOnBed() || IsFloating()) return NULL;
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=PattynStokesApproximationEnum) return NULL;
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	if(approximation!=HOFSApproximationEnum) return NULL;
+
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int numnodes  = vnumnodes+pnumnodes;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	ElementVector* pe=new ElementVector(nodes,numnodes,this->parameters,FSvelocityEnum);
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
 	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);
-	Input* vzpattyn_input=inputs->GetInput(VzPattynEnum);   _assert_(vzpattyn_input);
+	Input* vzHO_input=inputs->GetInput(VzHOEnum);   _assert_(vzHO_input);
 
 	for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<3;j++) xyz_list_tria[i][j]=xyz_list[i][j];
@@ -7348,23 +8882,24 @@
 		GetNodalFunctionsP1(basis, gauss);
 
-		vzpattyn_input->GetInputValue(&w, gauss);
-		vzpattyn_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
+		vzHO_input->GetInputValue(&w, gauss);
+		vzHO_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
 
 		BedNormal(&bed_normal[0],xyz_list_tria);
 		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
 		friction->GetAlpha2(&alpha2_gauss, gauss,VxEnum,VyEnum,VzEnum);
 
 		for(i=0;i<NUMVERTICES2D;i++){
-			pe->values[i*NDOF4+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*NDOF4+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*NDOF4+2]+=Jdet2d*gauss->weight*2*viscosity*(dw[0]*bed_normal[0]+dw[1]*bed_normal[1]+dw[2]*bed_normal[2])*basis[i];
+			pe->values[i*NDOF3+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*NDOF3+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*NDOF3+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*/
-	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+	TransformLoadVectorCoord(pe,nodes,vnumnodes+pnumnodes,cs_list);
 
 	/*Clean up and return*/
+	xDelete<int>(cs_list);
 	delete gauss;
 	delete friction;
@@ -7372,6 +8907,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticHoriz{{{*/
-ElementVector* Penta::CreatePVectorDiagnosticHoriz(void){
+/*FUNCTION Penta::CreatePVectorStressbalanceHoriz{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceHoriz(void){
 
 	int approximation;
@@ -7379,22 +8914,22 @@
 
 	switch(approximation){
-		case MacAyealApproximationEnum:
-			return CreatePVectorDiagnosticMacAyeal();
-		case PattynApproximationEnum:
-			return CreatePVectorDiagnosticPattyn();
+		case SSAApproximationEnum:
+			return CreatePVectorStressbalanceSSA();
+		case HOApproximationEnum:
+			return CreatePVectorStressbalanceHO();
 		case L1L2ApproximationEnum:
-			return CreatePVectorDiagnosticL1L2();
-		case HutterApproximationEnum:
+			return CreatePVectorStressbalanceL1L2();
+		case SIAApproximationEnum:
 			return NULL;
 		case NoneApproximationEnum:
 			return NULL;
-		case StokesApproximationEnum:
-			return CreatePVectorDiagnosticStokes();
-		case MacAyealPattynApproximationEnum:
-			return CreatePVectorDiagnosticMacAyealPattyn();
-		case MacAyealStokesApproximationEnum:
-			return CreatePVectorDiagnosticMacAyealStokes();
-		case PattynStokesApproximationEnum:
-			return CreatePVectorDiagnosticPattynStokes();
+		case FSApproximationEnum:
+			return CreatePVectorStressbalanceFS();
+		case SSAHOApproximationEnum:
+			return CreatePVectorStressbalanceSSAHO();
+		case SSAFSApproximationEnum:
+			return CreatePVectorStressbalanceSSAFS();
+		case HOFSApproximationEnum:
+			return CreatePVectorStressbalanceHOFS();
 		default:
 			_error_("Approximation " << EnumToStringx(approximation) << " not supported yet");
@@ -7402,10 +8937,10 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticMacAyealPattyn{{{*/
-ElementVector* Penta::CreatePVectorDiagnosticMacAyealPattyn(void){
+/*FUNCTION Penta::CreatePVectorStressbalanceSSAHO{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceSSAHO(void){
 
 	/*compute all load vectors for this element*/
-	ElementVector* pe1=CreatePVectorDiagnosticMacAyeal();
-	ElementVector* pe2=CreatePVectorDiagnosticPattyn();
+	ElementVector* pe1=CreatePVectorStressbalanceSSA();
+	ElementVector* pe2=CreatePVectorStressbalanceHO();
 	ElementVector* pe =new ElementVector(pe1,pe2);
 
@@ -7416,11 +8951,20 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticMacAyealStokes{{{*/
-ElementVector* Penta::CreatePVectorDiagnosticMacAyealStokes(void){
+/*FUNCTION Penta::CreatePVectorStressbalanceSSAFS{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceSSAFS(void){
 
 	/*compute all load vectors for this element*/
-	ElementVector* pe1=CreatePVectorDiagnosticMacAyeal();
-	ElementVector* pe2=CreatePVectorDiagnosticStokes();
-	ElementVector* pe3=CreatePVectorCouplingMacAyealStokes();
+	int init = this->element_type;
+	this->element_type=P1Enum;
+	ElementVector* pe1=CreatePVectorStressbalanceSSA();
+	this->element_type=init;
+	ElementVector* pe2=CreatePVectorStressbalanceFS();
+	int indices[3]={18,19,20};
+	this->element_type=MINIcondensedEnum;
+	ElementMatrix* Ke = CreateKMatrixStressbalanceFS();
+	this->element_type=init;
+	pe2->StaticCondensation(Ke,3,&indices[0]);
+	delete Ke;
+	ElementVector* pe3=CreatePVectorCouplingSSAFS();
 	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
 
@@ -7432,11 +8976,20 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticPattynStokes{{{*/
-ElementVector* Penta::CreatePVectorDiagnosticPattynStokes(void){
+/*FUNCTION Penta::CreatePVectorStressbalanceHOFS{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceHOFS(void){
 
 	/*compute all load vectors for this element*/
-	ElementVector* pe1=CreatePVectorDiagnosticPattyn();
-	ElementVector* pe2=CreatePVectorDiagnosticStokes();
-	ElementVector* pe3=CreatePVectorCouplingPattynStokes();
+	int init = this->element_type;
+	this->element_type=P1Enum;
+	ElementVector* pe1=CreatePVectorStressbalanceHO();
+	this->element_type=init;
+	ElementVector* pe2=CreatePVectorStressbalanceFS();
+	int indices[3]={18,19,20};
+	this->element_type=MINIcondensedEnum;
+	ElementMatrix* Ke = CreateKMatrixStressbalanceFS();
+	this->element_type=init;
+	pe2->StaticCondensation(Ke,3,&indices[0]);
+	delete Ke;
+	ElementVector* pe3=CreatePVectorCouplingHOFS();
 	ElementVector* pe =new ElementVector(pe1,pe2,pe3);
 
@@ -7448,23 +9001,26 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticHutter{{{*/
-ElementVector* Penta::CreatePVectorDiagnosticHutter(void){
+/*FUNCTION Penta::CreatePVectorStressbalanceSIA{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceSIA(void){
 
 	/*Intermediaries*/
-	int          i,j;
-	int          node0,node1;
-	int          connectivity[2];
-	IssmDouble   Jdet;
-	IssmDouble   xyz_list[NUMVERTICES][3];
-	IssmDouble   xyz_list_segment[2][3];
-	IssmDouble   z_list[NUMVERTICES];
-	IssmDouble   slope[2];
-	IssmDouble   slope2,constant_part;
-	IssmDouble   rho_ice,gravity,n,B;
-	IssmDouble   ub,vb,z_g,surface,thickness;
-	GaussPenta*  gauss=NULL;
+	int         i,j;
+	int         node0,node1;
+	IssmDouble  connectivity[2];
+	IssmDouble  Jdet;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  xyz_list_segment[2][3];
+	IssmDouble  z_list[NUMVERTICES];
+	IssmDouble  slope[2];
+	IssmDouble  slope2,constant_part;
+	IssmDouble  rho_ice,gravity,n,B;
+	IssmDouble  ub,vb,z_g,surface,thickness;
+	GaussPenta* gauss=NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes(); _assert_(numnodes==6); 
 
 	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+	ElementVector* pe=new ElementVector(nodes,numnodes,this->parameters);
 
 	/*Retrieve all inputs and parameters*/
@@ -7482,6 +9038,6 @@
 	/*Loop on the three segments*/
 	for(i=0;i<3;i++){
-		node0=i;
-		node1=i+3;
+
+		node0=i; node1=i+3;
 
 		for(j=0;j<3;j++){
@@ -7490,6 +9046,6 @@
 		}
 
-		connectivity[0]=nodes[node0]->GetConnectivity();
-		connectivity[1]=nodes[node1]->GetConnectivity();
+		connectivity[0]=(IssmDouble)vertices[node0]->Connectivity();
+		connectivity[1]=(IssmDouble)vertices[node1]->Connectivity();
 
 		/*Loop on the Gauss points: */
@@ -7504,26 +9060,28 @@
 
 			slope2=pow(slope[0],2)+pow(slope[1],2);
-			constant_part=-2*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2));
+			constant_part=-2.*pow(rho_ice*gravity,n)*pow(slope2,((n-1.)/2.));
 
 			PentaRef::GetInputValue(&z_g,&z_list[0],gauss);
 			GetSegmentJacobianDeterminant(&Jdet,&xyz_list_segment[0][0],gauss);
 
-			if (IsOnSurface()){
-				for(j=0;j<NDOF2;j++) pe->values[2*node1+j]+=constant_part*pow((surface-z_g)/B,n)*slope[j]*Jdet*gauss->weight/(IssmDouble)connectivity[1];
+			if(IsOnSurface()){
+				pe->values[2*node1+0]+=constant_part*pow((surface-z_g)/B,n)*slope[0]*Jdet*gauss->weight/connectivity[1];
+				pe->values[2*node1+1]+=constant_part*pow((surface-z_g)/B,n)*slope[1]*Jdet*gauss->weight/connectivity[1];
 			}
-			else{//connectivity is too large, should take only half on it
-				for(j=0;j<NDOF2;j++) pe->values[2*node1+j]+=constant_part*pow((surface-z_g)/B,n)*slope[j]*Jdet*gauss->weight*2/(IssmDouble)connectivity[1];
+			else{/*connectivity is too large, should take only half on it*/
+				pe->values[2*node1+0]+=constant_part*pow((surface-z_g)/B,n)*slope[0]*Jdet*gauss->weight*2./connectivity[1];
+				pe->values[2*node1+1]+=constant_part*pow((surface-z_g)/B,n)*slope[1]*Jdet*gauss->weight*2./connectivity[1];
 			}
 		}
 		delete gauss;
 
-		//Deal with lower surface
-		if (IsOnBed()){
-			constant_part=-1.58*pow((IssmDouble)10.0,-(IssmDouble)10.0)*rho_ice*gravity*thickness;
+		/*Deal with lower surface*/
+		if(IsOnBed()){
+			constant_part=-1.58*1.e-10*rho_ice*gravity*thickness;
 			ub=constant_part*slope[0];
 			vb=constant_part*slope[1];
 
-			pe->values[2*node0]+=ub/(IssmDouble)connectivity[0];
-			pe->values[2*node0+1]+=vb/(IssmDouble)connectivity[0];
+			pe->values[2*node0+0]+=ub/connectivity[0];
+			pe->values[2*node0+1]+=vb/connectivity[0];
 		}
 	}
@@ -7533,12 +9091,12 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticMacAyeal{{{*/
-ElementVector* Penta::CreatePVectorDiagnosticMacAyeal(void){
+/*FUNCTION Penta::CreatePVectorStressbalanceSSA{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceSSA(void){
 
 	if (!IsOnBed()) return NULL;
 
 	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-	ElementVector* pe=tria->CreatePVectorDiagnosticMacAyeal();
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	ElementVector* pe=tria->CreatePVectorStressbalanceSSA();
 	delete tria->material; delete tria;
 
@@ -7547,12 +9105,12 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticL1L2{{{*/
-ElementVector* Penta::CreatePVectorDiagnosticL1L2(void){
+/*FUNCTION Penta::CreatePVectorStressbalanceL1L2{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceL1L2(void){
 
 	if (!IsOnBed()) return NULL;
 
 	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-	ElementVector* pe=tria->CreatePVectorDiagnosticMacAyeal();
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	ElementVector* pe=tria->CreatePVectorStressbalanceSSA();
 	delete tria->material; delete tria;
 
@@ -7561,9 +9119,20 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticPattyn{{{*/
-ElementVector* Penta::CreatePVectorDiagnosticPattyn(void){
-
-	/*Constants*/
-	const int    numdof=NDOF2*NUMVERTICES;
+/*FUNCTION Penta::CreatePVectorStressbalanceHO{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceHO(void){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorStressbalanceHODrivingStress();
+	ElementVector* pe2=CreatePVectorStressbalanceHOFront();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorStressbalanceHODrivingStress{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceHODrivingStress(void){
 
 	/*Intermediaries*/
@@ -7573,9 +9142,12 @@
 	IssmDouble  driving_stress_baseline,thickness;
 	IssmDouble  xyz_list[NUMVERTICES][3];
-	IssmDouble  basis[6];
 	GaussPenta  *gauss=NULL;
 
-	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,PattynApproximationEnum);
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize vector*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters,HOApproximationEnum);
+	IssmDouble*    basis = xNewZeroInit<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -7591,5 +9163,5 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctionsP1(basis, gauss);
+		GetNodalFunctions(basis,gauss);
 
 		thickness_input->GetInputValue(&thickness, gauss);
@@ -7598,69 +9170,338 @@
 		driving_stress_baseline=matpar->GetRhoIce()*matpar->GetG();
 
-		for(i=0;i<NUMVERTICES;i++) for(j=0;j<NDOF2;j++) pe->values[i*NDOF2+j]+= -driving_stress_baseline*slope[j]*Jdet*gauss->weight*basis[i];
+		for(i=0;i<numnodes;i++){
+			pe->values[i*NDOF2+0]+= -driving_stress_baseline*slope[0]*Jdet*gauss->weight*basis[i];
+			pe->values[i*NDOF2+1]+= -driving_stress_baseline*slope[1]*Jdet*gauss->weight*basis[i];
+		}
 	}
 
 	/*Transform coordinate system*/
-	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYEnum);
+	TransformLoadVectorCoord(pe,nodes,numnodes,XYEnum);
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
 	delete gauss;
 	return pe;
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticStokes {{{*/
-ElementVector* Penta::CreatePVectorDiagnosticStokes(void){
-
-	/*compute all load vectors for this element*/
-	ElementVector* pe1=CreatePVectorDiagnosticStokesViscous();
-	ElementVector* pe2=CreatePVectorDiagnosticStokesShelf();
-	ElementVector* pe =new ElementVector(pe1,pe2);
+/*FUNCTION Penta::CreatePVectorStressbalanceHOFront{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceHOFront(void){
+
+	/*Intermediaries */
+	IssmDouble  ls[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	bool        isfront;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/*If the level set is awlays <=0, there is no ice front here*/
+	isfront = false;
+	if(ls[0]>0. || ls[1]>0. || ls[2]>0.){
+		if(ls[0]*ls[1]<0. || ls[0]*ls[2]<0. || (ls[0]*ls[1]+ls[0]*ls[2]+ls[1]*ls[2]==0.)){
+			isfront = true;
+		}
+	}
+
+	/*If no front, return NULL*/
+	if(!isfront) return NULL;
+
+	/*Intermediaries*/
+	IssmDouble  rho_ice,rho_water,gravity;
+	IssmDouble  Jdet,surface,z_g,water_pressure,ice_pressure,air_pressure;
+	IssmDouble  surface_under_water,base_under_water,pressure;
+	IssmDouble  xyz_list_front[4][3];
+	IssmDouble  area_coordinates[4][3];
+	IssmDouble  normal[3];
+	GaussPenta* gauss;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters,HOApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	Input* surface_input=inputs->GetInput(SurfaceEnum); _assert_(surface_input);
+	rho_water=matpar->GetRhoWater();
+	rho_ice  =matpar->GetRhoIce();
+	gravity  =matpar->GetG();
+	GetZeroLevelsetCoordinates(&xyz_list_front[0][0],xyz_list,MaskIceLevelsetEnum);
+	GetAreaCoordinates(&area_coordinates[0][0],xyz_list_front,xyz_list,4);
+	GetQuadNormal(&normal[0],xyz_list_front);
+
+	/*Initialize gauss points*/
+	IssmDouble zmax=xyz_list[0][2]; for(int i=1;i<6;i++) if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
+	IssmDouble zmin=xyz_list[0][2]; for(int i=1;i<6;i++) if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
+	if(zmax>0 && zmin<0) gauss=new GaussPenta(area_coordinates,3,10); //refined in vertical because of the sea level discontinuity
+	else                 gauss=new GaussPenta(area_coordinates,3,3);
+
+	/* Start  looping on the number of gaussian points: */
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		surface_input->GetInputValue(&surface,gauss);
+		z_g=GetZcoord(gauss);
+		GetNodalFunctions(basis,gauss);
+		GetQuadJacobianDeterminant(&Jdet,xyz_list_front,gauss);
+
+		water_pressure = rho_water*gravity*min(0.,z_g);//0 if the gaussian point is above water level
+		ice_pressure   = rho_ice*gravity*(surface-z_g);
+		air_pressure   = 0;
+		pressure       = ice_pressure + water_pressure + air_pressure;
+
+		for (int i=0;i<numnodes;i++){
+			pe->values[2*i+0]+= pressure*Jdet*gauss->weight*normal[0]*basis[i];
+			pe->values[2*i+1]+= pressure*Jdet*gauss->weight*normal[1]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,numnodes,XYEnum);
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorStressbalanceFS {{{*/
+ElementVector* Penta::CreatePVectorStressbalanceFS(void){
+
+	ElementVector* pe1;
+	ElementVector* pe2;
+	ElementVector* pe3;
+	ElementVector* pe;
+
+	/*compute all stiffness matrices for this element*/
+	pe1=CreatePVectorStressbalanceFSViscous();
+	pe2=CreatePVectorStressbalanceFSShelf();
+	pe3=CreatePVectorStressbalanceFSFront();
+	pe =new ElementVector(pe1,pe2,pe3);
 
 	/*clean-up and return*/
 	delete pe1;
 	delete pe2;
+	delete pe3;
 	return pe;
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticStokesViscous {{{*/
-ElementVector* Penta::CreatePVectorDiagnosticStokesViscous(void){
-
-	/*Constants*/
-	const int numdofbubble=NDOF4*NUMVERTICES+NDOF3*1;
+/*FUNCTION Penta::CreatePVectorStressbalanceFSFront{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceFSFront(void){
+
+	/*Intermediaries */
+	int         i;
+	IssmDouble  ls[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	bool        isfront;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/*If the level set is awlays <=0, there is no ice front here*/
+	isfront = false;
+	if(ls[0]>0. || ls[1]>0. || ls[2]>0.){
+		if(ls[0]*ls[1]<0. || ls[0]*ls[2]<0. || (ls[0]*ls[1]+ls[0]*ls[2]+ls[1]*ls[2]==0.)){
+			isfront = true;
+		}
+	}
+
+	/*If no front, return NULL*/
+	if(!isfront) return NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	IssmDouble  rho_ice,rho_water,gravity;
+	IssmDouble  Jdet,z_g,water_pressure,air_pressure;
+	IssmDouble  surface_under_water,base_under_water,pressure;
+	IssmDouble  xyz_list_front[4][3];
+	IssmDouble  area_coordinates[4][3];
+	IssmDouble  normal[3];
+	GaussPenta* gauss;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	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*/
+	ElementVector* pe     = new ElementVector(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	rho_water=matpar->GetRhoWater();
+	rho_ice  =matpar->GetRhoIce();
+	gravity  =matpar->GetG();
+	GetZeroLevelsetCoordinates(&xyz_list_front[0][0],xyz_list,MaskIceLevelsetEnum);
+	GetAreaCoordinates(&area_coordinates[0][0],xyz_list_front,xyz_list,4);
+	GetQuadNormal(&normal[0],xyz_list_front);
+
+	/*Start looping on Gaussian points*/
+	IssmDouble zmax=xyz_list[0][2]; for(int i=1;i<6;i++) if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
+	IssmDouble zmin=xyz_list[0][2]; for(int i=1;i<6;i++) if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
+	if(zmax>0 && zmin<0) gauss=new GaussPenta(area_coordinates,3,30); //refined in vertical because of the sea level discontinuity
+	else                 gauss=new GaussPenta(area_coordinates,3,3);
+
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		z_g=GetZcoord(gauss);
+		GetNodalFunctionsVelocity(vbasis,gauss);
+		GetQuadJacobianDeterminant(&Jdet,xyz_list_front,gauss);
+
+		water_pressure=rho_water*gravity*min(0.,z_g);//0 if the gaussian point is above water level
+		air_pressure=0;
+		pressure = water_pressure + air_pressure;
+
+		for(i=0;i<vnumnodes;i++){
+			pe->values[3*i+0]+= pressure*Jdet*gauss->weight*normal[0]*vbasis[i];
+			pe->values[3*i+1]+= pressure*Jdet*gauss->weight*normal[1]*vbasis[i];
+			pe->values[3*i+2]+= pressure*Jdet*gauss->weight*normal[2]*vbasis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,(vnumnodes+pnumnodes),cs_list);
+
+	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Penta::PVectorGLSstabilization{{{*/
+void Penta::PVectorGLSstabilization(ElementVector* pe){
 
 	/*Intermediaries*/
 	int        i,j;
 	int        approximation;
-	IssmDouble Jdet,viscosity;
-	IssmDouble gravity,rho_ice,stokesreconditioning;
+	IssmDouble Jdet,gravity,rho_ice,B,D_scalar_stab,viscosity;
+	IssmDouble forcex,forcey,forcez,diameter,FSreconditioning;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble l1l6[6]; //for the six nodes and the bubble 
+	IssmDouble dh1dh6[3][NUMVERTICES];
+	GaussPenta *gauss=NULL;
+
+	/*Stabilization*/
+	bool       stabilization = true;
+	IssmDouble dbasis[3][6];
+	IssmDouble dmu[3];
+	IssmDouble mu;
+	IssmDouble dnodalbasis[6][6][3];
+	IssmDouble SW[6][4][4];
+	int p,q,ii;
+	int c=3; //index of pressure
+
+	/*Retrieve all inputs and parameters*/
+	rho_ice=matpar->GetRhoIce();
+	gravity=matpar->GetG();
+	B=material->GetB();
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	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);
+
+	/*Find minimal length*/
+	diameter=MinEdgeLength(xyz_list);
+
+		gauss=new GaussPenta();
+		for(int iv=0;iv<6;iv++){
+			gauss->GaussVertex(iv);
+			GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+			for(i=0;i<6;i++){
+				for(j=0;j<3;j++){
+					dnodalbasis[i][iv][j] = dbasis[j][i];
+				}
+			}
+		}
+		delete gauss;
+
+	/* Start  looping on the number of gaussian points: */
+	gauss=new GaussPenta(5,5);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctionsP1(&l1l6[0], gauss);
+		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		material->GetViscosity3dFS(&viscosity,&epsilon[0]);
+
+		GetNodalFunctionsP1Derivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+		dmu[0]=0.; dmu[1]=0.; dmu[2]=0.;
+		mu = 2.*viscosity;
+		for(p=0;p<6;p++) for(i=0;i<4;i++) for(j=0;j<4;j++){
+			SW[p][i][j]=0.;
+		}
+		for(p=0;p<6;p++){
+			for(i=0;i<3;i++){
+				SW[p][c][i] += dbasis[i][p];
+				for(j=0;j<3;j++){
+					SW[p][i][i] += -dmu[j]*dbasis[j][p];
+					SW[p][j][i] += -dmu[j]*dbasis[i][p];
+					for(ii=0;ii<6;ii++){
+						SW[p][i][i] += -mu*dnodalbasis[p][ii][j]*dbasis[j][ii];
+						SW[p][j][i] += -mu*dnodalbasis[p][ii][i]*dbasis[j][ii];
+					}
+				}
+			}
+		}
+		IssmDouble tau = 1./3.*pow(diameter,2)/(8.*2.*viscosity);
+		for(p=0;p<6;p++){
+			for(j=0;j<4;j++){
+				pe->values[p*4+j] += gauss->weight*Jdet*tau*rho_ice*forcex*SW[p][j][0];
+				pe->values[p*4+j] += gauss->weight*Jdet*tau*rho_ice*forcey*SW[p][j][1];
+				pe->values[p*4+j] += gauss->weight*Jdet*tau*rho_ice*(forcez-gravity)*SW[p][j][2];
+			}
+		}
+	}
+
+	/*Clean up*/
+	delete gauss;
+}
+/*}}}*/
+/*FUNCTION Penta::CreatePVectorStressbalanceFSViscous {{{*/
+ElementVector* Penta::CreatePVectorStressbalanceFSViscous(void){
+
+	/*Intermediaries*/
+	int        i,j;
+	int        approximation;
+	IssmDouble Jdet,gravity,rho_ice;
 	IssmDouble forcex,forcey,forcez;
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
-	IssmDouble l1l7[7]; //for the six nodes and the bubble 
-	IssmDouble B[8][numdofbubble];
-	IssmDouble B_prime[8][numdofbubble];
-	IssmDouble B_prime_bubble[8][3];
-	IssmDouble D[8][8]={0.0};
-	IssmDouble D_scalar;
-	IssmDouble Pe_gaussian[numdofbubble]={0.0}; //for the six nodes and the bubble 
-	IssmDouble Ke_temp[numdofbubble][3]={0.0}; //for the six nodes and the bubble 
 	GaussPenta *gauss=NULL;
 
 	/*Initialize Element vector and return if necessary*/
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=StokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum && approximation!=PattynStokesApproximationEnum) return NULL;
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	if(approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum && approximation!=HOFSApproximationEnum) return NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	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*/
+	ElementVector* pe     = new ElementVector(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
 
 	/*Retrieve all inputs and parameters*/
-	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
-	rho_ice=matpar->GetRhoIce();
-	gravity=matpar->GetG();
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	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);
 	Input* loadingforcex_input=inputs->GetInput(LoadingforceXEnum);  _assert_(loadingforcex_input);
 	Input* loadingforcey_input=inputs->GetInput(LoadingforceYEnum);  _assert_(loadingforcey_input);
 	Input* loadingforcez_input=inputs->GetInput(LoadingforceZEnum);  _assert_(loadingforcez_input);
+	rho_ice = matpar->GetRhoIce();
+	gravity = matpar->GetG();
 
 	/* Start  looping on the number of gaussian points: */
@@ -7671,48 +9512,30 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetBStokes(&B[0][0],&xyz_list[0][0],gauss); 
-		GetBprimeStokes(&B_prime[0][0],&xyz_list[0][0], gauss); 
-		GetNodalFunctionsMINI(&l1l7[0], gauss);
-
-		this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
-		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
-
-		loadingforcex_input->GetInputValue(&forcex, gauss);
-		loadingforcey_input->GetInputValue(&forcey, gauss);
-		loadingforcez_input->GetInputValue(&forcez, gauss);
-
-		for(i=0;i<NUMVERTICES+1;i++){
-			Pe_gaussian[i*NDOF4+2]+=-rho_ice*gravity*Jdet*gauss->weight*l1l7[i];
-			Pe_gaussian[i*NDOF4+0]+=forcex*Jdet*gauss->weight*l1l7[i];
-			Pe_gaussian[i*NDOF4+1]+=forcey*Jdet*gauss->weight*l1l7[i];
-			Pe_gaussian[i*NDOF4+2]+=forcez*Jdet*gauss->weight*l1l7[i];
-		}
-
-		/*Get bubble part of Bprime */
-		for(i=0;i<8;i++) for(j=0;j<3;j++) B_prime_bubble[i][j]=B_prime[i][j+24];
-
-		D_scalar=gauss->weight*Jdet;
-		for (i=0;i<6;i++) D[i][i]=D_scalar*2*viscosity;
-		for (i=6;i<8;i++) D[i][i]=-D_scalar*stokesreconditioning;
-
-		TripleMultiply(&B[0][0],8,numdofbubble,1,
-					&D[0][0],8,8,0,
-					&B_prime_bubble[0][0],8,3,0,
-					&Ke_temp[0][0],1);
-	}
-
-	/*Condensation*/
-	ReduceVectorStokes(pe->values, &Ke_temp[0][0], &Pe_gaussian[0]);
+		GetNodalFunctionsVelocity(vbasis, gauss);
+
+		loadingforcex_input->GetInputValue(&forcex,gauss);
+		loadingforcey_input->GetInputValue(&forcey,gauss);
+		loadingforcez_input->GetInputValue(&forcez,gauss);
+
+		for(i=0;i<vnumnodes;i++){
+			pe->values[i*NDOF3+2] += -rho_ice*gravity*Jdet*gauss->weight*vbasis[i];
+			pe->values[i*NDOF3+0] += +rho_ice*forcex *Jdet*gauss->weight*vbasis[i];
+			pe->values[i*NDOF3+1] += +rho_ice*forcey *Jdet*gauss->weight*vbasis[i];
+			pe->values[i*NDOF3+2] += +rho_ice*forcez *Jdet*gauss->weight*vbasis[i];
+		}
+	}
 
 	/*Transform coordinate system*/
-	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+	TransformLoadVectorCoord(pe,nodes,vnumnodes+pnumnodes,cs_list);
 
 	/*Clean up and return*/
 	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
 	return pe;
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticStokesShelf{{{*/
-ElementVector* Penta::CreatePVectorDiagnosticStokesShelf(void){
+/*FUNCTION Penta::CreatePVectorStressbalanceFSShelf{{{*/
+ElementVector* Penta::CreatePVectorStressbalanceFSShelf(void){
 
 	/*Intermediaries*/
@@ -7725,5 +9548,4 @@
 	IssmDouble	bed_normal[3];
 	IssmDouble  dz[3];
-	IssmDouble  basis[6]; //for the six nodes of the penta
 	IssmDouble  Jdet2d;
 	GaussPenta  *gauss=NULL;
@@ -7732,9 +9554,21 @@
 	if(!IsOnBed() || !IsFloating()) return NULL;
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-	this->parameters->FindParam(&shelf_dampening,DiagnosticShelfDampeningEnum);
-	if(approximation!=StokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum && approximation!=PattynStokesApproximationEnum) return NULL;
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
+	if(approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum && approximation!=HOFSApproximationEnum) return NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	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*/
+	ElementVector* pe     = new ElementVector(nodes,vnumnodes+pnumnodes,this->parameters,FSvelocityEnum);
+	IssmDouble*    vbasis = xNew<IssmDouble>(vnumnodes);
 
 	/*Retrieve all inputs and parameters*/
+	this->parameters->FindParam(&shelf_dampening,StressbalanceShelfDampeningEnum);
 	rho_water=matpar->GetRhoWater();
 	gravity=matpar->GetG();
@@ -7754,5 +9588,5 @@
 
 		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
-		GetNodalFunctionsP1(basis, gauss);
+		GetNodalFunctionsVelocity(vbasis, gauss);
 
 		BedNormal(&bed_normal[0],xyz_list_tria);
@@ -7763,28 +9597,34 @@
 			vy_input->GetInputValue(&vy, gauss);
 			vz_input->GetInputValue(&vz, gauss);
-			dt=0;
+			dt=0.;
 			normal_vel=bed_normal[0]*vx+bed_normal[1]*vy+bed_normal[2]*vz;
 			damper=gravity*rho_water*pow(1+pow(dz[0],2)+pow(dz[1],2),0.5)*normal_vel*dt;
 		}
-		else damper=0;
+		else damper=0.;
 		water_pressure=gravity*rho_water*bed;
 
-		for(i=0;i<NUMVERTICES;i++) for(j=0;j<3;j++) pe->values[i*NDOF4+j]+=(water_pressure+damper)*gauss->weight*Jdet2d*basis[i]*bed_normal[j];
+		for(i=0;i<vnumnodes;i++){
+			pe->values[3*i+0]+=(water_pressure+damper)*gauss->weight*Jdet2d*vbasis[i]*bed_normal[0];
+			pe->values[3*i+1]+=(water_pressure+damper)*gauss->weight*Jdet2d*vbasis[i]*bed_normal[1];
+			pe->values[3*i+2]+=(water_pressure+damper)*gauss->weight*Jdet2d*vbasis[i]*bed_normal[2];
+		}
 	}
 
 	/*Transform coordinate system*/
-	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYZPEnum);
+	TransformLoadVectorCoord(pe,nodes,(vnumnodes+pnumnodes),cs_list);
 
 	/*Clean up and return*/
 	delete gauss;
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(vbasis);
 	return pe;
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticVert {{{*/
-ElementVector* Penta::CreatePVectorDiagnosticVert(void){
+/*FUNCTION Penta::CreatePVectorStressbalanceVert {{{*/
+ElementVector* Penta::CreatePVectorStressbalanceVert(void){
 
 	/*compute all load vectors for this element*/
-	ElementVector* pe1=CreatePVectorDiagnosticVertVolume();
-	ElementVector* pe2=CreatePVectorDiagnosticVertBase();
+	ElementVector* pe1=CreatePVectorStressbalanceVertVolume();
+	ElementVector* pe2=CreatePVectorStressbalanceVertBase();
 	ElementVector* pe =new ElementVector(pe1,pe2);
 
@@ -7795,6 +9635,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticVertVolume {{{*/
-ElementVector* Penta::CreatePVectorDiagnosticVertVolume(void){
+/*FUNCTION Penta::CreatePVectorStressbalanceVertVolume {{{*/
+ElementVector* Penta::CreatePVectorStressbalanceVertVolume(void){
 
 	/*Constants*/
@@ -7818,7 +9658,7 @@
 	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
 	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
-	Input* vzstokes_input=NULL;
-	if(approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
-		vzstokes_input=inputs->GetInput(VzStokesEnum); _assert_(vzstokes_input);
+	Input* vzFS_input=NULL;
+	if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+		vzFS_input=inputs->GetInput(VzFSEnum); _assert_(vzFS_input);
 	}
 
@@ -7834,6 +9674,6 @@
 		vx_input->GetInputDerivativeValue(&du[0],&xyz_list[0][0],gauss);
 		vy_input->GetInputDerivativeValue(&dv[0],&xyz_list[0][0],gauss);
-		if(approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
-			vzstokes_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
+		if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+			vzFS_input->GetInputDerivativeValue(&dw[0],&xyz_list[0][0],gauss);
 			dwdz=dw[2];
 		}
@@ -7850,6 +9690,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreatePVectorDiagnosticVertBase {{{*/
-ElementVector* Penta::CreatePVectorDiagnosticVertBase(void){
+/*FUNCTION Penta::CreatePVectorStressbalanceVertBase {{{*/
+ElementVector* Penta::CreatePVectorStressbalanceVertBase(void){
 
 	/*Constants*/
@@ -7880,7 +9720,7 @@
 	Input* vx_input=inputs->GetInput(VxEnum);                                  _assert_(vx_input);
 	Input* vy_input=inputs->GetInput(VyEnum);                                  _assert_(vy_input);
-	Input* vzstokes_input=NULL;
-	if(approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
-		vzstokes_input=inputs->GetInput(VzStokesEnum);       _assert_(vzstokes_input);
+	Input* vzFS_input=NULL;
+	if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+		vzFS_input=inputs->GetInput(VzFSEnum);       _assert_(vzFS_input);
 	}
 
@@ -7895,6 +9735,6 @@
 		vx_input->GetInputValue(&vx, gauss);
 		vy_input->GetInputValue(&vy, gauss);
-		if(approximation==PattynStokesApproximationEnum || approximation==MacAyealStokesApproximationEnum){
-			vzstokes_input->GetInputValue(&vz, gauss);
+		if(approximation==HOFSApproximationEnum || approximation==SSAFSApproximationEnum){
+			vzFS_input->GetInputValue(&vz, gauss);
 		}
 		else vz=0;
@@ -7914,6 +9754,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateJacobianDiagnosticHoriz{{{*/
-ElementMatrix* Penta::CreateJacobianDiagnosticHoriz(void){
+/*FUNCTION Penta::CreateJacobianStressbalanceHoriz{{{*/
+ElementMatrix* Penta::CreateJacobianStressbalanceHoriz(void){
 
 	int approximation;
@@ -7921,10 +9761,10 @@
 
 	switch(approximation){
-		case MacAyealApproximationEnum:
-			return CreateJacobianDiagnosticMacayeal2d();
-		case PattynApproximationEnum:
-			return CreateJacobianDiagnosticPattyn();
-		case StokesApproximationEnum:
-			return CreateJacobianDiagnosticStokes();
+		case SSAApproximationEnum:
+			return CreateJacobianStressbalanceSSA2d();
+		case HOApproximationEnum:
+			return CreateJacobianStressbalanceHO();
+		case FSApproximationEnum:
+			return CreateJacobianStressbalanceFS();
 		case NoneApproximationEnum:
 			return NULL;
@@ -7934,6 +9774,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateJacobianDiagnosticMacayeal2d{{{*/
-ElementMatrix* Penta::CreateJacobianDiagnosticMacayeal2d(void){
+/*FUNCTION Penta::CreateJacobianStressbalanceSSA2d{{{*/
+ElementMatrix* Penta::CreateJacobianStressbalanceSSA2d(void){
 
 	/*Figure out if this penta is collapsed. If so, then bailout, except if it is at the 
@@ -7956,6 +9796,6 @@
 
 	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
-	ElementMatrix* Ke=tria->CreateJacobianDiagnosticMacayeal();
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
+	ElementMatrix* Ke=tria->CreateJacobianStressbalanceSSA();
 	delete tria->material; delete tria;
 
@@ -7968,6 +9808,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateJacobianDiagnosticPattyn{{{*/
-ElementMatrix* Penta::CreateJacobianDiagnosticPattyn(void){
+/*FUNCTION Penta::CreateJacobianStressbalanceHO{{{*/
+ElementMatrix* Penta::CreateJacobianStressbalanceHO(void){
 
 	/*Constants*/
@@ -7986,6 +9826,6 @@
 	GaussPenta *gauss=NULL;
 
-	/*Initialize Jacobian with regular Pattyn (first part of the Gateau derivative)*/
-	ElementMatrix* Ke=CreateKMatrixDiagnosticPattyn();
+	/*Initialize Jacobian with regular HO (first part of the Gateau derivative)*/
+	ElementMatrix* Ke=CreateKMatrixStressbalanceHO();
 
 	/*Retrieve all inputs and parameters*/
@@ -8003,5 +9843,5 @@
 		GetNodalFunctionsP1Derivatives(&dphi[0][0],&xyz_list[0][0],gauss);
 
-		this->GetStrainRate3dPattyn(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		this->GetStrainRate3dHO(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
 		material->GetViscosityDerivativeEpsSquare(&mu_prime,&epsilon[0]);
 		eps1[0]=2*epsilon[0]+epsilon[1];   eps2[0]=epsilon[2];
@@ -8032,12 +9872,9 @@
 }
 /*}}}*/
-/*FUNCTION Penta::CreateJacobianDiagnosticStokes{{{*/
-ElementMatrix* Penta::CreateJacobianDiagnosticStokes(void){
-
-	/*Constants*/
-	const int    numdof=NDOF4*NUMVERTICES;
+/*FUNCTION Penta::CreateJacobianStressbalanceFS{{{*/
+ElementMatrix* Penta::CreateJacobianStressbalanceFS(void){
 
 	/*Intermediaries */
-	int        i,j;
+	int        i,j,approximation;
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble Jdet;
@@ -8046,17 +9883,31 @@
 	IssmDouble eps3dotdphii,eps3dotdphij;
 	IssmDouble mu_prime;
-	IssmDouble epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
 	IssmDouble eps1[3],eps2[3],eps3[3];
-	IssmDouble dphi[3][NUMVERTICES];
 	GaussPenta *gauss=NULL;
 
-	/*Initialize Jacobian with regular Stokes (first part of the Gateau derivative)*/
-	ElementMatrix* Ke=CreateKMatrixDiagnosticStokes();
+	/*If on water or not FS, skip stiffness: */
+	//inputs->GetInputValue(&approximation,ApproximationEnum);
+	//if(approximation!=FSApproximationEnum && approximation!=SSAFSApproximationEnum && approximation!=HOFSApproximationEnum) return NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int numdof    = vnumnodes*NDOF3 + pnumnodes*NDOF1;
+
+	/*Prepare coordinate system list*/
+	int* cs_list = xNew<int>(vnumnodes+pnumnodes);
+	for(i=0;i<vnumnodes;i++) cs_list[i]           = XYZEnum;
+	for(i=0;i<pnumnodes;i++) cs_list[vnumnodes+i] = PressureEnum;
+
+	/*Initialize Jacobian with regular FS (first part of the Gateau derivative)*/
+	ElementMatrix* Ke=CreateKMatrixStressbalanceFS();
+	IssmDouble*    dbasis = xNew<IssmDouble>(3*vnumnodes);
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	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);
+	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 gaussian points: */
@@ -8066,8 +9917,13 @@
 		gauss->GaussPoint(ig);
 
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctionsP1Derivatives(&dphi[0][0],&xyz_list[0][0],gauss);
-
-		this->GetStrainRate3dPattyn(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
+		GetJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
+		GetNodalFunctionsDerivativesVelocity(dbasis,&xyz_list[0][0],gauss);
+
+		//this->GetStrainRate3d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input,vz_input);
+		//material->GetViscosityDerivativeEpsSquareFS(&mu_prime,&epsilon[0]);
+		//eps1[0]=epsilon[0];   eps2[0]=epsilon[3];   eps3[0]=epsilon[4];
+		//eps1[1]=epsilon[3];   eps2[1]=epsilon[1];   eps3[1]=epsilon[5];
+		//eps1[2]=epsilon[4];   eps2[2]=epsilon[5];   eps3[2]=epsilon[2];
+		this->GetStrainRate3dHO(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
 		material->GetViscosityDerivativeEpsSquare(&mu_prime,&epsilon[0]);
 		eps1[0]=epsilon[0];   eps2[0]=epsilon[2];   eps3[0]=epsilon[3];
@@ -8075,24 +9931,24 @@
 		eps1[2]=epsilon[3];   eps2[2]=epsilon[4];   eps3[2]= -epsilon[0] -epsilon[1];
 
-		for(i=0;i<6;i++){
-			for(j=0;j<6;j++){
-				eps1dotdphii=eps1[0]*dphi[0][i]+eps1[1]*dphi[1][i]+eps1[2]*dphi[2][i];
-				eps1dotdphij=eps1[0]*dphi[0][j]+eps1[1]*dphi[1][j]+eps1[2]*dphi[2][j];
-				eps2dotdphii=eps2[0]*dphi[0][i]+eps2[1]*dphi[1][i]+eps2[2]*dphi[2][i];
-				eps2dotdphij=eps2[0]*dphi[0][j]+eps2[1]*dphi[1][j]+eps2[2]*dphi[2][j];
-				eps3dotdphii=eps3[0]*dphi[0][i]+eps3[1]*dphi[1][i]+eps3[2]*dphi[2][i];
-				eps3dotdphij=eps3[0]*dphi[0][j]+eps3[1]*dphi[1][j]+eps3[2]*dphi[2][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;
+		for(i=0;i<vnumnodes-1;i++){
+			for(j=0;j<vnumnodes-1;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*(3*i+0)+3*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps1dotdphii;
+				Ke->values[numdof*(3*i+0)+3*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps1dotdphii;
+				Ke->values[numdof*(3*i+0)+3*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps1dotdphii;
+
+				Ke->values[numdof*(3*i+1)+3*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps2dotdphii;
+				Ke->values[numdof*(3*i+1)+3*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps2dotdphii;
+				Ke->values[numdof*(3*i+1)+3*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps2dotdphii;
+
+				Ke->values[numdof*(3*i+2)+3*j+0]+=gauss->weight*Jdet*2*mu_prime*eps1dotdphij*eps3dotdphii;
+				Ke->values[numdof*(3*i+2)+3*j+1]+=gauss->weight*Jdet*2*mu_prime*eps2dotdphij*eps3dotdphii;
+				Ke->values[numdof*(3*i+2)+3*j+2]+=gauss->weight*Jdet*2*mu_prime*eps3dotdphij*eps3dotdphii;
 			}
 		}
@@ -8100,22 +9956,23 @@
 
 	/*Transform Coordinate System*/
-	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
+	TransformStiffnessMatrixCoord(Ke,nodes,(vnumnodes+pnumnodes),cs_list);
 
 	/*Clean up and return*/
+	xDelete<int>(cs_list);
+	xDelete<IssmDouble>(dbasis);
 	delete gauss;
 	return Ke;
 }
 /*}}}*/
-/*FUNCTION Penta::GetSolutionFromInputsDiagnosticHoriz{{{*/
-void  Penta::GetSolutionFromInputsDiagnosticHoriz(Vector<IssmDouble>* solution){
-
-	const int    numdof=NDOF2*NUMVERTICES;
-
-	int         i;
+/*FUNCTION Penta::GetSolutionFromInputsStressbalanceHoriz{{{*/
+void  Penta::GetSolutionFromInputsStressbalanceHoriz(Vector<IssmDouble>* solution){
+
 	int         approximation;
-	int        *doflist        = NULL;
+	int        *doflist = NULL;
 	IssmDouble  vx,vy;
-	IssmDouble  values[numdof];
-	GaussPenta *gauss;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+	int numdof   = numnodes*NDOF2;
 
 	/*Get approximation enum and dof list: */
@@ -8124,15 +9981,14 @@
 	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
 
-	/*If the element is a coupling, do nothing: every node is also on an other elements 
-	 * (as coupling is between MacAyeal and Pattyn) so the other element will take care of it*/
+	/*Fetch dof list and allocate solution vectors*/
 	GetDofList(&doflist,approximation,GsetEnum);
+	IssmDouble* values = xNew<IssmDouble>(numdof);
 
 	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
-	/*P1 element only for now*/
-	gauss=new GaussPenta();
-	for(i=0;i<NUMVERTICES;i++){
+	GaussPenta* gauss=new GaussPenta();
+	for(int i=0;i<numnodes;i++){
+		gauss->GaussNode(this->element_type,i);
 
 		/*Recover vx and vy*/
-		gauss->GaussVertex(i);
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
@@ -8146,9 +10002,10 @@
 	/*Free ressources:*/
 	delete gauss;
+	xDelete<IssmDouble>(values);
 	xDelete<int>(doflist);
 }
 /*}}}*/
-/*FUNCTION Penta::GetSolutionFromInputsDiagnosticHutter{{{*/
-void  Penta::GetSolutionFromInputsDiagnosticHutter(Vector<IssmDouble>* solution){
+/*FUNCTION Penta::GetSolutionFromInputsStressbalanceSIA{{{*/
+void  Penta::GetSolutionFromInputsStressbalanceSIA(Vector<IssmDouble>* solution){
 
 	const int    numdof=NDOF2*NUMVERTICES;
@@ -8185,6 +10042,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::GetSolutionFromInputsDiagnosticVert{{{*/
-void  Penta::GetSolutionFromInputsDiagnosticVert(Vector<IssmDouble>* solution){
+/*FUNCTION Penta::GetSolutionFromInputsStressbalanceVert{{{*/
+void  Penta::GetSolutionFromInputsStressbalanceVert(Vector<IssmDouble>* solution){
 
 	const int    numdof=NDOF1*NUMVERTICES;
@@ -8218,18 +10075,26 @@
 }
 /*}}}*/
-/*FUNCTION Penta::GetSolutionFromInputsDiagnosticStokes{{{*/
-void  Penta::GetSolutionFromInputsDiagnosticStokes(Vector<IssmDouble>* solution){
-
-	const int    numdof=NDOF4*NUMVERTICES;
-
-	int          i;
-	int*         doflist=NULL;
-	IssmDouble       vx,vy,vz,p;
-	IssmDouble       stokesreconditioning;
-	IssmDouble       values[numdof];
-	GaussPenta   *gauss;
+/*FUNCTION Penta::GetSolutionFromInputsStressbalanceFS{{{*/
+void  Penta::GetSolutionFromInputsStressbalanceFS(Vector<IssmDouble>* solution){
+
+	int*         vdoflist=NULL;
+	int*         pdoflist=NULL;
+	IssmDouble   vx,vy,vz,p;
+	IssmDouble   FSreconditioning;
+	GaussPenta  *gauss;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int vnumdof   = vnumnodes*NDOF3;
+	int pnumdof   = pnumnodes*NDOF1;
+
+	/*Initialize values*/
+	IssmDouble* vvalues = xNew<IssmDouble>(vnumdof);
+	IssmDouble* pvalues = xNew<IssmDouble>(pnumdof);
 
 	/*Get dof list: */
-	GetDofList(&doflist,StokesApproximationEnum,GsetEnum);
+	GetDofListVelocity(&vdoflist,GsetEnum);
+	GetDofListPressure(&pdoflist,GsetEnum);
 	Input* vx_input=inputs->GetInput(VxEnum);       _assert_(vx_input);
 	Input* vy_input=inputs->GetInput(VyEnum);       _assert_(vy_input);
@@ -8237,28 +10102,33 @@
 	Input* p_input =inputs->GetInput(PressureEnum); _assert_(p_input);
 
-	/*Recondition pressure: */
-	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
-
-	/*Ok, we have vx vy vz and P in values, fill in vx vy vz P arrays: */
-	/*P1 element only for now*/
-	gauss=new GaussPenta();
-	for(i=0;i<NUMVERTICES;i++){
-		gauss->GaussVertex(i);
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+
+	/*Ok, we have vx vy vz in values, fill in vx vy vz arrays: */
+	gauss = new GaussPenta();
+	for(int i=0;i<vnumnodes;i++){
+		gauss->GaussNode(this->VelocityInterpolation(),i);
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
 		vz_input->GetInputValue(&vz,gauss);
+		vvalues[i*NDOF3+0]=vx;
+		vvalues[i*NDOF3+1]=vy;
+		vvalues[i*NDOF3+2]=vz;
+	}
+	for(int i=0;i<pnumnodes;i++){
+		gauss->GaussNode(this->PressureInterpolation(),i);
 		p_input ->GetInputValue(&p ,gauss);
-		values[i*NDOF4+0]=vx;
-		values[i*NDOF4+1]=vy;
-		values[i*NDOF4+2]=vz;
-		values[i*NDOF4+3]=p/stokesreconditioning;
+		pvalues[i]=p/FSreconditioning;
 	}
 
 	/*Add value to global vector*/
-	solution->SetValues(numdof,doflist,values,INS_VAL);
+	solution->SetValues(vnumdof,vdoflist,vvalues,INS_VAL);
+	solution->SetValues(pnumdof,pdoflist,pvalues,INS_VAL);
 
 	/*Free ressources:*/
 	delete gauss;
-	xDelete<int>(doflist);
+	xDelete<int>(pdoflist);
+	xDelete<int>(vdoflist);
+	xDelete<IssmDouble>(pvalues);
+	xDelete<IssmDouble>(vvalues);
 }
 /*}}}*/
@@ -8302,6 +10172,6 @@
 
 	/* Get eps_b*/
-	vx_input->GetVxStrainRate3dPattyn(epsilonvx,xyz_list,gauss);
-	vy_input->GetVyStrainRate3dPattyn(epsilonvy,xyz_list,gauss);
+	vx_input->GetVxStrainRate3dHO(epsilonvx,xyz_list,gauss);
+	vy_input->GetVyStrainRate3dHO(epsilonvy,xyz_list,gauss);
 	for(i=0;i<5;i++) epsilon[i]=epsilonvx[i]+epsilonvy[i];
 	eps_b = sqrt(epsilon[0]*epsilon[0] + epsilon[1]*epsilon[1] + epsilon[0]*epsilon[1] + epsilon[2]*epsilon[2]);
@@ -8324,5 +10194,5 @@
 	/*Viscosity*/
 	viscosity = 1./(2.*A*(tau_par*tau_par + tau_perp*tau_perp));
-	_assert_(!isnan(viscosity));
+	_assert_(!xIsNan(viscosity));
 	_assert_(viscosity > 0.);
 
@@ -8332,6 +10202,6 @@
 }
 /*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticHoriz {{{*/
-void  Penta::InputUpdateFromSolutionDiagnosticHoriz(IssmDouble* solution){
+/*FUNCTION Penta::InputUpdateFromSolutionStressbalanceHoriz {{{*/
+void  Penta::InputUpdateFromSolutionStressbalanceHoriz(IssmDouble* solution){
 
 	int  approximation;
@@ -8340,6 +10210,6 @@
 	inputs->GetInputValue(&approximation,ApproximationEnum);
 
-	/*MacAyeal, everything is done by the element on bed*/
-	if (approximation==MacAyealApproximationEnum){
+	/*SSA, everything is done by the element on bed*/
+	if (approximation==SSAApproximationEnum){
 		if (!IsOnBed()){
 			/*Do nothing. Element on bed will take care of it*/
@@ -8347,5 +10217,5 @@
 		}
 		else{
-			InputUpdateFromSolutionDiagnosticMacAyeal(solution);
+			InputUpdateFromSolutionStressbalanceSSA(solution);
 			return;
 		}
@@ -8353,26 +10223,296 @@
 	if (approximation==L1L2ApproximationEnum){
 		if (!IsOnBed()) return;
-		InputUpdateFromSolutionDiagnosticL1L2(solution);
+		InputUpdateFromSolutionStressbalanceL1L2(solution);
 		return;
 	}
-	else if (approximation==PattynApproximationEnum){
-		InputUpdateFromSolutionDiagnosticPattyn(solution);
-	}
-	else if (approximation==PattynStokesApproximationEnum){
-		InputUpdateFromSolutionDiagnosticPattynStokes(solution);
-	}
-	else if (approximation==MacAyealStokesApproximationEnum){
-		InputUpdateFromSolutionDiagnosticMacAyealStokes(solution);
-	}
-	else if (approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
-		InputUpdateFromSolutionDiagnosticStokes(solution);
-	}
-	else if (approximation==MacAyealPattynApproximationEnum){
-		InputUpdateFromSolutionDiagnosticMacAyealPattyn(solution);
-	}
-}
-/*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticMacAyeal {{{*/
-void  Penta::InputUpdateFromSolutionDiagnosticMacAyeal(IssmDouble* solution){
+	else if (approximation==HOApproximationEnum){
+		InputUpdateFromSolutionStressbalanceHO(solution);
+	}
+	else if (approximation==HOFSApproximationEnum){
+		InputUpdateFromSolutionStressbalanceHOFS(solution);
+	}
+	else if (approximation==SSAFSApproximationEnum){
+		InputUpdateFromSolutionStressbalanceSSAFS(solution);
+	}
+	else if (approximation==FSApproximationEnum || approximation==NoneApproximationEnum){
+		InputUpdateFromSolutionStressbalanceFS(solution);
+	}
+	else if (approximation==SSAHOApproximationEnum){
+		InputUpdateFromSolutionStressbalanceSSAHO(solution);
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionStressbalanceSSA {{{*/
+void  Penta::InputUpdateFromSolutionStressbalanceSSA(IssmDouble* solution){
+
+	int         numnodes = this->NumberofNodes();
+	int         numdof   = NDOF2*numnodes;
+
+	int         i;
+	IssmDouble  rho_ice,g;
+	IssmDouble  values[2*NUMVERTICES];
+	IssmDouble  vx[NUMVERTICES];
+	IssmDouble  vy[NUMVERTICES];
+	IssmDouble  vz[NUMVERTICES];
+	IssmDouble  vel[NUMVERTICES];
+	IssmDouble  pressure[NUMVERTICES];
+	IssmDouble  surface[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	int        *doflist = NULL;
+	Penta      *penta   = NULL;
+
+	/*Get dof list: */
+	GetDofList(&doflist,SSAApproximationEnum,GsetEnum);
+
+	/*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*/
+	TransformSolutionCoord(&values[0],nodes,NUMVERTICES2D,XYEnum); /*2D: only the first 3 nodes are taken*/
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays and extrude */
+	for(i=0;i<3;i++){
+		vx[i]  =values[i*NDOF2+0];
+		vy[i]  =values[i*NDOF2+1];
+		vx[i+3]=vx[i];
+		vy[i+3]=vy[i];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get parameters fro pressure computation*/
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+
+	/*Start looping over all elements above current element and update all inputs*/
+	penta=this;
+	for(;;){
+
+		/*Get node data: */
+		GetVerticesCoordinates(&xyz_list[0][0],penta->vertices,NUMVERTICES);
+
+		/*Now Compute vel*/
+		GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
+		for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+		/*Now compute pressure*/
+		GetInputListOnVertices(&surface[0],SurfaceEnum);
+		for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+
+		/*Now, we have to move the previous Vx and Vy inputs  to old 
+		 * status, otherwise, we'll wipe them off: */
+		penta->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+		penta->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+		penta->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+		/*Add vx and vy as inputs to the tria element: */
+		penta->inputs->AddInput(new PentaInput(VxEnum,vx,P1Enum));
+		penta->inputs->AddInput(new PentaInput(VyEnum,vy,P1Enum));
+		penta->inputs->AddInput(new PentaInput(VelEnum,vel,P1Enum));
+		penta->inputs->AddInput(new PentaInput(PressureEnum,pressure,P1Enum));
+
+		/*Stop if we have reached the surface*/
+		if (penta->IsOnSurface()) break;
+
+		/* get upper Penta*/
+		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
+	}
+
+	/*Free ressources:*/
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionStressbalanceSSAHO {{{*/
+void  Penta::InputUpdateFromSolutionStressbalanceSSAHO(IssmDouble* solution){
+
+	const int    numdof=NDOF2*NUMVERTICES;
+	const int    numdof2d=NDOF2*NUMVERTICES2D;
+
+	int     i;
+	IssmDouble  rho_ice,g;
+	IssmDouble  SSA_values[numdof];
+	IssmDouble  HO_values[numdof];
+	IssmDouble  vx[NUMVERTICES];
+	IssmDouble  vy[NUMVERTICES];
+	IssmDouble  vz[NUMVERTICES];
+	IssmDouble  vel[NUMVERTICES];
+	IssmDouble  pressure[NUMVERTICES];
+	IssmDouble  surface[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	int*    doflistp = NULL;
+	int*    doflistm = NULL;
+	Penta   *penta   = NULL;
+
+	/*OK, we have to add results of this element for HO 
+	 * and results from the penta at base for SSA. Now recover results*/
+	penta=GetBasalElement();
+
+	/*Get dof listof this element (HO dofs) and of the penta at base (SSA dofs): */
+	GetDofList(&doflistp,HOApproximationEnum,GsetEnum);
+	penta->GetDofList(&doflistm,SSAApproximationEnum,GsetEnum);
+
+	/*Get node data: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof2d;i++){
+		HO_values[i]=solution[doflistp[i]];
+		SSA_values[i]=solution[doflistm[i]];
+	}
+	for(i=numdof2d;i<numdof;i++){
+		HO_values[i]=solution[doflistp[i]];
+		SSA_values[i]=SSA_values[i-numdof2d];
+	}
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&SSA_values[0],penta->nodes,NUMVERTICES,XYEnum);
+	TransformSolutionCoord(&HO_values[0],   this->nodes,NUMVERTICES,XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		vx[i]=SSA_values[i*NDOF2+0]+HO_values[i*NDOF2+0];
+		vy[i]=SSA_values[i*NDOF2+1]+HO_values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Now Compute vel*/
+	GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
+	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
+	 *so the pressure is just the pressure at the z elevation: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnVertices(&surface[0],SurfaceEnum);
+	for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaInput(VxEnum,vx,P1Enum));
+	this->inputs->AddInput(new PentaInput(VyEnum,vy,P1Enum));
+	this->inputs->AddInput(new PentaInput(VelEnum,vel,P1Enum));
+	this->inputs->AddInput(new PentaInput(PressureEnum,pressure,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<int>(doflistp);
+	xDelete<int>(doflistm);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionStressbalanceSSAFS {{{*/
+void  Penta::InputUpdateFromSolutionStressbalanceSSAFS(IssmDouble* solution){
+
+	const int    numdofm=NDOF2*NUMVERTICES;
+	const int    numdofs=NDOF3*NUMVERTICES;
+	const int    numdof2d=NDOF2*NUMVERTICES2D;
+	const int    numdofpressure=NDOF1*NUMVERTICES;
+
+	int     i;
+	IssmDouble  FSreconditioning;
+	IssmDouble  SSA_values[numdofm];
+	IssmDouble  FS_values[numdofs];
+	IssmDouble  Pressure_values[numdofs];
+	IssmDouble  vx[NUMVERTICES];
+	IssmDouble  vy[NUMVERTICES];
+	IssmDouble  vz[NUMVERTICES];
+	IssmDouble  vzSSA[NUMVERTICES];
+	IssmDouble  vzFS[NUMVERTICES];
+	IssmDouble  vel[NUMVERTICES];
+	IssmDouble  pressure[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	int*    doflistm        = NULL;
+	int*    doflists        = NULL;
+	int*    doflistpressure = NULL;
+	Penta   *penta          = NULL;
+
+	/*OK, we have to add results of this element for SSA 
+	 * and results from the penta at base for SSA. Now recover results*/
+	penta=GetBasalElement();
+
+	/*Get dof listof this element (SSA dofs) and of the penta at base (SSA dofs): */
+	penta->GetDofList(&doflistm,SSAApproximationEnum,GsetEnum);
+	GetDofList(&doflists,FSvelocityEnum,GsetEnum);
+	GetDofListPressure(&doflistpressure,GsetEnum);
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+
+	/*Get node data: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+
+	/*Use the dof list to index into the solution vector: */
+	for(i=0;i<numdof2d;i++){
+		SSA_values[i]=solution[doflistm[i]];
+		SSA_values[i+numdof2d]=solution[doflistm[i]];
+	}
+	for(i=0;i<numdofs;i++)FS_values[i]=solution[doflists[i]];
+	for(i=0;i<numdofpressure;i++) Pressure_values[i]=solution[doflistpressure[i]];
+
+	/*Transform solution in Cartesian Space*/
+	TransformSolutionCoord(&SSA_values[0],this->nodes,NUMVERTICES,XYEnum);
+	TransformSolutionCoord(&FS_values[0],this->nodes,NUMVERTICES,XYZEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<NUMVERTICES;i++){
+		vx[i]=FS_values[i*NDOF3+0]+SSA_values[i*NDOF2+0];
+		vy[i]=FS_values[i*NDOF3+1]+SSA_values[i*NDOF2+1];
+		vzFS[i]=FS_values[i*NDOF3+2];
+		pressure[i]=Pressure_values[i*NDOF1]*FSreconditioning;
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzFS[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz*/
+	Input* vzSSA_input=inputs->GetInput(VzSSAEnum);
+	if (vzSSA_input){
+		if (vzSSA_input->ObjectEnum()!=PentaInputEnum){
+			_error_("Cannot compute Vel as VzSSA is of type " << EnumToStringx(vzSSA_input->ObjectEnum()));
+		}
+		GetInputListOnVertices(&vzSSA[0],VzSSAEnum);
+	}
+	else{
+		_error_("Cannot update solution as VzSSA is not present");
+	}
+
+	/*Now Compute vel*/
+	for(i=0;i<NUMVERTICES;i++) {
+		vz[i]=vzSSA[i]+vzFS[i];
+		vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	}
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new PentaInput(VxEnum,vx,P1Enum));
+	this->inputs->AddInput(new PentaInput(VyEnum,vy,P1Enum));
+	this->inputs->AddInput(new PentaInput(VzEnum,vz,P1Enum));
+	this->inputs->AddInput(new PentaInput(VzFSEnum,vzFS,P1Enum));
+	this->inputs->AddInput(new PentaInput(VelEnum,vel,P1Enum));
+	this->inputs->AddInput(new PentaInput(PressureEnum,pressure,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<int>(doflistm);
+	xDelete<int>(doflists);
+	xDelete<int>(doflistpressure);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionStressbalanceL1L2 {{{*/
+void  Penta::InputUpdateFromSolutionStressbalanceL1L2(IssmDouble* solution){
 
 	const int    numdof=NDOF2*NUMVERTICES;
@@ -8392,5 +10532,5 @@
 
 	/*Get dof list: */
-	GetDofList(&doflist,MacAyealApproximationEnum,GsetEnum);
+	GetDofList(&doflist,L1L2ApproximationEnum,GsetEnum);
 
 	/*Use the dof list to index into the solution vector: */
@@ -8438,8 +10578,8 @@
 
 		/*Add vx and vy as inputs to the tria element: */
-		penta->inputs->AddInput(new PentaP1Input(VxEnum,vx));
-		penta->inputs->AddInput(new PentaP1Input(VyEnum,vy));
-		penta->inputs->AddInput(new PentaP1Input(VelEnum,vel));
-		penta->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+		penta->inputs->AddInput(new PentaInput(VxEnum,vx,P1Enum));
+		penta->inputs->AddInput(new PentaInput(VyEnum,vy,P1Enum));
+		penta->inputs->AddInput(new PentaInput(VelEnum,vel,P1Enum));
+		penta->inputs->AddInput(new PentaInput(PressureEnum,pressure,P1Enum));
 
 		/*Stop if we have reached the surface*/
@@ -8454,54 +10594,37 @@
 }
 /*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticMacAyealPattyn {{{*/
-void  Penta::InputUpdateFromSolutionDiagnosticMacAyealPattyn(IssmDouble* solution){
-
-	const int    numdof=NDOF2*NUMVERTICES;
-	const int    numdof2d=NDOF2*NUMVERTICES2D;
-
-	int     i;
+/*FUNCTION Penta::InputUpdateFromSolutionStressbalanceHO {{{*/
+void  Penta::InputUpdateFromSolutionStressbalanceHO(IssmDouble* solution){
+
+	int         i;
 	IssmDouble  rho_ice,g;
-	IssmDouble  macayeal_values[numdof];
-	IssmDouble  pattyn_values[numdof];
-	IssmDouble  vx[NUMVERTICES];
-	IssmDouble  vy[NUMVERTICES];
-	IssmDouble  vz[NUMVERTICES];
-	IssmDouble  vel[NUMVERTICES];
-	IssmDouble  pressure[NUMVERTICES];
-	IssmDouble  surface[NUMVERTICES];
 	IssmDouble  xyz_list[NUMVERTICES][3];
-	int*    doflistp = NULL;
-	int*    doflistm = NULL;
-	Penta   *penta   = NULL;
-
-	/*OK, we have to add results of this element for pattyn 
-	 * and results from the penta at base for macayeal. Now recover results*/
-	penta=GetBasalElement();
-
-	/*Get dof listof this element (pattyn dofs) and of the penta at base (macayeal dofs): */
-	GetDofList(&doflistp,PattynApproximationEnum,GsetEnum);
-	penta->GetDofList(&doflistm,MacAyealApproximationEnum,GsetEnum);
-
-	/*Get node data: */
+	int        *doflist = NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+	int numdof   = numnodes*NDOF2;
+
+	/*Fetch dof list and allocate solution vectors*/
+	GetDofList(&doflist,HOApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numdof);
+	IssmDouble* vx        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vy        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vz        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vel       = xNew<IssmDouble>(numnodes);
+	IssmDouble* pressure  = xNew<IssmDouble>(numnodes);
+	IssmDouble* surface   = 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*/
+	TransformSolutionCoord(&values[0],nodes,NUMVERTICES,XYEnum);
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 
-	/*Use the dof list to index into the solution vector: */
-	for(i=0;i<numdof2d;i++){
-		pattyn_values[i]=solution[doflistp[i]];
-		macayeal_values[i]=solution[doflistm[i]];
-	}
-	for(i=numdof2d;i<numdof;i++){
-		pattyn_values[i]=solution[doflistp[i]];
-		macayeal_values[i]=macayeal_values[i-numdof2d];
-	}
-
-	/*Transform solution in Cartesian Space*/
-	TransformSolutionCoord(&macayeal_values[0],penta->nodes,NUMVERTICES,XYEnum);
-	TransformSolutionCoord(&pattyn_values[0],   this->nodes,NUMVERTICES,XYEnum);
-
 	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
-	for(i=0;i<NUMVERTICES;i++){
-		vx[i]=macayeal_values[i*NDOF2+0]+pattyn_values[i*NDOF2+0];
-		vy[i]=macayeal_values[i*NDOF2+1]+pattyn_values[i*NDOF2+1];
+	for(i=0;i<numnodes;i++){
+		vx[i]=values[i*NDOF2+0];
+		vy[i]=values[i*NDOF2+1];
 
 		/*Check solution*/
@@ -8510,7 +10633,7 @@
 	}
 
-	/*Now Compute vel*/
-	GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
-	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	/*Get Vz and compute vel*/
+	GetInputListOnNodes(&vz[0],VzEnum,0.);
+	for(i=0;i<numnodes;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
 
 	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
@@ -8528,45 +10651,54 @@
 
 	/*Add vx and vy as inputs to the tria element: */
-	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
-	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
-	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
-	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+	this->inputs->AddInput(new PentaInput(VxEnum,vx,P1Enum));
+	this->inputs->AddInput(new PentaInput(VyEnum,vy,P1Enum));
+	this->inputs->AddInput(new PentaInput(VelEnum,vel,P1Enum));
+	this->inputs->AddInput(new PentaInput(PressureEnum,pressure,P1Enum));
 
 	/*Free ressources:*/
-	xDelete<int>(doflistp);
-	xDelete<int>(doflistm);
-}
-/*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticMacAyealStokes {{{*/
-void  Penta::InputUpdateFromSolutionDiagnosticMacAyealStokes(IssmDouble* solution){
-
-	const int    numdofm=NDOF2*NUMVERTICES;
-	const int    numdofs=NDOF4*NUMVERTICES;
-	const int    numdof2d=NDOF2*NUMVERTICES2D;
-
-	int     i;
-	IssmDouble  stokesreconditioning;
-	IssmDouble  macayeal_values[numdofm];
-	IssmDouble  stokes_values[numdofs];
-	IssmDouble  vx[NUMVERTICES];
-	IssmDouble  vy[NUMVERTICES];
-	IssmDouble  vz[NUMVERTICES];
-	IssmDouble  vzmacayeal[NUMVERTICES];
-	IssmDouble  vzstokes[NUMVERTICES];
-	IssmDouble  vel[NUMVERTICES];
-	IssmDouble  pressure[NUMVERTICES];
-	IssmDouble  xyz_list[NUMVERTICES][3];
-	int*    doflistm        = NULL;
-	int*    doflists        = NULL;
-	Penta   *penta          = NULL;
-
-	/*OK, we have to add results of this element for macayeal 
-	 * and results from the penta at base for macayeal. Now recover results*/
+	xDelete<IssmDouble>(surface);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(values);
+	xDelete<int>(doflist);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionStressbalanceHOFS {{{*/
+void  Penta::InputUpdateFromSolutionStressbalanceHOFS(IssmDouble* solution){
+
+	const int    numdofp=NDOF2*NUMVERTICES;
+	const int    numdofs=NDOF3*NUMVERTICES;
+	const int    numdofpressure=NDOF1*NUMVERTICES;
+
+	int        i;
+	IssmDouble HO_values[numdofp];
+	IssmDouble FS_values[numdofs];
+	IssmDouble Pressure_values[numdofpressure];
+	IssmDouble vx[NUMVERTICES];
+	IssmDouble vy[NUMVERTICES];
+	IssmDouble vz[NUMVERTICES];
+	IssmDouble vzHO[NUMVERTICES];
+	IssmDouble vzFS[NUMVERTICES];
+	IssmDouble vel[NUMVERTICES];
+	IssmDouble pressure[NUMVERTICES];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble FSreconditioning;
+	int*       doflistp        = NULL;
+	int*       doflists        = NULL;
+	int*       doflistpressure = NULL;
+	Penta      *penta          = NULL;
+
+	/*OK, we have to add results of this element for HO 
+	 * and results from the penta at base for SSA. Now recover results*/
 	penta=GetBasalElement();
 
-	/*Get dof listof this element (macayeal dofs) and of the penta at base (macayeal dofs): */
-	penta->GetDofList(&doflistm,MacAyealApproximationEnum,GsetEnum);
-	GetDofList(&doflists,StokesApproximationEnum,GsetEnum);
-	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
+	/*Get dof listof this element (HO dofs) and of the penta at base (SSA dofs): */
+	GetDofList(&doflistp,HOApproximationEnum,GsetEnum);
+	GetDofList(&doflists,FSvelocityEnum,GsetEnum);
+	GetDofListPressure(&doflistpressure,GsetEnum);
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
 
 	/*Get node data: */
@@ -8574,45 +10706,41 @@
 
 	/*Use the dof list to index into the solution vector: */
-	for(i=0;i<numdof2d;i++){
-		macayeal_values[i]=solution[doflistm[i]];
-		macayeal_values[i+numdof2d]=solution[doflistm[i]];
-	}
-	for(i=0;i<numdofs;i++){
-		stokes_values[i]=solution[doflists[i]];
-	}
+	for(i=0;i<numdofp;i++) HO_values[i]=solution[doflistp[i]];
+	for(i=0;i<numdofs;i++) FS_values[i]=solution[doflists[i]];
+	for(i=0;i<numdofpressure;i++) Pressure_values[i]=solution[doflistpressure[i]];
 
 	/*Transform solution in Cartesian Space*/
-	TransformSolutionCoord(&macayeal_values[0],this->nodes,NUMVERTICES,XYEnum);
-	TransformSolutionCoord(&stokes_values[0],this->nodes,NUMVERTICES,XYZPEnum);
+	TransformSolutionCoord(&HO_values[0],this->nodes,NUMVERTICES,XYEnum);
+	TransformSolutionCoord(&FS_values[0],this->nodes,NUMVERTICES,XYZEnum);
 
 	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
 	for(i=0;i<NUMVERTICES;i++){
-		vx[i]=stokes_values[i*NDOF4+0]+macayeal_values[i*NDOF2+0];
-		vy[i]=stokes_values[i*NDOF4+1]+macayeal_values[i*NDOF2+1];
-		vzstokes[i]=stokes_values[i*NDOF4+2];
-		pressure[i]=stokes_values[i*NDOF4+3]*stokesreconditioning;
+		vx[i]=FS_values[i*NDOF3+0]+HO_values[i*NDOF2+0];
+		vy[i]=FS_values[i*NDOF3+1]+HO_values[i*NDOF2+1];
+		vzFS[i]=FS_values[i*NDOF3+2];
+		pressure[i]=Pressure_values[i*NDOF1]*FSreconditioning;
 
 		/*Check solution*/
 		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
 		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vzstokes[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vzFS[i])) _error_("NaN found in solution vector");
 		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
 	}
 
 	/*Get Vz*/
-	Input* vzmacayeal_input=inputs->GetInput(VzMacAyealEnum);
-	if (vzmacayeal_input){
-		if (vzmacayeal_input->ObjectEnum()!=PentaP1InputEnum){
-			_error_("Cannot compute Vel as VzMacAyeal is of type " << EnumToStringx(vzmacayeal_input->ObjectEnum()));
-		}
-		GetInputListOnVertices(&vzmacayeal[0],VzMacAyealEnum);
+	Input* vzHO_input=inputs->GetInput(VzHOEnum);
+	if (vzHO_input){
+		if (vzHO_input->ObjectEnum()!=PentaInputEnum){
+			_error_("Cannot compute Vel as VzHO is of type " << EnumToStringx(vzHO_input->ObjectEnum()));
+		}
+		GetInputListOnVertices(&vzHO[0],VzHOEnum);
 	}
 	else{
-		_error_("Cannot update solution as VzMacAyeal is not present");
+		_error_("Cannot update solution as VzHO is not present");
 	}
 
 	/*Now Compute vel*/
 	for(i=0;i<NUMVERTICES;i++) {
-		vz[i]=vzmacayeal[i]+vzstokes[i];
+		vz[i]=vzHO[i]+vzFS[i];
 		vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
 	}
@@ -8626,269 +10754,22 @@
 
 	/*Add vx and vy as inputs to the tria element: */
-	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
-	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
-	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
-	this->inputs->AddInput(new PentaP1Input(VzStokesEnum,vzstokes));
-	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
-	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
-
-	/*Free ressources:*/
-	xDelete<int>(doflistm);
-	xDelete<int>(doflists);
-}
-/*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticL1L2 {{{*/
-void  Penta::InputUpdateFromSolutionDiagnosticL1L2(IssmDouble* solution){
-
-	const int    numdof=NDOF2*NUMVERTICES;
-
-	int     i;
-	IssmDouble  rho_ice,g;
-	IssmDouble  values[numdof];
-	IssmDouble  vx[NUMVERTICES];
-	IssmDouble  vy[NUMVERTICES];
-	IssmDouble  vz[NUMVERTICES];
-	IssmDouble  vel[NUMVERTICES];
-	IssmDouble  pressure[NUMVERTICES];
-	IssmDouble  surface[NUMVERTICES];
-	IssmDouble  xyz_list[NUMVERTICES][3];
-	int    *doflist = NULL;
-	Penta  *penta   = NULL;
-
-	/*Get dof list: */
-	GetDofList(&doflist,L1L2ApproximationEnum,GsetEnum);
-
-	/*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*/
-	TransformSolutionCoord(&values[0],nodes,NUMVERTICES2D,XYEnum); /*2D: only the first 3 nodes are taken*/
-
-	/*Ok, we have vx and vy in values, fill in vx and vy arrays and extrude */
-	for(i=0;i<3;i++){
-		vx[i]  =values[i*NDOF2+0];
-		vy[i]  =values[i*NDOF2+1];
-		vx[i+3]=vx[i];
-		vy[i+3]=vy[i];
-
-		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
-	}
-
-	/*Get parameters fro pressure computation*/
-	rho_ice=matpar->GetRhoIce();
-	g=matpar->GetG();
-
-	/*Start looping over all elements above current element and update all inputs*/
-	penta=this;
-	for(;;){
-
-		/*Get node data: */
-		GetVerticesCoordinates(&xyz_list[0][0],penta->vertices,NUMVERTICES);
-
-		/*Now Compute vel*/
-		GetInputListOnVertices(&vz[0],VzEnum,0.0); //default is 0
-		for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
-
-		/*Now compute pressure*/
-		GetInputListOnVertices(&surface[0],SurfaceEnum);
-		for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
-
-		/*Now, we have to move the previous Vx and Vy inputs  to old 
-		 * status, otherwise, we'll wipe them off: */
-		penta->inputs->ChangeEnum(VxEnum,VxPicardEnum);
-		penta->inputs->ChangeEnum(VyEnum,VyPicardEnum);
-		penta->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
-
-		/*Add vx and vy as inputs to the tria element: */
-		penta->inputs->AddInput(new PentaP1Input(VxEnum,vx));
-		penta->inputs->AddInput(new PentaP1Input(VyEnum,vy));
-		penta->inputs->AddInput(new PentaP1Input(VelEnum,vel));
-		penta->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
-
-		/*Stop if we have reached the surface*/
-		if (penta->IsOnSurface()) break;
-
-		/* get upper Penta*/
-		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
-	}
-
-	/*Free ressources:*/
-	xDelete<int>(doflist);
-}
-/*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticPattyn {{{*/
-void  Penta::InputUpdateFromSolutionDiagnosticPattyn(IssmDouble* solution){
-
-	const int    numdof=NDOF2*NUMVERTICES;
-
-	int    i;
-	IssmDouble rho_ice,g;
-	IssmDouble values[numdof];
-	IssmDouble vx[NUMVERTICES];
-	IssmDouble vy[NUMVERTICES];
-	IssmDouble vz[NUMVERTICES];
-	IssmDouble vel[NUMVERTICES];
-	IssmDouble pressure[NUMVERTICES];
-	IssmDouble surface[NUMVERTICES];
-	IssmDouble xyz_list[NUMVERTICES][3];
-	int*   doflist = NULL;
-
-	/*Get dof list: */
-	GetDofList(&doflist,PattynApproximationEnum,GsetEnum);
-
-	/*Get node data: */
-	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*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*/
-	TransformSolutionCoord(&values[0],nodes,NUMVERTICES,XYEnum);
-
-	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
-	for(i=0;i<NUMVERTICES;i++){
-		vx[i]=values[i*NDOF2+0];
-		vy[i]=values[i*NDOF2+1];
-
-		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
-	}
-
-	/*Get Vz*/
-	Input* vz_input=inputs->GetInput(VzEnum);
-	if (vz_input){
-		GetInputListOnVertices(&vz[0],VzEnum);
-	}
-	else{
-		for(i=0;i<NUMVERTICES;i++) vz[i]=0.0;
-	}
-
-	/*Now Compute vel*/
-	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
-
-	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
-	 *so the pressure is just the pressure at the z elevation: */
-	rho_ice=matpar->GetRhoIce();
-	g=matpar->GetG();
-	GetInputListOnVertices(&surface[0],SurfaceEnum);
-	for(i=0;i<NUMVERTICES;i++) pressure[i]=rho_ice*g*(surface[i]-xyz_list[i][2]);
-
-	/*Now, we have to move the previous Vx and Vy inputs  to old 
-	 * status, otherwise, we'll wipe them off: */
-	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
-	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
-	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
-
-	/*Add vx and vy as inputs to the tria element: */
-	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
-	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
-	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
-	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
-
-	/*Free ressources:*/
-	xDelete<int>(doflist);
-}
-/*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticPattynStokes {{{*/
-void  Penta::InputUpdateFromSolutionDiagnosticPattynStokes(IssmDouble* solution){
-
-	const int    numdofp=NDOF2*NUMVERTICES;
-	const int    numdofs=NDOF4*NUMVERTICES;
-
-	int    i;
-	IssmDouble pattyn_values[numdofp];
-	IssmDouble stokes_values[numdofs];
-	IssmDouble vx[NUMVERTICES];
-	IssmDouble vy[NUMVERTICES];
-	IssmDouble vz[NUMVERTICES];
-	IssmDouble vzpattyn[NUMVERTICES];
-	IssmDouble vzstokes[NUMVERTICES];
-	IssmDouble vel[NUMVERTICES];
-	IssmDouble pressure[NUMVERTICES];
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble stokesreconditioning;
-	int*   doflistp      = NULL;
-	int*   doflists      = NULL;
-	Penta  *penta        = NULL;
-
-	/*OK, we have to add results of this element for pattyn 
-	 * and results from the penta at base for macayeal. Now recover results*/
-	penta=GetBasalElement();
-
-	/*Get dof listof this element (pattyn dofs) and of the penta at base (macayeal dofs): */
-	GetDofList(&doflistp,PattynApproximationEnum,GsetEnum);
-	GetDofList(&doflists,StokesApproximationEnum,GsetEnum);
-	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
-
-	/*Get node data: */
-	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-
-	/*Use the dof list to index into the solution vector: */
-	for(i=0;i<numdofp;i++) pattyn_values[i]=solution[doflistp[i]];
-	for(i=0;i<numdofs;i++) stokes_values[i]=solution[doflists[i]];
-
-	/*Transform solution in Cartesian Space*/
-	TransformSolutionCoord(&pattyn_values[0],this->nodes,NUMVERTICES,XYEnum);
-	TransformSolutionCoord(&stokes_values[0],this->nodes,NUMVERTICES,XYZPEnum);
-
-	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
-	for(i=0;i<NUMVERTICES;i++){
-		vx[i]=stokes_values[i*NDOF4+0]+pattyn_values[i*NDOF2+0];
-		vy[i]=stokes_values[i*NDOF4+1]+pattyn_values[i*NDOF2+1];
-		vzstokes[i]=stokes_values[i*NDOF4+2];
-		pressure[i]=stokes_values[i*NDOF4+3]*stokesreconditioning;
-
-		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vzstokes[i])) _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
-	}
-
-	/*Get Vz*/
-	Input* vzpattyn_input=inputs->GetInput(VzPattynEnum);
-	if (vzpattyn_input){
-		if (vzpattyn_input->ObjectEnum()!=PentaP1InputEnum){
-			_error_("Cannot compute Vel as VzPattyn is of type " << EnumToStringx(vzpattyn_input->ObjectEnum()));
-		}
-		GetInputListOnVertices(&vzpattyn[0],VzPattynEnum);
-	}
-	else{
-		_error_("Cannot update solution as VzPattyn is not present");
-	}
-
-	/*Now Compute vel*/
-	for(i=0;i<NUMVERTICES;i++) {
-		vz[i]=vzpattyn[i]+vzstokes[i];
-		vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
-	}
-
-	/*Now, we have to move the previous Vx and Vy inputs  to old 
-	 * status, otherwise, we'll wipe them off: */
-	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
-	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
-	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
-	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
-
-	/*Add vx and vy as inputs to the tria element: */
-	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
-	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
-	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
-	this->inputs->AddInput(new PentaP1Input(VzStokesEnum,vzstokes));
-	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
-	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+	this->inputs->AddInput(new PentaInput(VxEnum,vx,P1Enum));
+	this->inputs->AddInput(new PentaInput(VyEnum,vy,P1Enum));
+	this->inputs->AddInput(new PentaInput(VzEnum,vz,P1Enum));
+	this->inputs->AddInput(new PentaInput(VzFSEnum,vzFS,P1Enum));
+	this->inputs->AddInput(new PentaInput(VelEnum,vel,P1Enum));
+	this->inputs->AddInput(new PentaInput(PressureEnum,pressure,P1Enum));
 
 	/*Free ressources:*/
 	xDelete<int>(doflistp);
 	xDelete<int>(doflists);
-}
-/*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticHutter {{{*/
-void  Penta::InputUpdateFromSolutionDiagnosticHutter(IssmDouble* solution){
-
-	const int    numdof=NDOF2*NUMVERTICES;
+	xDelete<int>(doflistpressure);
+}
+/*}}}*/
+/*FUNCTION Penta::InputUpdateFromSolutionStressbalanceSIA {{{*/
+void  Penta::InputUpdateFromSolutionStressbalanceSIA(IssmDouble* solution){
+
+	int         numnodes = this->NumberofNodes();
+	int         numdof=NDOF2*numnodes;
 
 	int     i;
@@ -8941,8 +10822,8 @@
 
 	/*Add vx and vy as inputs to the tria element: */
-	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
-	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
-	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
-	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+	this->inputs->AddInput(new PentaInput(VxEnum,vx,P1Enum));
+	this->inputs->AddInput(new PentaInput(VyEnum,vy,P1Enum));
+	this->inputs->AddInput(new PentaInput(VelEnum,vel,P1Enum));
+	this->inputs->AddInput(new PentaInput(PressureEnum,pressure,P1Enum));
 
 	/*Free ressources:*/
@@ -8950,11 +10831,12 @@
 }
 /*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticVert {{{*/
-void  Penta::InputUpdateFromSolutionDiagnosticVert(IssmDouble* solution){
-
-	const int numdof=NDOF1*NUMVERTICES;
-
-	int      i;
-	int      approximation;
+/*FUNCTION Penta::InputUpdateFromSolutionStressbalanceVert {{{*/
+void  Penta::InputUpdateFromSolutionStressbalanceVert(IssmDouble* solution){
+
+	int          numnodes = this->NumberofNodes();
+	int          numdof=NDOF1*numnodes;
+
+	int          i;
+	int          approximation;
 	IssmDouble   rho_ice,g;
 	IssmDouble   values[numdof];
@@ -8962,16 +10844,16 @@
 	IssmDouble   vy[NUMVERTICES];
 	IssmDouble   vz[NUMVERTICES];
-	IssmDouble   vzmacayeal[NUMVERTICES];
-	IssmDouble   vzpattyn[NUMVERTICES];
-	IssmDouble   vzstokes[NUMVERTICES];
+	IssmDouble   vzSSA[NUMVERTICES];
+	IssmDouble   vzHO[NUMVERTICES];
+	IssmDouble   vzFS[NUMVERTICES];
 	IssmDouble   vel[NUMVERTICES];
 	IssmDouble   pressure[NUMVERTICES];
 	IssmDouble   surface[NUMVERTICES];
 	IssmDouble   xyz_list[NUMVERTICES][3];
-	int*     doflist      = NULL;
-
-	/*Get the approximation and do nothing if the element in Stokes or None*/
+	int*         doflist      = NULL;
+
+	/*Get the approximation and do nothing if the element in FS or None*/
 	inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation==StokesApproximationEnum || approximation==NoneApproximationEnum){
+	if(approximation==FSApproximationEnum || approximation==NoneApproximationEnum){
 		return;
 	}
@@ -8994,27 +10876,27 @@
 	GetInputListOnVertices(&vy[0],VyEnum,0.0); //default is 0
 
-	/*Do some modifications if we actually have a PattynStokes or MacAyealStokes element*/
-	if(approximation==PattynStokesApproximationEnum){
-		Input* vzstokes_input=inputs->GetInput(VzStokesEnum);
-		if (vzstokes_input){
-			if (vzstokes_input->ObjectEnum()!=PentaP1InputEnum) _error_("Cannot compute Vel as VzStokes is of type " << EnumToStringx(vzstokes_input->ObjectEnum()));
-			GetInputListOnVertices(&vzstokes[0],VzStokesEnum);
-		}
-		else _error_("Cannot compute Vz as VzStokes in not present in PattynStokes element");
+	/*Do some modifications if we actually have a HOFS or SSAFS element*/
+	if(approximation==HOFSApproximationEnum){
+		Input* vzFS_input=inputs->GetInput(VzFSEnum);
+		if (vzFS_input){
+			if (vzFS_input->ObjectEnum()!=PentaInputEnum) _error_("Cannot compute Vel as VzFS is of type " << EnumToStringx(vzFS_input->ObjectEnum()));
+			GetInputListOnVertices(&vzFS[0],VzFSEnum);
+		}
+		else _error_("Cannot compute Vz as VzFS in not present in HOFS element");
 		for(i=0;i<NUMVERTICES;i++){
-			vzpattyn[i]=vz[i];
-			vz[i]=vzpattyn[i]+vzstokes[i];
-		}
-	}
-	else if(approximation==MacAyealStokesApproximationEnum){
-		Input* vzstokes_input=inputs->GetInput(VzStokesEnum);
-		if (vzstokes_input){
-			if (vzstokes_input->ObjectEnum()!=PentaP1InputEnum) _error_("Cannot compute Vel as VzStokes is of type " << EnumToStringx(vzstokes_input->ObjectEnum()));
-			GetInputListOnVertices(&vzstokes[0],VzStokesEnum);
-		}
-		else _error_("Cannot compute Vz as VzStokes in not present in MacAyealStokes element");
+			vzHO[i]=vz[i];
+			vz[i]=vzHO[i]+vzFS[i];
+		}
+	}
+	else if(approximation==SSAFSApproximationEnum){
+		Input* vzFS_input=inputs->GetInput(VzFSEnum);
+		if (vzFS_input){
+			if (vzFS_input->ObjectEnum()!=PentaInputEnum) _error_("Cannot compute Vel as VzFS is of type " << EnumToStringx(vzFS_input->ObjectEnum()));
+			GetInputListOnVertices(&vzFS[0],VzFSEnum);
+		}
+		else _error_("Cannot compute Vz as VzFS in not present in SSAFS element");
 		for(i=0;i<NUMVERTICES;i++){
-			vzmacayeal[i]=vz[i];
-			vz[i]=vzmacayeal[i]+vzstokes[i];
+			vzSSA[i]=vz[i];
+			vz[i]=vzSSA[i]+vzFS[i];
 		}
 	}
@@ -9024,6 +10906,6 @@
 
 	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 3D, 
-	 *so the pressure is just the pressure at the z elevation: except it this is a PattynStokes element */
-	if(approximation!=PattynStokesApproximationEnum &&  approximation!=MacAyealStokesApproximationEnum){
+	 *so the pressure is just the pressure at the z elevation: except it this is a HOFS element */
+	if(approximation!=HOFSApproximationEnum &&  approximation!=SSAFSApproximationEnum){
 		rho_ice=matpar->GetRhoIce();
 		g=matpar->GetG();
@@ -9036,16 +10918,16 @@
 	this->inputs->ChangeEnum(VzEnum,VzPicardEnum);
 
-	if(approximation!=PattynStokesApproximationEnum && approximation!=MacAyealStokesApproximationEnum){
+	if(approximation!=HOFSApproximationEnum && approximation!=SSAFSApproximationEnum){
 		this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
-		this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
-	}
-	else if(approximation==PattynStokesApproximationEnum){
-		this->inputs->AddInput(new PentaP1Input(VzPattynEnum,vzpattyn));
-	}
-	else if(approximation==MacAyealStokesApproximationEnum){
-		this->inputs->AddInput(new PentaP1Input(VzMacAyealEnum,vzmacayeal));
-	}
-	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
-	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
+		this->inputs->AddInput(new PentaInput(PressureEnum,pressure,P1Enum));
+	}
+	else if(approximation==HOFSApproximationEnum){
+		this->inputs->AddInput(new PentaInput(VzHOEnum,vzHO,P1Enum));
+	}
+	else if(approximation==SSAFSApproximationEnum){
+		this->inputs->AddInput(new PentaInput(VzSSAEnum,vzSSA,P1Enum));
+	}
+	this->inputs->AddInput(new PentaInput(VzEnum,vz,P1Enum));
+	this->inputs->AddInput(new PentaInput(VelEnum,vel,P1Enum));
 
 	/*Free ressources:*/
@@ -9053,46 +10935,57 @@
 }
 /*}}}*/
-/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticStokes {{{*/
-void  Penta::InputUpdateFromSolutionDiagnosticStokes(IssmDouble* solution){
-
-	const int numdof=NDOF4*NUMVERTICES;
-
-	int     i;
-	IssmDouble  values[numdof];
-	IssmDouble  vx[NUMVERTICES];
-	IssmDouble  vy[NUMVERTICES];
-	IssmDouble  vz[NUMVERTICES];
-	IssmDouble  vel[NUMVERTICES];
-	IssmDouble  pressure[NUMVERTICES];
-	IssmDouble  stokesreconditioning;
-	int*    doflist=NULL;
+/*FUNCTION Penta::InputUpdateFromSolutionStressbalanceFS {{{*/
+void  Penta::InputUpdateFromSolutionStressbalanceFS(IssmDouble* solution){
+
+	int          i;
+	int*         vdoflist=NULL;
+	int*         pdoflist=NULL;
+	IssmDouble   FSreconditioning;
+	GaussPenta  *gauss;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumnodes = this->NumberofNodesPressure();
+	int vnumdof   = vnumnodes*NDOF3;
+	int pnumdof   = pnumnodes*NDOF1;
+
+	/*Initialize values*/
+	IssmDouble* vvalues  = xNew<IssmDouble>(vnumdof);
+	IssmDouble* pvalues  = xNew<IssmDouble>(pnumdof);
+	IssmDouble* vx       = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* vy       = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* vz       = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* vel      = xNew<IssmDouble>(vnumnodes);
+	IssmDouble* pressure = xNew<IssmDouble>(vnumnodes);
 
 	/*Get dof list: */
-	GetDofList(&doflist,StokesApproximationEnum,GsetEnum);
+	GetDofListVelocity(&vdoflist,GsetEnum);
+	GetDofListPressure(&pdoflist,GsetEnum);
 
 	/*Use the dof list to index into the solution vector: */
-	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
+	for(i=0;i<vnumdof;i++) vvalues[i]=solution[vdoflist[i]];
+	for(i=0;i<pnumdof;i++) pvalues[i]=solution[pdoflist[i]];
 
 	/*Transform solution in Cartesian Space*/
-	TransformSolutionCoord(&values[0],nodes,NUMVERTICES,XYZPEnum);
+	TransformSolutionCoord(&vvalues[0],nodes,vnumnodes,XYZEnum);
 
 	/*Ok, we have vx and vy in values, fill in all arrays: */
-	for(i=0;i<NUMVERTICES;i++){
-		vx[i]=values[i*NDOF4+0];
-		vy[i]=values[i*NDOF4+1];
-		vz[i]=values[i*NDOF4+2];
-		pressure[i]=values[i*NDOF4+3];
-
-		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i]))       _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i]))       _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vz[i]))       _error_("NaN found in solution vector");
+	for(i=0;i<vnumnodes;i++){
+		vx[i] = vvalues[i*NDOF3+0];
+		vy[i] = vvalues[i*NDOF3+1];
+		vz[i] = vvalues[i*NDOF3+2];
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vz[i])) _error_("NaN found in solution vector");
+	}
+	for(i=0;i<pnumnodes;i++){
+		pressure[i] = pvalues[i];
 		if(xIsNan<IssmDouble>(pressure[i])) _error_("NaN found in solution vector");
 	}
 
 	/*Recondition pressure and compute vel: */
-	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
-	for(i=0;i<NUMVERTICES;i++) pressure[i]=pressure[i]*stokesreconditioning;
-	for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
+	this->parameters->FindParam(&FSreconditioning,StressbalanceFSreconditioningEnum);
+	for(i=0;i<pnumnodes;i++) pressure[i]=pressure[i]*FSreconditioning;
+	for(i=0;i<vnumnodes;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
 
 	/*Now, we have to move the previous inputs  to old 
@@ -9104,12 +10997,20 @@
 
 	/*Add vx and vy as inputs to the tria element: */
-	this->inputs->AddInput(new PentaP1Input(VxEnum,vx));
-	this->inputs->AddInput(new PentaP1Input(VyEnum,vy));
-	this->inputs->AddInput(new PentaP1Input(VzEnum,vz));
-	this->inputs->AddInput(new PentaP1Input(VelEnum,vel));
-	this->inputs->AddInput(new PentaP1Input(PressureEnum,pressure));
+	this->inputs->AddInput(new PentaInput(VxEnum,vx,P1Enum));
+	this->inputs->AddInput(new PentaInput(VyEnum,vy,P1Enum));
+	this->inputs->AddInput(new PentaInput(VzEnum,vz,P1Enum));
+	this->inputs->AddInput(new PentaInput(VelEnum,vel,P1Enum));
+	this->inputs->AddInput(new PentaInput(PressureEnum,pressure,P1Enum));
 
 	/*Free ressources:*/
-	xDelete<int>(doflist);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(vvalues);
+	xDelete<IssmDouble>(pvalues);
+	xDelete<int>(vdoflist);
+	xDelete<int>(pdoflist);
 }
 /*}}}*/
@@ -9130,5 +11031,5 @@
 
 	/*Spawn Tria element from the base of the Penta: */
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	ElementMatrix* Ke=tria->CreateKMatrixBalancethickness();
 	delete tria->material; delete tria;
@@ -9152,5 +11053,5 @@
 
 	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	ElementVector* pe=tria->CreatePVectorBalancethickness();
 	delete tria->material; delete tria;
@@ -9172,5 +11073,5 @@
 	if (!IsOnBed()) return NULL;
 
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	ElementMatrix* Ke=tria->CreateKMatrixHydrologyDCInefficient();
 	delete tria->material; delete tria;
@@ -9185,5 +11086,5 @@
 	if (!IsOnBed()) return NULL;
 
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	ElementMatrix* Ke=tria->CreateKMatrixHydrologyDCEfficient();
 	delete tria->material; delete tria;
@@ -9199,5 +11100,5 @@
 
 	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	ElementVector* pe=tria->CreatePVectorHydrologyDCInefficient();
 	delete tria->material; delete tria;
@@ -9213,5 +11114,5 @@
 
 	/*Call Tria function*/
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	ElementVector* pe=tria->CreatePVectorHydrologyDCEfficient();
 	delete tria->material; delete tria;
@@ -9225,6 +11126,6 @@
 
 	if (!IsOnBed()) return;
-	
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	tria->GetHydrologyDCInefficientHmax(ph_max,innode);
 	delete tria->material; delete tria;
@@ -9235,6 +11136,6 @@
 
 	if (!IsOnBed()) return;
-	
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	tria->GetHydrologyTransfer(transfer);
 	delete tria->material; delete tria;
@@ -9276,6 +11177,6 @@
 
 	if (!IsOnBed())return;
-	
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	tria->HydrologyEPLGetActive(active_vec);
 	delete tria->material; delete tria;
@@ -9287,9 +11188,9 @@
 
 	if (!IsOnBed())return;
-	
-	Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.
+
+	Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.
 	tria->HydrologyEPLGetMask(vec_mask);
 	delete tria->material; delete tria;
-	
+
 }
 /*}}}*/
@@ -9327,15 +11228,17 @@
 		this->parameters->FindParam(&kmax,HydrologySedimentKmaxEnum);
 		this->parameters->FindParam(&penalty_factor,HydrologydcPenaltyFactorEnum);
-		
+
 		kappa=kmax*pow(10.,penalty_factor);
-		
-		Tria* tria=(Tria*)SpawnTria(0,1,2); //nodes 0, 1 and 2 make the new tria.	
+
+		Tria* tria=(Tria*)SpawnTria(0); //lower face is 0, upper face is 1.	
 		for(int i=0;i<NUMVERTICES2D;i++){
 			tria->GetHydrologyDCInefficientHmax(&h_max,nodes[i]);
 			if(values[i]>h_max){
 				residual[i]=kappa*(values[i]-h_max);
+				residual[i+numdof2d]=residual[i];
 			}
 			else{
 				residual[i]=0.0;
+				residual[i+numdof2d]=residual[i];
 			}
 		}
@@ -9347,6 +11250,6 @@
 	for(;;){
 		/*Add input to the element: */
-		penta->inputs->AddInput(new PentaP1Input(SedimentHeadEnum,values));
-		penta->inputs->AddInput(new PentaP1Input(SedimentHeadResidualEnum,residual));
+		penta->inputs->AddInput(new PentaInput(SedimentHeadEnum,values,P1Enum));
+		penta->inputs->AddInput(new PentaInput(SedimentHeadResidualEnum,residual,P1Enum));
 
 		/*Stop if we have reached the surface*/
@@ -9365,13 +11268,15 @@
 #ifdef _HAVE_GROUNDINGLINE_
 /*FUNCTION Penta::MigrateGroundingLine{{{*/
-void  Penta::MigrateGroundingLine(IssmDouble* old_floating_ice,IssmDouble* sheet_ungrounding){
-
-	int     i,migration_style;
-	bool    floatingelement = false;
-	bool    groundedelement = false;
-	IssmDouble  bed_hydro,yts,gl_melting_rate;
-	IssmDouble  rho_water,rho_ice,density;
-	IssmDouble  melting[NUMVERTICES],phi[NUMVERTICES];
-	IssmDouble  h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],ba[NUMVERTICES];
+void  Penta::MigrateGroundingLine(IssmDouble* phi_ungrounding){
+
+	int        i,migration_style;
+	bool       oldfloating;
+	bool       floatingelement = false;
+	bool       groundedelement = false;
+	IssmDouble bed_hydro,yts,gl_melting_rate;
+	IssmDouble rho_water,rho_ice,density;
+	IssmDouble h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],r[NUMVERTICES];
+	IssmDouble melting[NUMVERTICES],phi[NUMVERTICES];
+	bool       grounded[NUMVERTICES],floating[NUMVERTICES];
 
 	if(!IsOnBed()) return;
@@ -9384,19 +11289,20 @@
 	GetInputListOnVertices(&s[0],SurfaceEnum);
 	GetInputListOnVertices(&b[0],BedEnum);
-	GetInputListOnVertices(&ba[0],BathymetryEnum);
-	if(migration_style==SubelementMigrationEnum) GetInputListOnVertices(&phi[0],GLlevelsetEnum);
-	rho_water=matpar->GetRhoWater();
-	rho_ice=matpar->GetRhoIce();
-	density=rho_ice/rho_water;
+	GetInputListOnVertices(&r[0],BathymetryEnum);
+	GetInputListOnVertices(&phi[0],MaskGroundediceLevelsetEnum);
+	rho_water   = matpar->GetRhoWater();
+	rho_ice     = matpar->GetRhoIce();
+	density     = rho_ice/rho_water;
+	oldfloating = this->IsFloating(); //figure out if the element is floating before starting to change everything
 
 	/*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(reCast<bool,IssmDouble>(old_floating_ice[nodes[i]->Sid()])){
-			if(b[i]<=ba[i]){ 
-				b[i]=ba[i];
-				s[i]=b[i]+h[i];
-				nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,false));
-				nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,true));
+		if(phi[i]<=0){
+			if(b[i]<=r[i]){ 
+				b[i]        = r[i];
+				s[i]        = b[i]+h[i];
+				floating[i] = false;
+				grounded[i] = true;
 			}
 		}
@@ -9405,17 +11311,17 @@
 		else{
 			bed_hydro=-density*h[i];
-			if (bed_hydro>ba[i]){
+			if(bed_hydro>r[i]){
 				/*Unground only if the element is connected to the ice shelf*/
-				if(migration_style==AgressiveMigrationEnum || migration_style==SubelementMigrationEnum){
-					s[i]=(1-density)*h[i];
-					b[i]=-density*h[i];
-					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,true));
-					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,false));
+				if(migration_style==AgressiveMigrationEnum || migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
+					s[i]        = (1-density)*h[i];
+					b[i]        = -density*h[i];
+					floating[i] = true;
+					grounded[i] = false;
 				}
-				else if(migration_style==SoftMigrationEnum && reCast<int,IssmDouble>(sheet_ungrounding[nodes[i]->Sid()])){
-					s[i]=(1-density)*h[i];
-					b[i]=-density*h[i];
-					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,true));
-					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,false));
+				else if(migration_style==SoftMigrationEnum && phi_ungrounding[vertices[i]->Pid()]<0.){
+					s[i]        = (1-density)*h[i];
+					b[i]        = -density*h[i];
+					floating[i] = true;
+					grounded[i] = false;
 				}
 				else{
@@ -9426,8 +11332,21 @@
 	}
 
+	/*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,ElementEnum);
+
 	/*SubelementMigrationEnum: if one grounded, all grounded*/
-	if(migration_style==SubelementMigrationEnum){
+	if(migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
 		for(i=0;i<NUMVERTICES;i++){
-			if(nodes[i]->IsGrounded()){
+			if(phi[i]>0.){
 				groundedelement=true;
 				break;
@@ -9438,5 +11357,5 @@
 	else{
 		for(i=0;i<NUMVERTICES;i++){
-			if(nodes[i]->IsFloating()){
+			if(phi[i]<=0.){
 				floatingelement=true;
 				break;
@@ -9446,27 +11365,16 @@
 
    /*Add basal melting rate if element just ungrounded*/
-	if(!this->IsFloating() && floatingelement==true){
+	if(!oldfloating && floatingelement==true){
 		for(i=0;i<NUMVERTICES;i++)melting[i]=gl_melting_rate/yts;
-		this->inputs->AddInput(new PentaP1Input(BasalforcingsMeltingRateEnum,&melting[0]));
+		this->inputs->AddInput(new PentaInput(BasalforcingsMeltingRateEnum,&melting[0],P1Enum));
 	} 
 
 	/*Update inputs*/
-	this->inputs->AddInput(new PentaP1Input(SurfaceEnum,&s[0]));
-	this->inputs->AddInput(new PentaP1Input(BedEnum,&b[0]));
-   this->inputs->AddInput(new BoolInput(MaskElementonfloatingiceEnum,floatingelement));
-
-	/*Recalculate phi*/
-	if(migration_style==SubelementMigrationEnum){
-		for(i=0;i<NUMVERTICES;i++) phi[i]=h[i]+ba[i]/density;
-		this->inputs->AddInput(new PentaP1Input(GLlevelsetEnum,&phi[0]));
-		this->InputExtrude(GLlevelsetEnum,ElementEnum);
-	}
+	this->inputs->AddInput(new PentaInput(SurfaceEnum,&s[0],P1Enum));
+	this->inputs->AddInput(new PentaInput(BedEnum,&b[0],P1Enum));
 
 	/*Extrude inputs*/
 	this->InputExtrude(SurfaceEnum,ElementEnum);
 	this->InputExtrude(BedEnum,ElementEnum);
-	this->InputExtrude(MaskElementonfloatingiceEnum,ElementEnum);
-	this->InputExtrude(MaskVertexonfloatingiceEnum,NodeEnum);
-	this->InputExtrude(MaskVertexongroundediceEnum,NodeEnum);
 }
 /*}}}*/
@@ -9474,6 +11382,5 @@
 void  Penta::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){
 
-	int     i;
-	IssmDouble  h[NUMVERTICES],ba[NUMVERTICES];
+	IssmDouble  h[NUMVERTICES],r[NUMVERTICES],gl[NUMVERTICES];
 	IssmDouble  bed_hydro;
 	IssmDouble  rho_water,rho_ice,density;
@@ -9484,14 +11391,15 @@
 	density=rho_ice/rho_water;
 	GetInputListOnVertices(&h[0],ThicknessEnum);
-	GetInputListOnVertices(&ba[0],BathymetryEnum);
+	GetInputListOnVertices(&r[0],BathymetryEnum);
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
 
 	/*go through vertices, and figure out which ones are on the ice sheet, and want to unground: */
-	for(i=0;i<NUMVERTICES;i++){
+	for(int i=0;i<NUMVERTICES;i++){
 		/*Find if grounded vertices want to start floating*/
-		if (!nodes[i]->IsFloating()){
+		if (gl[i]>0.){
 			bed_hydro=-density*h[i];
-			if (bed_hydro>ba[i]){
+			if(bed_hydro>r[i]){
 				/*Vertex that could potentially unground, flag it*/
-				potential_ungrounding->SetValue(nodes[i]->Sid(),1,INS_VAL);
+				potential_ungrounding->SetValue(vertices[i]->Pid(),1,INS_VAL);
 			}
 		}
@@ -9507,9 +11415,9 @@
 	/*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[nodes[i]->Sid()])){
-			vec_nodes_on_iceshelf->SetValue(nodes[i]->Sid(),1,INS_VAL);
+		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[nodes[i]->Sid()]==0){
+			if(nodes_on_iceshelf[vertices[i]->Pid()]>=0.){
 				nflipped++;
 			}
Index: /issm/trunk/src/c/classes/Elements/Penta.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Penta.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Elements/Penta.h	(revision 16137)
@@ -40,5 +40,4 @@
 		Matpar      *matpar;                      // 1 material parameter
 		Penta      **verticalneighbors;           // 2 neighbors: first one under, second one above
-		int          horizontalneighborsids[3];
 
 		Parameters  *parameters;                  //pointer to solution parameters
@@ -63,11 +62,7 @@
 		void  InputUpdateFromConstant(int constant, int name);
 		void  InputUpdateFromSolution(IssmDouble* solutiong);
-		void  InputUpdateFromVector(bool* vector, int name, int type);
 		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVector(int* vector, int name, int type);
 		#ifdef _HAVE_DAKOTA_
-		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
 		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
 		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type);
 		#endif
@@ -81,5 +76,5 @@
 		void   Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters);
 		void   SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Materials* materials,Parameters* parameters);
-		void   SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
+		void   SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum);
 		void   CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
 		void   CreateDVector(Vector<IssmDouble>* df);
@@ -90,4 +85,5 @@
 		int    GetNodeIndex(Node* node);
 		void   GetNodesSidList(int* sidlist);
+		void   GetNodesLidList(int* lidlist);
 		int    GetNumberOfNodes(void);
 		void   GetSolutionFromInputs(Vector<IssmDouble>* solution);
@@ -113,8 +109,7 @@
 		void   SmbGradients();
 		IssmDouble SurfaceArea(void);
-		void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type);
+		void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
 		int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum);
 		IssmDouble TimeAdapt();
-		int*   GetHorizontalNeighboorSids(void);
 		void   ViscousHeatingCreateInput(void);
 
@@ -146,10 +141,10 @@
 		void   GradientIndexing(int* indexing,int control_index);
 		void   Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index);
-		void   GradjDragMacAyeal(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjDragPattyn(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjDragStokes(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjBbarMacAyeal(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjBbarPattyn(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjBbarStokes(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjDragSSA(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjDragHO(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjDragFS(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjBbarSSA(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjBbarHO(Vector<IssmDouble>* gradient,int control_index);
+		void   GradjBbarFS(Vector<IssmDouble>* gradient,int control_index);
 		void   GetVectorFromControlInputs(Vector<IssmDouble>* gradient,int control_enum,int control_index,const char* data);
 		void   SetControlInputsFromVector(IssmDouble* vector,int control_enum,int control_index);
@@ -170,7 +165,7 @@
 		void   InputControlUpdate(IssmDouble scalar,bool save_parameter);
 		#endif
-		
+
 		#ifdef _HAVE_GROUNDINGLINE_
-		void   MigrateGroundingLine(IssmDouble* old_floating_ice,IssmDouble* sheet_ungrounding);
+		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);
@@ -179,13 +174,23 @@
 		/*}}}*/
 		/*Penta specific routines:{{{*/
-		void	  BedNormal(IssmDouble* bed_normal, IssmDouble xyz_list[3][3]);
+		void	         BedNormal(IssmDouble* bed_normal, IssmDouble xyz_list[3][3]);
 		ElementMatrix* CreateBasalMassMatrix(void);
-		ElementMatrix* CreateKMatrixPrognostic(void);
-		ElementVector* CreatePVectorPrognostic(void);
+		ElementMatrix* CreateKMatrix(void);
+		ElementMatrix* CreateKMatrixMasstransport(void);
+		ElementMatrix* CreateKMatrixFreeSurfaceTop(void);
+		ElementMatrix* CreateKMatrixFreeSurfaceBase(void);
+		ElementVector* CreatePVector(void);
+		ElementVector* CreatePVectorMasstransport(void);
+		ElementVector* CreatePVectorFreeSurfaceTop(void);
+		ElementVector* CreatePVectorFreeSurfaceBase(void);
 		ElementVector* CreatePVectorSlope(void);
+		void           GetAreaCoordinates(IssmDouble *area_coordinates,IssmDouble xyz_zero[3][3],IssmDouble xyz_list[6][3],int numpoints);
 		void	         GetDofList(int** pdoflist,int approximation_enum,int setenum);
+		void	         GetDofListVelocity(int** pdoflist,int setenum);
+		void	         GetDofListPressure(int** pdoflist,int setenum);
 		void	         GetVertexPidList(int* doflist);
 		void           GetVertexSidList(int* sidlist);
 		void           GetConnectivityList(int* connectivity);
+		void           GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating);
 		IssmDouble     GetGroundedPortion(IssmDouble* xyz_list);
 		int            GetElementType(void);
@@ -193,124 +198,131 @@
 		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype);
 		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
+		void           GetInputListOnNodes(IssmDouble* pvalue,int enumtype);
+		void           GetInputListOnNodes(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
 		void           GetInputValue(IssmDouble* pvalue,Node* node,int enumtype);
 		void	         GetPhi(IssmDouble* phi, IssmDouble*  epsilon, IssmDouble viscosity);
+		void           GetQuadNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]);
 		void	         GetSolutionFromInputsEnthalpy(Vector<IssmDouble>* solutiong);
 		IssmDouble     GetStabilizationParameter(IssmDouble u, IssmDouble v, IssmDouble w, IssmDouble diameter, IssmDouble kappa);
-		void    GetStrainRate3dPattyn(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input);
-		void    GetStrainRate3d(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input, Input* vz_input);
-		Penta*  GetUpperElement(void);
-		Penta*  GetLowerElement(void);
-		Penta*  GetBasalElement(void);
-		void	  InputExtrude(int enum_type,int object_type);
-		void    InputUpdateFromSolutionPrognostic(IssmDouble* solutiong);
-		void    InputUpdateFromSolutionOneDof(IssmDouble* solutiong,int enum_type);
-		void    InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solutiong,int enum_type);
-		bool	  IsInput(int name);
-		bool	  IsOnSurface(void);
-		bool	  IsOnBed(void);
-		bool    IsFloating(void); 
-		bool    IsNodeOnShelf(); 
-		bool    IsNodeOnShelfFromFlags(IssmDouble* flags);
-		bool    IsOnWater(void); 
-		IssmDouble  MinEdgeLength(IssmDouble xyz_list[6][3]);
-		void	  ReduceMatrixStokes(IssmDouble* Ke_reduced, IssmDouble* Ke_temp);
-		void	  ReduceVectorStokes(IssmDouble* Pe_reduced, IssmDouble* Ke_temp, IssmDouble* Pe_temp);
-		void	  SetClone(int* minranks);
-		Tria*	  SpawnTria(int g0, int g1, int g2);
-		void	  SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]);
-		void     UpdateConstraints(void);
-
-		#ifdef _HAVE_DIAGNOSTIC_
-		ElementMatrix* CreateKMatrixCouplingMacAyealPattyn(void);
-		ElementMatrix* CreateKMatrixCouplingMacAyealPattynViscous(void);
-		ElementMatrix* CreateKMatrixCouplingMacAyealPattynFriction(void);
-		ElementMatrix* CreateKMatrixCouplingMacAyealStokes(void);
-		ElementMatrix* CreateKMatrixCouplingMacAyealStokesViscous(void);
-		ElementMatrix* CreateKMatrixCouplingMacAyealStokesFriction(void);
-		ElementMatrix* CreateKMatrixCouplingPattynStokes(void);
-		ElementMatrix* CreateKMatrixDiagnosticHoriz(void);
+		void           GetStrainRate3dHO(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input);
+		void           GetStrainRate3d(IssmDouble* epsilon,IssmDouble* xyz_list, GaussPenta* gauss, Input* vx_input, Input* vy_input, Input* vz_input);
+		Penta*         GetUpperElement(void);
+		void           GetZeroLevelsetCoordinates(IssmDouble* xyz_zero,IssmDouble xyz_list[6][3],int levelsetenum);
+		Penta*         GetLowerElement(void);
+		Penta*         GetBasalElement(void);
+		void	         InputExtrude(int enum_type,int object_type);
+		void           InputUpdateFromSolutionMasstransport(IssmDouble* solutiong);
+		void           InputUpdateFromSolutionFreeSurfaceTop(IssmDouble* solutiong);
+		void           InputUpdateFromSolutionFreeSurfaceBase(IssmDouble* solutiong);
+		void           InputUpdateFromSolutionOneDof(IssmDouble* solutiong,int enum_type);
+		void           InputUpdateFromSolutionOneDofCollapsed(IssmDouble* solutiong,int enum_type);
+		bool	         IsInput(int name);
+		bool	         IsOnSurface(void);
+		bool	         IsOnBed(void);
+		bool           IsFloating(void); 
+		bool           IsNodeOnShelfFromFlags(IssmDouble* flags);
+		bool           NoIceInElement(void); 
+		IssmDouble     MinEdgeLength(IssmDouble xyz_list[6][3]);
+		void	         ReduceMatrixFS(IssmDouble* Ke_reduced, IssmDouble* Ke_temp);
+		void	         ReduceVectorFS(IssmDouble* Pe_reduced, IssmDouble* Ke_temp, IssmDouble* Pe_temp);
+		void	         SetClone(int* minranks);
+		Tria*	         SpawnTria(int location);
+		void	         SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]);
+
+		#ifdef _HAVE_STRESSBALANCE_
+		ElementMatrix* CreateKMatrixCouplingSSAHO(void);
+		ElementMatrix* CreateKMatrixCouplingSSAHOViscous(void);
+		ElementMatrix* CreateKMatrixCouplingSSAHOFriction(void);
+		ElementMatrix* CreateKMatrixCouplingSSAFS(void);
+		ElementMatrix* CreateKMatrixCouplingSSAFSViscous(void);
+		ElementMatrix* CreateKMatrixCouplingSSAFSFriction(void);
+		ElementMatrix* CreateKMatrixCouplingHOFS(void);
+		ElementMatrix* CreateKMatrixStressbalanceHoriz(void);
 		ElementMatrix* CreateKMatrixAdjointHoriz(void);
-		ElementVector* CreateDVectorDiagnosticHoriz(void);
-		ElementVector* CreateDVectorDiagnosticStokes(void);
-		ElementMatrix* CreateKMatrixDiagnosticHutter(void);
-		ElementMatrix* CreateKMatrixDiagnosticMacAyeal2d(void);
-		ElementMatrix* CreateKMatrixDiagnosticMacAyeal3d(void);
-		ElementMatrix* CreateKMatrixDiagnosticMacAyeal3dViscous(void);
-		ElementMatrix* CreateKMatrixDiagnosticMacAyeal3dFriction(void);
-		ElementMatrix* CreateKMatrixDiagnosticMacAyealPattyn(void);
-		ElementMatrix* CreateKMatrixDiagnosticMacAyealStokes(void);
-		ElementMatrix* CreateKMatrixDiagnosticL1L2(void);
-		ElementMatrix* CreateKMatrixDiagnosticL1L2Viscous(void);
-		ElementMatrix* CreateKMatrixDiagnosticL1L2Friction(void);
-		ElementMatrix* CreateKMatrixDiagnosticPattyn(void);
-		ElementMatrix* CreateKMatrixDiagnosticPattynViscous(void);
-		ElementMatrix* CreateKMatrixDiagnosticPattynFriction(void);
-		ElementMatrix* CreateKMatrixDiagnosticPattynStokes(void);
-		ElementMatrix* CreateKMatrixDiagnosticStokes(void);
-		ElementMatrix* CreateKMatrixDiagnosticStokesViscous(void);
-		ElementMatrix* CreateKMatrixDiagnosticStokesFriction(void);
-		ElementMatrix* CreateKMatrixDiagnosticVert(void);
-		ElementMatrix* CreateKMatrixDiagnosticVertVolume(void);
-		ElementMatrix* CreateKMatrixDiagnosticVertSurface(void);
-		ElementMatrix* CreateJacobianDiagnosticHoriz(void);
-		ElementMatrix* CreateJacobianDiagnosticMacayeal2d(void);
-		ElementMatrix* CreateJacobianDiagnosticPattyn(void);
-		ElementMatrix* CreateJacobianDiagnosticStokes(void);
-		void           InputUpdateFromSolutionDiagnosticHoriz( IssmDouble* solutiong);
-		void           InputUpdateFromSolutionDiagnosticMacAyeal( IssmDouble* solutiong);
-		void           InputUpdateFromSolutionDiagnosticMacAyealPattyn( IssmDouble* solutiong);
-		void           InputUpdateFromSolutionDiagnosticMacAyealStokes( IssmDouble* solutiong);
-		void           InputUpdateFromSolutionDiagnosticL1L2( IssmDouble* solutiong);
-		void           InputUpdateFromSolutionDiagnosticPattyn( IssmDouble* solutiong);
-		void           InputUpdateFromSolutionDiagnosticPattynStokes( IssmDouble* solutiong);
-		void           InputUpdateFromSolutionDiagnosticHutter( IssmDouble* solutiong);
-		void           InputUpdateFromSolutionDiagnosticVert( IssmDouble* solutiong);
-		void           InputUpdateFromSolutionDiagnosticStokes( IssmDouble* solutiong);
-		void	         GetSolutionFromInputsDiagnosticHoriz(Vector<IssmDouble>* solutiong);
-		void	         GetSolutionFromInputsDiagnosticHutter(Vector<IssmDouble>* solutiong);
-		void	         GetSolutionFromInputsDiagnosticStokes(Vector<IssmDouble>* solutiong);
-		void	         GetSolutionFromInputsDiagnosticVert(Vector<IssmDouble>* solutiong);
-		ElementVector* CreatePVectorCouplingMacAyealStokes(void);
-		ElementVector* CreatePVectorCouplingMacAyealStokesViscous(void);
-		ElementVector* CreatePVectorCouplingMacAyealStokesFriction(void);
-		ElementVector* CreatePVectorCouplingPattynStokes(void);
-		ElementVector* CreatePVectorCouplingPattynStokesViscous(void);
-		ElementVector* CreatePVectorCouplingPattynStokesFriction(void);
-		ElementVector* CreatePVectorDiagnosticHoriz(void);
-		ElementVector* CreatePVectorDiagnosticHutter(void);
-		ElementVector* CreatePVectorDiagnosticMacAyeal(void);
-		ElementVector* CreatePVectorDiagnosticMacAyealPattyn(void);
-		ElementVector* CreatePVectorDiagnosticMacAyealStokes(void);
-		ElementVector* CreatePVectorDiagnosticL1L2(void);
-		ElementVector* CreatePVectorDiagnosticPattyn(void);
-		ElementVector* CreatePVectorDiagnosticPattynStokes(void);
-		ElementVector* CreatePVectorDiagnosticStokes(void);
-		ElementVector* CreatePVectorDiagnosticStokesViscous(void);
-		ElementVector* CreatePVectorDiagnosticStokesShelf(void);
-		ElementVector* CreatePVectorDiagnosticVert(void);
-		ElementVector* CreatePVectorDiagnosticVertVolume(void);
-		ElementVector* CreatePVectorDiagnosticVertBase(void);
-		void GetL1L2Viscosity(IssmDouble*, IssmDouble*, GaussPenta*, Input*, Input*, Input*);
+		ElementVector* CreateDVectorStressbalanceHoriz(void);
+		ElementVector* CreateDVectorStressbalanceFS(void);
+		ElementMatrix* CreateKMatrixStressbalanceSIA(void);
+		ElementMatrix* CreateKMatrixStressbalanceSSA2d(void);
+		ElementMatrix* CreateKMatrixStressbalanceSSA3d(void);
+		ElementMatrix* CreateKMatrixStressbalanceSSA3dViscous(void);
+		ElementMatrix* CreateKMatrixStressbalanceSSA3dFriction(void);
+		ElementMatrix* CreateKMatrixStressbalanceSSAHO(void);
+		ElementMatrix* CreateKMatrixStressbalanceSSAFS(void);
+		ElementMatrix* CreateKMatrixStressbalanceL1L2(void);
+		ElementMatrix* CreateKMatrixStressbalanceL1L2Viscous(void);
+		ElementMatrix* CreateKMatrixStressbalanceL1L2Friction(void);
+		ElementMatrix* CreateKMatrixStressbalanceHO(void);
+		ElementMatrix* CreateKMatrixStressbalanceHOViscous(void);
+		ElementMatrix* CreateKMatrixStressbalanceHOFriction(void);
+		ElementMatrix* CreateKMatrixStressbalanceHOFS(void);
+		ElementMatrix* CreateKMatrixStressbalanceFS(void);
+		ElementMatrix* CreateKMatrixStressbalanceFSViscous(void);
+		void           KMatrixGLSstabilization(ElementMatrix* Ke);
+		ElementMatrix* CreateKMatrixStressbalanceFSFriction(void);
+		ElementMatrix* CreateKMatrixStressbalanceVert(void);
+		ElementMatrix* CreateKMatrixStressbalanceVertVolume(void);
+		ElementMatrix* CreateKMatrixStressbalanceVertSurface(void);
+		ElementMatrix* CreateJacobianStressbalanceHoriz(void);
+		ElementMatrix* CreateJacobianStressbalanceSSA2d(void);
+		ElementMatrix* CreateJacobianStressbalanceHO(void);
+		ElementMatrix* CreateJacobianStressbalanceFS(void);
+		void           InputUpdateFromSolutionStressbalanceHoriz( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionStressbalanceSSA( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionStressbalanceSSAHO( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionStressbalanceSSAFS( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionStressbalanceL1L2( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionStressbalanceHO( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionStressbalanceHOFS( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionStressbalanceSIA( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionStressbalanceVert( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionStressbalanceFS( IssmDouble* solutiong);
+		void	         GetSolutionFromInputsStressbalanceHoriz(Vector<IssmDouble>* solutiong);
+		void	         GetSolutionFromInputsStressbalanceSIA(Vector<IssmDouble>* solutiong);
+		void	         GetSolutionFromInputsStressbalanceFS(Vector<IssmDouble>* solutiong);
+		void	         GetSolutionFromInputsStressbalanceVert(Vector<IssmDouble>* solutiong);
+		ElementVector* CreatePVectorCouplingSSAFS(void);
+		ElementVector* CreatePVectorCouplingSSAFSViscous(void);
+		ElementVector* CreatePVectorCouplingSSAFSFriction(void);
+		ElementVector* CreatePVectorCouplingHOFS(void);
+		ElementVector* CreatePVectorCouplingHOFSViscous(void);
+		ElementVector* CreatePVectorCouplingHOFSFriction(void);
+		ElementVector* CreatePVectorStressbalanceHoriz(void);
+		ElementVector* CreatePVectorStressbalanceSIA(void);
+		ElementVector* CreatePVectorStressbalanceSSA(void);
+		ElementVector* CreatePVectorStressbalanceSSAHO(void);
+		ElementVector* CreatePVectorStressbalanceSSAFS(void);
+		ElementVector* CreatePVectorStressbalanceL1L2(void);
+		ElementVector* CreatePVectorStressbalanceHO(void);
+		ElementVector* CreatePVectorStressbalanceHODrivingStress(void);
+		ElementVector* CreatePVectorStressbalanceHOFront(void);
+		ElementVector* CreatePVectorStressbalanceHOFS(void);
+		ElementVector* CreatePVectorStressbalanceFS(void);
+		ElementVector* CreatePVectorStressbalanceFSFront(void);
+		ElementVector* CreatePVectorStressbalanceFSViscous(void);
+		void           PVectorGLSstabilization(ElementVector* pe);
+		ElementVector* CreatePVectorStressbalanceFSShelf(void);
+		ElementVector* CreatePVectorStressbalanceVert(void);
+		ElementVector* CreatePVectorStressbalanceVertVolume(void);
+		ElementVector* CreatePVectorStressbalanceVertBase(void);
+		void           GetL1L2Viscosity(IssmDouble*, IssmDouble*, GaussPenta*, Input*, Input*, Input*);
 		#endif
 
 		#ifdef _HAVE_CONTROL_
 		ElementVector* CreatePVectorAdjointHoriz(void);
-		ElementMatrix* CreateKMatrixAdjointMacAyeal2d(void);
-		ElementMatrix* CreateKMatrixAdjointPattyn(void);
-		ElementMatrix* CreateKMatrixAdjointStokes(void);
-		ElementVector* CreatePVectorAdjointMacAyeal(void);
-		ElementVector* CreatePVectorAdjointPattyn(void);
-		ElementVector* CreatePVectorAdjointStokes(void);
-		void    InputUpdateFromSolutionAdjointHoriz( IssmDouble* solutiong);
-		void    InputUpdateFromSolutionAdjointStokes( IssmDouble* solutiong);
+		ElementMatrix* CreateKMatrixAdjointSSA2d(void);
+		ElementMatrix* CreateKMatrixAdjointHO(void);
+		ElementMatrix* CreateKMatrixAdjointFS(void);
+		ElementVector* CreatePVectorAdjointSSA(void);
+		ElementVector* CreatePVectorAdjointHO(void);
+		ElementVector* CreatePVectorAdjointFS(void);
+		void           InputUpdateFromSolutionAdjointHoriz( IssmDouble* solutiong);
+		void           InputUpdateFromSolutionAdjointFS( IssmDouble* solutiong);
 		#endif
 
 		#ifdef _HAVE_HYDROLOGY_
-		
 		ElementMatrix* CreateKMatrixHydrologyDCInefficient(void);
 		ElementMatrix* CreateKMatrixHydrologyDCEfficient(void);
 		ElementVector* CreatePVectorHydrologyDCInefficient(void);
 		ElementVector* CreatePVectorHydrologyDCEfficient(void);
-		
 		void    GetHydrologyDCInefficientHmax(IssmDouble* ph_max, Node* innode);
 		void    GetHydrologyTransfer(Vector<IssmDouble>* transfer);
@@ -320,4 +332,5 @@
 		void    InputUpdateFromSolutionHydrologyDCInefficient(IssmDouble* solution);
 		#endif
+
 		#ifdef _HAVE_THERMAL_
 		ElementMatrix* CreateKMatrixEnthalpy(void);
@@ -337,8 +350,12 @@
 		ElementVector* CreatePVectorThermalShelf(void);
 		ElementVector* CreatePVectorThermalSheet(void);
-		void	       GetSolutionFromInputsThermal(Vector<IssmDouble>* solutiong);
-		void           InputUpdateFromSolutionThermal( IssmDouble* solutiong);
-		void           InputUpdateFromSolutionEnthalpy( IssmDouble* solutiong);
-		#endif
+		void	         GetSolutionFromInputsThermal(Vector<IssmDouble>* solutiong);
+		void           InputUpdateFromSolutionThermal(IssmDouble* solutiong);
+		void           InputUpdateFromSolutionEnthalpy(IssmDouble* solutiong);
+		void           UpdateThermalBasalConstraints(void);
+		void           ComputeBasalMeltingrate(void);
+		void           DrainWaterfraction(void);
+		#endif
+
 		#ifdef _HAVE_BALANCED_
 		ElementMatrix* CreateKMatrixBalancethickness(void);
Index: /issm/trunk/src/c/classes/Elements/PentaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Elements/PentaRef.cpp	(revision 16137)
@@ -18,5 +18,8 @@
 #define NUMNODESP1    6
 #define NUMNODESP1_2d 3
-#define NUMNODESMINI  7
+#define NUMNODESP1b   7
+#define NUMNODESP1xP2 9
+#define NUMNODESP2xP1 12
+#define NUMNODESP2    15
 
 /*Object constructors and destructor*/
@@ -44,6 +47,4 @@
 void PentaRef::SetElementType(int type,int type_counter){
 
-	_assert_(type==P1Enum || type==P1DGEnum);
-
 	/*initialize element type*/
 	this->element_type_list[type_counter]=type;
@@ -52,6 +53,6 @@
 
 /*Reference Element numerics*/
-/*FUNCTION PentaRef::GetBMacAyealPattyn {{{*/
-void PentaRef::GetBMacAyealPattyn(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss){
+/*FUNCTION PentaRef::GetBSSAHO {{{*/
+void PentaRef::GetBSSAHO(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* 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
@@ -71,18 +72,18 @@
 
 	/*Build B: */
-	for (int i=0;i<NUMNODESP1;i++){
-		*(B+NDOF2*NUMNODESP1*0+NDOF2*i)=dbasis[0][i]; 
-		*(B+NDOF2*NUMNODESP1*0+NDOF2*i+1)=0.0;
-
-		*(B+NDOF2*NUMNODESP1*1+NDOF2*i)=0.0;
-		*(B+NDOF2*NUMNODESP1*1+NDOF2*i+1)=dbasis[1][i];
-
-		*(B+NDOF2*NUMNODESP1*2+NDOF2*i)=(float).5*dbasis[1][i]; 
-		*(B+NDOF2*NUMNODESP1*2+NDOF2*i+1)=(float).5*dbasis[0][i]; 
-	}
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetBMacAyealStokes{{{*/
-void PentaRef::GetBMacAyealStokes(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss){
+	for(int i=0;i<NUMNODESP1;i++){
+		B[NDOF2*NUMNODESP1*0+NDOF2*i+0] = dbasis[0][i];
+		B[NDOF2*NUMNODESP1*0+NDOF2*i+1] = 0.;
+
+		B[NDOF2*NUMNODESP1*1+NDOF2*i+0] = 0.;
+		B[NDOF2*NUMNODESP1*1+NDOF2*i+1] = dbasis[1][i];
+
+		B[NDOF2*NUMNODESP1*2+NDOF2*i+0] = .5*dbasis[1][i];
+		B[NDOF2*NUMNODESP1*2+NDOF2*i+1] = .5*dbasis[0][i];
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBSSAFS{{{*/
+void PentaRef::GetBSSAFS(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* 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
@@ -97,38 +98,52 @@
 	 */
 
-	int    i;
-	IssmDouble dh1dh7[3][NUMNODESMINI];
-	IssmDouble l1l6[NUMNODESP1];
-
-	/*Get dh1dh6 in actual coordinate system: */
-	GetNodalFunctionsMINIDerivatives(&dh1dh7[0][0],xyz_list, gauss);
-	GetNodalFunctionsP1(l1l6, gauss);
+	int i;
+	IssmDouble dbasismini[3][NUMNODESP1b];
+	IssmDouble basis[NUMNODESP1];
+
+	/*Get dbasis in actual coordinate system: */
+	GetNodalFunctionsMINIDerivatives(&dbasismini[0][0],xyz_list, gauss);
+	GetNodalFunctionsP1(basis,gauss);
 
 	/*Build B: */
-	for (i=0;i<NUMNODESMINI;i++){
-		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i)=dh1dh7[0][i]; //B[0][NDOF4*i]=dh1dh6[0][i];
-		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+1)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+2)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+1)=dh1dh7[1][i];
-		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+2)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i)=0.5*dh1dh7[1][i];
-		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+1)=0.5*dh1dh7[0][i];
-		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+2)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+1)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+2)=0;
-	}
-
-	for (i=0;i<NUMNODESP1;i++){ //last column not for the bubble function
-		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+3)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+3)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+3)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+3)=l1l6[i];
-	}
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetBPattyn {{{*/
-void PentaRef::GetBPattyn(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss){
+	for(i=0;i<NUMNODESP1;i++){
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*i+0] = dbasismini[0][i];
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*i+1] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*i+2] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*i+0] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*i+1] = dbasismini[1][i];
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*i+2] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*i+0] = 0.5*dbasismini[1][i];
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*i+1] = 0.5*dbasismini[0][i];
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*i+2] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*3+NDOF3*i+0] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*3+NDOF3*i+1] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*3+NDOF3*i+2] = 0.;
+	}
+	for(i=0;i<1;i++){
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*(NUMNODESP1+i)+0] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*(NUMNODESP1+i)+1] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*(NUMNODESP1+i)+2] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*(NUMNODESP1+i)+0] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*(NUMNODESP1+i)+1] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*(NUMNODESP1+i)+2] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*(NUMNODESP1+i)+0] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*(NUMNODESP1+i)+1] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*(NUMNODESP1+i)+2] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*3+NDOF3*(NUMNODESP1+i)+0] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*3+NDOF3*(NUMNODESP1+i)+1] = 0.;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*3+NDOF3*(NUMNODESP1+i)+2] = 0.;
+	}
+
+	for(i=0;i<NUMNODESP1;i++){ //last column not for the bubble function
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NUMNODESP1b*NDOF3+i] = 0;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NUMNODESP1b*NDOF3+i] = 0;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NUMNODESP1b*NDOF3+i] = 0;
+		B[(NDOF3*NUMNODESP1b+NUMNODESP1)*3+NUMNODESP1b*NDOF3+i] = basis[i];
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBHO {{{*/
+void PentaRef::GetBHO(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* 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
@@ -141,72 +156,74 @@
 	 * where h is the interpolation function for node i.
 	 *
-	 * We assume B has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
-	 */
-
-	IssmDouble dbasis[3][NUMNODESP1];
-
-	/*Get dbasis in actual coordinate system: */
-	GetNodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list, gauss);
+	 * We assume B has been allocated already, of size: 5x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 
 	/*Build B: */
-	for (int i=0;i<NUMNODESP1;i++){
-		*(B+NDOF2*NUMNODESP1*0+NDOF2*i)=dbasis[0][i]; 
-		*(B+NDOF2*NUMNODESP1*0+NDOF2*i+1)=0.0;
-
-		*(B+NDOF2*NUMNODESP1*1+NDOF2*i)=0.0;
-		*(B+NDOF2*NUMNODESP1*1+NDOF2*i+1)=dbasis[1][i];
-
-		*(B+NDOF2*NUMNODESP1*2+NDOF2*i)=(float).5*dbasis[1][i]; 
-		*(B+NDOF2*NUMNODESP1*2+NDOF2*i+1)=(float).5*dbasis[0][i]; 
-
-		*(B+NDOF2*NUMNODESP1*3+NDOF2*i)=(float).5*dbasis[2][i]; 
-		*(B+NDOF2*NUMNODESP1*3+NDOF2*i+1)=0.0;
-
-		*(B+NDOF2*NUMNODESP1*4+NDOF2*i)=0.0;
-		*(B+NDOF2*NUMNODESP1*4+NDOF2*i+1)=(float).5*dbasis[2][i]; 
-	}
-
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetBprimePattyn {{{*/
-void PentaRef::GetBprimePattyn(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss_coord){
+	for(int i=0;i<numnodes;i++){
+		B[NDOF2*numnodes*0+NDOF2*i+0] = dbasis[0*numnodes+i];
+		B[NDOF2*numnodes*0+NDOF2*i+1] = 0.;
+		B[NDOF2*numnodes*1+NDOF2*i+0] = 0.;
+		B[NDOF2*numnodes*1+NDOF2*i+1] = dbasis[1*numnodes+i];
+		B[NDOF2*numnodes*2+NDOF2*i+0] = .5*dbasis[1*numnodes+i];
+		B[NDOF2*numnodes*2+NDOF2*i+1] = .5*dbasis[0*numnodes+i];
+		B[NDOF2*numnodes*3+NDOF2*i+0] = .5*dbasis[2*numnodes+i];
+		B[NDOF2*numnodes*3+NDOF2*i+1] = 0.;
+		B[NDOF2*numnodes*4+NDOF2*i+0] = 0.;
+		B[NDOF2*numnodes*4+NDOF2*i+1] = .5*dbasis[2*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBprimeHO {{{*/
+void PentaRef::GetBprimeHO(IssmDouble* B,IssmDouble* xyz_list,GaussPenta* gauss){
 	/*Compute B  prime 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
 	 * by: 
 	 *       Bi=[ 2*dh/dx     dh/dy   ]
-	 *                [   dh/dx    2*dh/dy  ]
-	 *                [ dh/dy      dh/dx    ]
-	 *                [ dh/dz         0     ]
-	 *                [  0         dh/dz    ]
+	 *          [   dh/dx    2*dh/dy  ]
+	 *          [ dh/dy      dh/dx    ]
+	 *          [ dh/dz         0     ]
+	 *          [  0         dh/dz    ]
 	 * where h is the interpolation function for node i.
 	 *
-	 * We assume B has been allocated already, of size: 5x(NDOF2*NUMNODESP1)
-	 */
-	IssmDouble dbasis[3][NUMNODESP1];
-
-	/*Get dbasis in actual coordinate system: */
-	GetNodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list, gauss_coord);
+	 * We assume B has been allocated already, of size: 5x(NDOF2*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 
 	/*Build BPrime: */
-	for (int i=0;i<NUMNODESP1;i++){
-		*(B+NDOF2*NUMNODESP1*0+NDOF2*i)=2.0*dbasis[0][i]; 
-		*(B+NDOF2*NUMNODESP1*0+NDOF2*i+1)=dbasis[1][i];
-
-		*(B+NDOF2*NUMNODESP1*1+NDOF2*i)=dbasis[0][i];
-		*(B+NDOF2*NUMNODESP1*1+NDOF2*i+1)=2.0*dbasis[1][i];
-
-		*(B+NDOF2*NUMNODESP1*2+NDOF2*i)=dbasis[1][i]; 
-		*(B+NDOF2*NUMNODESP1*2+NDOF2*i+1)=dbasis[0][i]; 
-
-		*(B+NDOF2*NUMNODESP1*3+NDOF2*i)=dbasis[2][i]; 
-		*(B+NDOF2*NUMNODESP1*3+NDOF2*i+1)=0.0;
-
-		*(B+NDOF2*NUMNODESP1*4+NDOF2*i)=0.0;
-		*(B+NDOF2*NUMNODESP1*4+NDOF2*i+1)=dbasis[2][i]; 
-	}
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetBprimeMacAyealStokes{{{*/
-void PentaRef::GetBprimeMacAyealStokes(IssmDouble* Bprime, IssmDouble* xyz_list, GaussPenta* gauss){
+	for(int i=0;i<numnodes;i++){
+		B[NDOF2*numnodes*0+NDOF2*i+0]=2.*dbasis[0*numnodes+i]; 
+		B[NDOF2*numnodes*0+NDOF2*i+1]=dbasis[1*numnodes+i];
+		B[NDOF2*numnodes*1+NDOF2*i+0]=dbasis[0*numnodes+i];
+		B[NDOF2*numnodes*1+NDOF2*i+1]=2.*dbasis[1*numnodes+i];
+		B[NDOF2*numnodes*2+NDOF2*i+0]=dbasis[1*numnodes+i]; 
+		B[NDOF2*numnodes*2+NDOF2*i+1]=dbasis[0*numnodes+i]; 
+		B[NDOF2*numnodes*3+NDOF2*i+0]=dbasis[2*numnodes+i]; 
+		B[NDOF2*numnodes*3+NDOF2*i+1]=0.;
+		B[NDOF2*numnodes*4+NDOF2*i+0]=0.;
+		B[NDOF2*numnodes*4+NDOF2*i+1]=dbasis[2*numnodes+i]; 
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBprimeSSAFS{{{*/
+void PentaRef::GetBprimeSSAFS(IssmDouble* Bprime, IssmDouble* xyz_list, GaussPenta* 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
@@ -221,32 +238,176 @@
 
 	int    i;
-	IssmDouble dh1dh7[3][NUMNODESMINI];
-
-	/*Get dh1dh6 in actual coordinate system: */
-	GetNodalFunctionsMINIDerivatives(&dh1dh7[0][0],xyz_list, gauss);
+	IssmDouble dbasismini[3][NUMNODESP1b];
+
+	/*Get dbasis in actual coordinate system: */
+	GetNodalFunctionsMINIDerivatives(&dbasismini[0][0],xyz_list, gauss);
 
 	/*Build Bprime: */
-	for (i=0;i<NUMNODESMINI;i++){
-		*(Bprime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i)=2*dh1dh7[0][i]; //Bprime[0][NDOF4*i]=dh1dh6[0][i];
-		*(Bprime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+1)=dh1dh7[1][i];
-		*(Bprime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+2)=0;
-		*(Bprime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i)=dh1dh7[0][i];
-		*(Bprime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+1)=2*dh1dh7[1][i];
-		*(Bprime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+2)=0;
-		*(Bprime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i)=dh1dh7[1][i];
-		*(Bprime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+1)=dh1dh7[0][i];
-		*(Bprime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+2)=0;
-	}
-
-	for (i=0;i<NUMNODESP1;i++){ //last column not for the bubble function
-		*(Bprime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+3)=0;
-		*(Bprime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+3)=0;
-		*(Bprime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+3)=0;
-	}
-
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetBStokes {{{*/
-void PentaRef::GetBStokes(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss){
+	for(i=0;i<NUMNODESP1;i++){
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*i+0] = 2.*dbasismini[0][i];
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*i+1] = dbasismini[1][i];
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*i+2] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*i+0] = dbasismini[0][i];
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*i+1] = 2.*dbasismini[1][i];
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*i+2] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*i+0] = dbasismini[1][i];
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*i+1] = dbasismini[0][i];
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*i+2] = 0.;
+	}
+
+	for(i=0;i<1;i++){ //Add zeros for the bubble function
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*(NUMNODESP1+i)+0] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*(NUMNODESP1+i)+1] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NDOF3*(NUMNODESP1+i)+2] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*(NUMNODESP1+i)+0] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*(NUMNODESP1+i)+1] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NDOF3*(NUMNODESP1+i)+2] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*(NUMNODESP1+i)+0] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*(NUMNODESP1+i)+1] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NDOF3*(NUMNODESP1+i)+2] = 0.;
+	}
+
+	for(i=0;i<NUMNODESP1;i++){ //last column not for the bubble function
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*0+NUMNODESP1b*NDOF3+i] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*1+NUMNODESP1b*NDOF3+i] = 0.;
+		Bprime[(NDOF3*NUMNODESP1b+NUMNODESP1)*2+NUMNODESP1b*NDOF3+i] = 0.;
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBFSstrainrate {{{*/
+void PentaRef::GetBFSstrainrate(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss){
+
+	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 3*NDOF4. 
+	 * For node i, Bi can be expressed in the actual coordinate system
+	 * by: 		Bi=[ dh/dx          0              0     ]
+	 *					[   0           dh/dy           0     ]
+	 *					[   0             0           dh/dy   ]
+	 *					[ 1/2*dh/dy    1/2*dh/dx        0     ]
+	 *					[ 1/2*dh/dz       0         1/2*dh/dx ]
+	 *					[   0          1/2*dh/dz    1/2*dh/dy ]
+	 *	where h is the interpolation function for node i.
+	 *	Same thing for Bb except the last column that does not exist.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B[3*numnodes*0+3*i+0] = dbasis[0*numnodes+i+0];
+		B[3*numnodes*0+3*i+1] = 0.;
+		B[3*numnodes*0+3*i+2] = 0.;
+
+		B[3*numnodes*1+3*i+0] = 0.;
+		B[3*numnodes*1+3*i+1] = dbasis[1*numnodes+i+0];
+		B[3*numnodes*1+3*i+2] = 0.;
+
+		B[3*numnodes*2+3*i+0] = 0.;
+		B[3*numnodes*2+3*i+1] = 0.;
+		B[3*numnodes*2+3*i+2] = dbasis[2*numnodes+i+0];
+
+		B[3*numnodes*3+3*i+0] = .5*dbasis[1*numnodes+i+0];
+		B[3*numnodes*3+3*i+1] = .5*dbasis[0*numnodes+i+0];
+		B[3*numnodes*3+3*i+2] = 0.;
+
+		B[3*numnodes*4+3*i+0] = .5*dbasis[2*numnodes+i+0];
+		B[3*numnodes*4+3*i+1] = 0.;
+		B[3*numnodes*4+3*i+2] = .5*dbasis[0*numnodes+i+0];
+
+		B[3*numnodes*5+3*i+0] = 0.;
+		B[3*numnodes*5+3*i+1] = .5*dbasis[2*numnodes+i+0];
+		B[3*numnodes*5+3*i+2] = .5*dbasis[1*numnodes+i+0];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(dbasis);
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBFS {{{*/
+void PentaRef::GetBFS(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* 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
+	 * by: 	   Bvi=[ dh/dx          0              0      ]
+	 *					[   0           dh/dy           0      ]
+	 *					[   0             0           dh/dy    ]
+	 *					[ 1/2*dh/dy    1/2*dh/dx        0      ]
+	 *					[ 1/2*dh/dz       0         1/2*dh/dx  ]
+	 *					[   0          1/2*dh/dz    1/2*dh/dy  ]
+	 *					[   0             0             0      ]
+	 *					[ dh/dx         dh/dy         dh/dz    ]
+	 *
+	 * by: 	  Bpi=[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ h ]
+	 *					[ 0 ]
+	 *	where h is the interpolation function for node i.
+	 *	Same thing for Bb except the last column that does not exist.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes = this->NumberofNodesPressure();
+	int vnumnodes = this->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(3*vnumnodes);
+	IssmDouble* pbasis =xNew<IssmDouble>(pnumnodes);
+	GetNodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+	GetNodalFunctionsPressure(pbasis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<vnumnodes;i++){
+		B[(3*vnumnodes+pnumnodes)*0+3*i+0] = vdbasis[0*vnumnodes+i];
+		B[(3*vnumnodes+pnumnodes)*0+3*i+1] = 0.;
+		B[(3*vnumnodes+pnumnodes)*0+3*i+2] = 0.;
+		B[(3*vnumnodes+pnumnodes)*1+3*i+0] = 0.;
+		B[(3*vnumnodes+pnumnodes)*1+3*i+1] = vdbasis[1*vnumnodes+i];
+		B[(3*vnumnodes+pnumnodes)*1+3*i+2] = 0.;
+		B[(3*vnumnodes+pnumnodes)*2+3*i+0] = 0.;
+		B[(3*vnumnodes+pnumnodes)*2+3*i+1] = 0.;
+		B[(3*vnumnodes+pnumnodes)*2+3*i+2] = vdbasis[2*vnumnodes+i];
+		B[(3*vnumnodes+pnumnodes)*3+3*i+0] = .5*vdbasis[1*vnumnodes+i];
+		B[(3*vnumnodes+pnumnodes)*3+3*i+1] = .5*vdbasis[0*vnumnodes+i];
+		B[(3*vnumnodes+pnumnodes)*3+3*i+2] = 0.;
+		B[(3*vnumnodes+pnumnodes)*4+3*i+0] = .5*vdbasis[2*vnumnodes+i];
+		B[(3*vnumnodes+pnumnodes)*4+3*i+1] = 0.;
+		B[(3*vnumnodes+pnumnodes)*4+3*i+2] = .5*vdbasis[0*vnumnodes+i];
+		B[(3*vnumnodes+pnumnodes)*5+3*i+0] = 0.;
+		B[(3*vnumnodes+pnumnodes)*5+3*i+1] = .5*vdbasis[2*vnumnodes+i];
+		B[(3*vnumnodes+pnumnodes)*5+3*i+2] = .5*vdbasis[1*vnumnodes+i];
+		B[(3*vnumnodes+pnumnodes)*6+3*i+0] = 0.;
+		B[(3*vnumnodes+pnumnodes)*6+3*i+1] = 0.;
+		B[(3*vnumnodes+pnumnodes)*6+3*i+2] = 0.;
+		B[(3*vnumnodes+pnumnodes)*7+3*i+0] = vdbasis[0*vnumnodes+i];
+		B[(3*vnumnodes+pnumnodes)*7+3*i+1] = vdbasis[1*vnumnodes+i];
+		B[(3*vnumnodes+pnumnodes)*7+3*i+2] = vdbasis[2*vnumnodes+i];
+	}
+	for(int i=0;i<pnumnodes;i++){
+		B[(3*vnumnodes+pnumnodes)*0+(3*vnumnodes)+i] = 0.;
+		B[(3*vnumnodes+pnumnodes)*1+(3*vnumnodes)+i] = 0.;
+		B[(3*vnumnodes+pnumnodes)*2+(3*vnumnodes)+i] = 0.;
+		B[(3*vnumnodes+pnumnodes)*3+(3*vnumnodes)+i] = 0.;
+		B[(3*vnumnodes+pnumnodes)*4+(3*vnumnodes)+i] = 0.;
+		B[(3*vnumnodes+pnumnodes)*5+(3*vnumnodes)+i] = 0.;
+		B[(3*vnumnodes+pnumnodes)*6+(3*vnumnodes)+i] = pbasis[i];
+		B[(3*vnumnodes+pnumnodes)*7+(3*vnumnodes)+i] = 0.;
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+	xDelete<IssmDouble>(pbasis);
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBFSGLS {{{*/
+void PentaRef::GetBFSGLS(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss){
 
 	/*Compute B  matrix. B=[B1 B2 B3 B4 B5 B6] where Bi is of size 3*NDOF4. 
@@ -265,55 +426,132 @@
 
 	int i;
-
-	IssmDouble dh1dh7[3][NUMNODESMINI];
-	IssmDouble l1l6[NUMNODESP1];
-
-	/*Get dh1dh7 in actual coordinate system: */
-	GetNodalFunctionsMINIDerivatives(&dh1dh7[0][0],xyz_list, gauss);
-	GetNodalFunctionsP1(l1l6, gauss);
+	IssmDouble dbasis[3][NUMNODESP1];
+	IssmDouble basis[NUMNODESP1];
+
+	/*Get dbasismini in actual coordinate system: */
+	GetNodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list, gauss);
+	GetNodalFunctionsP1(&basis[0], gauss);
 
 	/*Build B: */
-	for (i=0;i<NUMNODESMINI;i++){
-		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i)=dh1dh7[0][i]; //B[0][NDOF4*i]=dh1dh6[0][i];
-		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+1)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+2)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+1)=dh1dh7[1][i];
-		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+2)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+1)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+2)=dh1dh7[2][i];
-		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i)=(float).5*dh1dh7[1][i]; 
-		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+1)=(float).5*dh1dh7[0][i]; 
-		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+2)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*4+NDOF4*i)=(float).5*dh1dh7[2][i];
-		*(B+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+1)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+2)=(float).5*dh1dh7[0][i];
-		*(B+(NDOF4*NUMNODESP1+3)*5+NDOF4*i)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+1)=(float).5*dh1dh7[2][i];
-		*(B+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+2)=(float).5*dh1dh7[1][i];
-		*(B+(NDOF4*NUMNODESP1+3)*6+NDOF4*i)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+1)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+2)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*7+NDOF4*i)=dh1dh7[0][i];
-		*(B+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+1)=dh1dh7[1][i];
-		*(B+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+2)=dh1dh7[2][i];
-	}
-
-	for (i=0;i<NUMNODESP1;i++){ //last column not for the bubble function
-		*(B+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+3)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+3)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+3)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+3)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+3)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+3)=0;
-		*(B+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+3)=l1l6[i];
-		*(B+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+3)=0;
-	}
-
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetBprimeStokes {{{*/
-void PentaRef::GetBprimeStokes(IssmDouble* B_prime, IssmDouble* xyz_list, GaussPenta* gauss){
+	for(i=0;i<NUMNODESP1;i++){
+		B[(NDOF4*NUMNODESP1)*0+NDOF4*i+0] = dbasis[0][i];
+		B[(NDOF4*NUMNODESP1)*0+NDOF4*i+1] = 0.;
+		B[(NDOF4*NUMNODESP1)*0+NDOF4*i+2] = 0.;
+		B[(NDOF4*NUMNODESP1)*1+NDOF4*i+0] = 0.;
+		B[(NDOF4*NUMNODESP1)*1+NDOF4*i+1] = dbasis[1][i];
+		B[(NDOF4*NUMNODESP1)*1+NDOF4*i+2] = 0.;
+		B[(NDOF4*NUMNODESP1)*2+NDOF4*i+0] = 0.;
+		B[(NDOF4*NUMNODESP1)*2+NDOF4*i+1] = 0.;
+		B[(NDOF4*NUMNODESP1)*2+NDOF4*i+2] = dbasis[2][i];
+		B[(NDOF4*NUMNODESP1)*3+NDOF4*i+0] = .5*dbasis[1][i];
+		B[(NDOF4*NUMNODESP1)*3+NDOF4*i+1] = .5*dbasis[0][i];
+		B[(NDOF4*NUMNODESP1)*3+NDOF4*i+2] = 0.;
+		B[(NDOF4*NUMNODESP1)*4+NDOF4*i+0] = .5*dbasis[2][i];
+		B[(NDOF4*NUMNODESP1)*4+NDOF4*i+1] = 0.;
+		B[(NDOF4*NUMNODESP1)*4+NDOF4*i+2] = .5*dbasis[0][i];
+		B[(NDOF4*NUMNODESP1)*5+NDOF4*i+0] = 0.;
+		B[(NDOF4*NUMNODESP1)*5+NDOF4*i+1] = .5*dbasis[2][i];
+		B[(NDOF4*NUMNODESP1)*5+NDOF4*i+2] = .5*dbasis[1][i];
+		B[(NDOF4*NUMNODESP1)*6+NDOF4*i+0] = 0.;
+		B[(NDOF4*NUMNODESP1)*6+NDOF4*i+1] = 0.;
+		B[(NDOF4*NUMNODESP1)*6+NDOF4*i+2] = 0.;
+		B[(NDOF4*NUMNODESP1)*7+NDOF4*i+0] = dbasis[0][i];
+		B[(NDOF4*NUMNODESP1)*7+NDOF4*i+1] = dbasis[1][i];
+		B[(NDOF4*NUMNODESP1)*7+NDOF4*i+2] = dbasis[2][i];
+	}
+
+	for(i=0;i<NUMNODESP1;i++){ //last column not for the bubble function
+		B[(NDOF4*NUMNODESP1)*0+NDOF4*i+3] = 0.;
+		B[(NDOF4*NUMNODESP1)*1+NDOF4*i+3] = 0.;
+		B[(NDOF4*NUMNODESP1)*2+NDOF4*i+3] = 0.;
+		B[(NDOF4*NUMNODESP1)*3+NDOF4*i+3] = 0.;
+		B[(NDOF4*NUMNODESP1)*4+NDOF4*i+3] = 0.;
+		B[(NDOF4*NUMNODESP1)*5+NDOF4*i+3] = 0.;
+		B[(NDOF4*NUMNODESP1)*6+NDOF4*i+3] = basis[i];
+		B[(NDOF4*NUMNODESP1)*7+NDOF4*i+3] = 0.;
+	}
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBprimeFS {{{*/
+void PentaRef::GetBprimeFS(IssmDouble* B_prime, IssmDouble* xyz_list, GaussPenta* 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' = [  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  ]
+	 *					 [  dh/dx   dh/dy    dh/dz  ]
+	 *					 [   0      0          0    ]
+	 *
+	 * by: 	  Bpi=[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ 0 ]
+	 *					[ h ]
+	 *	where h is the interpolation function for node i.
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes = this->NumberofNodesPressure();
+	int vnumnodes = this->NumberofNodesVelocity();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vdbasis=xNew<IssmDouble>(3*vnumnodes);
+	IssmDouble* pbasis =xNew<IssmDouble>(pnumnodes);
+	GetNodalFunctionsDerivativesVelocity(vdbasis,xyz_list,gauss);
+	GetNodalFunctionsPressure(pbasis,gauss);
+
+	/*Build B_prime: */
+	for(int i=0;i<vnumnodes;i++){
+		B_prime[(3*vnumnodes+pnumnodes)*0+3*i+0] = vdbasis[0*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*0+3*i+1] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*0+3*i+2] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*1+3*i+0] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*1+3*i+1] = vdbasis[1*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*1+3*i+2] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*2+3*i+0] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*2+3*i+1] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*2+3*i+2] = vdbasis[2*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*3+3*i+0] = vdbasis[1*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*3+3*i+1] = vdbasis[0*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*3+3*i+2] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*4+3*i+0] = vdbasis[2*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*4+3*i+1] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*4+3*i+2] = vdbasis[0*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*5+3*i+0] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*5+3*i+1] = vdbasis[2*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*5+3*i+2] = vdbasis[1*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*6+3*i+0] = vdbasis[0*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*6+3*i+1] = vdbasis[1*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*6+3*i+2] = vdbasis[2*vnumnodes+i];
+		B_prime[(3*vnumnodes+pnumnodes)*7+3*i+0] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*7+3*i+1] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*7+3*i+2] = 0.;
+	}
+	for(int i=0;i<pnumnodes;i++){
+		B_prime[(3*vnumnodes+pnumnodes)*0+(3*vnumnodes)+i] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*1+(3*vnumnodes)+i] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*2+(3*vnumnodes)+i] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*3+(3*vnumnodes)+i] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*4+(3*vnumnodes)+i] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*5+(3*vnumnodes)+i] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*6+(3*vnumnodes)+i] = 0.;
+		B_prime[(3*vnumnodes+pnumnodes)*7+(3*vnumnodes)+i] = pbasis[i];
+	}
+
+	/*Clean up*/
+	xDelete<IssmDouble>(vdbasis);
+	xDelete<IssmDouble>(pbasis);
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBprimeFSGLS {{{*/
+void PentaRef::GetBprimeFSGLS(IssmDouble* B_prime, IssmDouble* xyz_list, GaussPenta* 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
@@ -333,48 +571,48 @@
 
 	int i;
-	IssmDouble dh1dh7[3][NUMNODESMINI];
-	IssmDouble l1l6[NUMNODESP1];
-
-	/*Get dh1dh7 in actual coordinate system: */
-	GetNodalFunctionsMINIDerivatives(&dh1dh7[0][0],xyz_list, gauss);
-	GetNodalFunctionsP1(l1l6, gauss);
+	IssmDouble dbasis[3][NUMNODESP1];
+	IssmDouble basis[NUMNODESP1];
+
+	/*Get dbasismini in actual coordinate system: */
+	GetNodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list, gauss);
+	GetNodalFunctionsP1(basis, gauss);
 
 	/*B_primeuild B_prime: */
-	for (i=0;i<NUMNODESMINI;i++){
-		*(B_prime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i)=dh1dh7[0][i]; //B_prime[0][NDOF4*i]=dh1dh6[0][i];
-		*(B_prime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+1)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+2)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+1)=dh1dh7[1][i];
-		*(B_prime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+2)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+1)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+2)=dh1dh7[2][i];
-		*(B_prime+(NDOF4*NUMNODESP1+3)*3+NDOF4*i)=dh1dh7[1][i]; 
-		*(B_prime+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+1)=dh1dh7[0][i]; 
-		*(B_prime+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+2)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*4+NDOF4*i)=dh1dh7[2][i];
-		*(B_prime+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+1)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+2)=dh1dh7[0][i];
-		*(B_prime+(NDOF4*NUMNODESP1+3)*5+NDOF4*i)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+1)=dh1dh7[2][i];
-		*(B_prime+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+2)=dh1dh7[1][i];
-		*(B_prime+(NDOF4*NUMNODESP1+3)*6+NDOF4*i)=dh1dh7[0][i];
-		*(B_prime+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+1)=dh1dh7[1][i];
-		*(B_prime+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+2)=dh1dh7[2][i];
-		*(B_prime+(NDOF4*NUMNODESP1+3)*7+NDOF4*i)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+1)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+2)=0;
-	}
-
-	for (i=0;i<NUMNODESP1;i++){ //last column not for the bubble function
-		*(B_prime+(NDOF4*NUMNODESP1+3)*0+NDOF4*i+3)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*1+NDOF4*i+3)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*2+NDOF4*i+3)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*3+NDOF4*i+3)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*4+NDOF4*i+3)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*5+NDOF4*i+3)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*6+NDOF4*i+3)=0;
-		*(B_prime+(NDOF4*NUMNODESP1+3)*7+NDOF4*i+3)=l1l6[i];
+	for(i=0;i<NUMNODESP1;i++){
+		B_prime[(NDOF4*NUMNODESP1)*0+NDOF4*i+0] = dbasis[0][i];
+		B_prime[(NDOF4*NUMNODESP1)*0+NDOF4*i+1] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*0+NDOF4*i+2] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*1+NDOF4*i+0] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*1+NDOF4*i+1] = dbasis[1][i];
+		B_prime[(NDOF4*NUMNODESP1)*1+NDOF4*i+2] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*2+NDOF4*i+0] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*2+NDOF4*i+1] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*2+NDOF4*i+2] = dbasis[2][i];
+		B_prime[(NDOF4*NUMNODESP1)*3+NDOF4*i+0] = dbasis[1][i];
+		B_prime[(NDOF4*NUMNODESP1)*3+NDOF4*i+1] = dbasis[0][i];
+		B_prime[(NDOF4*NUMNODESP1)*3+NDOF4*i+2] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*4+NDOF4*i+0] = dbasis[2][i];
+		B_prime[(NDOF4*NUMNODESP1)*4+NDOF4*i+1] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*4+NDOF4*i+2] = dbasis[0][i];
+		B_prime[(NDOF4*NUMNODESP1)*5+NDOF4*i+0] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*5+NDOF4*i+1] = dbasis[2][i];
+		B_prime[(NDOF4*NUMNODESP1)*5+NDOF4*i+2] = dbasis[1][i];
+		B_prime[(NDOF4*NUMNODESP1)*6+NDOF4*i+0] = dbasis[0][i];
+		B_prime[(NDOF4*NUMNODESP1)*6+NDOF4*i+1] = dbasis[1][i];
+		B_prime[(NDOF4*NUMNODESP1)*6+NDOF4*i+2] = dbasis[2][i];
+		B_prime[(NDOF4*NUMNODESP1)*7+NDOF4*i+0] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*7+NDOF4*i+1] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*7+NDOF4*i+2] = 0.;
+	}
+
+	for(i=0;i<NUMNODESP1;i++){ //last column 
+		B_prime[(NDOF4*NUMNODESP1)*0+NDOF4*i+3] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*1+NDOF4*i+3] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*2+NDOF4*i+3] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*3+NDOF4*i+3] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*4+NDOF4*i+3] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*5+NDOF4*i+3] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*6+NDOF4*i+3] = 0.;
+		B_prime[(NDOF4*NUMNODESP1)*7+NDOF4*i+3] = - basis[i];
 	}
 
@@ -394,16 +632,20 @@
 	 */
 
-	/*Same thing in the actual coordinate system: */
-	IssmDouble l1l6[6];
-
-	/*Get dh1dh2dh3 in actual coordinates system : */
-	GetNodalFunctionsP1(l1l6, gauss);
-
-	/*Build B': */
-	for (int i=0;i<NUMNODESP1;i++){
-		*(B_advec+NDOF1*NUMNODESP1*0+NDOF1*i)=l1l6[i]; 
-		*(B_advec+NDOF1*NUMNODESP1*1+NDOF1*i)=l1l6[i]; 
-		*(B_advec+NDOF1*NUMNODESP1*2+NDOF1*i)=l1l6[i]; 
-	}
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B_advec[numnodes*0+i] = basis[i];
+		B_advec[numnodes*1+i] = basis[i];
+		B_advec[numnodes*2+i] = basis[i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
 }
 /*}}}*/
@@ -418,19 +660,23 @@
 	 * where h is the interpolation function for node i.
 	 *
-	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
-	 */
-
-	/*Same thing in the actual coordinate system: */
-	IssmDouble dh1dh6[3][NUMNODESP1];
-
-	/*Get dh1dh2dh3 in actual coordinates system : */
-	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list,gauss);
-
-	/*Build B': */
-	for (int i=0;i<NUMNODESP1;i++){
-		*(B_conduct+NDOF1*NUMNODESP1*0+NDOF1*i)=dh1dh6[0][i]; 
-		*(B_conduct+NDOF1*NUMNODESP1*1+NDOF1*i)=dh1dh6[1][i]; 
-		*(B_conduct+NDOF1*NUMNODESP1*2+NDOF1*i)=dh1dh6[2][i]; 
-	}
+	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+
+	/*Build B: */
+	for(int i=0;i<numnodes;i++){
+		B_conduct[numnodes*0+i] = dbasis[0*numnodes+i];
+		B_conduct[numnodes*1+i] = dbasis[1*numnodes+i];
+		B_conduct[numnodes*2+i] = dbasis[2*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
 }
 /*}}}*/
@@ -440,15 +686,18 @@
 		where hi is the interpolation function for node i.*/
 
-	int i;
-	IssmDouble dh1dh6[3][NUMNODESP1];
-
-	/*Get dh1dh6 in actual coordinate system: */
-	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list, gauss);
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 
 	/*Build B: */
-	for (i=0;i<NUMNODESP1;i++){
-		B[i]=dh1dh6[2][i];  
-	}
-
+	for(int i=0;i<numnodes;i++){
+		B[i] = dbasis[2*numnodes+i];  
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
 }
 /*}}}*/
@@ -463,31 +712,34 @@
 	 * where h is the interpolation function for node i.
 	 *
-	 * We assume B has been allocated already, of size: 3x(NDOF1*NUMNODESP1)
-	 */
-
-	/*Same thing in the actual coordinate system: */
-	IssmDouble dh1dh6[3][NUMNODESP1];
-
-	/*Get dh1dh2dh3 in actual coordinates system : */
-	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list,gauss);
+	 * We assume B has been allocated already, of size: 3x(NDOF1*numnodes)
+	 */
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* dbasis=xNew<IssmDouble>(3*numnodes);
+	GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
 
 	/*Build B': */
-	for (int i=0;i<NUMNODESP1;i++){
-		*(Bprime_advec+NDOF1*NUMNODESP1*0+NDOF1*i)=dh1dh6[0][i]; 
-		*(Bprime_advec+NDOF1*NUMNODESP1*1+NDOF1*i)=dh1dh6[1][i]; 
-		*(Bprime_advec+NDOF1*NUMNODESP1*2+NDOF1*i)=dh1dh6[2][i]; 
-	}
+	for(int i=0;i<numnodes;i++){
+		Bprime_advec[numnodes*0+i] = dbasis[0*numnodes+i];
+		Bprime_advec[numnodes*1+i] = dbasis[1*numnodes+i];
+		Bprime_advec[numnodes*2+i] = dbasis[2*numnodes+i];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(dbasis);
 }
 /*}}}*/
 /*FUNCTION PentaRef::GetBprimeVert{{{*/
 void PentaRef::GetBprimeVert(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss){
-	/* Compute Bprime  matrix. Bprime=[L1 L2 L3 L4 L5 L6] where Li is the nodal function for node i*/
-
-	GetNodalFunctionsP1(B, gauss);
-
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetBPattynFriction{{{*/
-void PentaRef::GetBPattynFriction(IssmDouble* B, GaussPenta* gauss){
+
+	GetNodalFunctions(B,gauss);
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetBHOFriction{{{*/
+void PentaRef::GetBHOFriction(IssmDouble* B, GaussPenta* gauss){
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is square and of size 2x2. 
 	 ** For node i, Bi can be expressed in the actual coordinate system
@@ -500,57 +752,65 @@
 	 **/
 
-	IssmDouble basis[6];
-
-	/*Get l1l6 in actual coordinate system: */
-	GetNodalFunctionsP1(&basis[0],gauss);
-
-	for(int i=0;i<NUMNODESP1;i++){
-		B[2*NUMNODESP1*0+2*i+0]=basis[i]; 
-		B[2*NUMNODESP1*0+2*i+1]=0.;
-		B[2*NUMNODESP1*1+2*i+0]=0.;
-		B[2*NUMNODESP1*1+2*i+1]=basis[i];
-	}
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* basis=xNew<IssmDouble>(numnodes);
+	GetNodalFunctions(basis,gauss);
+
+	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];
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(basis);
 } 
 /*}}}*/
-/*FUNCTION PentaRef::GetLStokes{{{*/
-void PentaRef::GetLStokes(IssmDouble* LStokes, GaussPenta* gauss){
-	/*
-	 * Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+/*FUNCTION PentaRef::GetLFS{{{*/
+void PentaRef::GetLFS(IssmDouble* LFS, GaussPenta* 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: 
-	 *       Li=[ h 0 ]
-	 *	 	      [ 0 h ]
-	 *		      [ 0 0 ]
-	 *		      [ 0 0 ]
+	 *       Li=[ h 0 0 0 ]
+	 *	 	      [ 0 h 0 0 ]
 	 * where h is the interpolation function for node i.
 	 */
 
-	const int num_dof=4;
-	IssmDouble l1l2l3[NUMNODESP1_2d];
-
-	/*Get l1l2l3 in actual coordinate system: */
-	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
-
-	/*Build LStokes: */
-	for (int i=0;i<3;i++){
-		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+0)=l1l2l3[i];
-		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0.;
-		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+2)=0.;
-		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+3)=0.;
-
-		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+0)=0.;
-		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
-		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+2)=0.;
-		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+3)=0.;
-	}
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetLprimeStokes {{{*/
-void PentaRef::GetLprimeStokes(IssmDouble* LprimeStokes, IssmDouble* xyz_list, GaussPenta* gauss){
-
-	/*
-	 * Compute Lprime  matrix. Lprime=[Lp1 Lp2 Lp3] where Lpi is square and of size numdof. 
+	/*Fetch number of nodes for this finite element*/
+	int pnumnodes = this->NumberofNodesPressure();
+	int vnumnodes = this->NumberofNodesVelocity();
+	int pnumdof   = pnumnodes;
+	int vnumdof   = vnumnodes*NDOF3;
+
+	/*Get nodal functions derivatives*/
+	IssmDouble* vbasis=xNew<IssmDouble>(vnumnodes);
+	GetNodalFunctionsVelocity(vbasis,gauss);
+
+	/*Build LFS: */
+	for(int i=0;i<vnumnodes;i++){
+		LFS[(vnumdof+pnumdof)*0+3*i+0] = vbasis[i];
+		LFS[(vnumdof+pnumdof)*0+3*i+1] = 0.;
+		LFS[(vnumdof+pnumdof)*0+3*i+2] = 0.;
+
+		LFS[(vnumdof+pnumdof)*1+3*i+0] = 0.;
+		LFS[(vnumdof+pnumdof)*1+3*i+1] = vbasis[i];
+		LFS[(vnumdof+pnumdof)*1+3*i+2] = 0.;
+	}
+
+	for(int i=0;i<pnumnodes;i++){
+		LFS[(vnumdof+pnumdof)*0+i+vnumdof+0] = 0.;
+		LFS[(vnumdof+pnumdof)*1+i+vnumdof+0] = 0.;
+	}
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(vbasis);
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetLprimeFS {{{*/
+void PentaRef::GetLprimeFS(IssmDouble* LprimeFS, IssmDouble* xyz_list, GaussPenta* gauss){
+	/* 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: 
@@ -589,77 +849,77 @@
 	int num_dof=4;
 
-	IssmDouble l1l2l3[NUMNODESP1_2d];
-	IssmDouble dh1dh6[3][NUMNODESP1];
-
-	/*Get l1l2l3 in actual coordinate system: */
-	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
-
-	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list,gauss);
-
-	/*Build LprimeStokes: */
-	for (i=0;i<3;i++){
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i)=l1l2l3[i]; //LprimeStokes[0][NDOF2*i]=dh1dh3[0][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+2)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+2)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+2)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+1)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+2)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+2)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+2)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+2)=dh1dh6[2][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+2)=dh1dh6[2][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*8+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*8+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*8+num_dof*i+2)=dh1dh6[2][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*8+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*9+num_dof*i)=dh1dh6[2][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*9+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*9+num_dof*i+2)=dh1dh6[0][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*9+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*10+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*10+num_dof*i+1)=dh1dh6[2][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*10+num_dof*i+2)=dh1dh6[1][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*10+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*11+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*11+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*11+num_dof*i+2)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*11+num_dof*i+3)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*12+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*12+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*12+num_dof*i+2)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*12+num_dof*i+3)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*13+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*13+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*13+num_dof*i+2)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*13+num_dof*i+3)=l1l2l3[i];
-	}
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetLMacAyealStokes {{{*/
-void PentaRef::GetLMacAyealStokes(IssmDouble* LStokes, GaussPenta* gauss){
+	IssmDouble L1L2l3[NUMNODESP1_2d];
+	IssmDouble dbasis[3][NUMNODESP1];
+
+	/*Get L1L2l3 in actual coordinate system: */
+	L1L2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	L1L2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	L1L2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	GetNodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build LprimeFS: */
+	for(int i=0;i<3;i++){
+		LprimeFS[num_dof*NUMNODESP1_2d*0+num_dof*i+0]  = L1L2l3[i];
+		LprimeFS[num_dof*NUMNODESP1_2d*0+num_dof*i+1]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*0+num_dof*i+2]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*0+num_dof*i+3]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*1+num_dof*i+0]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*1+num_dof*i+1]  = L1L2l3[i];
+		LprimeFS[num_dof*NUMNODESP1_2d*1+num_dof*i+2]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*1+num_dof*i+3]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*2+num_dof*i+0]  = L1L2l3[i];
+		LprimeFS[num_dof*NUMNODESP1_2d*2+num_dof*i+1]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*2+num_dof*i+2]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*2+num_dof*i+3]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*3+num_dof*i+0]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*3+num_dof*i+1]  = L1L2l3[i];
+		LprimeFS[num_dof*NUMNODESP1_2d*3+num_dof*i+2]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*3+num_dof*i+3]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*4+num_dof*i+0]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*4+num_dof*i+1]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*4+num_dof*i+2]  = L1L2l3[i];
+		LprimeFS[num_dof*NUMNODESP1_2d*4+num_dof*i+3]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*5+num_dof*i+0]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*5+num_dof*i+1]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*5+num_dof*i+2]  = L1L2l3[i];
+		LprimeFS[num_dof*NUMNODESP1_2d*5+num_dof*i+3]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*6+num_dof*i+0]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*6+num_dof*i+1]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*6+num_dof*i+2]  = dbasis[2][i];
+		LprimeFS[num_dof*NUMNODESP1_2d*6+num_dof*i+3]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*7+num_dof*i+0]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*7+num_dof*i+1]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*7+num_dof*i+2]  = dbasis[2][i];
+		LprimeFS[num_dof*NUMNODESP1_2d*7+num_dof*i+3]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*8+num_dof*i+0]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*8+num_dof*i+1]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*8+num_dof*i+2]  = dbasis[2][i];
+		LprimeFS[num_dof*NUMNODESP1_2d*8+num_dof*i+3]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*9+num_dof*i+0]  = dbasis[2][i];
+		LprimeFS[num_dof*NUMNODESP1_2d*9+num_dof*i+1]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*9+num_dof*i+2]  = dbasis[0][i];
+		LprimeFS[num_dof*NUMNODESP1_2d*9+num_dof*i+3]  = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*10+num_dof*i+0] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*10+num_dof*i+1] = dbasis[2][i];
+		LprimeFS[num_dof*NUMNODESP1_2d*10+num_dof*i+2] = dbasis[1][i];
+		LprimeFS[num_dof*NUMNODESP1_2d*10+num_dof*i+3] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*11+num_dof*i+0] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*11+num_dof*i+1] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*11+num_dof*i+2] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*11+num_dof*i+3] = L1L2l3[i];
+		LprimeFS[num_dof*NUMNODESP1_2d*12+num_dof*i+0] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*12+num_dof*i+1] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*12+num_dof*i+2] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*12+num_dof*i+3] = L1L2l3[i];
+		LprimeFS[num_dof*NUMNODESP1_2d*13+num_dof*i+0] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*13+num_dof*i+1] = 0;
+		LprimeFS[num_dof*NUMNODESP1_2d*13+num_dof*i+2] = 0;
+		LprimeFS[num_dof*NUMNODESP1_2d*13+num_dof*i+3] = L1L2l3[i];
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetLSSAFS {{{*/
+void PentaRef::GetLSSAFS(IssmDouble* LFS, GaussPenta* gauss){
 	/*
 	 * Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
@@ -677,41 +937,36 @@
 	 */
 
-	int i;
 	int num_dof=2;
-
-	IssmDouble l1l2l3[NUMNODESP1_2d];
-
-	/*Get l1l2l3 in actual coordinate system: */
-	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
-
-	/*Build LStokes: */
-	for (i=0;i<3;i++){
-		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i)=l1l2l3[i]; //LStokes[0][NDOF2*i]=dh1dh3[0][i];
-		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
-		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i)=l1l2l3[i];
-		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+1)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+1)=l1l2l3[i];
-		*(LStokes+num_dof*NUMNODESP1_2d*4+num_dof*i)=l1l2l3[i];
-		*(LStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+1)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*5+num_dof*i)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+1)=l1l2l3[i];
-		*(LStokes+num_dof*NUMNODESP1_2d*6+num_dof*i)=l1l2l3[i];
-		*(LStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+1)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*7+num_dof*i)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+1)=l1l2l3[i];
-
-	}
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetLprimeMacAyealStokes {{{*/
-void PentaRef::GetLprimeMacAyealStokes(IssmDouble* LprimeStokes, IssmDouble* xyz_list, GaussPenta* gauss){
-
-	/*
-	 * Compute Lprime  matrix. Lprime=[Lp1 Lp2 Lp3] where Lpi is square and of size numdof. 
+	IssmDouble L1L2l3[NUMNODESP1_2d];
+
+	/*Get L1L2l3 in actual coordinate system: */
+	L1L2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	L1L2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	L1L2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	/*Build LFS: */
+	for(int i=0;i<3;i++){
+		LFS[num_dof*NUMNODESP1_2d*0+num_dof*i+0] = L1L2l3[i];
+		LFS[num_dof*NUMNODESP1_2d*0+num_dof*i+1] = 0;
+		LFS[num_dof*NUMNODESP1_2d*1+num_dof*i+0] = 0;
+		LFS[num_dof*NUMNODESP1_2d*1+num_dof*i+1] = L1L2l3[i];
+		LFS[num_dof*NUMNODESP1_2d*2+num_dof*i+0] = L1L2l3[i];
+		LFS[num_dof*NUMNODESP1_2d*2+num_dof*i+1] = 0;
+		LFS[num_dof*NUMNODESP1_2d*3+num_dof*i+0] = 0;
+		LFS[num_dof*NUMNODESP1_2d*3+num_dof*i+1] = L1L2l3[i];
+		LFS[num_dof*NUMNODESP1_2d*4+num_dof*i+0] = L1L2l3[i];
+		LFS[num_dof*NUMNODESP1_2d*4+num_dof*i+1] = 0;
+		LFS[num_dof*NUMNODESP1_2d*5+num_dof*i+0] = 0;
+		LFS[num_dof*NUMNODESP1_2d*5+num_dof*i+1] = L1L2l3[i];
+		LFS[num_dof*NUMNODESP1_2d*6+num_dof*i+0] = L1L2l3[i];
+		LFS[num_dof*NUMNODESP1_2d*6+num_dof*i+1] = 0;
+		LFS[num_dof*NUMNODESP1_2d*7+num_dof*i+0] = 0;
+		LFS[num_dof*NUMNODESP1_2d*7+num_dof*i+1] = L1L2l3[i];
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetLprimeSSAFS {{{*/
+void PentaRef::GetLprimeSSAFS(IssmDouble* LprimeFS, IssmDouble* xyz_list, GaussPenta* gauss){
+	/* 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: 
@@ -726,104 +981,132 @@
 	 * where h is the interpolation function for node i.
 	 */
-	int i;
-	int num_dof=4;
-
-	IssmDouble l1l2l3[NUMNODESP1_2d];
-	IssmDouble dh1dh6[3][NUMNODESP1];
-
-	/*Get l1l2l3 in actual coordinate system: */
-	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
-
-	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list,gauss);
-
-	/*Build LprimeStokes: */
-	for (i=0;i<3;i++){
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i)=l1l2l3[i]; //LprimeStokes[0][NDOF2*i]=dh1dh3[0][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+2)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+2)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+2)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+2)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+2)=dh1dh6[2][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*4+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+2)=dh1dh6[2][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*5+num_dof*i+3)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+2)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*6+num_dof*i+3)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+2)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*7+num_dof*i+3)=l1l2l3[i];
-	}
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetLStokesMacAyeal {{{*/
-void PentaRef::GetLStokesMacAyeal(IssmDouble* LStokes, GaussPenta* gauss){
-	/*
-	 * Compute L  matrix. L=[L1 L2 L3] where Li is square and of size numdof. 
+	int num_dof=3;
+	int num_dof_vel=3*NUMNODESP1b;
+	int num_dof_total=3*NUMNODESP1b+1*NUMNODESP1;
+	IssmDouble L1L2l3[NUMNODESP1_2d];
+	IssmDouble dbasis[3][NUMNODESP1];
+
+	/*Get L1L2l3 in actual coordinate system: */
+	L1L2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	L1L2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	L1L2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	GetNodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build LprimeFS: */
+	for(int i=0;i<3;i++){
+		LprimeFS[num_dof_total*0+num_dof*i+0] = L1L2l3[i];
+		LprimeFS[num_dof_total*0+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*0+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*1+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*1+num_dof*i+1] = L1L2l3[i];
+		LprimeFS[num_dof_total*1+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+2] = L1L2l3[i];
+		LprimeFS[num_dof_total*3+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*3+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*3+num_dof*i+2] = L1L2l3[i];
+		LprimeFS[num_dof_total*4+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*4+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*4+num_dof*i+2] = dbasis[2][i];
+		LprimeFS[num_dof_total*5+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*5+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*5+num_dof*i+2] = dbasis[2][i];
+		LprimeFS[num_dof_total*6+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*6+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*6+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+2] = 0.;
+	}
+	for(int i=3;i<7;i++){
+		LprimeFS[num_dof_total*0+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*0+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*0+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*1+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*1+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*1+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*2+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*3+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*3+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*3+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*4+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*4+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*4+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*5+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*5+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*5+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*6+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*6+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*6+num_dof*i+2] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+0] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+1] = 0.;
+		LprimeFS[num_dof_total*7+num_dof*i+2] = 0.;
+	}
+	for(int i=0;i<3;i++){
+		LprimeFS[num_dof_total*0+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*1+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*2+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*3+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*4+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*5+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*6+num_dof_vel+i] = L1L2l3[i];
+		LprimeFS[num_dof_total*7+num_dof_vel+i] = L1L2l3[i];
+	}
+	for(int i=3;i<6;i++){
+		LprimeFS[num_dof_total*0+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*1+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*2+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*3+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*4+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*5+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*6+num_dof_vel+i] = 0.;
+		LprimeFS[num_dof_total*7+num_dof_vel+i] = 0.;
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetLFSSSA {{{*/
+void PentaRef::GetLFSSSA(IssmDouble* LFS, GaussPenta* 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: 
-	 *       Li=[ h    0    0   0]
-	 *	 	      [ 0    h    0   0]
-	 *		      [ 0    0    h   0]
-	 *		      [ 0    0    h   0]
+	 *       Li=[ h    0    0 ]
+	 *	 	      [ 0    h    0 ]
+	 *		      [ 0    0    h ]
+	 *		      [ 0    0    h ]
 	 * where h is the interpolation function for node i.
 	 */
 
-	int i;
-	int num_dof=4;
-
-	IssmDouble l1l2l3[NUMNODESP1_2d];
-
-	/*Get l1l2l3 in actual coordinate system: */
-	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
-
-	/*Build LStokes: */
-	for (i=0;i<3;i++){
-		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i)=l1l2l3[i]; //LStokes[0][NDOF2*i]=dh1dh3[0][i];
-		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+2)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+3)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
-		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+2)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+3)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+1)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+2)=l1l2l3[i];
-		*(LStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+3)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+1)=0;
-		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+2)=l1l2l3[i];
-		*(LStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+3)=0;
-
-	}
-}
-/*}}}*/
-/*FUNCTION PentaRef::GetLprimeStokesMacAyeal {{{*/
-void PentaRef::GetLprimeStokesMacAyeal(IssmDouble* LprimeStokes, IssmDouble* xyz_list, GaussPenta* gauss){
-
-	/*
-	 * Compute Lprime  matrix. Lprime=[Lp1 Lp2 Lp3] where Lpi is square and of size numdof. 
+	int num_dof=3;
+	IssmDouble L1L2l3[NUMNODESP1_2d];
+
+	/*Get L1L2l3 in actual coordinate system: */
+	L1L2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	L1L2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	L1L2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+
+	/*Build LFS: */
+	for(int i=0;i<3;i++){
+		LFS[num_dof*NUMNODESP1_2d*0+num_dof*i+0] = L1L2l3[i];
+		LFS[num_dof*NUMNODESP1_2d*0+num_dof*i+1] = 0.;
+		LFS[num_dof*NUMNODESP1_2d*0+num_dof*i+2] = 0.;
+		LFS[num_dof*NUMNODESP1_2d*1+num_dof*i+0] = 0.;
+		LFS[num_dof*NUMNODESP1_2d*1+num_dof*i+1] = L1L2l3[i];
+		LFS[num_dof*NUMNODESP1_2d*1+num_dof*i+2] = 0.;
+		LFS[num_dof*NUMNODESP1_2d*2+num_dof*i+0] = 0.;
+		LFS[num_dof*NUMNODESP1_2d*2+num_dof*i+1] = 0.;
+		LFS[num_dof*NUMNODESP1_2d*2+num_dof*i+2] = L1L2l3[i];
+		LFS[num_dof*NUMNODESP1_2d*3+num_dof*i+0] = 0.;
+		LFS[num_dof*NUMNODESP1_2d*3+num_dof*i+1] = 0.;
+		LFS[num_dof*NUMNODESP1_2d*3+num_dof*i+2] = L1L2l3[i];
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetLprimeFSSSA {{{*/
+void PentaRef::GetLprimeFSSSA(IssmDouble* LprimeFS, IssmDouble* xyz_list, GaussPenta* gauss){
+	/* 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: 
@@ -834,27 +1117,24 @@
 	 * where h is the interpolation function for node i.
 	 */
-	int i;
 	int num_dof=2;
-
-	IssmDouble l1l2l3[NUMNODESP1_2d];
-	IssmDouble dh1dh6[3][NUMNODESP1];
-
-	/*Get l1l2l3 in actual coordinate system: */
-	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	l1l2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	l1l2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
-
-	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list,gauss);
-
-	/*Build LprimeStokes: */
-	for (i=0;i<3;i++){
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i)=l1l2l3[i]; //LprimeStokes[0][NDOF2*i]=dh1dh3[0][i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*0+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*1+num_dof*i+1)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i)=l1l2l3[i];
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*2+num_dof*i+1)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i)=0;
-		*(LprimeStokes+num_dof*NUMNODESP1_2d*3+num_dof*i+1)=l1l2l3[i];
+	IssmDouble L1L2l3[NUMNODESP1_2d];
+	IssmDouble dbasis[3][NUMNODESP1];
+
+	/*Get L1L2l3 in actual coordinate system: */
+	L1L2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	L1L2l3[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	L1L2l3[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+	GetNodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list,gauss);
+
+	/*Build LprimeFS: */
+	for(int i=0;i<3;i++){
+		LprimeFS[num_dof*NUMNODESP1_2d*0+num_dof*i+0] = L1L2l3[i];
+		LprimeFS[num_dof*NUMNODESP1_2d*0+num_dof*i+1] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*1+num_dof*i+0] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*1+num_dof*i+1] = L1L2l3[i];
+		LprimeFS[num_dof*NUMNODESP1_2d*2+num_dof*i+0] = L1L2l3[i];
+		LprimeFS[num_dof*NUMNODESP1_2d*2+num_dof*i+1] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*3+num_dof*i+0] = 0.;
+		LprimeFS[num_dof*NUMNODESP1_2d*3+num_dof*i+1] = L1L2l3[i];
 	}
 }
@@ -862,11 +1142,9 @@
 /*FUNCTION PentaRef::GetJacobian {{{*/
 void PentaRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussPenta* gauss){
-
 	/*The Jacobian is constant over the element, discard the gaussian points. 
 	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
 
-	IssmDouble A1,A2,A3; //area coordinates
-	IssmDouble xi,eta,zi; //parametric coordinates
-
+	IssmDouble A1,A2,A3;  // area coordinates
+	IssmDouble xi,eta,zi; // parametric coordinates
 	IssmDouble x1,x2,x3,x4,x5,x6;
 	IssmDouble y1,y2,y3,y4,y5,y6;
@@ -874,45 +1152,43 @@
 
 	/*Figure out xi,eta and zi (parametric coordinates), for this gaussian point: */
-	A1=gauss->coord1;
-	A2=gauss->coord2;
-	A3=gauss->coord3;
-
+	A1  = gauss->coord1;
+	A2  = gauss->coord2;
+	A3  = gauss->coord3;
 	xi  = A2-A1;
 	eta = SQRT3*A3;
 	zi  = gauss->coord4;
 
-	x1=*(xyz_list+3*0+0);
-	x2=*(xyz_list+3*1+0);
-	x3=*(xyz_list+3*2+0);
-	x4=*(xyz_list+3*3+0);
-	x5=*(xyz_list+3*4+0);
-	x6=*(xyz_list+3*5+0);
-
-	y1=*(xyz_list+3*0+1);
-	y2=*(xyz_list+3*1+1);
-	y3=*(xyz_list+3*2+1);
-	y4=*(xyz_list+3*3+1);
-	y5=*(xyz_list+3*4+1);
-	y6=*(xyz_list+3*5+1);
-
-	z1=*(xyz_list+3*0+2);
-	z2=*(xyz_list+3*1+2);
-	z3=*(xyz_list+3*2+2);
-	z4=*(xyz_list+3*3+2);
-	z5=*(xyz_list+3*4+2);
-	z6=*(xyz_list+3*5+2);
-
-	*(J+NDOF3*0+0)=0.25*(x1-x2-x4+x5)*zi+0.25*(-x1+x2-x4+x5);
-	*(J+NDOF3*1+0)=SQRT3/12.0*(x1+x2-2*x3-x4-x5+2*x6)*zi+SQRT3/12.0*(-x1-x2+2*x3-x4-x5+2*x6);
-	*(J+NDOF3*2+0)=SQRT3/12.0*(x1+x2-2*x3-x4-x5+2*x6)*eta+1/4*(x1-x2-x4+x5)*xi +0.25*(-x1+x5-x2+x4);
-
-	*(J+NDOF3*0+1)=0.25*(y1-y2-y4+y5)*zi+0.25*(-y1+y2-y4+y5);
-	*(J+NDOF3*1+1)=SQRT3/12.0*(y1+y2-2*y3-y4-y5+2*y6)*zi+SQRT3/12.0*(-y1-y2+2*y3-y4-y5+2*y6);
-	*(J+NDOF3*2+1)=SQRT3/12.0*(y1+y2-2*y3-y4-y5+2*y6)*eta+0.25*(y1-y2-y4+y5)*xi+0.25*(y4-y1+y5-y2);
-
-	*(J+NDOF3*0+2)=0.25*(z1-z2-z4+z5)*zi+0.25*(-z1+z2-z4+z5);
-	*(J+NDOF3*1+2)=SQRT3/12.0*(z1+z2-2*z3-z4-z5+2*z6)*zi+SQRT3/12.0*(-z1-z2+2*z3-z4-z5+2*z6);
-	*(J+NDOF3*2+2)=SQRT3/12.0*(z1+z2-2*z3-z4-z5+2*z6)*eta+0.25*(z1-z2-z4+z5)*xi+0.25*(-z1+z5-z2+z4);
-
+	x1=xyz_list[3*0+0];
+	x2=xyz_list[3*1+0];
+	x3=xyz_list[3*2+0];
+	x4=xyz_list[3*3+0];
+	x5=xyz_list[3*4+0];
+	x6=xyz_list[3*5+0];
+
+	y1=xyz_list[3*0+1];
+	y2=xyz_list[3*1+1];
+	y3=xyz_list[3*2+1];
+	y4=xyz_list[3*3+1];
+	y5=xyz_list[3*4+1];
+	y6=xyz_list[3*5+1];
+
+	z1=xyz_list[3*0+2];
+	z2=xyz_list[3*1+2];
+	z3=xyz_list[3*2+2];
+	z4=xyz_list[3*3+2];
+	z5=xyz_list[3*4+2];
+	z6=xyz_list[3*5+2];
+
+	J[NDOF3*0+0] = 0.25*(x1-x2-x4+x5)*zi+0.25*(-x1+x2-x4+x5);
+	J[NDOF3*1+0] = SQRT3/12.0*(x1+x2-2*x3-x4-x5+2*x6)*zi+SQRT3/12.0*(-x1-x2+2*x3-x4-x5+2*x6);
+	J[NDOF3*2+0] = SQRT3/12.0*(x1+x2-2*x3-x4-x5+2*x6)*eta+1/4*(x1-x2-x4+x5)*xi +0.25*(-x1+x5-x2+x4);
+
+	J[NDOF3*0+1] = 0.25*(y1-y2-y4+y5)*zi+0.25*(-y1+y2-y4+y5);
+	J[NDOF3*1+1] = SQRT3/12.0*(y1+y2-2*y3-y4-y5+2*y6)*zi+SQRT3/12.0*(-y1-y2+2*y3-y4-y5+2*y6);
+	J[NDOF3*2+1] = SQRT3/12.0*(y1+y2-2*y3-y4-y5+2*y6)*eta+0.25*(y1-y2-y4+y5)*xi+0.25*(y4-y1+y5-y2);
+
+	J[NDOF3*0+2] = 0.25*(z1-z2-z4+z5)*zi+0.25*(-z1+z2-z4+z5);
+	J[NDOF3*1+2] = SQRT3/12.0*(z1+z2-2*z3-z4-z5+2*z6)*zi+SQRT3/12.0*(-z1-z2+2*z3-z4-z5+2*z6);
+	J[NDOF3*2+2] = SQRT3/12.0*(z1+z2-2*z3-z4-z5+2*z6)*eta+0.25*(z1-z2-z4+z5)*xi+0.25*(-z1+z5-z2+z4);
 }
 /*}}}*/
@@ -937,21 +1213,19 @@
 	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
 
-	IssmDouble x1,x2,x3,y1,y2,y3,z1,z2,z3;
-
-	x1=*(xyz_list+3*0+0);
-	y1=*(xyz_list+3*0+1);
-	z1=*(xyz_list+3*0+2);
-	x2=*(xyz_list+3*1+0);
-	y2=*(xyz_list+3*1+1);
-	z2=*(xyz_list+3*1+2);
-	x3=*(xyz_list+3*2+0);
-	y3=*(xyz_list+3*2+1);
-	z3=*(xyz_list+3*2+2);
+	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.0*pow(pow(((y2-y1)*(z3-z1)-(z2-z1)*(y3-y1)),2.0)+pow(((z2-z1)*(x3-x1)-(x2-x1)*(z3-z1)),2.0)+pow(((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)),2.0),0.5);
+	*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!");
 }
-/*}}}*/
+/*}}}*
 /*FUNCTION PentaRef::GetSegmentJacobianDeterminant{{{*/
 void PentaRef::GetSegmentJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussPenta* gauss){
@@ -959,14 +1233,12 @@
 	 * J is assumed to have been allocated of size NDOF2xNDOF2.*/
 
-	IssmDouble x1,x2,y1,y2,z1,z2;
-
-	x1=*(xyz_list+3*0+0);
-	y1=*(xyz_list+3*0+1);
-	z1=*(xyz_list+3*0+2);
-	x2=*(xyz_list+3*1+0);
-	y2=*(xyz_list+3*1+1);
-	z2=*(xyz_list+3*1+2);
-
-	*Jdet=1.0/2.0*sqrt(pow(x2-x1,2.) + pow(y2-y1,2.) + pow(z2-z1,2.));
+	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!");
 
@@ -992,22 +1264,143 @@
 	_assert_(basis);
 
+	/*Get current coordinates in reference element*/
+	IssmDouble zeta=gauss->coord4;
+
 	switch(this->element_type){
-		case P1Enum:
-		case P1DGEnum:
-			basis[0]=gauss->coord1*(1.-gauss->coord4)/2.;
-			basis[1]=gauss->coord2*(1.-gauss->coord4)/2.;
-			basis[2]=gauss->coord3*(1.-gauss->coord4)/2.;
-			basis[3]=gauss->coord1*(1.+gauss->coord4)/2.;
-			basis[4]=gauss->coord2*(1.+gauss->coord4)/2.;
-			basis[5]=gauss->coord3*(1.+gauss->coord4)/2.;
+		case P1Enum: case P1DGEnum:
+			basis[0]=gauss->coord1*(1.-zeta)/2.;
+			basis[1]=gauss->coord2*(1.-zeta)/2.;
+			basis[2]=gauss->coord3*(1.-zeta)/2.;
+			basis[3]=gauss->coord1*(1.+zeta)/2.;
+			basis[4]=gauss->coord2*(1.+zeta)/2.;
+			basis[5]=gauss->coord3*(1.+zeta)/2.;
+			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			basis[0]=gauss->coord1*(1.-zeta)/2.;
+			basis[1]=gauss->coord2*(1.-zeta)/2.;
+			basis[2]=gauss->coord3*(1.-zeta)/2.;
+			basis[3]=gauss->coord1*(1.+zeta)/2.;
+			basis[4]=gauss->coord2*(1.+zeta)/2.;
+			basis[5]=gauss->coord3*(1.+zeta)/2.;
+			basis[6]=27.*gauss->coord1*gauss->coord2*gauss->coord3*(1.+zeta)*(1.-zeta);
+			return;
+		case P2xP1Enum:
+			/*Corner nodes*/
+			basis[ 0]=gauss->coord1*(2.*gauss->coord1-1.)*(1.-zeta)/2.;
+			basis[ 1]=gauss->coord2*(2.*gauss->coord2-1.)*(1.-zeta)/2.;
+			basis[ 2]=gauss->coord3*(2.*gauss->coord3-1.)*(1.-zeta)/2.;
+			basis[ 3]=gauss->coord1*(2.*gauss->coord1-1.)*(1.+zeta)/2.;
+			basis[ 4]=gauss->coord2*(2.*gauss->coord2-1.)*(1.+zeta)/2.;
+			basis[ 5]=gauss->coord3*(2.*gauss->coord3-1.)*(1.+zeta)/2.;
+			/*mid-sides of triangles*/
+			basis[ 6]=4.*gauss->coord3*gauss->coord2*(1.-zeta)/2.;
+			basis[ 7]=4.*gauss->coord3*gauss->coord1*(1.-zeta)/2.;
+			basis[ 8]=4.*gauss->coord1*gauss->coord2*(1.-zeta)/2.;
+			basis[ 9]=4.*gauss->coord3*gauss->coord2*(1.+zeta)/2.;
+			basis[10]=4.*gauss->coord3*gauss->coord1*(1.+zeta)/2.;
+			basis[11]=4.*gauss->coord1*gauss->coord2*(1.+zeta)/2.;
+			return;
+		case P1xP2Enum:
+			/*Corner nodes*/
+			basis[ 0]=gauss->coord1*zeta*(zeta-1.)/2.;
+			basis[ 1]=gauss->coord2*zeta*(zeta-1.)/2.;
+			basis[ 2]=gauss->coord3*zeta*(zeta-1.)/2.;
+			basis[ 3]=gauss->coord1*zeta*(zeta+1.)/2.;
+			basis[ 4]=gauss->coord2*zeta*(zeta+1.)/2.;
+			basis[ 5]=gauss->coord3*zeta*(zeta+1.)/2.;
+			/*mid-sides of quads*/
+			basis[ 6]=gauss->coord1*(1.-zeta*zeta);
+			basis[ 7]=gauss->coord2*(1.-zeta*zeta);
+			basis[ 8]=gauss->coord3*(1.-zeta*zeta);
+			return;
+		case P2Enum:
+			/*Corner nodes*/
+			basis[ 0]=gauss->coord1*(2.*gauss->coord1-1.)*zeta*(zeta-1.)/2.;
+			basis[ 1]=gauss->coord2*(2.*gauss->coord2-1.)*zeta*(zeta-1.)/2.;
+			basis[ 2]=gauss->coord3*(2.*gauss->coord3-1.)*zeta*(zeta-1.)/2.;
+			basis[ 3]=gauss->coord1*(2.*gauss->coord1-1.)*zeta*(zeta+1.)/2.;
+			basis[ 4]=gauss->coord2*(2.*gauss->coord2-1.)*zeta*(zeta+1.)/2.;
+			basis[ 5]=gauss->coord3*(2.*gauss->coord3-1.)*zeta*(zeta+1.)/2.;
+			/*mid-sides of quads*/
+			basis[ 6]=gauss->coord1*(1.-zeta*zeta);
+			basis[ 7]=gauss->coord2*(1.-zeta*zeta);
+			basis[ 8]=gauss->coord3*(1.-zeta*zeta);
+			/*mid-sides of triangles*/
+			basis[ 9]=2.*gauss->coord3*gauss->coord2*zeta*(zeta-1.);
+			basis[10]=2.*gauss->coord3*gauss->coord1*zeta*(zeta-1.);
+			basis[11]=2.*gauss->coord1*gauss->coord2*zeta*(zeta-1.);
+			basis[12]=2.*gauss->coord3*gauss->coord2*zeta*(zeta+1.);
+			basis[13]=2.*gauss->coord3*gauss->coord1*zeta*(zeta+1.);
+			basis[14]=2.*gauss->coord1*gauss->coord2*zeta*(zeta+1.);
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsVelocity{{{*/
+void PentaRef::GetNodalFunctionsVelocity(IssmDouble* basis,GaussPenta* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	switch(this->element_type){
+		case P1P1Enum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = P1P1Enum;
+			return;
+		case P1P1GLSEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = P1P1GLSEnum;
+			return;
+		case MINIcondensedEnum:
+			this->element_type = P1bubbleEnum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = MINIcondensedEnum;
 			return;
 		case MINIEnum:
-			basis[0]=gauss->coord1*(1.-gauss->coord4)/2.;
-			basis[1]=gauss->coord2*(1.-gauss->coord4)/2.;
-			basis[2]=gauss->coord3*(1.-gauss->coord4)/2.;
-			basis[3]=gauss->coord1*(1.+gauss->coord4)/2.;
-			basis[4]=gauss->coord2*(1.+gauss->coord4)/2.;
-			basis[5]=gauss->coord3*(1.+gauss->coord4)/2.;
-			basis[6]=27.*gauss->coord1*gauss->coord2*gauss->coord3*(1.+gauss->coord4)*(1.-gauss->coord4);
+			this->element_type = P1bubbleEnum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = MINIEnum;
+			return;
+		case TaylorHoodEnum:
+			this->element_type = P2Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = TaylorHoodEnum;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsPressure{{{*/
+void PentaRef::GetNodalFunctionsPressure(IssmDouble* basis,GaussPenta* gauss){
+	/*This routine returns the values of the nodal functions  at the gaussian point.*/
+
+	switch(this->element_type){
+		case P1P1Enum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = P1P1Enum;
+			return;
+		case P1P1GLSEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = P1P1GLSEnum;
+			return;
+		case MINIcondensedEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = MINIcondensedEnum;
+			return;
+		case MINIEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = MINIEnum;
+			return;
+		case TaylorHoodEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctions(basis,gauss);
+			this->element_type = TaylorHoodEnum;
 			return;
 		default:
@@ -1046,4 +1439,73 @@
 	}
 
+	/*Clean up*/
+	xDelete<IssmDouble>(dbasis_ref);
+
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsDerivativesVelocity{{{*/
+void PentaRef::GetNodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list, GaussPenta* gauss){
+	switch(this->element_type){
+		case P1P1Enum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = P1P1Enum;
+			return;
+		case P1P1GLSEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = P1P1GLSEnum;
+			return;
+		case MINIcondensedEnum:
+			this->element_type = P1bubbleEnum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = MINIcondensedEnum;
+			return;
+		case MINIEnum:
+			this->element_type = P1bubbleEnum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = MINIEnum;
+			return;
+		case TaylorHoodEnum:
+			this->element_type = P2Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = TaylorHoodEnum;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION PentaRef::GetNodalFunctionsDerivativesPressure{{{*/
+void PentaRef::GetNodalFunctionsDerivativesPressure(IssmDouble* dbasis,IssmDouble* xyz_list, GaussPenta* gauss){
+	switch(this->element_type){
+		case P1P1Enum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = P1P1Enum;
+			return;
+		case P1P1GLSEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = P1P1GLSEnum;
+			return;
+		case MINIcondensedEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = MINIcondensedEnum;
+			return;
+		case MINIEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = MINIEnum;
+			return;
+		case TaylorHoodEnum:
+			this->element_type = P1Enum;
+			this->GetNodalFunctionsDerivatives(dbasis,xyz_list,gauss);
+			this->element_type = TaylorHoodEnum;
+			return;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
 }
 /*}}}*/
@@ -1057,6 +1519,4 @@
 
 	/*Get current coordinates in reference element*/
-	IssmDouble r=gauss->coord2-gauss->coord1;
-	IssmDouble s=-3.0/SQRT3*(gauss->coord1+gauss->coord2-2.0/3.0);
 	IssmDouble zeta=gauss->coord4;
 
@@ -1064,61 +1524,215 @@
 		case P1Enum: case P1DGEnum:
 			/*Nodal function 1*/
-			dbasis[NUMNODESP1*0+0]=-0.5*(1.0-zeta)/2.0;
-			dbasis[NUMNODESP1*1+0]=-SQRT3/6.0*(1.0-zeta)/2.0;
-			dbasis[NUMNODESP1*2+0]=-0.5*(-0.5*r-SQRT3/6.0*s+ONETHIRD);
+			dbasis[NUMNODESP1*0+0]   = (zeta-1.)/4.;
+			dbasis[NUMNODESP1*1+0]   = SQRT3/12.*(zeta-1.);
+			dbasis[NUMNODESP1*2+0]   = -.5*gauss->coord1;
 			/*Nodal function 2*/
-			dbasis[NUMNODESP1*0+1]=0.5*(1.0-zeta)/2.0;
-			dbasis[NUMNODESP1*1+1]=-SQRT3/6.0*(1.0-zeta)/2.0;
-			dbasis[NUMNODESP1*2+1]=-0.5*(0.5*r-SQRT3/6.0*s+ONETHIRD);
+			dbasis[NUMNODESP1*0+1]   = (1.-zeta)/4.;
+			dbasis[NUMNODESP1*1+1]   = SQRT3/12.*(zeta-1);
+			dbasis[NUMNODESP1*2+1]   = -.5*gauss->coord2;
 			/*Nodal function 3*/
-			dbasis[NUMNODESP1*0+2]=0;
-			dbasis[NUMNODESP1*1+2]=SQRT3/3.0*(1.0-zeta)/2.0;
-			dbasis[NUMNODESP1*2+2]=-0.5*(SQRT3/3.0*s+ONETHIRD);
+			dbasis[NUMNODESP1*0+2]   = 0.;
+			dbasis[NUMNODESP1*1+2]   = SQRT3/6.*(1.-zeta);
+			dbasis[NUMNODESP1*2+2]   = -.5*gauss->coord3;
 			/*Nodal function 4*/
-			dbasis[NUMNODESP1*0+3]=-0.5*(1.0+zeta)/2.0;
-			dbasis[NUMNODESP1*1+3]=-SQRT3/6.0*(1.0+zeta)/2.0;
-			dbasis[NUMNODESP1*2+3]=0.5*(-0.5*r-SQRT3/6.0*s+ONETHIRD);
+			dbasis[NUMNODESP1*0+3]   = -(1.+zeta)/4.;
+			dbasis[NUMNODESP1*1+3]   = -SQRT3/12.*(1.+zeta);
+			dbasis[NUMNODESP1*2+3]   = .5*gauss->coord1;
 			/*Nodal function 5*/
-			dbasis[NUMNODESP1*0+4]=0.5*(1.0+zeta)/2.0;
-			dbasis[NUMNODESP1*1+4]=-SQRT3/6.0*(1.0+zeta)/2.0;
-			dbasis[NUMNODESP1*2+4]=0.5*(0.5*r-SQRT3/6.0*s+ONETHIRD);
+			dbasis[NUMNODESP1*0+4]   = (1.+zeta)/4.;
+			dbasis[NUMNODESP1*1+4]   = -SQRT3/12.*(1.+zeta);
+			dbasis[NUMNODESP1*2+4]   = .5*gauss->coord2;
 			/*Nodal function 6*/
-			dbasis[NUMNODESP1*0+5]=0;
-			dbasis[NUMNODESP1*1+5]=SQRT3/3.0*(1.0+zeta)/2.0;
-			dbasis[NUMNODESP1*2+5]=0.5*(SQRT3/3.0*s+ONETHIRD);
-		case MINIEnum:
+			dbasis[NUMNODESP1*0+5]   = 0.;
+			dbasis[NUMNODESP1*1+5]   = SQRT3/6.*(1.+zeta);
+			dbasis[NUMNODESP1*2+5]   = .5*gauss->coord3;
+			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
 			/*Nodal function 1*/
-			dbasis[NUMNODESMINI*0+0]=-0.5*(1.0-zeta)/2.0;
-			dbasis[NUMNODESMINI*1+0]=-SQRT3/6.0*(1.0-zeta)/2.0;
-			dbasis[NUMNODESMINI*2+0]=-0.5*(-0.5*r-SQRT3/6.0*s+ONETHIRD);
+			dbasis[NUMNODESP1b*0+0]   = (zeta-1.)/4.;
+			dbasis[NUMNODESP1b*1+0]   = SQRT3/12.*(zeta-1.);
+			dbasis[NUMNODESP1b*2+0]   = -.5*gauss->coord1;
 			/*Nodal function 2*/
-			dbasis[NUMNODESMINI*0+1]=0.5*(1.0-zeta)/2.0;
-			dbasis[NUMNODESMINI*1+1]=-SQRT3/6.0*(1.0-zeta)/2.0;
-			dbasis[NUMNODESMINI*2+1]=-0.5*(0.5*r-SQRT3/6.0*s+ONETHIRD);
+			dbasis[NUMNODESP1b*0+1]   = (1.-zeta)/4.;
+			dbasis[NUMNODESP1b*1+1]   = SQRT3/12.*(zeta-1);
+			dbasis[NUMNODESP1b*2+1]   = -.5*gauss->coord2;
 			/*Nodal function 3*/
-			dbasis[NUMNODESMINI*0+2]=0;
-			dbasis[NUMNODESMINI*1+2]=SQRT3/3.0*(1.0-zeta)/2.0;
-			dbasis[NUMNODESMINI*2+2]=-0.5*(SQRT3/3.0*s+ONETHIRD);
+			dbasis[NUMNODESP1b*0+2]   = 0.;
+			dbasis[NUMNODESP1b*1+2]   = SQRT3/6.*(1.-zeta);
+			dbasis[NUMNODESP1b*2+2]   = -.5*gauss->coord3;
 			/*Nodal function 4*/
-			dbasis[NUMNODESMINI*0+3]=-0.5*(1.0+zeta)/2.0;
-			dbasis[NUMNODESMINI*1+3]=-SQRT3/6.0*(1.0+zeta)/2.0;
-			dbasis[NUMNODESMINI*2+3]=0.5*(-0.5*r-SQRT3/6.0*s+ONETHIRD);
+			dbasis[NUMNODESP1b*0+3]   = -(1.+zeta)/4.;
+			dbasis[NUMNODESP1b*1+3]   = -SQRT3/12.*(1.+zeta);
+			dbasis[NUMNODESP1b*2+3]   = .5*gauss->coord1;
 			/*Nodal function 5*/
-			dbasis[NUMNODESMINI*0+4]=0.5*(1.0+zeta)/2.0;
-			dbasis[NUMNODESMINI*1+4]=-SQRT3/6.0*(1.0+zeta)/2.0;
-			dbasis[NUMNODESMINI*2+4]=0.5*(0.5*r-SQRT3/6.0*s+ONETHIRD);
+			dbasis[NUMNODESP1b*0+4]   = (1.+zeta)/4.;
+			dbasis[NUMNODESP1b*1+4]   = -SQRT3/12.*(1.+zeta);
+			dbasis[NUMNODESP1b*2+4]   = .5*gauss->coord2;
 			/*Nodal function 6*/
-			dbasis[NUMNODESMINI*0+5]=0;
-			dbasis[NUMNODESMINI*1+5]=SQRT3/3.0*(1.0+zeta)/2.0;
-			dbasis[NUMNODESMINI*2+5]=0.5*(SQRT3/3.0*s+ONETHIRD);
+			dbasis[NUMNODESP1b*0+5]   = 0.;
+			dbasis[NUMNODESP1b*1+5]   = SQRT3/6.*(1.+zeta);
+			dbasis[NUMNODESP1b*2+5]   = .5*gauss->coord3;
 			/*Nodal function 7*/
-			dbasis[NUMNODESMINI*0+6]=9.0/2.0*r*(1.0+zeta)*(zeta-1.0)*(SQRT3*s+1.0);
-			dbasis[NUMNODESMINI*1+6]=9.0/4.0*(1+zeta)*(1-zeta)*(SQRT3*pow(s,2.0)-2.0*s-SQRT3*pow(r,2.0));
-			dbasis[NUMNODESMINI*2+6]=27*gauss->coord1*gauss->coord2*gauss->coord3*(-2.0*zeta);
+			dbasis[NUMNODESP1b*0+6] = 27.*(1.+zeta)*(1.-zeta)*(-.5*gauss->coord2*gauss->coord3 + .5*gauss->coord1*gauss->coord3);
+			dbasis[NUMNODESP1b*1+6] = 27.*(1.+zeta)*(1.-zeta)*SQRT3*(-1./6.*gauss->coord2*gauss->coord3 - 1./6.*gauss->coord1*gauss->coord3 +1./3.*gauss->coord1*gauss->coord2);
+			dbasis[NUMNODESP1b*2+6] = -54*gauss->coord1*gauss->coord2*gauss->coord3*zeta;
+			return;
+		case P2xP1Enum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP2xP1*0+0 ] = .5*(1.-zeta)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2xP1*1+0 ] = .5*(1.-zeta)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2xP1*2+0 ] = -.5*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 2*/
+			dbasis[NUMNODESP2xP1*0+1 ] = .5*(1.-zeta)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2xP1*1+1 ] = .5*(1.-zeta)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2xP1*2+1 ] = -.5*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 3*/
+			dbasis[NUMNODESP2xP1*0+2 ] = 0.;
+			dbasis[NUMNODESP2xP1*1+2 ] = .5*(1.-zeta)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2xP1*2+2 ] = -.5*gauss->coord3*(2.*gauss->coord3-1.);
+			/*Nodal function 4*/
+			dbasis[NUMNODESP2xP1*0+3 ] = .5*(1.+zeta)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2xP1*1+3 ] = .5*(1.+zeta)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2xP1*2+3 ] = .5*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 5*/
+			dbasis[NUMNODESP2xP1*0+4 ] = .5*(1.+zeta)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2xP1*1+4 ] = .5*(1.+zeta)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2xP1*2+4 ] = .5*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 6*/
+			dbasis[NUMNODESP2xP1*0+5 ] = 0.;
+			dbasis[NUMNODESP2xP1*1+5 ] = .5*(1.+zeta)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2xP1*2+5 ] = .5*gauss->coord3*(2.*gauss->coord3-1.);
+
+			/*Nodal function 7*/
+			dbasis[NUMNODESP2xP1*0+6 ] = (1.-zeta)*gauss->coord3;
+			dbasis[NUMNODESP2xP1*1+6 ] = .5*(1.-zeta)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2xP1*2+6 ] = -2.*gauss->coord3*gauss->coord2;
+			/*Nodal function 8*/
+			dbasis[NUMNODESP2xP1*0+7 ] = -(1.-zeta)*gauss->coord3;
+			dbasis[NUMNODESP2xP1*1+7 ] = .5*(1.-zeta)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2xP1*2+7 ] = -2.*gauss->coord3*gauss->coord1;
+			/*Nodal function 9*/
+			dbasis[NUMNODESP2xP1*0+8 ] = (1.-zeta)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2xP1*1+8 ] = .5*(1.-zeta)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2xP1*2+8 ] = -2.*gauss->coord1*gauss->coord2;
+			/*Nodal function 10*/
+			dbasis[NUMNODESP2xP1*0+9 ] = (1.+zeta)*gauss->coord3;
+			dbasis[NUMNODESP2xP1*1+9 ] = .5*(1.+zeta)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2xP1*2+9 ] = 2.*gauss->coord3*gauss->coord2;
+			/*Nodal function 11*/
+			dbasis[NUMNODESP2xP1*0+10] = -(1.+zeta)*gauss->coord3;
+			dbasis[NUMNODESP2xP1*1+10] = .5*(1.+zeta)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2xP1*2+10] = 2.*gauss->coord3*gauss->coord1;
+			/*Nodal function 12*/
+			dbasis[NUMNODESP2xP1*0+11] = (1.+zeta)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2xP1*1+11] = .5*(1.+zeta)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2xP1*2+11] = 2.*gauss->coord1*gauss->coord2;
+			return;
+		case P1xP2Enum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP1xP2*0+0]   = -zeta*(zeta-1.)/4.;
+			dbasis[NUMNODESP1xP2*1+0]   = -SQRT3/12.*zeta*(zeta-1.);
+			dbasis[NUMNODESP1xP2*2+0]   = .5*(2.*zeta-1.)*gauss->coord1;
+			/*Nodal function 2*/
+			dbasis[NUMNODESP1xP2*0+1]   = zeta*(zeta-1.)/4.;
+			dbasis[NUMNODESP1xP2*1+1]   = -SQRT3/12.*zeta*(zeta-1);
+			dbasis[NUMNODESP1xP2*2+1]   = .5*(2.*zeta-1.)*gauss->coord2;
+			/*Nodal function 3*/
+			dbasis[NUMNODESP1xP2*0+2]   = 0.;
+			dbasis[NUMNODESP1xP2*1+2]   = SQRT3/6.*zeta*(zeta-1.);
+			dbasis[NUMNODESP1xP2*2+2]   = .5*(2.*zeta-1.)*gauss->coord3;
+			/*Nodal function 4*/
+			dbasis[NUMNODESP1xP2*0+3]   = -zeta*(zeta+1)/4.;
+			dbasis[NUMNODESP1xP2*1+3]   = -SQRT3/12.*zeta*(zeta+1.);
+			dbasis[NUMNODESP1xP2*2+3]   = .5*(2.*zeta+1.)*gauss->coord1;
+			/*Nodal function 5*/
+			dbasis[NUMNODESP1xP2*0+4]   = zeta*(zeta+1.)/4.;
+			dbasis[NUMNODESP1xP2*1+4]   = -SQRT3/12.*zeta*(zeta+1.);
+			dbasis[NUMNODESP1xP2*2+4]   = .5*(2.*zeta+1.)*gauss->coord2;
+			/*Nodal function 6*/
+			dbasis[NUMNODESP1xP2*0+5]   = 0.;
+			dbasis[NUMNODESP1xP2*1+5]   = SQRT3/6.*zeta*(zeta+1.);
+			dbasis[NUMNODESP1xP2*2+5]   = .5*(2.*zeta+1.)*gauss->coord3;
+
+			/*Nodal function 7*/
+			dbasis[NUMNODESP1xP2*0+6 ] = -0.5*(1.-zeta*zeta);
+			dbasis[NUMNODESP1xP2*1+6 ] = -SQRT3/6.*(1.-zeta*zeta);
+			dbasis[NUMNODESP1xP2*2+6 ] = -2.*zeta*gauss->coord1;
+			/*Nodal function 8*/
+			dbasis[NUMNODESP1xP2*0+7 ] = 0.5*(1.-zeta*zeta);
+			dbasis[NUMNODESP1xP2*1+7 ] = -SQRT3/6.*(1.-zeta*zeta);
+			dbasis[NUMNODESP1xP2*2+7 ] = -2.*zeta*gauss->coord2;
+			/*Nodal function 9*/
+			dbasis[NUMNODESP1xP2*0+8 ] = 0.;
+			dbasis[NUMNODESP1xP2*1+8 ] = SQRT3/3.*(1.-zeta*zeta);
+			dbasis[NUMNODESP1xP2*2+8 ] = -2.*zeta*gauss->coord3;
+			return;
+		case P2Enum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP2*0+0 ] = .5*zeta*(zeta-1.)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2*1+0 ] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2*2+0 ] = .5*(2.*zeta-1.)*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 2*/
+			dbasis[NUMNODESP2*0+1 ] = .5*zeta*(zeta-1.)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2*1+1 ] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2*2+1 ] = .5*(2.*zeta-1.)*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 3*/
+			dbasis[NUMNODESP2*0+2 ] = 0.;
+			dbasis[NUMNODESP2*1+2 ] = .5*zeta*(zeta-1.)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2*2+2 ] = .5*(2.*zeta-1.)*gauss->coord3*(2.*gauss->coord3-1.);
+			/*Nodal function 4*/
+			dbasis[NUMNODESP2*0+3 ] = .5*zeta*(zeta+1.)*(-2.*gauss->coord1 + 0.5);
+			dbasis[NUMNODESP2*1+3 ] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.);
+			dbasis[NUMNODESP2*2+3 ] = .5*(2.*zeta+1.)*gauss->coord1*(2.*gauss->coord1-1.);
+			/*Nodal function 5*/
+			dbasis[NUMNODESP2*0+4 ] = .5*zeta*(zeta+1.)*(+2.*gauss->coord2 - 0.5);
+			dbasis[NUMNODESP2*1+4 ] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.);
+			dbasis[NUMNODESP2*2+4 ] = .5*(2.*zeta+1.)*gauss->coord2*(2.*gauss->coord2-1.);
+			/*Nodal function 6*/
+			dbasis[NUMNODESP2*0+5 ] = 0.;
+			dbasis[NUMNODESP2*1+5 ] = .5*zeta*(zeta+1.)*(4.*SQRT3/3.*gauss->coord3 - SQRT3/3.);
+			dbasis[NUMNODESP2*2+5 ] = .5*(2.*zeta+1.)*gauss->coord3*(2.*gauss->coord3-1.);
+
+			/*Nodal function 7*/
+			dbasis[NUMNODESP2*0+6 ] = -0.5*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*1+6 ] = -SQRT3/6.*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*2+6 ] = -2.*zeta*gauss->coord1;
+			/*Nodal function 8*/
+			dbasis[NUMNODESP2*0+7 ] = 0.5*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*1+7 ] = -SQRT3/6.*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*2+7 ] = -2.*zeta*gauss->coord2;
+			/*Nodal function 9*/
+			dbasis[NUMNODESP2*0+8 ] = 0.;
+			dbasis[NUMNODESP2*1+8 ] = SQRT3/3.*(1.-zeta*zeta);
+			dbasis[NUMNODESP2*2+8 ] = -2.*zeta*gauss->coord3;
+
+			/*Nodal function 10*/
+			dbasis[NUMNODESP2*0+9 ] = zeta*(zeta-1.)*gauss->coord3;
+			dbasis[NUMNODESP2*1+9 ] = .5*zeta*(zeta-1.)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2*2+9 ] = 2.*gauss->coord3*gauss->coord2*(2.*zeta-1.);
+			/*Nodal function 11*/
+			dbasis[NUMNODESP2*0+10] = -zeta*(zeta-1.)*gauss->coord3;
+			dbasis[NUMNODESP2*1+10] = .5*zeta*(zeta-1.)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2*2+10] = 2.*gauss->coord3*gauss->coord1*(2.*zeta-1.);
+			/*Nodal function 12*/
+			dbasis[NUMNODESP2*0+11] = zeta*(zeta-1.)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2*1+11] = .5*zeta*(zeta-1.)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2*2+11] = 2.*gauss->coord1*gauss->coord2*(2.*zeta-1.);
+			/*Nodal function 13*/
+			dbasis[NUMNODESP2*0+12] = zeta*(zeta+1.)*gauss->coord3;
+			dbasis[NUMNODESP2*1+12] = .5*zeta*(zeta+1.)*(+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2*2+12] = 2.*gauss->coord3*gauss->coord2*(2.*zeta+1.);
+			/*Nodal function 14*/
+			dbasis[NUMNODESP2*0+13] = -zeta*(zeta+1.)*gauss->coord3;
+			dbasis[NUMNODESP2*1+13] = .5*zeta*(zeta+1.)*(+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3);
+			dbasis[NUMNODESP2*2+13] = 2.*gauss->coord3*gauss->coord1*(2.*zeta+1.);
+			/*Nodal function 15*/
+			dbasis[NUMNODESP2*0+14] = zeta*(zeta+1.)*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2*1+14] = .5*zeta*(zeta+1.)*(-2.*SQRT3/3.*(gauss->coord1+gauss->coord2));
+			dbasis[NUMNODESP2*2+14] = 2.*gauss->coord1*gauss->coord2*(2.*zeta+1.);
 			return;
 		default:
 			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
 	}
-
 
 }
@@ -1139,20 +1753,19 @@
 /*}}}*/
 /*FUNCTION PentaRef::GetNodalFunctionsMINIDerivatives{{{*/
-void PentaRef::GetNodalFunctionsMINIDerivatives(IssmDouble* dh1dh7,IssmDouble* xyz_list, GaussPenta* gauss){
+void PentaRef::GetNodalFunctionsMINIDerivatives(IssmDouble* dbasismini,IssmDouble* xyz_list, GaussPenta* gauss){
 
 	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
 	 * actual coordinate system): */
 
-	int       i;
-	IssmDouble    dh1dh7_ref[3][NUMNODESMINI];
+	IssmDouble    dbasismini_ref[3][NUMNODESP1b];
 	IssmDouble    Jinv[3][3];
 
 	/*Get derivative values with respect to parametric coordinate system: */
-	GetNodalFunctionsMINIDerivativesReference(&dh1dh7_ref[0][0], gauss); 
+	GetNodalFunctionsMINIDerivativesReference(&dbasismini_ref[0][0], gauss); 
 
 	/*Get Jacobian invert: */
 	GetJacobianInvert(&Jinv[0][0], xyz_list, gauss);
 
-	/*Build dh1dh6: 
+	/*Build dbasis: 
 	 *
 	 * [dhi/dx]= Jinv'*[dhi/dr]
@@ -1161,8 +1774,8 @@
 	 */
 
-	for (i=0;i<NUMNODESMINI;i++){
-		*(dh1dh7+NUMNODESMINI*0+i)=Jinv[0][0]*dh1dh7_ref[0][i]+Jinv[0][1]*dh1dh7_ref[1][i]+Jinv[0][2]*dh1dh7_ref[2][i];
-		*(dh1dh7+NUMNODESMINI*1+i)=Jinv[1][0]*dh1dh7_ref[0][i]+Jinv[1][1]*dh1dh7_ref[1][i]+Jinv[1][2]*dh1dh7_ref[2][i];
-		*(dh1dh7+NUMNODESMINI*2+i)=Jinv[2][0]*dh1dh7_ref[0][i]+Jinv[2][1]*dh1dh7_ref[1][i]+Jinv[2][2]*dh1dh7_ref[2][i];
+	for(int i=0;i<NUMNODESP1b;i++){
+		*(dbasismini+NUMNODESP1b*0+i)=Jinv[0][0]*dbasismini_ref[0][i]+Jinv[0][1]*dbasismini_ref[1][i]+Jinv[0][2]*dbasismini_ref[2][i];
+		*(dbasismini+NUMNODESP1b*1+i)=Jinv[1][0]*dbasismini_ref[0][i]+Jinv[1][1]*dbasismini_ref[1][i]+Jinv[1][2]*dbasismini_ref[2][i];
+		*(dbasismini+NUMNODESP1b*2+i)=Jinv[2][0]*dbasismini_ref[0][i]+Jinv[2][1]*dbasismini_ref[1][i]+Jinv[2][2]*dbasismini_ref[2][i];
 	}
 
@@ -1170,72 +1783,63 @@
 /*}}}*/
 /*FUNCTION PentaRef::GetNodalFunctionsMINIDerivativesReference{{{*/
-void PentaRef::GetNodalFunctionsMINIDerivativesReference(IssmDouble* dl1dl7,GaussPenta* gauss){
+void PentaRef::GetNodalFunctionsMINIDerivativesReference(IssmDouble* dbasis,GaussPenta* gauss){
 
 	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
 	 * natural coordinate system) at the gaussian point. */
-	IssmDouble r=gauss->coord2-gauss->coord1;
-	IssmDouble s=-3.0/SQRT3*(gauss->coord1+gauss->coord2-2.0/3.0);
 	IssmDouble zeta=gauss->coord4;
 
-	/*First nodal function: */
-	*(dl1dl7+NUMNODESMINI*0+0)=-0.5*(1.0-zeta)/2.0;
-	*(dl1dl7+NUMNODESMINI*1+0)=-SQRT3/6.0*(1.0-zeta)/2.0;
-	*(dl1dl7+NUMNODESMINI*2+0)=-0.5*(-0.5*r-SQRT3/6.0*s+ONETHIRD);
-
-	/*Second nodal function: */
-	*(dl1dl7+NUMNODESMINI*0+1)=0.5*(1.0-zeta)/2.0;
-	*(dl1dl7+NUMNODESMINI*1+1)=-SQRT3/6.0*(1.0-zeta)/2.0;
-	*(dl1dl7+NUMNODESMINI*2+1)=-0.5*(0.5*r-SQRT3/6.0*s+ONETHIRD);
-
-	/*Third nodal function: */
-	*(dl1dl7+NUMNODESMINI*0+2)=0;
-	*(dl1dl7+NUMNODESMINI*1+2)=SQRT3/3.0*(1.0-zeta)/2.0;
-	*(dl1dl7+NUMNODESMINI*2+2)=-0.5*(SQRT3/3.0*s+ONETHIRD);
-
-	/*Fourth nodal function: */
-	*(dl1dl7+NUMNODESMINI*0+3)=-0.5*(1.0+zeta)/2.0;
-	*(dl1dl7+NUMNODESMINI*1+3)=-SQRT3/6.0*(1.0+zeta)/2.0;
-	*(dl1dl7+NUMNODESMINI*2+3)=0.5*(-0.5*r-SQRT3/6.0*s+ONETHIRD);
-
-	/*Fith nodal function: */
-	*(dl1dl7+NUMNODESMINI*0+4)=0.5*(1.0+zeta)/2.0;
-	*(dl1dl7+NUMNODESMINI*1+4)=-SQRT3/6.0*(1.0+zeta)/2.0;
-	*(dl1dl7+NUMNODESMINI*2+4)=0.5*(0.5*r-SQRT3/6.0*s+ONETHIRD);
-
-	/*Sixth nodal function: */
-	*(dl1dl7+NUMNODESMINI*0+5)=0;
-	*(dl1dl7+NUMNODESMINI*1+5)=SQRT3/3.0*(1.0+zeta)/2.0;
-	*(dl1dl7+NUMNODESMINI*2+5)=0.5*(SQRT3/3.0*s+ONETHIRD);
-
-	/*Seventh nodal function: */
-	*(dl1dl7+NUMNODESMINI*0+6)=9.0/2.0*r*(1.0+zeta)*(zeta-1.0)*(SQRT3*s+1.0);
-	*(dl1dl7+NUMNODESMINI*1+6)=9.0/4.0*(1+zeta)*(1-zeta)*(SQRT3*pow(s,2.0)-2.0*s-SQRT3*pow(r,2.0));
-	*(dl1dl7+NUMNODESMINI*2+6)=27*gauss->coord1*gauss->coord2*gauss->coord3*(-2.0*zeta);
-
+	/*Nodal function 1*/
+	dbasis[NUMNODESP1b*0+0]=-0.5*(1.0-zeta)/2.0;
+	dbasis[NUMNODESP1b*1+0]=-SQRT3/6.0*(1.0-zeta)/2.0;
+	dbasis[NUMNODESP1b*2+0]=-0.5*gauss->coord1;
+	/*Nodal function 2*/
+	dbasis[NUMNODESP1b*0+1]=0.5*(1.0-zeta)/2.0;
+	dbasis[NUMNODESP1b*1+1]=-SQRT3/6.0*(1.0-zeta)/2.0;
+	dbasis[NUMNODESP1b*2+1]=-0.5*gauss->coord2;
+	/*Nodal function 3*/
+	dbasis[NUMNODESP1b*0+2]=0.;
+	dbasis[NUMNODESP1b*1+2]=SQRT3/3.0*(1.0-zeta)/2.0;
+	dbasis[NUMNODESP1b*2+2]=-0.5*gauss->coord3;
+	/*Nodal function 4*/
+	dbasis[NUMNODESP1b*0+3]=-0.5*(1.0+zeta)/2.0;
+	dbasis[NUMNODESP1b*1+3]=-SQRT3/6.0*(1.0+zeta)/2.0;
+	dbasis[NUMNODESP1b*2+3]=0.5*gauss->coord1;
+	/*Nodal function 5*/
+	dbasis[NUMNODESP1b*0+4]=0.5*(1.0+zeta)/2.0;
+	dbasis[NUMNODESP1b*1+4]=-SQRT3/6.0*(1.0+zeta)/2.0;
+	dbasis[NUMNODESP1b*2+4]=0.5*gauss->coord2;
+	/*Nodal function 6*/
+	dbasis[NUMNODESP1b*0+5]=0.;
+	dbasis[NUMNODESP1b*1+5]=SQRT3/3.0*(1.0+zeta)/2.0;
+	dbasis[NUMNODESP1b*2+5]=0.5*gauss->coord3;
+	/*Nodal function 7*/
+	dbasis[NUMNODESP1b*0+6]=27.*(1.+zeta)*(1.-zeta)*(-.5*gauss->coord2*gauss->coord3 + .5*gauss->coord1*gauss->coord3);
+	dbasis[NUMNODESP1b*1+6]=27.*(1.+zeta)*(1.-zeta)*SQRT3*(-1./6.*gauss->coord2*gauss->coord3 - 1./6.*gauss->coord1*gauss->coord3 +1./3.*gauss->coord1*gauss->coord2);
+	dbasis[NUMNODESP1b*2+6]=27*gauss->coord1*gauss->coord2*gauss->coord3*(-2.0*zeta);
 }
 /*}}}*/
 /*FUNCTION PentaRef::GetNodalFunctionsP1 {{{*/
-void PentaRef::GetNodalFunctionsP1(IssmDouble* l1l6, GaussPenta* gauss){
+void PentaRef::GetNodalFunctionsP1(IssmDouble* basis, GaussPenta* gauss){
 	/*This routine returns the values of the nodal functions  at the gaussian point.*/
 
-	l1l6[0]=gauss->coord1*(1-gauss->coord4)/2.0;
-	l1l6[1]=gauss->coord2*(1-gauss->coord4)/2.0;
-	l1l6[2]=gauss->coord3*(1-gauss->coord4)/2.0;
-	l1l6[3]=gauss->coord1*(1+gauss->coord4)/2.0;
-	l1l6[4]=gauss->coord2*(1+gauss->coord4)/2.0;
-	l1l6[5]=gauss->coord3*(1+gauss->coord4)/2.0;
+	basis[0]=gauss->coord1*(1-gauss->coord4)/2.0;
+	basis[1]=gauss->coord2*(1-gauss->coord4)/2.0;
+	basis[2]=gauss->coord3*(1-gauss->coord4)/2.0;
+	basis[3]=gauss->coord1*(1+gauss->coord4)/2.0;
+	basis[4]=gauss->coord2*(1+gauss->coord4)/2.0;
+	basis[5]=gauss->coord3*(1+gauss->coord4)/2.0;
 
 }
 /*}}}*/
 /*FUNCTION PentaRef::GetNodalFunctionsP1Derivatives {{{*/
-void PentaRef::GetNodalFunctionsP1Derivatives(IssmDouble* dh1dh6,IssmDouble* xyz_list, GaussPenta* gauss){
+void PentaRef::GetNodalFunctionsP1Derivatives(IssmDouble* dbasis,IssmDouble* xyz_list, GaussPenta* gauss){
 
 	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
 	 * actual coordinate system): */
-	IssmDouble    dh1dh6_ref[NDOF3][NUMNODESP1];
+	IssmDouble    dbasis_ref[NDOF3][NUMNODESP1];
 	IssmDouble    Jinv[NDOF3][NDOF3];
 
 	/*Get derivative values with respect to parametric coordinate system: */
-	GetNodalFunctionsP1DerivativesReference(&dh1dh6_ref[0][0], gauss); 
+	GetNodalFunctionsP1DerivativesReference(&dbasis_ref[0][0], gauss); 
 
 	/*Get Jacobian invert: */
@@ -1250,7 +1854,7 @@
 
 	for (int i=0;i<NUMNODESP1;i++){
-		*(dh1dh6+NUMNODESP1*0+i)=Jinv[0][0]*dh1dh6_ref[0][i]+Jinv[0][1]*dh1dh6_ref[1][i]+Jinv[0][2]*dh1dh6_ref[2][i];
-		*(dh1dh6+NUMNODESP1*1+i)=Jinv[1][0]*dh1dh6_ref[0][i]+Jinv[1][1]*dh1dh6_ref[1][i]+Jinv[1][2]*dh1dh6_ref[2][i];
-		*(dh1dh6+NUMNODESP1*2+i)=Jinv[2][0]*dh1dh6_ref[0][i]+Jinv[2][1]*dh1dh6_ref[1][i]+Jinv[2][2]*dh1dh6_ref[2][i];
+		*(dbasis+NUMNODESP1*0+i)=Jinv[0][0]*dbasis_ref[0][i]+Jinv[0][1]*dbasis_ref[1][i]+Jinv[0][2]*dbasis_ref[2][i];
+		*(dbasis+NUMNODESP1*1+i)=Jinv[1][0]*dbasis_ref[0][i]+Jinv[1][1]*dbasis_ref[1][i]+Jinv[1][2]*dbasis_ref[2][i];
+		*(dbasis+NUMNODESP1*2+i)=Jinv[2][0]*dbasis_ref[0][i]+Jinv[2][1]*dbasis_ref[1][i]+Jinv[2][2]*dbasis_ref[2][i];
 	}
 
@@ -1258,48 +1862,35 @@
 /*}}}*/
 /*FUNCTION PentaRef::GetNodalFunctionsP1DerivativesReference {{{*/
-void PentaRef::GetNodalFunctionsP1DerivativesReference(IssmDouble* dl1dl6,GaussPenta* gauss){
+void PentaRef::GetNodalFunctionsP1DerivativesReference(IssmDouble* dbasis,GaussPenta* gauss){
 
 	/*This routine returns the values of the nodal functions derivatives  (with respect to the 
 	 * natural coordinate system) at the gaussian point. Those values vary along xi,eta,z */
 
-	IssmDouble A1,A2,A3,z;
-
-	A1=gauss->coord1; _assert_(A1>=0 && A1<=1);//first area coordinate value. In term of xi and eta: A1=(1-xi)/2-eta/(2*SQRT3);
-	A2=gauss->coord2; _assert_(A2>=0 && A2<=1);//second area coordinate value In term of xi and eta: A2=(1+xi)/2-eta/(2*SQRT3);
-	A3=gauss->coord3; _assert_(A3>=0 && A3<=1);//third area coordinate value  In term of xi and eta: A3=y/SQRT3;
-	z =gauss->coord4; _assert_(z>=-1 &&  z<=1);//fourth vertical coordinate value. Corresponding nodal function: (1-z)/2 and (1+z)/2
-
-	/*First nodal function derivatives. The corresponding nodal function is N=A1*(1-z)/2. Its derivatives follow*/
-	*(dl1dl6+NUMNODESP1*0+0)=-0.5*(1.0-z)/2.0;
-	*(dl1dl6+NUMNODESP1*1+0)=-0.5/SQRT3*(1.0-z)/2.0;
-	*(dl1dl6+NUMNODESP1*2+0)=-0.5*A1;
-	//dbasis[NUMNODESP1*0+0]=-0.5*(1.0-zeta)/2.0;
-	//dbasis[NUMNODESP1*1+0]=-SQRT3/6.0*(1.0-zeta)/2.0;
-	//dbasis[NUMNODESP1*2+0]=-0.5*(-0.5*r-SQRT3/6.0*s+ONETHIRD);
-
-	/*Second nodal function: The corresponding nodal function is N=A2*(1-z)/2. Its derivatives follow*/
-	*(dl1dl6+NUMNODESP1*0+1)=0.5*(1.0-z)/2.0;
-	*(dl1dl6+NUMNODESP1*1+1)=-0.5/SQRT3*(1.0-z)/2.0;
-	*(dl1dl6+NUMNODESP1*2+1)=-0.5*A2;
-
-	/*Third nodal function: The corresponding nodal function is N=A3*(1-z)/2. Its derivatives follow*/
-	*(dl1dl6+NUMNODESP1*0+2)=0.0;
-	*(dl1dl6+NUMNODESP1*1+2)=1.0/SQRT3*(1.0-z)/2.0;
-	*(dl1dl6+NUMNODESP1*2+2)=-0.5*A3;
-
-	/*Fourth nodal function: The corresponding nodal function is N=A1*(1+z)/2. Its derivatives follow*/
-	*(dl1dl6+NUMNODESP1*0+3)=-0.5*(1.0+z)/2.0;
-	*(dl1dl6+NUMNODESP1*1+3)=-0.5/SQRT3*(1.0+z)/2.0;
-	*(dl1dl6+NUMNODESP1*2+3)=0.5*A1;
-
-	/*Fifth nodal function: The corresponding nodal function is N=A2*(1+z)/2. Its derivatives follow*/
-	*(dl1dl6+NUMNODESP1*0+4)=0.5*(1.0+z)/2.0;
-	*(dl1dl6+NUMNODESP1*1+4)=-0.5/SQRT3*(1.0+z)/2.0;
-	*(dl1dl6+NUMNODESP1*2+4)=0.5*A2;
-
-	/*Sixth nodal function: The corresponding nodal function is N=A3*(1+z)/2. Its derivatives follow*/
-	*(dl1dl6+NUMNODESP1*0+5)=0.0;
-	*(dl1dl6+NUMNODESP1*1+5)=1.0/SQRT3*(1.0+z)/2.0;
-	*(dl1dl6+NUMNODESP1*2+5)=0.5*A3;
+	IssmDouble zeta=gauss->coord4;
+
+	/*Nodal function 1*/
+	dbasis[NUMNODESP1*0+0]=-0.5*(1.0-zeta)/2.0;
+	dbasis[NUMNODESP1*1+0]=-SQRT3/6.0*(1.0-zeta)/2.0;
+	dbasis[NUMNODESP1*2+0]=-0.5*gauss->coord1;
+	/*Nodal function 2*/
+	dbasis[NUMNODESP1*0+1]=0.5*(1.0-zeta)/2.0;
+	dbasis[NUMNODESP1*1+1]=-SQRT3/6.0*(1.0-zeta)/2.0;
+	dbasis[NUMNODESP1*2+1]=-0.5*gauss->coord2;
+	/*Nodal function 3*/
+	dbasis[NUMNODESP1*0+2]=0.;
+	dbasis[NUMNODESP1*1+2]=SQRT3/3.0*(1.0-zeta)/2.0;
+	dbasis[NUMNODESP1*2+2]=-0.5*gauss->coord3;
+	/*Nodal function 4*/
+	dbasis[NUMNODESP1*0+3]=-0.5*(1.0+zeta)/2.0;
+	dbasis[NUMNODESP1*1+3]=-SQRT3/6.0*(1.0+zeta)/2.0;
+	dbasis[NUMNODESP1*2+3]=0.5*gauss->coord1;
+	/*Nodal function 5*/
+	dbasis[NUMNODESP1*0+4]=0.5*(1.0+zeta)/2.0;
+	dbasis[NUMNODESP1*1+4]=-SQRT3/6.0*(1.0+zeta)/2.0;
+	dbasis[NUMNODESP1*2+4]=0.5*gauss->coord2;
+	/*Nodal function 6*/
+	dbasis[NUMNODESP1*0+5]=0.;
+	dbasis[NUMNODESP1*1+5]=SQRT3/3.0*(1.0+zeta)/2.0;
+	dbasis[NUMNODESP1*2+5]=0.5*gauss->coord3;
 }
 /*}}}*/
@@ -1345,6 +1936,6 @@
 	/*Jdet = (Area of the trapezoid)/(Area trapezoid ref) with AreaRef = 4*/
 	/*Area of a trabezoid = altitude * (base1 + base2)/2 */
-	*Jdet= pow(pow(x2-x1,2.) + pow(y2-y1,2.),0.5) * (z4-z1 + z3-z2)/8;
-	if(*Jdet<0) _error_("negative jacobian determinant!");
+	*Jdet= sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)) * (z4-z1 + z3-z2)/8.;
+	if(*Jdet<0.) _error_("negative jacobian determinant!");
 
 }
@@ -1355,11 +1946,11 @@
 
 	/*intermediary*/
-	IssmDouble l1l6[6];
+	IssmDouble basis[6];
 
 	/*nodal functions: */
-	GetNodalFunctionsP1(&l1l6[0],gauss);
+	GetNodalFunctionsP1(&basis[0],gauss);
 
 	/*Assign output pointers:*/
-	*pvalue=l1l6[0]*plist[0]+l1l6[1]*plist[1]+l1l6[2]*plist[2]+l1l6[3]*plist[3]+l1l6[4]*plist[4]+l1l6[5]*plist[5];
+	*pvalue=basis[0]*plist[0]+basis[1]*plist[1]+basis[2]*plist[2]+basis[3]*plist[3]+basis[4]*plist[4]+basis[5]*plist[5];
 
 }
@@ -1367,5 +1958,7 @@
 /*FUNCTION PentaRef::GetInputDerivativeValue{{{*/
 void PentaRef::GetInputDerivativeValue(IssmDouble* p, IssmDouble* plist,IssmDouble* xyz_list, GaussPenta* gauss){
-	/*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:
+	/*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;
@@ -1374,13 +1967,13 @@
 	 *   p is a vector of size 3x1 already allocated.
 	 */
-	IssmDouble dh1dh6[3][NUMNODESP1];
+	IssmDouble dbasis[3][NUMNODESP1];
 
 	/*Get nodal funnctions derivatives in actual coordinate system: */
-	GetNodalFunctionsP1Derivatives(&dh1dh6[0][0],xyz_list, gauss);
+	GetNodalFunctionsP1Derivatives(&dbasis[0][0],xyz_list, gauss);
 
 	/*Assign output*/
-	p[0]=plist[0]*dh1dh6[0][0]+plist[1]*dh1dh6[0][1]+plist[2]*dh1dh6[0][2]+plist[3]*dh1dh6[0][3]+plist[4]*dh1dh6[0][4]+plist[5]*dh1dh6[0][5];
-	p[1]=plist[0]*dh1dh6[1][0]+plist[1]*dh1dh6[1][1]+plist[2]*dh1dh6[1][2]+plist[3]*dh1dh6[1][3]+plist[4]*dh1dh6[1][4]+plist[5]*dh1dh6[1][5];
-	p[2]=plist[0]*dh1dh6[2][0]+plist[1]*dh1dh6[2][1]+plist[2]*dh1dh6[2][2]+plist[3]*dh1dh6[2][3]+plist[4]*dh1dh6[2][4]+plist[5]*dh1dh6[2][5];
+	p[0]=plist[0]*dbasis[0][0]+plist[1]*dbasis[0][1]+plist[2]*dbasis[0][2]+plist[3]*dbasis[0][3]+plist[4]*dbasis[0][4]+plist[5]*dbasis[0][5];
+	p[1]=plist[0]*dbasis[1][0]+plist[1]*dbasis[1][1]+plist[2]*dbasis[1][2]+plist[3]*dbasis[1][3]+plist[4]*dbasis[1][4]+plist[5]*dbasis[1][5];
+	p[2]=plist[0]*dbasis[2][0]+plist[1]*dbasis[2][1]+plist[2]*dbasis[2][2]+plist[3]*dbasis[2][3]+plist[4]*dbasis[2][4]+plist[5]*dbasis[2][5];
 
 }
@@ -1390,6 +1983,15 @@
 
 	switch(this->element_type){
-		case P1Enum:   return NUMNODESP1;
-		case MINIEnum: return NUMNODESMINI;
+		case P1Enum:                return NUMNODESP1;
+		case P1bubbleEnum:          return NUMNODESP1b;
+		case P1bubblecondensedEnum: return NUMNODESP1b;
+		case P2Enum:                return NUMNODESP2;
+		case P2xP1Enum:             return NUMNODESP2xP1;
+		case P1xP2Enum:             return NUMNODESP1xP2;
+		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;
 		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
 	}
@@ -1398,2 +2000,178 @@
 }
 /*}}}*/
+/*FUNCTION PentaRef::NumberofNodesPressure{{{*/
+int PentaRef::NumberofNodesPressure(void){
+
+	switch(this->element_type){
+		case P1P1Enum:          return NUMNODESP1;
+		case P1P1GLSEnum:       return NUMNODESP1;
+		case MINIcondensedEnum: return NUMNODESP1;
+		case MINIEnum:          return NUMNODESP1;
+		case TaylorHoodEnum:    return NUMNODESP1;
+		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+/*FUNCTION PentaRef::NumberofNodesVelocity{{{*/
+int PentaRef::NumberofNodesVelocity(void){
+
+	switch(this->element_type){
+		case P1P1Enum:          return NUMNODESP1;
+		case P1P1GLSEnum:       return NUMNODESP1;
+		case MINIcondensedEnum: return NUMNODESP1b;
+		case MINIEnum:          return NUMNODESP1b;
+		case TaylorHoodEnum:    return NUMNODESP2;
+		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+/*FUNCTION PentaRef::VelocityInterpolation{{{*/
+int PentaRef::VelocityInterpolation(void){
+
+	switch(this->element_type){
+		case P1P1Enum:          return P1Enum;
+		case P1P1GLSEnum:       return P1Enum;
+		case MINIcondensedEnum: return P1bubbleEnum;
+		case MINIEnum:          return P1bubbleEnum;
+		case TaylorHoodEnum:    return P2Enum;
+		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+/*FUNCTION PentaRef::PressureInterpolation{{{*/
+int PentaRef::PressureInterpolation(void){
+
+	switch(this->element_type){
+		case P1P1Enum:          return P1Enum;
+		case P1P1GLSEnum:       return P1Enum;
+		case MINIcondensedEnum: return P1Enum;
+		case MINIEnum:          return P1Enum;
+		case TaylorHoodEnum:    return P1Enum;
+		default:       _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	return -1;
+}
+/*}}}*/
+/*FUNCTION PentaRef::BasalNodeIndices{{{*/
+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;
+			return;
+		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;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	/*Assign output pointer*/
+	*pnumindices = numindices;
+	*pindices    = indices;
+}
+/*}}}*/
+/*FUNCTION PentaRef::SurfaceNodeIndices{{{*/
+void PentaRef::SurfaceNodeIndices(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] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			break;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			break;
+		case P2xP1Enum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			indices[3] = 9;
+			indices[4] = 10;
+			indices[5] = 11;
+			break;
+		case P1xP2Enum:
+			numindices = 3;
+			indices    = xNew<int>(numindices);
+			indices[0] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			return;
+		case P2Enum:
+			numindices = 6;
+			indices    = xNew<int>(numindices);
+			indices[0] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			indices[3] = 12;
+			indices[4] = 13;
+			indices[5] = 14;
+			break;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+
+	/*Assign output pointer*/
+	*pnumindices = numindices;
+	*pindices    = indices;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Elements/PentaRef.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/PentaRef.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Elements/PentaRef.h	(revision 16137)
@@ -23,5 +23,9 @@
 		/*Numerics*/
 		void GetNodalFunctions(IssmDouble* basis, GaussPenta* gauss);
+		void GetNodalFunctionsVelocity(IssmDouble* basis, GaussPenta* gauss);
+		void GetNodalFunctionsPressure(IssmDouble* basis, GaussPenta* gauss);
 		void GetNodalFunctionsDerivatives(IssmDouble* dbasis,IssmDouble* xyz_list,GaussPenta* gauss);
+		void GetNodalFunctionsDerivativesVelocity(IssmDouble* dbasis,IssmDouble* xyz_list,GaussPenta* gauss);
+		void GetNodalFunctionsDerivativesPressure(IssmDouble* dbasis,IssmDouble* xyz_list,GaussPenta* gauss);
 		void GetNodalFunctionsDerivativesReference(IssmDouble* dbasis,GaussPenta* gauss);
 		void GetNodalFunctionsP1(IssmDouble* l1l6, GaussPenta* gauss);
@@ -38,11 +42,14 @@
 		void GetSegmentJacobianDeterminant(IssmDouble*  Jdet, IssmDouble* xyz_list,GaussPenta* gauss);
 		void GetJacobianInvert(IssmDouble*  Jinv, IssmDouble* xyz_list,GaussPenta* gauss);
-		void GetBMacAyealPattyn(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetBMacAyealStokes(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetBPattyn(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetBStokes(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetBprimeMacAyealStokes(IssmDouble* Bprime, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetBprimePattyn(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetBprimeStokes(IssmDouble* B_prime, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBSSAHO(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBSSAFS(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBHO(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBFSstrainrate(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBFS(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBFSGLS(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBprimeSSAFS(IssmDouble* Bprime, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBprimeHO(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBprimeFS(IssmDouble* B_prime, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBprimeFSGLS(IssmDouble* B_prime, IssmDouble* xyz_list, GaussPenta* gauss);
 		void GetBprimeVert(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
 		void GetBAdvec(IssmDouble* B_advec, IssmDouble* xyz_list, GaussPenta* gauss);
@@ -50,11 +57,11 @@
 		void GetBVert(IssmDouble* B, IssmDouble* xyz_list, GaussPenta* gauss);
 		void GetBprimeAdvec(IssmDouble* Bprime_advec, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetBPattynFriction(IssmDouble* L, GaussPenta* gauss);
-		void GetLStokes(IssmDouble* LStokes, GaussPenta* gauss);
-		void GetLprimeStokes(IssmDouble* LprimeStokes, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetLMacAyealStokes(IssmDouble* LMacAyealStokes, GaussPenta* gauss);
-		void GetLprimeMacAyealStokes(IssmDouble* LprimeMacAyealStokes, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetLStokesMacAyeal(IssmDouble* LStokesMacAyeal, GaussPenta* gauss);
-		void GetLprimeStokesMacAyeal(IssmDouble* LprimeStokesMacAyeal, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetBHOFriction(IssmDouble* L, GaussPenta* gauss);
+		void GetLFS(IssmDouble* LFS, GaussPenta* gauss);
+		void GetLprimeFS(IssmDouble* LprimeFS, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetLSSAFS(IssmDouble* LSSAFS, GaussPenta* gauss);
+		void GetLprimeSSAFS(IssmDouble* LprimeSSAFS, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetLFSSSA(IssmDouble* LFSSSA, GaussPenta* gauss);
+		void GetLprimeFSSSA(IssmDouble* LprimeFSSSA, IssmDouble* xyz_list, GaussPenta* gauss);
 		void GetInputValue(IssmDouble* pvalue,IssmDouble* plist, GaussPenta* gauss);
 		void GetInputValue(IssmDouble* pvalue,IssmDouble* plist,GaussTria* gauss){_error_("only PentaGauss are supported");};
@@ -62,5 +69,11 @@
 		void GetInputDerivativeValue(IssmDouble* pvalues, IssmDouble* plist,IssmDouble* xyz_list, GaussTria* gauss){_error_("only PentaGauss are supported");};
 
+		void BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement);
+		void SurfaceNodeIndices(int* pnumindices,int** pindices,int finiteelement);
 		int  NumberofNodes(void);
+		int  NumberofNodesVelocity(void);
+		int  NumberofNodesPressure(void);
+		int  VelocityInterpolation(void);
+		int  PressureInterpolation(void);
 };
 #endif
Index: /issm/trunk/src/c/classes/Elements/Tria.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Elements/Tria.cpp	(revision 16137)
@@ -24,5 +24,5 @@
 /*FUNCTION Tria::Tria(){{{*/
 Tria::Tria(){
-	
+
 	int i;
 
@@ -31,5 +31,4 @@
 	this->material = NULL;
 	this->matpar   = NULL;
-	for(i=0;i<3;i++)this->horizontalneighborsids[i]=UNDEF;
 	this->inputs     = NULL;
 	this->parameters = NULL;
@@ -50,11 +49,7 @@
 		this->parameters=NULL;
 
-		/*Build horizontalneighborsids list: */
-		_assert_(iomodel->Data(MeshElementconnectivityEnum));
-		//for (i=0;i<3;i++) this->horizontalneighborsids[i]=(int)iomodel->elementconnectivity[3*index+i]-1;
-
 		/*intialize inputs and results: */
-		this->inputs=new Inputs();
-		this->results=new Results();
+		this->inputs  = new Inputs();
+		this->results = new Results();
 
 		/*initialize pointers:*/
@@ -118,7 +113,4 @@
 	tria->matpar=(Matpar*)tria->hmatpar->delivers();
 
-	/*neighbors: */
-	for(i=0;i<3;i++)tria->horizontalneighborsids[i]=this->horizontalneighborsids[i];
-
 	return tria;
 }
@@ -127,5 +119,8 @@
 /*Other*/
 /*FUNCTION Tria::SetwiseNodeConnectivity{{{*/
-void Tria::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+void Tria::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){
+
+	/*Intermediaries*/
+	const int numnodes = this->NumberofNodes();
 
 	/*Output */
@@ -134,10 +129,14 @@
 
 	/*Loop over all nodes*/
-	for(int i=0;i<3;i++){
-
-		if(!flags[this->nodes[i]->Sid()]){
+	for(int i=0;i<numnodes;i++){
+
+		if(!flags[this->nodes[i]->Lid()]){
 
 			/*flag current node so that no other element processes it*/
-			flags[this->nodes[i]->Sid()]=true;
+			flags[this->nodes[i]->Lid()]=true;
+
+			int counter=0;
+			while(flagsindices[counter]>=0) counter++;
+			flagsindices[counter]=this->nodes[i]->Lid();
 
 			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
@@ -177,9 +176,35 @@
 }
 /*}}}*/
-/*FUNCTION Tria::CreateKMatrix {{{*/
+/*FUNCTION Tria::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs) {{{*/
 void  Tria::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
 
+	/*Skip if water element*/
+	if(NoIceInElement()) return;
+
+	/*Create element stiffness matrix*/
+	ElementMatrix* Ke=CreateKMatrix();
+
+	if(Ke){
+		/*Static condensation if requested*/
+		if(this->element_type==P1bubblecondensedEnum){
+			int size   = nodes[3]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int offset = 0;
+			for(int i=0;i<3;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int* indices=xNew<int>(size);
+			for(int i=0;i<size;i++) indices[i] = offset+i;
+			Ke->StaticCondensation(size,indices);
+			xDelete<int>(indices);
+		}
+
+		/*Add to global matrix*/
+		Ke->AddToGlobal(Kff,Kfs);
+		delete Ke;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrix(void) {{{*/
+ElementMatrix* Tria::CreateKMatrix(void){
+
 	/*retreive parameters: */
-	ElementMatrix* Ke=NULL;
 	int analysis_type;
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
@@ -190,44 +215,50 @@
 
 	/*Skip if water element*/
-	if(IsOnWater()) return;
+	if(NoIceInElement()) return NULL;
 
 	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-		#ifdef _HAVE_DIAGNOSTIC_
-		case DiagnosticHorizAnalysisEnum:
-			Ke=CreateKMatrixDiagnosticMacAyeal();
+		#ifdef _HAVE_STRESSBALANCE_
+		case StressbalanceAnalysisEnum:
+			return CreateKMatrixStressbalanceSSA();
 			break;
-		case DiagnosticHutterAnalysisEnum:
-			Ke=CreateKMatrixDiagnosticHutter();
+		case StressbalanceSIAAnalysisEnum:
+			return CreateKMatrixStressbalanceSIA();
 			break;
 		 #endif
 		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
-			Ke=CreateMassMatrix();
+			return CreateMassMatrix();
 			break;
-		case PrognosticAnalysisEnum:
-			Ke=CreateKMatrixPrognostic();
+		case MasstransportAnalysisEnum:
+			return CreateKMatrixMasstransport();
 			break;
 		#ifdef _HAVE_HYDROLOGY_
 		case HydrologyShreveAnalysisEnum:
-			Ke=CreateKMatrixHydrologyShreve();
+			return CreateKMatrixHydrologyShreve();
 			break;
 		case HydrologyDCInefficientAnalysisEnum:
-			Ke=CreateKMatrixHydrologyDCInefficient();
+			return CreateKMatrixHydrologyDCInefficient();
 			break;
 		case HydrologyDCEfficientAnalysisEnum:
-			Ke=CreateKMatrixHydrologyDCEfficient();
+			return CreateKMatrixHydrologyDCEfficient();
 			break;
 		#endif
 		#ifdef _HAVE_BALANCED_
 		case BalancethicknessAnalysisEnum:
-			Ke=CreateKMatrixBalancethickness();
+			return CreateKMatrixBalancethickness();
+			break;
+		case BalancevelocityAnalysisEnum:
+			return CreateKMatrixBalancevelocity();
+			break;
+		case SmoothedSurfaceSlopeXAnalysisEnum: case SmoothedSurfaceSlopeYAnalysisEnum:
+			return CreateKMatrixSmoothedSlope();
 			break;
 		#endif
 		#ifdef _HAVE_CONTROL_
 		case AdjointBalancethicknessAnalysisEnum:
-			Ke=CreateKMatrixAdjointBalancethickness();
+			return CreateKMatrixAdjointBalancethickness();
 			break;
 		case AdjointHorizAnalysisEnum:
-			Ke=CreateKMatrixAdjointMacAyeal();
+			return CreateKMatrixAdjointSSA();
 			break;
 		#endif
@@ -236,41 +267,38 @@
 	}
 
-	/*Add to global matrix*/
-	if(Ke){
-		Ke->AddToGlobal(Kff,Kfs);
-		delete Ke;
-	}
+	/*Make compiler happy*/
+	return NULL;
 }
 /*}}}*/
 /*FUNCTION Tria::CreateMassMatrix {{{*/
 ElementMatrix* Tria::CreateMassMatrix(void){
-
-	/*constants: */
-	const int    numdof=NDOF1*NUMVERTICES;
 
 	/* Intermediaries */
 	IssmDouble  D,Jdet;
 	IssmDouble  xyz_list[NUMVERTICES][3];
-	IssmDouble  basis[numdof];
-	GaussTria  *gauss = NULL;
-
-	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
-
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke    = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 
 	/* Start looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
 
-		GetNodalFunctions(&basis[0],gauss);
+		GetNodalFunctions(basis,gauss);
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
 		D=gauss->weight*Jdet;
 
-		TripleMultiply(&basis[0],1,3,1,
+		TripleMultiply(basis,1,numnodes,1,
 					&D,1,1,0,
-					&basis[0],1,3,0,
+					basis,1,numnodes,0,
 					&Ke->values[0],1);
 	}
@@ -278,4 +306,5 @@
 	/*Clean up and return*/
 	delete gauss;
+	xDelete<IssmDouble>(basis);
 	return Ke;
 }
@@ -287,6 +316,39 @@
 }
 /*}}}*/
-/*FUNCTION Tria::CreatePVector {{{*/
+/*FUNCTION Tria::CreatePVector(Vector<IssmDouble>* pf) {{{*/
 void  Tria::CreatePVector(Vector<IssmDouble>* pf){
+
+	/*Skip if water element*/
+	if(NoIceInElement()) return;
+
+	/*Create element load vector*/
+	ElementVector* pe = CreatePVector();
+
+	/*Add to global Vector*/
+	if(pe){
+		/*Static condensation if requested*/
+		if(this->element_type==P1bubblecondensedEnum){
+			int size   = nodes[3]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int offset = 0;
+			for(int i=0;i<3;i++) offset+=nodes[i]->GetNumberOfDofs(NoneApproximationEnum,GsetEnum);
+			int* indices=xNew<int>(size);
+			for(int i=0;i<size;i++) indices[i] = offset+i;
+
+			this->element_type=P1bubbleEnum;
+			ElementMatrix* Ke = CreateKMatrix();
+			this->element_type=P1bubblecondensedEnum;
+
+			pe->StaticCondensation(Ke,size,indices);
+			xDelete<int>(indices);
+			delete Ke;
+		}
+
+		pe->AddToGlobal(pf);
+		delete pe;
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVector(void){{{*/
+ElementVector* Tria::CreatePVector(void){
 
 	/*retrive parameters: */
@@ -301,55 +363,61 @@
 
 	/*Skip if water element*/
-	if(IsOnWater()) return;
+	if(NoIceInElement()) return NULL;
 
 	/*Just branch to the correct load generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-		#ifdef _HAVE_DIAGNOSTIC_
-		case DiagnosticHorizAnalysisEnum:
-			pe=CreatePVectorDiagnosticMacAyeal();
+#ifdef _HAVE_STRESSBALANCE_
+		case StressbalanceAnalysisEnum:
+			return CreatePVectorStressbalanceSSA();
 			break;
-		case DiagnosticHutterAnalysisEnum:
-			pe=CreatePVectorDiagnosticHutter();
+		case StressbalanceSIAAnalysisEnum:
+			return CreatePVectorStressbalanceSIA();
 			break;
-		#endif
+#endif
 		case BedSlopeXAnalysisEnum: case SurfaceSlopeXAnalysisEnum: case BedSlopeYAnalysisEnum: case SurfaceSlopeYAnalysisEnum:
-			pe=CreatePVectorSlope();
+			return CreatePVectorSlope();
 			break;
-		case PrognosticAnalysisEnum:
-			pe=CreatePVectorPrognostic();
+		case MasstransportAnalysisEnum:
+			return CreatePVectorMasstransport();
 			break;
-		#ifdef _HAVE_HYDROLOGY_
+#ifdef _HAVE_HYDROLOGY_
 		case HydrologyShreveAnalysisEnum:
-			pe=CreatePVectorHydrologyShreve();
+			return CreatePVectorHydrologyShreve();
 			break;
 		case HydrologyDCInefficientAnalysisEnum:
-			pe=CreatePVectorHydrologyDCInefficient();
+			return CreatePVectorHydrologyDCInefficient();
 			break;
 		case HydrologyDCEfficientAnalysisEnum:
-			pe=CreatePVectorHydrologyDCEfficient();
+			return CreatePVectorHydrologyDCEfficient();
 			break;
-		#endif
-		#ifdef _HAVE_BALANCED_
+#endif
+#ifdef _HAVE_BALANCED_
 		case BalancethicknessAnalysisEnum:
-			pe=CreatePVectorBalancethickness();
+			return CreatePVectorBalancethickness();
 			break;
-		#endif
-		#ifdef _HAVE_CONTROL_
+		case BalancevelocityAnalysisEnum:
+			return CreatePVectorBalancevelocity();
+			break;
+		case SmoothedSurfaceSlopeXAnalysisEnum:
+			return CreatePVectorSmoothedSlopeX();
+			break;
+		case SmoothedSurfaceSlopeYAnalysisEnum:
+			return CreatePVectorSmoothedSlopeY();
+			break;
+#endif
+#ifdef _HAVE_CONTROL_
 		case AdjointBalancethicknessAnalysisEnum:
-			pe=CreatePVectorAdjointBalancethickness();
+			return CreatePVectorAdjointBalancethickness();
 			break;
 		case AdjointHorizAnalysisEnum:
-			pe=CreatePVectorAdjointHoriz();
+			return CreatePVectorAdjointHoriz();
 			break;
-		#endif
+#endif
 		default:
 			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
 	}
 
-	/*Add to global Vector*/
-	if(pe){
-		pe->AddToGlobal(pf);
-		delete pe;
-	}
+	/*make compiler happy*/
+	return NULL;
 }
 /*}}}*/
@@ -357,18 +425,16 @@
 ElementVector* Tria::CreatePVectorSlope(void){
 
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
-
 	/*Intermediaries */
-	int        i;
-	int        analysis_type;
+	int        i,analysis_type;
 	IssmDouble Jdet;
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble slope[2];
-	IssmDouble basis[3];
-	GaussTria* gauss=NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
 
 	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -384,5 +450,5 @@
 
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
@@ -390,17 +456,18 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctions(basis, gauss);
+		GetNodalFunctions(basis,gauss);
 
 		slope_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],gauss);
 
-		if ( (analysis_type==SurfaceSlopeXAnalysisEnum) || (analysis_type==BedSlopeXAnalysisEnum)){
-			for(i=0;i<numdof;i++) pe->values[i]+=Jdet*gauss->weight*slope[0]*basis[i];
-		}
-		if ( (analysis_type==SurfaceSlopeYAnalysisEnum) || (analysis_type==BedSlopeYAnalysisEnum)){
-			for(i=0;i<numdof;i++) pe->values[i]+=Jdet*gauss->weight*slope[1]*basis[i];
+		if( (analysis_type==SurfaceSlopeXAnalysisEnum) || (analysis_type==BedSlopeXAnalysisEnum)){
+			for(i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*slope[0]*basis[i];
+		}
+		if( (analysis_type==SurfaceSlopeYAnalysisEnum) || (analysis_type==BedSlopeYAnalysisEnum)){
+			for(i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*slope[1]*basis[i];
 		}
 	}
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
 	delete gauss;
 	return pe;
@@ -420,11 +487,11 @@
 
 	/*Skip if water element*/
-	if(IsOnWater()) return;
+	if(NoIceInElement()) return;
 
 	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-#ifdef _HAVE_DIAGNOSTIC_
-		case DiagnosticHorizAnalysisEnum:
-			Ke=CreateJacobianDiagnosticMacayeal();
+#ifdef _HAVE_STRESSBALANCE_
+		case StressbalanceAnalysisEnum:
+			Ke=CreateJacobianStressbalanceSSA();
 			break;
 #endif
@@ -560,7 +627,4 @@
 	if (results) results->DeepEcho();
 	else _printf_("results=NULL\n");
-
-	_printf_("neighboor sids: \n");
-	_printf_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2] << "\n");
 
 	return;
@@ -672,7 +736,4 @@
 	if (results) results->Echo();
 	else _printf_("results=NULL\n");
-
-	_printf_("neighboor sids: \n");
-	_printf_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2] << "\n");
 }
 /*}}}*/
@@ -701,19 +762,56 @@
 }
 /*}}}*/
+/*FUNCTION Tria::GetAreaCoordinates{{{*/
+void Tria::GetAreaCoordinates(IssmDouble* area_coordinates,IssmDouble xyz_zero[3][3],IssmDouble xyz_list[3][3],int numpoints){
+	/*Computeportion of the element that is grounded*/ 
+
+	int         i,j,k;
+	IssmDouble  area_init,area_portion;
+	IssmDouble  xyz_bis[NUMVERTICES][3];
+
+	area_init=GetArea();
+
+	/*Initialize xyz_list with original xyz_list of triangle coordinates*/
+	for(j=0;j<3;j++){ 
+		for(k=0;k<3;k++){
+			xyz_bis[j][k]=xyz_list[j][k];
+		}
+	}
+	for(i=0;i<numpoints;i++){
+		for(j=0;j<3;j++){ 
+			for(k=0;k<3;k++){
+				/*Change appropriate line*/
+				xyz_bis[j][k]=xyz_zero[i][k];
+			}
+
+			/*Compute area fraction*/
+			area_portion=fabs(xyz_bis[1][0]*xyz_bis[2][1] - xyz_bis[1][1]*xyz_bis[2][0] + xyz_bis[0][0]*xyz_bis[1][1] - xyz_bis[0][1]*xyz_bis[1][0] + xyz_bis[2][0]*xyz_bis[0][1] - xyz_bis[2][1]*xyz_bis[0][0])/2.;
+			*(area_coordinates+3*i+j)=area_portion/area_init;
+
+			/*Reinitialize xyz_list*/
+			for(k=0;k<3;k++){
+				/*Reinitialize xyz_list with original coordinates*/
+				xyz_bis[j][k]=xyz_list[j][k];
+			}
+		}
+	}
+}
+/*}}}*/
 /*FUNCTION Tria::GetDofList {{{*/
 void  Tria::GetDofList(int** pdoflist, int approximation_enum,int setenum){
 
-	int i,j;
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*First, figure out size of doflist and create it: */
+	int numberofdofs=0;
+	for(int i=0;i<numnodes;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
+
+	/*Allocate output*/
+	int* doflist=xNew<int>(numberofdofs);
+
+	/*Populate: */
 	int count=0;
-	int numberofdofs=0;
-	int* doflist=NULL;
-
-	/*First, figure out size of doflist and create it: */
-	for(i=0;i<3;i++) numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
-	doflist=xNew<int>(numberofdofs);
-
-	/*Populate: */
-	count=0;
-	for(i=0;i<3;i++){
+	for(int i=0;i<numnodes;i++){
 		nodes[i]->GetDofList(doflist+count,approximation_enum,setenum);
 		count+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
@@ -732,10 +830,56 @@
 }
 /*}}}*/
-/*FUNCTION Tria::GetHorizontalNeighboorSids {{{*/
-int* Tria::GetHorizontalNeighboorSids(){
-
-	/*return TriaRef field*/
-	return &this->horizontalneighborsids[0];
-
+/*FUNCTION Tria::GetGroundedPart{{{*/
+void Tria::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;
 }
 /*}}}*/
@@ -744,17 +888,17 @@
 	/*Computeportion of the element that is grounded*/ 
 
-	bool               mainlyfloating = true;
-	const IssmPDouble  epsilon= 1.e-15;
+	bool              mainlyfloating = true;
+	const IssmPDouble epsilon        = 1.e-15;
 	IssmDouble         phi,s1,s2,area_init,area_grounded;
-	IssmDouble         gl[3];
+	IssmDouble         gl[NUMVERTICES];
 	IssmDouble         xyz_bis[3][3];
 
 	/*Recover parameters and values*/
-	GetInputListOnVertices(&gl[0],GLlevelsetEnum);
+	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;
+	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*/
@@ -842,56 +986,110 @@
 }
 /*}}}*/
-/*FUNCTION Tria::GetGroundedPart{{{*/
-void Tria::GetGroundedPart(int* point1,IssmDouble* fraction1,IssmDouble* fraction2, bool* mainlyfloating){
+/*FUNCTION Tria::GetSegmentNormal {{{*/
+void Tria:: GetSegmentNormal(IssmDouble* normal,IssmDouble xyz_list[2][3]){
+
+	/*Build unit outward pointing vector*/
+	IssmDouble vector[2];
+	IssmDouble norm;
+
+	vector[0]=xyz_list[1][0] - xyz_list[0][0];
+	vector[1]=xyz_list[1][1] - xyz_list[0][1];
+
+	norm=sqrt(vector[0]*vector[0] + vector[1]*vector[1]);
+
+	normal[0]= + vector[1]/norm;
+	normal[1]= - vector[0]/norm;
+}
+/*}}}*/
+/*FUNCTION Tria::GetZeroLevelsetCoordinates{{{*/
+void Tria::GetZeroLevelsetCoordinates(IssmDouble* xyz_zero,IssmDouble xyz_list[3][3],int levelsetenum){
 	/*Computeportion of the element that is grounded*/ 
 
-	bool               floating=true;
-	int                point;
-	const IssmPDouble  epsilon= 1.e-15;
-	IssmDouble         gl[3];
-	IssmDouble         f1,f2;
+	int         normal_orientation;
+	IssmDouble  s1,s2;
+	IssmDouble  levelset[NUMVERTICES];
 
 	/*Recover parameters and values*/
-	GetInputListOnVertices(&gl[0],GLlevelsetEnum);
-
-	/*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;
+	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;
+		/*New point 1*/
+		xyz_zero[3*normal_orientation+0]=xyz_list[2][0]+s1*(xyz_list[1][0]-xyz_list[2][0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[2][1]+s1*(xyz_list[1][1]-xyz_list[2][1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[2][2]+s1*(xyz_list[1][2]-xyz_list[2][2]);
+
+		/*New point 0*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[2][0]+s2*(xyz_list[0][0]-xyz_list[2][0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[2][1]+s2*(xyz_list[0][1]-xyz_list[2][1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[2][2]+s2*(xyz_list[0][2]-xyz_list[2][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][0]+s1*(xyz_list[2][0]-xyz_list[0][0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[0][1]+s1*(xyz_list[2][1]-xyz_list[0][1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[0][2]+s1*(xyz_list[2][2]-xyz_list[0][2]);
+
+		/*New point 2*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[0][0]+s2*(xyz_list[1][0]-xyz_list[0][0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[0][1]+s2*(xyz_list[1][1]-xyz_list[0][1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[0][2]+s2*(xyz_list[1][2]-xyz_list[0][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][0]+s1*(xyz_list[0][0]-xyz_list[1][0]);
+		xyz_zero[3*normal_orientation+1]=xyz_list[1][1]+s1*(xyz_list[0][1]-xyz_list[1][1]);
+		xyz_zero[3*normal_orientation+2]=xyz_list[1][2]+s1*(xyz_list[0][2]-xyz_list[1][2]);
+
+		/*New point 2*/
+		xyz_zero[3*(1-normal_orientation)+0]=xyz_list[1][0]+s2*(xyz_list[2][0]-xyz_list[1][0]);
+		xyz_zero[3*(1-normal_orientation)+1]=xyz_list[1][1]+s2*(xyz_list[2][1]-xyz_list[1][1]);
+		xyz_zero[3*(1-normal_orientation)+2]=xyz_list[1][2]+s2*(xyz_list[2][2]-xyz_list[1][2]);
+	}
+	else if(levelset[0]==0 && levelset[1]==0){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[0][0];
+		xyz_zero[3*0+1]=xyz_list[0][1];
+		xyz_zero[3*0+2]=xyz_list[0][2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[1][0];
+		xyz_zero[3*1+1]=xyz_list[1][1];
+		xyz_zero[3*1+2]=xyz_list[1][2];
+	}
+	else if(levelset[0]==0 && levelset[2]==0){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[2][0];
+		xyz_zero[3*0+1]=xyz_list[2][1];
+		xyz_zero[3*0+2]=xyz_list[2][2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[0][0];
+		xyz_zero[3*1+1]=xyz_list[0][1];
+		xyz_zero[3*1+2]=xyz_list[0][2];
+	}
+	else if(levelset[1]==0 && levelset[2]==0){ //front is on point 0 and 1
+		xyz_zero[3*0+0]=xyz_list[1][0];
+		xyz_zero[3*0+1]=xyz_list[1][1];
+		xyz_zero[3*0+2]=xyz_list[1][2];
+
+		/*New point 2*/
+		xyz_zero[3*1+0]=xyz_list[2][0];
+		xyz_zero[3*1+1]=xyz_list[2][1];
+		xyz_zero[3*1+2]=xyz_list[2][2];
+	}
+	else _error_("Case not covered");
 }
 /*}}}*/
@@ -912,23 +1110,26 @@
 	_assert_(sidlist);
 	_assert_(nodes);
-
-	for(int i=0;i<NUMVERTICES;i++){
+	int numnodes = this->NumberofNodes();
+
+	for(int i=0;i<numnodes;i++){
 		sidlist[i]=nodes[i]->Sid();
 	}
 }
 /*}}}*/
-/*FUNCTION Tria::GetNumberOfNodes{{{*/
+/*FUNCTION Tria::GetNodesLidList{{{*/
+void Tria::GetNodesLidList(int* lidlist){
+
+	_assert_(lidlist);
+	_assert_(nodes);
+	int numnodes = this->NumberofNodes();
+
+	for(int i=0;i<numnodes;i++){
+		lidlist[i]=nodes[i]->Lid();
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::GetNumberOfNodes;{{{*/
 int Tria::GetNumberOfNodes(void){
-
-	if(this->nodes==NULL) return 0;
-
-	switch(this->element_type){
-		case P1Enum:
-			return 3;
-		case P1DGEnum:
-			return 3;
-		default:
-			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
-	}
+	return this->NumberofNodes();
 }
 /*}}}*/
@@ -1007,8 +1208,8 @@
 
 	/* Start looping on the number of vertices: */
-	if (input){
+	if(input){
 		GaussTria* gauss=new GaussTria();
-		for (int iv=0;iv<this->NumberofNodes();iv++){
-			gauss->GaussNode(numnodes,iv);
+		for(int iv=0;iv<this->NumberofNodes();iv++){
+			gauss->GaussNode(this->element_type,iv);
 			input->GetInputValue(&pvalue[iv],gauss);
 		}
@@ -1016,5 +1217,5 @@
 	}
 	else{
-		for (int iv=0;iv<numnodes;iv++) pvalue[iv]=defaultvalue;
+		for(int iv=0;iv<numnodes;iv++) pvalue[iv]=defaultvalue;
 	}
 }
@@ -1033,5 +1234,5 @@
 	GaussTria* gauss=new GaussTria();
 	for (int iv=0;iv<this->NumberofNodes();iv++){
-		gauss->GaussNode(numnodes,iv);
+		gauss->GaussNode(this->element_type,iv);
 		input->GetInputValue(&pvalue[iv],gauss);
 	}
@@ -1066,5 +1267,5 @@
 /*FUNCTION Tria::GetConnectivityList {{{*/
 void  Tria::GetConnectivityList(int* connectivity){
-	for(int i=0;i<NUMVERTICES;i++) connectivity[i]=nodes[i]->GetConnectivity();
+	for(int i=0;i<NUMVERTICES;i++) connectivity[i]=vertices[i]->Connectivity();
 }
 /*}}}*/
@@ -1078,10 +1279,10 @@
 	/*Just branch to the correct InputUpdateFromSolution generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-	#ifdef _HAVE_DIAGNOSTIC_
-	case DiagnosticHorizAnalysisEnum:
-		GetSolutionFromInputsDiagnosticHoriz(solution);
+	#ifdef _HAVE_STRESSBALANCE_
+	case StressbalanceAnalysisEnum:
+		GetSolutionFromInputsStressbalanceHoriz(solution);
 		break;
-	case DiagnosticHutterAnalysisEnum:
-		GetSolutionFromInputsDiagnosticHutter(solution);
+	case StressbalanceSIAAnalysisEnum:
+		GetSolutionFromInputsStressbalanceSIA(solution);
 		break;
 	#endif
@@ -1259,9 +1460,9 @@
 	/*If we don't find it, no big deal, just don't do the transfer. Otherwise, build a new Result 
 	 * object out of the input, with the additional step and time information: */
-	this->results->AddObject((Object*)input->SpawnResult(step,time));
+	this->results->AddResult(input->SpawnResult(step,time));
 
 	#ifdef _HAVE_CONTROL_
 	if(input->ObjectEnum()==ControlInputEnum){
-		if(((ControlInput*)input)->gradient!=NULL) this->results->AddObject((Object*)((ControlInput*)input)->SpawnGradient(step,time));
+		if(((ControlInput*)input)->gradient!=NULL) this->results->AddResult(((ControlInput*)input)->SpawnGradient(step,time));
 	}
 	#endif
@@ -1317,5 +1518,5 @@
 	/*Recover vertices ids needed to initialize inputs*/
 	for(i=0;i<3;i++){ 
-		tria_vertex_ids[i]=reCast<int>(iomodel->Data(MeshElementsEnum)[3*index+i]); //ids for vertices are in the elements array from Matlab
+		tria_vertex_ids[i]=reCast<int>(iomodel->elements[3*index+i]); //ids for vertices are in the elements array from Matlab
 	}
 
@@ -1399,10 +1600,10 @@
 	/*Just branch to the correct InputUpdateFromSolution generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-		#ifdef _HAVE_DIAGNOSTIC_
-		case DiagnosticHorizAnalysisEnum:
-			InputUpdateFromSolutionDiagnosticHoriz(solution);
+		#ifdef _HAVE_STRESSBALANCE_
+		case StressbalanceAnalysisEnum:
+			InputUpdateFromSolutionStressbalanceHoriz(solution);
 			break;
-		case DiagnosticHutterAnalysisEnum:
-			InputUpdateFromSolutionDiagnosticHoriz(solution);
+		case StressbalanceSIAAnalysisEnum:
+			InputUpdateFromSolutionStressbalanceHoriz(solution);
 			break;
 		#endif
@@ -1412,5 +1613,5 @@
 			break;
 		case AdjointBalancethicknessAnalysisEnum:
-			InputUpdateFromSolutionAdjointBalancethickness(solution);
+			InputUpdateFromSolutionOneDof(solution,AdjointEnum);
 			break;
 		#endif
@@ -1430,4 +1631,13 @@
 			InputUpdateFromSolutionOneDof(solution,ThicknessEnum);
 			break;
+		case BalancevelocityAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,VelEnum);
+			break;
+		case SmoothedSurfaceSlopeXAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,SurfaceSlopeXEnum);
+			break;
+		case SmoothedSurfaceSlopeYAnalysisEnum:
+			InputUpdateFromSolutionOneDof(solution,SurfaceSlopeYEnum);
+			break;
 		#endif
 		case BedSlopeXAnalysisEnum:
@@ -1443,6 +1653,6 @@
 			InputUpdateFromSolutionOneDof(solution,SurfaceSlopeYEnum);
 			break;
-		case PrognosticAnalysisEnum:
-			InputUpdateFromSolutionPrognostic(solution);
+		case MasstransportAnalysisEnum:
+			InputUpdateFromSolutionMasstransport(solution);
 			break;
 		default:
@@ -1454,13 +1664,16 @@
 void  Tria::InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type){
 
-	const int  numdof         = NDOF1*NUMVERTICES;
-	int*       doflist        = NULL;
-	IssmDouble values[numdof];
-
-	/*Get dof list: */
+	/*Intermediary*/
+	int* doflist = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Fetch dof list and allocate solution vector*/
 	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numnodes);
 
 	/*Use the dof list to index into the solution vector: */
-	for(int i=0;i<numdof;i++){
+	for(int i=0;i<numnodes;i++){
 		values[i]=solution[doflist[i]];
 		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
@@ -1471,29 +1684,32 @@
 
 	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
 	xDelete<int>(doflist);
 }
 /*}}}*/
-/*FUNCTION Tria::InputUpdateFromSolutionPrognostic{{{*/
-void  Tria::InputUpdateFromSolutionPrognostic(IssmDouble* solution){
+/*FUNCTION Tria::InputUpdateFromSolutionMasstransport{{{*/
+void  Tria::InputUpdateFromSolutionMasstransport(IssmDouble* solution){
 
 	/*Intermediaries*/
-	const int numdof = NDOF1*NUMVERTICES;
-
-	int       i,hydroadjustment;
-	int*      doflist=NULL;
-	IssmDouble    rho_ice,rho_water,minthickness;
-	IssmDouble    newthickness[numdof];
-	IssmDouble    newbed[numdof];
-	IssmDouble    newsurface[numdof];
-	IssmDouble    oldbed[NUMVERTICES];
-	IssmDouble    oldsurface[NUMVERTICES];
-	IssmDouble    oldthickness[NUMVERTICES];
-
-	/*Get dof list: */
+	int        i,hydroadjustment;
+	int*       doflist=NULL;
+	IssmDouble rho_ice,rho_water,minthickness;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Fetch dof list and allocate solution vector*/
 	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* newthickness = xNew<IssmDouble>(numnodes);
+	IssmDouble* newbed       = xNew<IssmDouble>(numnodes);
+	IssmDouble* newsurface   = xNew<IssmDouble>(numnodes);
+	IssmDouble* oldthickness = xNew<IssmDouble>(numnodes);
+	IssmDouble* oldbed       = xNew<IssmDouble>(numnodes);
+	IssmDouble* oldsurface   = xNew<IssmDouble>(numnodes);
+	IssmDouble* phi          = xNew<IssmDouble>(numnodes);
 
 	/*Use the dof list to index into the solution vector: */
-	this->parameters->FindParam(&minthickness,PrognosticMinThicknessEnum);
-	for(i=0;i<numdof;i++){
+	this->parameters->FindParam(&minthickness,MasstransportMinThicknessEnum);
+	for(i=0;i<numnodes;i++){
 		newthickness[i]=solution[doflist[i]];
 		if(xIsNan<IssmDouble>(newthickness[i])) _error_("NaN found in solution vector");
@@ -1503,28 +1719,28 @@
 
 	/*Get previous bed, thickness and surface*/
-	GetInputListOnVertices(&oldbed[0],BedEnum);
-	GetInputListOnVertices(&oldsurface[0],SurfaceEnum);
-	GetInputListOnVertices(&oldthickness[0],ThicknessEnum);
-
-	/*Fing PrognosticHydrostaticAdjustment to figure out how to update the geometry:*/
-	this->parameters->FindParam(&hydroadjustment,PrognosticHydrostaticAdjustmentEnum);
+	GetInputListOnNodes(&oldbed[0],BedEnum);
+	GetInputListOnNodes(&oldsurface[0],SurfaceEnum);
+	GetInputListOnNodes(&oldthickness[0],ThicknessEnum);
+	GetInputListOnNodes(&phi[0],MaskGroundediceLevelsetEnum);
+
+	/*Find MasstransportHydrostaticAdjustment to figure out how to update the geometry:*/
+	this->parameters->FindParam(&hydroadjustment,MasstransportHydrostaticAdjustmentEnum);
 	rho_ice=matpar->GetRhoIce();
 	rho_water=matpar->GetRhoWater();
 
-	for(i=0;i<numdof;i++) {
+	for(i=0;i<numnodes;i++) {
 		/*If shelf: hydrostatic equilibrium*/
-		if (this->nodes[i]->IsGrounded()){
-			newsurface[i]=oldbed[i]+newthickness[i]; //surface = oldbed + newthickness
-			newbed[i]=oldbed[i];               //same bed: do nothing
+		if (phi[i]>0.){
+			newsurface[i] = oldbed[i]+newthickness[i]; //surface = oldbed + newthickness
+			newbed[i]     = oldbed[i];                 //same bed: do nothing
 		}
 		else{ //this is an ice shelf
-
 			if(hydroadjustment==AbsoluteEnum){
-				newsurface[i]=newthickness[i]*(1-rho_ice/rho_water);
-				newbed[i]=newthickness[i]*(-rho_ice/rho_water);
+				newsurface[i] = newthickness[i]*(1-rho_ice/rho_water);
+				newbed[i]     = newthickness[i]*(-rho_ice/rho_water);
 			}
 			else if(hydroadjustment==IncrementalEnum){
-				newsurface[i]=oldsurface[i]+(1.0-rho_ice/rho_water)*(newthickness[i]-oldthickness[i]); //surface = oldsurface + (1-di) * dH 
-				newbed[i]=oldbed[i]-rho_ice/rho_water*(newthickness[i]-oldthickness[i]); //bed = oldbed + di * dH
+				newsurface[i] = oldsurface[i]+(1.0-rho_ice/rho_water)*(newthickness[i]-oldthickness[i]); //surface = oldsurface + (1-di) * dH
+				newbed[i]     = oldbed[i]-rho_ice/rho_water*(newthickness[i]-oldthickness[i]); //bed               = oldbed + di * dH
 			}
 			else _error_("Hydrostatic adjustment " << hydroadjustment << " (" << EnumToStringx(hydroadjustment) << ") not supported yet");
@@ -1538,4 +1754,11 @@
 
 	/*Free ressources:*/
+	xDelete<IssmDouble>(newthickness);
+	xDelete<IssmDouble>(newbed);
+	xDelete<IssmDouble>(newsurface);
+	xDelete<IssmDouble>(oldthickness);
+	xDelete<IssmDouble>(oldbed);
+	xDelete<IssmDouble>(oldsurface);
+	xDelete<IssmDouble>(phi);
 	xDelete<int>(doflist);
 }
@@ -1544,10 +1767,11 @@
 void  Tria::InputUpdateFromVector(IssmDouble* vector, int name, int type){
 
-	const int   numdof         = NDOF1 *NUMVERTICES;
-	int        *doflist        = NULL;
-	IssmDouble  values[numdof];
 
 	/*Check that name is an element input*/
 	if (!IsInput(name)) return;
+
+	int         numnodes;
+	int        *doflist = NULL;
+	IssmDouble *values  = NULL;
 
 	switch(type){
@@ -1579,14 +1803,18 @@
 
 	case NodesEnum:
-		/*Get dof list: */
+
+		/*Get number of nodes and dof list: */
+		numnodes = this->NumberofNodes();
+		values   = xNew<IssmDouble>(numnodes);
 		GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
 
 		/*Use the dof list to index into the vector: */
-		for(int i=0;i<numdof;i++){
+		for(int i=0;i<numnodes;i++){
 			values[i]=vector[doflist[i]];
-			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
-		}
+			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in vector");
+		}
+
 		/*Add input to the element: */
-		this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+		this->inputs->AddInput(new TriaInput(name,values,this->element_type));
 
 		/*Free ressources:*/
@@ -1595,13 +1823,15 @@
 
 	case NodeSIdEnum:
-		for(int i=0;i<NUMVERTICES;i++){
+
+		/*Get number of nodes and dof list: */
+		numnodes = this->NumberofNodes();
+		values   = xNew<IssmDouble>(numnodes);
+
+		for(int i=0;i<numnodes;i++){
 			values[i]=vector[nodes[i]->Sid()];
-			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
+			if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in vector");
 		}
 		/*Add input to the element: */
-		this->inputs->AddInput(new TriaInput(name,values,P1Enum));
-
-		/*Free ressources:*/
-		xDelete<int>(doflist);
+		this->inputs->AddInput(new TriaInput(name,values,this->element_type));
 		return;
 
@@ -1610,14 +1840,8 @@
 	}
 
-}
-/*}}}*/
-/*FUNCTION Tria::InputUpdateFromVector(int* vector, int name, int type);{{{*/
-void  Tria::InputUpdateFromVector(int* vector, int name, int type){
-	_error_("not supported yet!");
-}
-/*}}}*/
-/*FUNCTION Tria::InputUpdateFromVector(bool* vector, int name, int type);{{{*/
-void  Tria::InputUpdateFromVector(bool* vector, int name, int type){
-	_error_("not supported yet!");
+	/*Clean-up*/
+	xDelete<int>(doflist);
+	xDelete<IssmDouble>(values);
+
 }
 /*}}}*/
@@ -1651,12 +1875,4 @@
 	IssmDouble time;
 	TransientInput* transientinput=NULL;
-	int    numberofvertices;
-	int    numberofelements;
-	IssmDouble yts;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->Constant(&yts,ConstantsYtsEnum);
 
 	/*Branch on type of vector: nodal or elementary: */
@@ -1665,10 +1881,10 @@
 		/*Recover vertices ids needed to initialize inputs*/
 		for(i=0;i<3;i++){ 
-			_assert_(iomodel->Data(MeshElementsEnum));
-			tria_vertex_ids[i]=reCast<int>(iomodel->Data(MeshElementsEnum)[3*index+i]); //ids for vertices are in the elements array from Matlab
+			_assert_(iomodel->elements);
+			tria_vertex_ids[i]=reCast<int>(iomodel->elements[3*index+i]); //ids for vertices are in the elements array from Matlab
 		}
 
 		/*Are we in transient or static? */
-		if(M==numberofvertices){
+		if(M==iomodel->numberofvertices){
 
 			/*create input values: */
@@ -1678,5 +1894,5 @@
 			this->inputs->AddInput(new TriaInput(vector_enum,nodeinputs,P1Enum));
 		}
-		else if(M==numberofvertices+1){
+		else if(M==iomodel->numberofvertices+1){
 			/*create transient input: */
 			for(t=0;t<N;t++){ //N is the number of times
@@ -1689,5 +1905,5 @@
 
 				/*time? :*/
-				time=(IssmDouble)vector[(M-1)*N+t]*yts;
+				time=(IssmDouble)vector[(M-1)*N+t];
 
 				if(t==0) transientinput=new TransientInput(vector_enum);
@@ -1696,9 +1912,9 @@
 			this->inputs->AddInput(transientinput);
 		}
-		else _error_("nodal vector is either numberofnodes or numberofnodes+1 long. Field provided (" << EnumToStringx(vector_enum) << ") is " << M << " long");
+		else _error_("nodal vector is either numberofvertices or numberofvertices+1 long. Field provided (" << EnumToStringx(vector_enum) << ") is " << M << " long");
 	}
 	else if(vector_type==2){ //element vector
 		/*Are we in transient or static? */
-		if(M==numberofelements){
+		if(M==iomodel->numberofelements){
 
 			/*static mode: create an input out of the element value: */
@@ -1732,5 +1948,6 @@
 				name==BathymetryEnum ||
 				name==BedEnum ||
-				name==GLlevelsetEnum ||
+				name==MaskGroundediceLevelsetEnum ||
+				name==MaskIceLevelsetEnum ||
 				name==SurfaceSlopeXEnum ||
 				name==SurfaceSlopeYEnum ||
@@ -1783,16 +2000,28 @@
 
 	bool shelf;
-	inputs->GetInputValue(&shelf,MaskElementonfloatingiceEnum);
+	int  migration_style;
+	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+
+	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==AgressiveMigrationEnum || migration_style==SoftMigrationEnum){ //Floating if all nodes are floating
+		if(this->inputs->Min(MaskGroundediceLevelsetEnum) > 0.) shelf=false;
+		else shelf=true;
+	}
+	else _error_("migration_style not implemented yet");
+
 	return shelf;
 }
 /*}}}*/
-/*FUNCTION Tria::IsNodeOnShelf {{{*/
-bool   Tria::IsNodeOnShelf(){
+/*FUNCTION Tria::IsNodeOnShelfFromFlags {{{*/
+bool   Tria::IsNodeOnShelfFromFlags(IssmDouble* flags){
 
 	int  i;
 	bool shelf=false;
 
-	for(i=0;i<3;i++){
-		if (nodes[i]->IsFloating()){
+	for(i=0;i<NUMVERTICES;i++){
+		if (flags[vertices[i]->Pid()]<0.){
 			shelf=true;
 			break;
@@ -1802,25 +2031,16 @@
 }
 /*}}}*/
-/*FUNCTION Tria::IsNodeOnShelfFromFlags {{{*/
-bool   Tria::IsNodeOnShelfFromFlags(IssmDouble* flags){
-
-	int  i;
-	bool shelf=false;
-
-	for(i=0;i<NUMVERTICES;i++){
-		if (reCast<bool>(flags[nodes[i]->Sid()])){
-			shelf=true;
-			break;
-		}
-	}
-	return shelf;
-}
-/*}}}*/
-/*FUNCTION Tria::IsOnWater {{{*/
-bool   Tria::IsOnWater(){
-
-	bool water;
-	inputs->GetInputValue(&water,MaskElementonwaterEnum);
-	return water;
+/*FUNCTION Tria::NoIceInElement {{{*/
+bool   Tria::NoIceInElement(){
+
+	/*Get levelset*/
+	IssmDouble ls[NUMVERTICES];
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/*If the level set is >0, ice is present in this element*/
+	if(ls[0]>0. || ls[1]>0. || ls[2]>0.) return false;
+
+	/*If the level set is awlays <=0, there is no ice here*/
+	return true;
 }
 /*}}}*/
@@ -2115,5 +2335,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
@@ -2203,60 +2423,79 @@
 }
 /*}}}*/
-/*FUNCTION Tria::Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type){{{*/
-void Tria::Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type){ //i is the element index
+/*FUNCTION Tria::Update{{{*/
+void Tria::Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finiteelement_type){
 
 	/*Intermediaries*/
-	int        i                   ,j;
-	int        tria_node_ids[3];
+	int        i,j;
 	int        tria_vertex_ids[3];
-	int        tria_type;
 	IssmDouble nodeinputs[3];
 	IssmDouble yts;
 	int        progstabilization,balancestabilization;
+	int        fe_ssa;
 	bool       dakota_analysis;
+	int        numnodes;
+	int*       tria_node_ids = NULL;
 
 	/*Checks if debuging*/
 	/*{{{*/
-	_assert_(iomodel->Data(MeshElementsEnum));
+	_assert_(iomodel->elements);
 	/*}}}*/
 
 	/*Fetch parameters: */
 	iomodel->Constant(&yts,ConstantsYtsEnum);
-	iomodel->Constant(&progstabilization,PrognosticStabilizationEnum);
+	iomodel->Constant(&progstabilization,MasstransportStabilizationEnum);
 	iomodel->Constant(&balancestabilization,BalancethicknessStabilizationEnum);
+	iomodel->Constant(&fe_ssa,FlowequationFeSSAEnum);
 	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
 
 	/*Recover element type*/
-	if ((analysis_type==PrognosticAnalysisEnum && progstabilization==3) || (analysis_type==BalancethicknessAnalysisEnum && balancestabilization==3)){
-		/*P1 Discontinuous Galerkin*/
-		tria_type=P1DGEnum;
-	}
-	else{
-		/*P1 Continuous Galerkin*/
-		tria_type=P1Enum;
-	}
-	this->SetElementType(tria_type,analysis_counter);
+	this->SetElementType(finiteelement_type,analysis_counter);
 
 	/*Recover vertices ids needed to initialize inputs*/
 	for(i=0;i<3;i++){ 
-		tria_vertex_ids[i]=reCast<int>(iomodel->Data(MeshElementsEnum)[3*index+i]); //ids for vertices are in the elements array from Matlab
+		tria_vertex_ids[i]=reCast<int>(iomodel->elements[3*index+i]); //ids for vertices are in the elements array from Matlab
 	}
 
 	/*Recover nodes ids needed to initialize the node hook.*/
-	if (tria_type==P1DGEnum){
-		/*Discontinuous Galerkin*/
-		tria_node_ids[0]=iomodel->nodecounter+3*index+1;
-		tria_node_ids[1]=iomodel->nodecounter+3*index+2;
-		tria_node_ids[2]=iomodel->nodecounter+3*index+3;
-	}
-	else{
-		/*Continuous Galerkin*/
-		for(i=0;i<3;i++){ 
-			tria_node_ids[i]=iomodel->nodecounter+reCast<int,IssmDouble>(*(iomodel->Data(MeshElementsEnum)+3*index+i)); //ids for vertices are in the elements array from Matlab
-		}
+	switch(finiteelement_type){
+		case P1Enum:
+			numnodes        = 3;
+			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];
+			break;
+		case P1DGEnum:
+			numnodes        = 3;
+			tria_node_ids   = xNew<int>(numnodes);
+			tria_node_ids[0]=iomodel->nodecounter+3*index+1;
+			tria_node_ids[1]=iomodel->nodecounter+3*index+2;
+			tria_node_ids[2]=iomodel->nodecounter+3*index+3;
+			break;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			numnodes        = 4;
+			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+index+1;
+			break;
+		case P2Enum:
+			numnodes        = 6;
+			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;
+			break;
+		default:
+			_error_("Finite element "<<EnumToStringx(finiteelement_type)<<" not supported yet");
 	}
 
 	/*hooks: */
-	this->SetHookNodes(tria_node_ids,3,analysis_counter); this->nodes=NULL; //set hook to nodes, for this analysis type
+	this->SetHookNodes(tria_node_ids,numnodes,analysis_counter); this->nodes=NULL;
+	xDelete<int>(tria_node_ids);
 
 	/*Fill with IoModel*/
@@ -2266,5 +2505,5 @@
 	switch(analysis_type){
 
-		case DiagnosticHorizAnalysisEnum:
+		case StressbalanceAnalysisEnum:
 
 			/*default vx,vy and vz: either observation or 0 */
@@ -2303,15 +2542,4 @@
 }
 /*}}}*/
-/*FUNCTION Tria::UpdateConstraints{{{*/
-void  Tria::UpdateConstraints(void){
-
-	int analysis_type;
-	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-
-	/*Skip if water element*/
-	if(IsOnWater()) return;
-
-}
-/*}}}*/
 
 #ifdef _HAVE_RESPONSES_
@@ -2362,5 +2590,5 @@
 	IssmDouble xyz_list[NUMVERTICES][3];
 
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
@@ -2384,7 +2612,6 @@
 IssmDouble Tria::MassFlux( IssmDouble* segment){
 
-	const int  numdofs=2;
 	int        dim;
-	IssmDouble mass_flux=0;
+	IssmDouble mass_flux=0.;
 	IssmDouble xyz_list[NUMVERTICES][3];
 	IssmDouble normal[2];
@@ -2599,5 +2826,5 @@
 	rho_ice=matpar->GetRhoIce();
 
-   if(IsOnWater())return 0;
+   if(NoIceInElement())return 0;
 
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
@@ -2748,11 +2975,11 @@
 #endif
 
-#ifdef _HAVE_DIAGNOSTIC_
-/*FUNCTION Tria::CreateKMatrixDiagnosticMacAyeal {{{*/
-ElementMatrix* Tria::CreateKMatrixDiagnosticMacAyeal(void){
+#ifdef _HAVE_STRESSBALANCE_
+/*FUNCTION Tria::CreateKMatrixStressbalanceSSA {{{*/
+ElementMatrix* Tria::CreateKMatrixStressbalanceSSA(void){
 
 	/*compute all stiffness matrices for this element*/
-	ElementMatrix* Ke1=CreateKMatrixDiagnosticMacAyealViscous();
-	ElementMatrix* Ke2=CreateKMatrixDiagnosticMacAyealFriction();
+	ElementMatrix* Ke1=CreateKMatrixStressbalanceSSAViscous();
+	ElementMatrix* Ke2=CreateKMatrixStressbalanceSSAFriction();
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
 
@@ -2763,6 +2990,6 @@
 }
 /*}}}*/
-/*FUNCTION Tria::CreateKMatrixDiagnosticMacAyealViscous{{{*/
-ElementMatrix* Tria::CreateKMatrixDiagnosticMacAyealViscous(void){
+/*FUNCTION Tria::CreateKMatrixStressbalanceSSAViscous{{{*/
+ElementMatrix* Tria::CreateKMatrixStressbalanceSSAViscous(void){
 
 	/*Intermediaries*/
@@ -2778,6 +3005,6 @@
 	int numdof   = numnodes*NDOF2;
 
-	/*Initialize Element matrix, vectors and Gaussian points*/
-	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,MacAyealApproximationEnum);
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,SSAApproximationEnum);
 	IssmDouble*    B      = xNew<IssmDouble>(3*numdof);
 	IssmDouble*    Bprime = xNew<IssmDouble>(3*numdof);
@@ -2791,8 +3018,8 @@
 	Input* vxold_input=inputs->GetInput(VxPicardEnum);      _assert_(vxold_input);
 	Input* vyold_input=inputs->GetInput(VyPicardEnum);      _assert_(vyold_input);
-	this->parameters->FindParam(&viscosity_overshoot,DiagnosticViscosityOvershootEnum);
+	this->parameters->FindParam(&viscosity_overshoot,StressbalanceViscosityOvershootEnum);
 
 	/* Start  looping on the number of gaussian points: */
-	GaussTria*     gauss  = new GaussTria(2);
+	GaussTria* gauss  = new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
@@ -2800,6 +3027,6 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetBMacAyeal(&B[0], &xyz_list[0][0], gauss);
-		GetBprimeMacAyeal(&Bprime[0], &xyz_list[0][0], gauss);
+		GetBSSA(&B[0], &xyz_list[0][0], gauss);
+		GetBprimeSSA(&Bprime[0], &xyz_list[0][0], gauss);
 
 		this->GetStrainRate2d(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
@@ -2820,16 +3047,16 @@
 
 	/*Transform Coordinate System*/
-	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+	TransformStiffnessMatrixCoord(Ke,nodes,numnodes,XYEnum);
 
 	/*Clean up and return*/
 	delete gauss;
-	xDelete<IssmDouble>(B);
 	xDelete<IssmDouble>(D);
 	xDelete<IssmDouble>(Bprime);
+	xDelete<IssmDouble>(B);
 	return Ke;
 }
 /*}}}*/
-/*FUNCTION Tria::CreateKMatrixDiagnosticMacAyealFriction {{{*/
-ElementMatrix* Tria::CreateKMatrixDiagnosticMacAyealFriction(void){
+/*FUNCTION Tria::CreateKMatrixStressbalanceSSAFriction {{{*/
+ElementMatrix* Tria::CreateKMatrixStressbalanceSSAFriction(void){
 
 	/*Intermediaries*/
@@ -2838,6 +3065,5 @@
 	int        analysis_type,migration_style;
 	int        point1;
-	IssmDouble alpha2;
-	IssmDouble Jdet;
+	IssmDouble alpha2,Jdet;
 	IssmDouble fraction1,fraction2;
 	IssmDouble phi=1.0;
@@ -2856,5 +3082,5 @@
 
 	/*Initialize Element matrix and vectors*/
-	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,MacAyealApproximationEnum);
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,SSAApproximationEnum);
 	IssmDouble*    B      = xNew<IssmDouble>(2*numdof);
 	IssmDouble*    D      = xNewZeroInit<IssmDouble>(2*2);
@@ -2876,5 +3102,5 @@
 	if(migration_style==SubelementMigrationEnum) phi=this->GetGroundedPortion(&xyz_list[0][0]);
 	if(migration_style==SubelementMigration2Enum){
-		gllevelset_input=inputs->GetInput(GLlevelsetEnum); _assert_(gllevelset_input);
+		gllevelset_input=inputs->GetInput(MaskGroundediceLevelsetEnum); _assert_(gllevelset_input);
 		this->GetGroundedPart(&point1,&fraction1,&fraction2,&mainlyfloating);
 		gauss=new GaussTria(point1,fraction1,fraction2,mainlyfloating,2);
@@ -2896,5 +3122,5 @@
 		}
 
-		GetBMacAyealFriction(&B[0], &xyz_list[0][0], gauss);
+		GetBSSAFriction(&B[0], &xyz_list[0][0], gauss);
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
 		D_scalar=alpha2*gauss->weight*Jdet;
@@ -2908,29 +3134,32 @@
 
 	/*Transform Coordinate System*/
-	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+	TransformStiffnessMatrixCoord(Ke,nodes,numnodes,XYEnum);
 
 	/*Clean up and return*/
 	delete gauss;
 	delete friction;
+	xDelete<IssmDouble>(D);
 	xDelete<IssmDouble>(B);
-	xDelete<IssmDouble>(D);
 	return Ke;
 }
 /*}}}*/
-/*FUNCTION Tria::CreateKMatrixDiagnosticHutter{{{*/
-ElementMatrix* Tria::CreateKMatrixDiagnosticHutter(void){
+/*FUNCTION Tria::CreateKMatrixStressbalanceSIA{{{*/
+ElementMatrix* Tria::CreateKMatrixStressbalanceSIA(void){
 
 	/*Intermediaries*/
-	const int numdof=NUMVERTICES*NDOF2;
-	int    i,connectivity;
+	IssmDouble connectivity;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes(); _assert_(numnodes==3); 
+	int numdof   = numnodes*NDOF2;
 
 	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+	ElementMatrix* Ke=new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
 
 	/*Create Element matrix*/
-	for(i=0;i<NUMVERTICES;i++){
-		connectivity=nodes[i]->GetConnectivity();
-		Ke->values[(2*i)*numdof  +(2*i)  ]=1/(IssmDouble)connectivity;
-		Ke->values[(2*i+1)*numdof+(2*i+1)]=1/(IssmDouble)connectivity;
+	for(int i=0;i<numnodes;i++){
+		connectivity=(IssmDouble)vertices[i]->Connectivity();
+		Ke->values[(2*i+0)*numdof+(2*i+0)]=1./connectivity;
+		Ke->values[(2*i+1)*numdof+(2*i+1)]=1./connectivity;
 	}
 
@@ -2939,13 +3168,28 @@
 }
 /*}}}*/
-/*FUNCTION Tria::CreatePVectorDiagnosticMacAyeal {{{*/
-ElementVector* Tria::CreatePVectorDiagnosticMacAyeal(){
+/*FUNCTION Tria::CreatePVectorStressbalanceSSA {{{*/
+ElementVector* Tria::CreatePVectorStressbalanceSSA(){
+
+	/*compute all load vectors for this element*/
+	ElementVector* pe1=CreatePVectorStressbalanceSSADrivingStress();
+	ElementVector* pe2=CreatePVectorStressbalanceSSAFront();
+	ElementVector* pe =new ElementVector(pe1,pe2);
+
+	/*clean-up and return*/
+	delete pe1;
+	delete pe2;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorStressbalanceSSADrivingStress {{{*/
+ElementVector* Tria::CreatePVectorStressbalanceSSADrivingStress(){
 
 	/*Intermediaries */
-	int            i,j;
-	IssmDouble     driving_stress_baseline,thickness;
-	IssmDouble     Jdet;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     slope[2];
+	int        i;
+	IssmDouble driving_stress_baseline,thickness;
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble slope[2];
+	IssmDouble icefrontlevel[3];
 
 	/*Fetch number of nodes and dof for this finite element*/
@@ -2954,6 +3198,5 @@
 
 	/*Initialize Element vector and vectors*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,MacAyealApproximationEnum);
-	GaussTria*     gauss  = new GaussTria(2);
+	ElementVector* pe=new ElementVector(nodes,numnodes,this->parameters,SSAApproximationEnum);
 	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
 
@@ -2963,6 +3206,8 @@
 	Input* surface_input=inputs->GetInput(SurfaceEnum);     _assert_(surface_input);
 	Input* drag_input=inputs->GetInput(FrictionCoefficientEnum);_assert_(drag_input);
+	GetInputListOnVertices(&icefrontlevel[0],BedEnum);
 
 	/* Start  looping on the number of gaussian points: */
+	GaussTria*     gauss  = new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
@@ -2977,33 +3222,114 @@
 
 		/*Build load vector: */
-		for (i=0;i<numnodes;i++){
-			for (j=0;j<NDOF2;j++){
-				pe->values[i*NDOF2+j]+=-driving_stress_baseline*slope[j]*Jdet*gauss->weight*basis[i];
-			}
+		for(i=0;i<numnodes;i++){
+			pe->values[i*NDOF2+0]+=-driving_stress_baseline*slope[0]*Jdet*gauss->weight*basis[i];
+			pe->values[i*NDOF2+1]+=-driving_stress_baseline*slope[1]*Jdet*gauss->weight*basis[i];
 		}
 	}
 
 	/*Transform coordinate system*/
-	TransformLoadVectorCoord(pe,nodes,NUMVERTICES,XYEnum);
+	TransformLoadVectorCoord(pe,nodes,numnodes,XYEnum);
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
 	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorStressbalanceSSAFront {{{*/
+ElementVector* Tria::CreatePVectorStressbalanceSSAFront(){
+
+	/*Intermediaries */
+	IssmDouble  ls[NUMVERTICES];
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	bool        isfront;
+
+	/*Retrieve all inputs and parameters*/
+	GetInputListOnVertices(&ls[0],MaskIceLevelsetEnum);
+
+	/*If the level set is awlays <0, there is no ice front here*/
+	isfront = false;
+	if(ls[0]>0. || ls[1]>0. || ls[2]>0.){
+		if(ls[0]*ls[1]<0. || ls[0]*ls[2]<0. || (ls[0]*ls[1]+ls[0]*ls[2]+ls[1]*ls[2]==0.)){
+			isfront = true;
+		}
+	}
+
+	/*If no front, return NULL*/
+	if(!isfront) return NULL;
+
+	/*Intermediaries*/
+	IssmDouble  rho_ice,rho_water,gravity;
+	IssmDouble  Jdet,thickness,bed,water_pressure,ice_pressure,air_pressure;
+	IssmDouble  surface_under_water,base_under_water,pressure;
+	IssmDouble  xyz_list_front[2][3];
+	IssmDouble  area_coordinates[2][3];
+	IssmDouble  normal[2];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters,SSAApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+	Input* bed_input      =inputs->GetInput(BedEnum);       _assert_(bed_input);
+	rho_water = matpar->GetRhoWater();
+	rho_ice   = matpar->GetRhoIce();
+	gravity   = matpar->GetG();
+	GetZeroLevelsetCoordinates(&xyz_list_front[0][0],xyz_list,MaskIceLevelsetEnum);
+	GetAreaCoordinates(&area_coordinates[0][0],xyz_list_front,xyz_list,2);
+	GetSegmentNormal(&normal[0],xyz_list_front);
+
+	/*Start looping on Gaussian points*/
+	GaussTria* gauss=new GaussTria(area_coordinates,3);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+		thickness_input->GetInputValue(&thickness,gauss);
+		bed_input->GetInputValue(&bed,gauss);
+		GetSegmentJacobianDeterminant(&Jdet,&xyz_list_front[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		surface_under_water = min(0.,thickness+bed); // 0 if the top of the glacier is above water level
+		base_under_water    = min(0.,bed);           // 0 if the bottom of the glacier is above water level
+		water_pressure = 1.0/2.0*gravity*rho_water*(pow(surface_under_water,2) - pow(base_under_water,2));
+		ice_pressure   = 1.0/2.0*gravity*rho_ice*pow(thickness,2);
+		air_pressure   = 0;
+		pressure = ice_pressure + water_pressure + air_pressure;
+
+		for (int i=0;i<numnodes;i++){
+			pe->values[2*i+0]+= pressure*Jdet*gauss->weight*normal[0]*basis[i];
+			pe->values[2*i+1]+= pressure*Jdet*gauss->weight*normal[1]*basis[i];
+		}
+	}
+
+	/*Transform coordinate system*/
+	TransformLoadVectorCoord(pe,nodes,numnodes,XYEnum);
+
+	/*Clean up and return*/
 	xDelete<IssmDouble>(basis);
+	delete gauss;
 	return pe;
 }
 /*}}}*/
-/*FUNCTION Tria::CreatePVectorDiagnosticHutter{{{*/
-ElementVector* Tria::CreatePVectorDiagnosticHutter(void){
+/*FUNCTION Tria::CreatePVectorStressbalanceSIA{{{*/
+ElementVector* Tria::CreatePVectorStressbalanceSIA(void){
 
 	/*Intermediaries */
-	int        i,connectivity;
-	IssmDouble     constant_part,ub,vb;
-	IssmDouble     rho_ice,gravity,n,B;
-	IssmDouble     slope2,thickness;
-	IssmDouble     slope[2];
-	GaussTria* gauss=NULL;
+	IssmDouble constant_part,ub,vb;
+	IssmDouble rho_ice,gravity,n,B;
+	IssmDouble slope2,thickness,connectivity;
+	IssmDouble slope[2];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes(); _assert_(numnodes==3); 
+	int numdof   = numnodes*NDOF2;
 
 	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+	ElementVector* pe=new ElementVector(nodes,numnodes,this->parameters);
 
 	/*Retrieve all inputs and parameters*/
@@ -3017,10 +3343,10 @@
 
 	/*Spawn 3 sing elements: */
-	gauss=new GaussTria();
-	for(i=0;i<NUMVERTICES;i++){
+	GaussTria* gauss=new GaussTria();
+	for(int i=0;i<numnodes;i++){
 
 		gauss->GaussVertex(i);
 
-		connectivity=nodes[i]->GetConnectivity();
+		connectivity=(IssmDouble)vertices[i]->Connectivity();
 
 		thickness_input->GetInputValue(&thickness,gauss);
@@ -3029,11 +3355,11 @@
 		slope2=pow(slope[0],2)+pow(slope[1],2);
 
-		constant_part=-2*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2));
-
-		ub=-1.58*pow((IssmDouble)10.0,(IssmDouble)-10.0)*rho_ice*gravity*thickness*slope[0];
-		vb=-1.58*pow((IssmDouble)10.0,(IssmDouble)-10.0)*rho_ice*gravity*thickness*slope[1];
-
-		pe->values[2*i]  =(ub-2.0*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2.0))*pow(thickness,n)/(pow(B,n)*(n+1))*slope[0])/(IssmDouble)connectivity;
-		pe->values[2*i+1]=(vb-2.0*pow(rho_ice*gravity,n)*pow(slope2,((n-1)/2.0))*pow(thickness,n)/(pow(B,n)*(n+1))*slope[1])/(IssmDouble)connectivity;
+		constant_part=-2.*pow(rho_ice*gravity,n)*pow(slope2,((n-1.)/2.));
+
+		ub=-1.58*1.e-10*rho_ice*gravity*thickness*slope[0];
+		vb=-1.58*1.e-10*rho_ice*gravity*thickness*slope[1];
+
+		pe->values[2*i+0]=(ub-2.*pow(rho_ice*gravity,n)*pow(slope2,((n-1.)/2.))*pow(thickness,n)/(pow(B,n)*(n+1))*slope[0])/connectivity;
+		pe->values[2*i+1]=(vb-2.*pow(rho_ice*gravity,n)*pow(slope2,((n-1.)/2.))*pow(thickness,n)/(pow(B,n)*(n+1))*slope[1])/connectivity;
 	}
 
@@ -3043,6 +3369,6 @@
 }
 /*}}}*/
-/*FUNCTION Tria::CreateJacobianDiagnosticMacayeal{{{*/
-ElementMatrix* Tria::CreateJacobianDiagnosticMacayeal(void){
+/*FUNCTION Tria::CreateJacobianStressbalanceSSA{{{*/
+ElementMatrix* Tria::CreateJacobianStressbalanceSSA(void){
 
 	/*Intermediaries */
@@ -3062,6 +3388,6 @@
 
 	/*Initialize Element matrix, vectors and Gaussian points*/
-	ElementMatrix* Ke=CreateKMatrixDiagnosticMacAyeal(); //Initialize Jacobian with regular MacAyeal (first part of the Gateau derivative)
-	IssmDouble*    dphi   = xNew<IssmDouble>(2*numnodes);
+	ElementMatrix* Ke=CreateKMatrixStressbalanceSSA(); //Initialize Jacobian with regular SSA (first part of the Gateau derivative)
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -3078,5 +3404,5 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctionsDerivatives(dphi,&xyz_list[0][0],gauss);
+		GetNodalFunctionsDerivatives(dbasis,&xyz_list[0][0],gauss);
 
 		thickness_input->GetInputValue(&thickness, gauss);
@@ -3088,8 +3414,8 @@
 		for(i=0;i<numnodes;i++){
 			for(j=0;j<numnodes;j++){
-				eps1dotdphii=eps1[0]*dphi[0*numnodes+i]+eps1[1]*dphi[1*numnodes+i];
-				eps1dotdphij=eps1[0]*dphi[0*numnodes+j]+eps1[1]*dphi[1*numnodes+j];
-				eps2dotdphii=eps2[0]*dphi[0*numnodes+i]+eps2[1]*dphi[1*numnodes+i];
-				eps2dotdphij=eps2[0]*dphi[0*numnodes+j]+eps2[1]*dphi[1*numnodes+j];
+				eps1dotdphii=eps1[0]*dbasis[0*numnodes+i]+eps1[1]*dbasis[1*numnodes+i];
+				eps1dotdphij=eps1[0]*dbasis[0*numnodes+j]+eps1[1]*dbasis[1*numnodes+j];
+				eps2dotdphii=eps2[0]*dbasis[0*numnodes+i]+eps2[1]*dbasis[1*numnodes+i];
+				eps2dotdphij=eps2[0]*dbasis[0*numnodes+j]+eps2[1]*dbasis[1*numnodes+j];
 
 				Ke->values[2*numnodes*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*thickness*eps1dotdphij*eps1dotdphii;
@@ -3102,14 +3428,14 @@
 
 	/*Transform Coordinate System*/
-	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+	TransformStiffnessMatrixCoord(Ke,nodes,numnodes,XYEnum);
 
 	/*Clean up and return*/
-	xDelete<IssmDouble>(dphi);
+	xDelete<IssmDouble>(dbasis);
 	delete gauss;
 	return Ke;
 }
 /*}}}*/
-/*FUNCTION Tria::GetSolutionFromInputsDiagnosticHoriz{{{*/
-void  Tria::GetSolutionFromInputsDiagnosticHoriz(Vector<IssmDouble>* solution){
+/*FUNCTION Tria::GetSolutionFromInputsStressbalanceHoriz{{{*/
+void  Tria::GetSolutionFromInputsStressbalanceHoriz(Vector<IssmDouble>* solution){
 
 	IssmDouble   vx,vy;
@@ -3130,9 +3456,7 @@
 
 	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
-	/*P1 element only for now*/
 	gauss=new GaussTria();
 	for(int i=0;i<numnodes;i++){
-
-		gauss->GaussNode(numnodes,i);
+		gauss->GaussNode(this->element_type,i);
 
 		/*Recover vx and vy*/
@@ -3147,10 +3471,10 @@
 	/*Free ressources:*/
 	delete gauss;
+	xDelete<IssmDouble>(values);
 	xDelete<int>(doflist);
-	xDelete<IssmDouble>(values);
-}
-/*}}}*/
-/*FUNCTION Tria::GetSolutionFromInputsDiagnosticHutter{{{*/
-void  Tria::GetSolutionFromInputsDiagnosticHutter(Vector<IssmDouble>* solution){
+}
+/*}}}*/
+/*FUNCTION Tria::GetSolutionFromInputsStressbalanceSIA{{{*/
+void  Tria::GetSolutionFromInputsStressbalanceSIA(Vector<IssmDouble>* solution){
 
 	const int    numdof=NDOF2*NUMVERTICES;
@@ -3190,6 +3514,78 @@
 }
 /*}}}*/
-/*FUNCTION Tria::InputUpdateFromSolutionDiagnosticHoriz {{{*/
-void  Tria::InputUpdateFromSolutionDiagnosticHoriz(IssmDouble* solution){
+/*FUNCTION Tria::InputUpdateFromSolutionStressbalanceHoriz {{{*/
+void  Tria::InputUpdateFromSolutionStressbalanceHoriz(IssmDouble* solution){
+
+	int        i;
+	IssmDouble rho_ice,g;
+	int*       doflist=NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+	int numdof   = numnodes*NDOF2;
+
+	/*Fetch dof list and allocate solution vectors*/
+	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numdof);
+	IssmDouble* vx        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vy        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vz        = xNew<IssmDouble>(numnodes);
+	IssmDouble* vel       = xNew<IssmDouble>(numnodes);
+	IssmDouble* pressure  = xNew<IssmDouble>(numnodes);
+	IssmDouble* thickness = 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*/
+	TransformSolutionCoord(&values[0],nodes,numnodes,XYEnum);
+
+	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
+	for(i=0;i<numnodes;i++){
+		vx[i]=values[i*NDOF2+0];
+		vy[i]=values[i*NDOF2+1];
+
+		/*Check solution*/
+		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
+		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
+	}
+
+	/*Get Vz and compute vel*/
+	GetInputListOnNodes(&vz[0],VzEnum,0.);
+	for(i=0;i<numnodes;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
+
+	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 2D, 
+	 *so the pressure is just the pressure at the bedrock: */
+	rho_ice=matpar->GetRhoIce();
+	g=matpar->GetG();
+	GetInputListOnNodes(&thickness[0],ThicknessEnum);
+	for(i=0;i<numnodes;i++) pressure[i]=rho_ice*g*thickness[i];
+
+	/*Now, we have to move the previous Vx and Vy inputs  to old 
+	 * status, otherwise, we'll wipe them off: */
+	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
+	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
+	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
+
+	/*Add vx and vy as inputs to the tria element: */
+	this->inputs->AddInput(new TriaInput(VxEnum,vx,P1Enum));
+	this->inputs->AddInput(new TriaInput(VyEnum,vy,P1Enum));
+	this->inputs->AddInput(new TriaInput(VelEnum,vel,P1Enum));
+	this->inputs->AddInput(new TriaInput(PressureEnum,pressure,P1Enum));
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(thickness);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(values);
+	xDelete<int>(doflist);
+
+}
+/*}}}*/
+/*FUNCTION Tria::InputUpdateFromSolutionStressbalanceSIA {{{*/
+void  Tria::InputUpdateFromSolutionStressbalanceSIA(IssmDouble* solution){
 
 	int        i;
@@ -3251,83 +3647,12 @@
 
 	/*Free ressources:*/
+	xDelete<IssmDouble>(thickness);
+	xDelete<IssmDouble>(pressure);
+	xDelete<IssmDouble>(vel);
+	xDelete<IssmDouble>(vz);
+	xDelete<IssmDouble>(vy);
+	xDelete<IssmDouble>(vx);
+	xDelete<IssmDouble>(values);
 	xDelete<int>(doflist);
-	xDelete<IssmDouble>(values);
-	xDelete<IssmDouble>(vx);
-	xDelete<IssmDouble>(vy);
-	xDelete<IssmDouble>(vz);
-	xDelete<IssmDouble>(vel);
-	xDelete<IssmDouble>(pressure);
-	xDelete<IssmDouble>(thickness);
-}
-/*}}}*/
-/*FUNCTION Tria::InputUpdateFromSolutionDiagnosticHutter {{{*/
-void  Tria::InputUpdateFromSolutionDiagnosticHutter(IssmDouble* solution){
-
-	int        i;
-	IssmDouble rho_ice,g;
-	int*       doflist=NULL;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	int numnodes = this->NumberofNodes();
-	int numdof   = numnodes*NDOF2;
-
-	/*Fetch dof list and allocate solution vectors*/
-	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	IssmDouble* values    = xNew<IssmDouble>(numdof);
-	IssmDouble* vx        = xNew<IssmDouble>(numdof);
-	IssmDouble* vy        = xNew<IssmDouble>(numdof);
-	IssmDouble* vz        = xNew<IssmDouble>(numdof);
-	IssmDouble* vel       = xNew<IssmDouble>(numdof);
-	IssmDouble* pressure  = xNew<IssmDouble>(numdof);
-	IssmDouble* thickness = xNew<IssmDouble>(numdof);
-
-	/*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*/
-	TransformSolutionCoord(&values[0],nodes,numnodes,XYEnum);
-
-	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
-	for(i=0;i<numnodes;i++){
-		vx[i]=values[i*NDOF2+0];
-		vy[i]=values[i*NDOF2+1];
-
-		/*Check solution*/
-		if(xIsNan<IssmDouble>(vx[i])) _error_("NaN found in solution vector");
-		if(xIsNan<IssmDouble>(vy[i])) _error_("NaN found in solution vector");
-	}
-
-	/*Get Vz and compute vel*/
-	GetInputListOnNodes(&vz[0],VzEnum,0.);
-	for(i=0;i<numnodes;i++) vel[i]=sqrt(vx[i]*vx[i] + vy[i]*vy[i] + vz[i]*vz[i]);
-
-	/*For pressure: we have not computed pressure in this analysis, for this element. We are in 2D, 
-	 *so the pressure is just the pressure at the bedrock: */
-	rho_ice=matpar->GetRhoIce();
-	g=matpar->GetG();
-	GetInputListOnNodes(&thickness[0],ThicknessEnum);
-	for(i=0;i<numnodes;i++) pressure[i]=rho_ice*g*thickness[i];
-
-	/*Now, we have to move the previous Vx and Vy inputs  to old 
-	 * status, otherwise, we'll wipe them off: */
-	this->inputs->ChangeEnum(VxEnum,VxPicardEnum);
-	this->inputs->ChangeEnum(VyEnum,VyPicardEnum);
-	this->inputs->ChangeEnum(PressureEnum,PressurePicardEnum);
-
-	/*Add vx and vy as inputs to the tria element: */
-	this->inputs->AddInput(new TriaInput(VxEnum,vx,P1Enum));
-	this->inputs->AddInput(new TriaInput(VyEnum,vy,P1Enum));
-	this->inputs->AddInput(new TriaInput(VelEnum,vel,P1Enum));
-	this->inputs->AddInput(new TriaInput(PressureEnum,pressure,P1Enum));
-
-	/*Free ressources:*/
-	xDelete<int>(doflist);
-	xDelete<IssmDouble>(values);
-	xDelete<IssmDouble>(vx);
-	xDelete<IssmDouble>(vy);
-	xDelete<IssmDouble>(vz);
-	xDelete<IssmDouble>(vel);
-	xDelete<IssmDouble>(pressure);
-	xDelete<IssmDouble>(thickness);
 }
 /*}}}*/
@@ -3350,5 +3675,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater()) return 0;
+	if(NoIceInElement()) return 0;
 
 	/*Retrieve all inputs we will be needing: */
@@ -3492,16 +3817,16 @@
 
 	/*If on water, grad = 0: */
-	if(IsOnWater()) return;
+	if(NoIceInElement()) return;
 
 	/*First deal with ∂/∂alpha(KU-F)*/
 	switch(control_type){
 		case FrictionCoefficientEnum:
-			GradjDragMacAyeal(gradient,control_index);
+			GradjDragSSA(gradient,control_index);
 			break;
 		case MaterialsRheologyBbarEnum:
-			GradjBMacAyeal(gradient,control_index);
+			GradjBSSA(gradient,control_index);
 			break;
 		case MaterialsRheologyZbarEnum:
-			GradjZMacAyeal(gradient,control_index);
+			GradjZSSA(gradient,control_index);
 			break;
 		case BalancethicknessThickeningRateEnum:
@@ -3635,6 +3960,6 @@
 }
 /*}}}*/
-/*FUNCTION Tria::GradjBMacAyeal{{{*/
-void  Tria::GradjBMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+/*FUNCTION Tria::GradjBSSA{{{*/
+void  Tria::GradjBSSA(Vector<IssmDouble>* gradient,int control_index){
 
 	/*Intermediaries*/
@@ -3692,6 +4017,6 @@
 }
 /*}}}*/
-/*FUNCTION Tria::GradjZMacAyeal{{{*/
-void  Tria::GradjZMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+/*FUNCTION Tria::GradjZSSA{{{*/
+void  Tria::GradjZSSA(Vector<IssmDouble>* gradient,int control_index){
 
 	/*Intermediaries*/
@@ -3749,6 +4074,6 @@
 }
 /*}}}*/
-/*FUNCTION Tria::GradjDragMacAyeal {{{*/
-void  Tria::GradjDragMacAyeal(Vector<IssmDouble>* gradient,int control_index){
+/*FUNCTION Tria::GradjDragSSA {{{*/
+void  Tria::GradjDragSSA(Vector<IssmDouble>* gradient,int control_index){
 
 	int        i;
@@ -4119,5 +4444,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater()) return 0;
+	if(NoIceInElement()) return 0;
 
 	/*Retrieve all inputs we will be needing: */
@@ -4140,5 +4465,5 @@
 
 		/*Tikhonov regularization: J = 1/2 ((dp/dx)^2 + (dp/dy)^2) */ 
-		Jelem+=weight*1/2*(pow(dp[0],2.)+pow(dp[1],2.))*Jdet*gauss->weight;
+		Jelem+=weight*1/2*(dp[0]*dp[0] + dp[1]*dp[1])*Jdet*gauss->weight;
 	}
 
@@ -4158,5 +4483,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/* Get node coordinates and dof list: */
@@ -4207,5 +4532,5 @@
 IssmDouble Tria::SurfaceLogVelMisfit(int weight_index){
 
-	IssmDouble Jelem=0;
+	IssmDouble Jelem=0.;
 	IssmDouble misfit,Jdet;
 	IssmDouble epsvel=2.220446049250313e-16;
@@ -4217,5 +4542,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/* Get node coordinates and dof list: */
@@ -4277,5 +4602,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/* Get node coordinates and dof list: */
@@ -4316,5 +4641,4 @@
 					pow(log((fabs(vy)+epsvel)/(fabs(vyobs)+epsvel)),2) );
 
-
 		/*Add to cost function*/
 		Jelem+=misfit*weight*Jdet*gauss->weight;
@@ -4336,5 +4660,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/* Get node coordinates and dof list: */
@@ -4395,5 +4719,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/* Get node coordinates and dof list: */
@@ -4457,5 +4781,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater()) return 0;
+	if(NoIceInElement()) return 0;
 
 	/*Retrieve all inputs we will be needing: */
@@ -4501,5 +4825,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater()) return 0;
+	if(NoIceInElement()) return 0;
 
 	/*Retrieve all inputs we will be needing: */
@@ -4552,5 +4876,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater()) return 0;
+	if(NoIceInElement()) return 0;
 
 	/*Retrieve all inputs we will be needing: */
@@ -4600,5 +4924,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater())return 0;
+	if(NoIceInElement())return 0;
 
 	/*Retrieve all inputs we will be needing: */
@@ -4635,22 +4959,21 @@
 ElementVector* Tria::CreatePVectorAdjointBalancethickness(void){
 
-	/*Constants*/
-	const int    numdof=1*NUMVERTICES;
-
 	/*Intermediaries */
-	int         i,resp;
-	IssmDouble  Jdet;
-	IssmDouble  thickness,thicknessobs,weight;
-	int         num_responses;
-	IssmDouble  xyz_list[NUMVERTICES][3];
-	IssmDouble  basis[3];
-	IssmDouble  dbasis[NDOF2][NUMVERTICES];
-	IssmDouble  dH[2];
-	IssmDouble  vx,vy,vel;
-	GaussTria *gauss     = NULL;
+	int        i,resp;
+	IssmDouble Jdet;
+	IssmDouble thickness,thicknessobs,weight;
+	int        num_responses;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dH[2];
+	IssmDouble vx,vy,vel;
 	int       *responses = NULL;
 
-	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and vectors*/
+	ElementVector* pe     = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -4665,5 +4988,5 @@
 
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
@@ -4672,5 +4995,5 @@
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
 		GetNodalFunctions(basis, gauss);
-		GetNodalFunctionsDerivatives(&dbasis[0][0],&xyz_list[0][0],gauss);
+		GetNodalFunctionsDerivatives(dbasis,&xyz_list[0][0],gauss);
 
 		thickness_input->GetInputValue(&thickness, gauss);
@@ -4683,10 +5006,10 @@
 			case ThicknessAbsMisfitEnum:
 				weights_input->GetInputValue(&weight, gauss,resp);
-				for(i=0;i<numdof;i++) pe->values[i]+=(thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
+				for(i=0;i<numnodes;i++) pe->values[i]+=(thicknessobs-thickness)*weight*Jdet*gauss->weight*basis[i];
 				break;
 			case ThicknessAbsGradientEnum:
 				weights_input->GetInputValue(&weight, gauss,resp);
-				for(i=0;i<numdof;i++) pe->values[i]+= - weight*dH[0]*dbasis[0][i]*Jdet*gauss->weight;
-				for(i=0;i<numdof;i++) pe->values[i]+= - weight*dH[1]*dbasis[1][i]*Jdet*gauss->weight;
+				for(i=0;i<numnodes;i++) pe->values[i]+= - weight*dH[0]*dbasis[0*numnodes+i]*Jdet*gauss->weight;
+				for(i=0;i<numnodes;i++) pe->values[i]+= - weight*dH[1]*dbasis[1*numnodes+i]*Jdet*gauss->weight;
 				break;
 			case ThicknessAlongGradientEnum:
@@ -4697,5 +5020,5 @@
 				vx  = vx/(vel+1.e-9);
 				vy  = vy/(vel+1.e-9);
-				for(i=0;i<numdof;i++) pe->values[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0][i]*vx+dbasis[1][i]*vy)*Jdet*gauss->weight;
+				for(i=0;i<numnodes;i++) pe->values[i]+= - weight*(dH[0]*vx+dH[1]*vy)*(dbasis[0*numnodes+i]*vx+dbasis[1*numnodes+i]*vy)*Jdet*gauss->weight;
 				break;
 			case ThicknessAcrossGradientEnum:
@@ -4706,5 +5029,5 @@
 				vx  = vx/(vel+1.e-9);
 				vy  = vy/(vel+1.e-9);
-				for(i=0;i<numdof;i++) pe->values[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0][i]*(-vy)+dbasis[1][i]*vx)*Jdet*gauss->weight;
+				for(i=0;i<numnodes;i++) pe->values[i]+= - weight*(dH[0]*(-vy)+dH[1]*vx)*(dbasis[0*numnodes+i]*(-vy)+dbasis[1*numnodes+i]*vx)*Jdet*gauss->weight;
 				break;
 			default:
@@ -4714,6 +5037,8 @@
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<int>(responses);
 	delete gauss;
-	xDelete<int>(responses);
 	return pe;
 }
@@ -4721,7 +5046,4 @@
 /*FUNCTION Tria::CreatePVectorAdjointHoriz{{{*/
 ElementVector* Tria::CreatePVectorAdjointHoriz(void){
-
-	/*Constants*/
-	const int    numdof=NDOF2*NUMVERTICES;
 
 	/*Intermediaries */
@@ -4729,17 +5051,19 @@
 	int       *responses=NULL;
 	int        num_responses;
-	IssmDouble     Jdet;
-	IssmDouble     obs_velocity_mag,velocity_mag;
-	IssmDouble     dux,duy;
-	IssmDouble     epsvel=2.220446049250313e-16;
-	IssmDouble     meanvel=3.170979198376458e-05; /*1000 m/yr*/
-	IssmDouble     scalex=0,scaley=0,scale=0,S=0;
-	IssmDouble     vx,vy,vxobs,vyobs,weight;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     basis[3];
-	GaussTria* gauss=NULL;
+	IssmDouble Jdet;
+	IssmDouble obs_velocity_mag,velocity_mag;
+	IssmDouble dux,duy;
+	IssmDouble epsvel=2.220446049250313e-16;
+	IssmDouble meanvel=3.170979198376458e-05; /*1000 m/yr*/
+	IssmDouble scalex=0.,scaley=0.,scale=0.,S=0.;
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
 
 	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -4761,5 +5085,5 @@
 
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(4);
+	GaussTria* gauss=new GaussTria(4);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
@@ -4792,5 +5116,5 @@
 					 *        du     obs
 					 */
-					for (i=0;i<NUMVERTICES;i++){
+					for(i=0;i<numnodes;i++){
 						dux=vxobs-vx;
 						duy=vyobs-vy;
@@ -4811,5 +5135,5 @@
 					 *               obs
 					 */
-					for (i=0;i<NUMVERTICES;i++){
+					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;
@@ -4832,5 +5156,5 @@
 					 *            
 					 */
-					for (i=0;i<NUMVERTICES;i++){
+					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;
@@ -4852,5 +5176,5 @@
 					 *        du      S  2 sqrt(...)           obs
 					 */
-					for (i=0;i<NUMVERTICES;i++){
+					for(i=0;i<numnodes;i++){
 						scale=1./(S*2*sqrt(pow(vx-vxobs,2)+pow(vy-vyobs,2))+epsvel);
 						dux=scale*(vxobs-vx);
@@ -4870,5 +5194,5 @@
 					 *        du                         |u| + eps  |u|                           u + eps
 					 */
-					for (i=0;i<NUMVERTICES;i++){
+					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);
@@ -4899,189 +5223,7 @@
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<int>(responses);
 	delete gauss;
-	xDelete<int>(responses);
-	return pe;
-}
-/*}}}*/
-/*FUNCTION Tria::CreatePVectorAdjointStokes{{{*/
-ElementVector* Tria::CreatePVectorAdjointStokes(void){
-
-	/*Intermediaries */
-	int        i,resp;
-	int       *responses=NULL;
-	int        num_responses;
-	IssmDouble     Jdet;
-	IssmDouble     obs_velocity_mag,velocity_mag;
-	IssmDouble     dux,duy;
-	IssmDouble     epsvel=2.220446049250313e-16;
-	IssmDouble     meanvel=3.170979198376458e-05; /*1000 m/yr*/
-	IssmDouble     scalex=0,scaley=0,scale=0,S=0;
-	IssmDouble     vx,vy,vxobs,vyobs,weight;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     basis[3];
-	GaussTria* gauss=NULL;
-
-	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters,StokesApproximationEnum);
-
-	/*Retrieve all inputs and parameters*/
-	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	this->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
-	this->parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
-	Input* weights_input = inputs->GetInput(InversionCostFunctionsCoefficientsEnum);   _assert_(weights_input);
-	Input* vx_input      = inputs->GetInput(VxEnum);        _assert_(vx_input);
-	Input* vy_input      = inputs->GetInput(VyEnum);        _assert_(vy_input);
-	Input* vxobs_input   = inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
-	Input* vyobs_input   = inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);
-
-	/*Get Surface if required by one response*/
-	for(resp=0;resp<num_responses;resp++){
-		if(responses[resp]==SurfaceAverageVelMisfitEnum){
-			inputs->GetInputValue(&S,SurfaceAreaEnum); break;
-		}
-	}
-
-	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(4);
-	for(int ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		/* Get Jacobian determinant: */
-		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-
-		/*Get all parameters at gaussian point*/
-		vx_input->GetInputValue(&vx,gauss);
-		vy_input->GetInputValue(&vy,gauss);
-		vxobs_input->GetInputValue(&vxobs,gauss);
-		vyobs_input->GetInputValue(&vyobs,gauss);
-		GetNodalFunctions(basis, gauss);
-
-		/*Loop over all requested responses*/
-		for(resp=0;resp<num_responses;resp++){
-
-			weights_input->GetInputValue(&weight,gauss,resp);
-
-			switch(responses[resp]){
-
-				case SurfaceAbsVelMisfitEnum:
-					/*
-					 *      1  [           2              2 ]
-					 * J = --- | (u - u   )  +  (v - v   )  |
-					 *      2  [       obs            obs   ]
-					 *
-					 *        dJ
-					 * DU = - -- = (u   - u )
-					 *        du     obs
-					 */
-					for (i=0;i<NUMVERTICES;i++){
-						dux=vxobs-vx;
-						duy=vyobs-vy;
-						pe->values[i*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
-					}
-					break;
-				case SurfaceRelVelMisfitEnum:
-					/*
-					 *      1  [     \bar{v}^2             2   \bar{v}^2              2 ]
-					 * J = --- | -------------  (u - u   ) + -------------  (v - v   )  |
-					 *      2  [  (u   + eps)^2       obs    (v   + eps)^2       obs    ]
-					 *              obs                        obs                      
-					 *
-					 *        dJ     \bar{v}^2
-					 * DU = - -- = ------------- (u   - u )
-					 *        du   (u   + eps)^2    obs
-					 *               obs
-					 */
-					for (i=0;i<NUMVERTICES;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*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
-					}
-					break;
-				case SurfaceLogVelMisfitEnum:
-					/*
-					 *                 [        vel + eps     ] 2
-					 * J = 4 \bar{v}^2 | log ( -----------  ) |  
-					 *                 [       vel   + eps    ]
-					 *                            obs
-					 *
-					 *        dJ                 2 * log(...)
-					 * DU = - -- = - 4 \bar{v}^2 -------------  u
-					 *        du                 vel^2 + eps
-					 *            
-					 */
-					for (i=0;i<NUMVERTICES;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*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
-					}
-					break;
-				case SurfaceAverageVelMisfitEnum:
-					/*
-					 *      1                    2              2
-					 * J = ---  sqrt(  (u - u   )  +  (v - v   )  )
-					 *      S                obs            obs
-					 *
-					 *        dJ      1       1 
-					 * DU = - -- = - --- ----------- * 2 (u - u   )
-					 *        du      S  2 sqrt(...)           obs
-					 */
-					for (i=0;i<NUMVERTICES;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*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
-					}
-					break;
-				case SurfaceLogVxVyMisfitEnum:
-					/*
-					 *      1            [        |u| + eps     2          |v| + eps     2  ]
-					 * J = --- \bar{v}^2 | log ( -----------  )   +  log ( -----------  )   |  
-					 *      2            [       |u    |+ eps              |v    |+ eps     ]
-					 *                              obs                       obs
-					 *        dJ                              1      u                             1
-					 * DU = - -- = - \bar{v}^2 log(u...) --------- ----  ~ - \bar{v}^2 log(u...) ------
-					 *        du                         |u| + eps  |u|                           u + eps
-					 */
-					for (i=0;i<NUMVERTICES;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*NDOF4+0]+=dux*weight*Jdet*gauss->weight*basis[i]; 
-						pe->values[i*NDOF4+1]+=duy*weight*Jdet*gauss->weight*basis[i]; 
-					}
-					break;
-				case DragCoefficientAbsGradientEnum:
-					/*Nothing in P vector*/
-					break;
-				case ThicknessAbsGradientEnum:
-					/*Nothing in P vector*/
-					break;
-				case ThicknessAcrossGradientEnum:
-					/*Nothing in P vector*/
-					break;
-				case ThicknessAlongGradientEnum:
-					/*Nothing in P vector*/
-					break;
-				case RheologyBbarAbsGradientEnum:
-					/*Nothing in P vector*/
-					break;
-				default:
-					_error_("response " << EnumToStringx(responses[resp]) << " not supported yet");
-			}
-		}
-	}
-
-	/*Clean up and return*/
-	delete gauss;
-	xDelete<int>(responses);
 	return pe;
 }
@@ -5101,5 +5243,5 @@
 
 	/*If on water, return 0: */
-	if(IsOnWater()) return 0;
+	if(NoIceInElement()) return 0;
 
 	/*Retrieve all inputs we will be needing: */
@@ -5152,26 +5294,25 @@
 }
 /*}}}*/
-/*FUNCTION Tria::CreateKMatrixAdjointMacAyeal{{{*/
-ElementMatrix* Tria::CreateKMatrixAdjointMacAyeal(void){
-
-	/*Constants*/
-	const int    numdof=NDOF2*NUMVERTICES;
+/*FUNCTION Tria::CreateKMatrixAdjointSSA{{{*/
+ElementMatrix* Tria::CreateKMatrixAdjointSSA(void){
 
 	/*Intermediaries */
-	int        i,j;
-	bool       incomplete_adjoint;
-	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble Jdet,thickness;
-	IssmDouble eps1dotdphii,eps1dotdphij;
-	IssmDouble eps2dotdphii,eps2dotdphij;
-	IssmDouble mu_prime;
-	IssmDouble epsilon[3];/* epsilon=[exx,eyy,exy];*/
-	IssmDouble eps1[2],eps2[2];
-	IssmDouble dphi[2][NUMVERTICES];
-	GaussTria *gauss=NULL;
-
-	/*Initialize Jacobian with regular MacAyeal (first part of the Gateau derivative)*/
+	int         i,j;
+	bool        incomplete_adjoint;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  Jdet,thickness;
+	IssmDouble  eps1dotdphii,eps1dotdphij;
+	IssmDouble  eps2dotdphii,eps2dotdphij;
+	IssmDouble  mu_prime;
+	IssmDouble  epsilon[3];/* epsilon=[exx,eyy,exy];*/
+	IssmDouble  eps1[2],eps2[2];
+	GaussTria  *gauss=NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Jacobian with regular SSA (first part of the Gateau derivative)*/
 	parameters->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
-	ElementMatrix* Ke=CreateKMatrixDiagnosticMacAyeal();
+	ElementMatrix* Ke=CreateKMatrixStressbalanceSSA();
 	if(incomplete_adjoint) return Ke;
 
@@ -5182,4 +5323,7 @@
 	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
 
+	/*Allocate dbasis*/
+	IssmDouble* dbasis = xNew<IssmDouble>(2*numnodes);
+
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
@@ -5189,5 +5333,5 @@
 
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctionsDerivatives(&dphi[0][0],&xyz_list[0][0],gauss);
+		GetNodalFunctionsDerivatives(dbasis,&xyz_list[0][0],gauss);
 
 		thickness_input->GetInputValue(&thickness, gauss);
@@ -5197,15 +5341,15 @@
 		eps1[1]=epsilon[2];                eps2[1]=epsilon[0]+2*epsilon[1];
 
-		for(i=0;i<3;i++){
-			for(j=0;j<3;j++){
-				eps1dotdphii=eps1[0]*dphi[0][i]+eps1[1]*dphi[1][i];
-				eps1dotdphij=eps1[0]*dphi[0][j]+eps1[1]*dphi[1][j];
-				eps2dotdphii=eps2[0]*dphi[0][i]+eps2[1]*dphi[1][i];
-				eps2dotdphij=eps2[0]*dphi[0][j]+eps2[1]*dphi[1][j];
-
-				Ke->values[6*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*thickness*eps1dotdphij*eps1dotdphii;
-				Ke->values[6*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*thickness*eps2dotdphij*eps1dotdphii;
-				Ke->values[6*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*thickness*eps1dotdphij*eps2dotdphii;
-				Ke->values[6*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*thickness*eps2dotdphij*eps2dotdphii;
+		for(i=0;i<numnodes;i++){
+			for(j=0;j<numnodes;j++){
+				eps1dotdphii=eps1[0]*dbasis[0*numnodes+i]+eps1[1]*dbasis[1*numnodes+i];
+				eps1dotdphij=eps1[0]*dbasis[0*numnodes+j]+eps1[1]*dbasis[1*numnodes+j];
+				eps2dotdphii=eps2[0]*dbasis[0*numnodes+i]+eps2[1]*dbasis[1*numnodes+i];
+				eps2dotdphij=eps2[0]*dbasis[0*numnodes+j]+eps2[1]*dbasis[1*numnodes+j];
+
+				Ke->values[2*numnodes*(2*i+0)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*thickness*eps1dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+0)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*thickness*eps2dotdphij*eps1dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+0]+=gauss->weight*Jdet*2*mu_prime*thickness*eps1dotdphij*eps2dotdphii;
+				Ke->values[2*numnodes*(2*i+1)+2*j+1]+=gauss->weight*Jdet*2*mu_prime*thickness*eps2dotdphij*eps2dotdphii;
 			}
 		}
@@ -5213,8 +5357,9 @@
 
 	/*Transform Coordinate System*/
-	TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYEnum);
+	TransformStiffnessMatrixCoord(Ke,nodes,numnodes,XYEnum);
 
 	/*Clean up and return*/
 	delete gauss;
+	xDelete<IssmDouble>(dbasis);
 	//Ke->Transpose();
 	return Ke;
@@ -5224,20 +5369,25 @@
 void  Tria::InputUpdateFromSolutionAdjointHoriz(IssmDouble* solution){
 
-	const int numdof=NDOF2*NUMVERTICES;
-
-	int       i;
-	int*      doflist=NULL;
-	IssmDouble    values[numdof];
-	IssmDouble    lambdax[NUMVERTICES];
-	IssmDouble    lambday[NUMVERTICES];
-
-	/*Get dof list: */
+	int  i;
+	int* doflist=NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+	int numdof   = numnodes*NDOF2;
+
+	/*Fetch dof list and allocate solution vectors*/
 	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*/
+	TransformSolutionCoord(&values[0],nodes,numnodes,XYEnum);
+
 	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
-	for(i=0;i<NUMVERTICES;i++){
+	for(i=0;i<numnodes;i++){
 		lambdax[i]=values[i*NDOF2+0];
 		lambday[i]=values[i*NDOF2+1];
@@ -5253,33 +5403,7 @@
 
 	/*Free ressources:*/
-	xDelete<int>(doflist);
-}
-/*}}}*/
-/*FUNCTION Tria::InputUpdateFromSolutionAdjointBalancethickness {{{*/
-void  Tria::InputUpdateFromSolutionAdjointBalancethickness(IssmDouble* solution){
-
-	const int numdof=NDOF1*NUMVERTICES;
-
-	int       i;
-	int*      doflist=NULL;
-	IssmDouble    values[numdof];
-	IssmDouble    lambda[NUMVERTICES];
-
-	/*Get dof list: */
-	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-
-	/*Use the dof list to index into the solution vector: */
-	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];
-
-	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
-	for(i=0;i<numdof;i++){
-		lambda[i]=values[i];
-		if(xIsNan<IssmDouble>(lambda[i])) _error_("NaN found in solution vector");
-	}
-
-	/*Add vx and vy as inputs to the tria element: */
-	this->inputs->AddInput(new TriaInput(AdjointEnum,lambda,P1Enum));
-
-	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(lambdax);
+	xDelete<IssmDouble>(lambday);
 	xDelete<int>(doflist);
 }
@@ -5353,24 +5477,23 @@
 ElementMatrix* Tria::CreateKMatrixMelting(void){
 
-	/*Constants*/
-	const int  numdof=NUMVERTICES*NDOF1;
-
 	/*Intermediaries */
 	IssmDouble heatcapacity,latentheat;
 	IssmDouble Jdet,D_scalar;
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble basis[3];
-	GaussTria *gauss=NULL;
-
-	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and vectors*/
+	ElementMatrix* Ke=new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	latentheat=matpar->GetLatentHeat();
-	heatcapacity=matpar->GetHeatCapacity();
+	latentheat   = matpar->GetLatentHeat();
+	heatcapacity = matpar->GetHeatCapacity();
 
 	/* Start looping on the number of gauss  (nodes on the bedrock) */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
@@ -5382,11 +5505,12 @@
 		D_scalar=latentheat/heatcapacity*gauss->weight*Jdet;
 
-		TripleMultiply(&basis[0],numdof,1,0,
+		TripleMultiply(basis,numnodes,1,0,
 					&D_scalar,1,1,0,
-					&basis[0],1,numdof,0,
+					basis,1,numnodes,0,
 					&Ke->values[0],1);
 	}
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
 	delete gauss;
 	return Ke;
@@ -5398,12 +5522,12 @@
 /*FUNCTION Tria::AllActive{{{*/
 bool Tria::AllActive(void){
-	
+
 	/*Intermediaries*/
 	const int  numnodes = NUMVERTICES;
-	
+
 	for(int i=0;i<numnodes;i++){
 		if(!this->nodes[i]->IsActive()) return false;
 	}
-	
+
 	return true;
 }
@@ -5411,12 +5535,12 @@
 /*FUNCTION Tria::AnyActive{{{*/
 bool Tria::AnyActive(void){
-	
+
 	/*Intermediaries*/
 	const int  numnodes = NUMVERTICES;
-	
+
 	for(int i=0;i<numnodes;i++){
 		if(this->nodes[i]->IsActive()) return true;
 	}
-	
+
 	return false;
 }/*}}}*/
@@ -5452,5 +5576,5 @@
 
 	gauss=new GaussTria();
-	for (int iv=0;iv<NUMVERTICES;iv++){
+	for(int iv=0;iv<NUMVERTICES;iv++){
 		gauss->GaussVertex(iv);
 		surfaceslopex_input->GetInputValue(&dsdx,gauss);
@@ -5478,30 +5602,25 @@
 ElementMatrix* Tria::CreateKMatrixHydrologyShreve(void){
 
-	/*Constants*/
-	const int  numdof=NDOF1*NUMVERTICES;
-
-/*Intermediaries */
+	/*Intermediaries */
 	IssmDouble diffusivity;
-	IssmDouble Jdettria,DL_scalar,dt,h;
+	IssmDouble Jdet,D_scalar,dt,h;
 	IssmDouble vx,vy,vel,dvxdx,dvydy;
 	IssmDouble dvx[2],dvy[2];
-	IssmDouble v_gauss[2]={0.0};
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble basis[NUMVERTICES];
-	IssmDouble B[2][NUMVERTICES];
-	IssmDouble Bprime[2][NUMVERTICES];
-	IssmDouble K[2][2]                        ={0.0};
-	IssmDouble KDL[2][2]                      ={0.0};
-	IssmDouble DL[2][2]                        ={0.0};
-	IssmDouble DLprime[2][2]                   ={0.0};
-	GaussTria *gauss=NULL;
-
-/*Skip if water or ice shelf element*/
-	if(IsOnWater() | IsFloating()) return NULL;
-
-/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
-
-/*Create water velocity vx and vy from current inputs*/
+
+	/*Skip if water or ice shelf element*/
+	if(NoIceInElement() | IsFloating()) return NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2];
+
+	/*Create water velocity vx and vy from current inputs*/
 	CreateHydrologyWaterVelocityInput();
 
@@ -5514,12 +5633,12 @@
 	h=sqrt(2*this->GetArea());
 
-/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	/* Start  looping on the number of gaussian points: */
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
 
-		GetJacobianDeterminant(&Jdettria, &xyz_list[0][0],gauss);
-		GetNodalFunctions(&basis[0],gauss);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
 
 		vx_input->GetInputValue(&vx,gauss);
@@ -5528,51 +5647,50 @@
 		vy_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
 
-		DL_scalar=gauss->weight*Jdettria;
-
-		TripleMultiply(&basis[0],1,numdof,1,
-					&DL_scalar,1,1,0,
-					&basis[0],1,numdof,0,
-					&Ke->values[0],1);
-
-		GetBPrognostic(&B[0][0], &xyz_list[0][0], gauss);
-		GetBprimePrognostic(&Bprime[0][0], &xyz_list[0][0], gauss);
+		D_scalar=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					Ke->values,1);
+
+		GetBMasstransport(B,&xyz_list[0][0], gauss);
+		GetBprimeMasstransport(Bprime,&xyz_list[0][0], gauss);
 
 		dvxdx=dvx[0];
 		dvydy=dvy[1];
-		DL_scalar=dt*gauss->weight*Jdettria;
-
-		DL[0][0]=DL_scalar*dvxdx;
-		DL[1][1]=DL_scalar*dvydy;
-		DLprime[0][0]=DL_scalar*vx;
-		DLprime[1][1]=DL_scalar*vy;
-
-		TripleMultiply( &B[0][0],2,numdof,1,
-										&DL[0][0],2,2,0,
-										&B[0][0],2,numdof,0,
-										&Ke->values[0],1);
-
-		TripleMultiply( &B[0][0],2,numdof,1,
-										&DLprime[0][0],2,2,0,
-										&Bprime[0][0],2,numdof,0,
-										&Ke->values[0],1);
+		D_scalar=dt*gauss->weight*Jdet;
+
+		D[0][0]=D_scalar*dvxdx;
+		D[0][1]=0.;
+		D[1][0]=0.;
+		D[1][1]=D_scalar*dvydy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					B,2,numnodes,0,
+					&Ke->values[0],1);
+
+		D[0][0]=D_scalar*vx;
+		D[1][1]=D_scalar*vy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
+					&Ke->values[0],1);
 
 		/*Artificial diffusivity*/
 		vel=sqrt(vx*vx+vy*vy);
-		K[0][0]=diffusivity*h/(2*vel)*vx*vx;
-		K[1][0]=diffusivity*h/(2*vel)*vy*vx;
-		K[0][1]=diffusivity*h/(2*vel)*vx*vy;
-		K[1][1]=diffusivity*h/(2*vel)*vy*vy;
-		KDL[0][0]=DL_scalar*K[0][0];
-		KDL[1][0]=DL_scalar*K[1][0];
-		KDL[0][1]=DL_scalar*K[0][1];
-		KDL[1][1]=DL_scalar*K[1][1];
-
-		TripleMultiply( &Bprime[0][0],2,numdof,1,
-										&KDL[0][0],2,2,0,
-										&Bprime[0][0],2,numdof,0,
-										&Ke->values[0],1);
-	}
-
-/*Clean up and return*/
+		D[0][0]=D_scalar*diffusivity*h/(2*vel)*vx*vx;
+		D[1][0]=D_scalar*diffusivity*h/(2*vel)*vy*vx;
+		D[0][1]=D_scalar*diffusivity*h/(2*vel)*vx*vy;
+		D[1][1]=D_scalar*diffusivity*h/(2*vel)*vy*vy;
+		TripleMultiply(Bprime,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
+					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
 	delete gauss;
 	return Ke;
@@ -5581,7 +5699,4 @@
 /*FUNCTION Tria::CreateKMatrixHydrologyDCInefficient{{{*/
 ElementMatrix* Tria::CreateKMatrixHydrologyDCInefficient(void){
-
-	/*constants: */
-	const int    numdof=NDOF1*NUMVERTICES;
 
 	/* Intermediaries */
@@ -5590,11 +5705,13 @@
 	IssmDouble  sediment_storing;
 	IssmDouble  xyz_list[NUMVERTICES][3];
-	IssmDouble  B[2][numdof];
-	IssmDouble  basis[NUMVERTICES];
-	IssmDouble  D[2][2];
-	GaussTria   *gauss = NULL;
-
-	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters);
+	IssmDouble*    B      = xNew<IssmDouble>(5*numnodes);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble     D[2][2];
 
 	/*Retrieve all inputs and parameters*/
@@ -5605,5 +5722,5 @@
 
 	/* Start looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
@@ -5617,8 +5734,8 @@
 		D[0][0]=D_scalar; D[0][1]=0.;
 		D[1][0]=0.;       D[1][1]=D_scalar;
-		GetBHydro(&B[0][0],&xyz_list[0][0],gauss); 
-		TripleMultiply(&B[0][0],2,numdof,1,
+		GetBHydro(B,&xyz_list[0][0],gauss); 
+		TripleMultiply(B,2,numnodes,1,
 					&D[0][0],2,2,0,
-					&B[0][0],2,numdof,0,
+					B,2,numnodes,0,
 					&Ke->values[0],1);
 
@@ -5628,11 +5745,13 @@
 			D_scalar=sediment_storing*gauss->weight*Jdet;
 
-			TripleMultiply(&basis[0],numdof,1,0,
+			TripleMultiply(basis,numnodes,1,0,
 						&D_scalar,1,1,0,
-						&basis[0],1,numdof,0,
+						basis,1,numnodes,0,
 						&Ke->values[0],1);
 		}
 	}
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
 	delete gauss;
 	return Ke;
@@ -5641,7 +5760,4 @@
 /*FUNCTION Tria::CreateKMatrixHydrologyDCEfficient{{{*/
 ElementMatrix* Tria::CreateKMatrixHydrologyDCEfficient(void){
-
-	/*constants: */
-	const int    numdof=NDOF1*NUMVERTICES;
 
 	/* Intermediaries */
@@ -5650,8 +5766,4 @@
 	IssmDouble  epl_storing;
 	IssmDouble  xyz_list[NUMVERTICES][3];
-	IssmDouble  B[2][numdof];
-	IssmDouble  basis[NUMVERTICES];
-	IssmDouble  D[2][2];
-	GaussTria   *gauss = NULL;
 
 	/*Check that all nodes are active, else return empty matrix*/
@@ -5660,6 +5772,12 @@
 	}
 
-	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters);
+	IssmDouble*    B      = xNew<IssmDouble>(5*numnodes);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble     D[2][2];
 
 	/*Retrieve all inputs and parameters*/
@@ -5670,5 +5788,5 @@
 
 	/* Start looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
@@ -5681,22 +5799,25 @@
 		D[0][0]=D_scalar; D[0][1]=0.;
 		D[1][0]=0.;       D[1][1]=D_scalar;
-		GetBHydro(&B[0][0],&xyz_list[0][0],gauss); 
-		TripleMultiply(&B[0][0],2,numdof,1,
-									 &D[0][0],2,2,0,
-									 &B[0][0],2,numdof,0,
-									 &Ke->values[0],1);
+		GetBHydro(B,&xyz_list[0][0],gauss); 
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					B,2,numnodes,0,
+					&Ke->values[0],1);
 
 		/*Transient*/
 		if(reCast<bool,IssmDouble>(dt)){
-			GetNodalFunctions(&basis[0],gauss);
+			GetNodalFunctions(basis,gauss);
 			D_scalar=epl_storing*gauss->weight*Jdet;
 
-			TripleMultiply(&basis[0],numdof,1,0,
+			TripleMultiply(basis,numnodes,1,0,
 						&D_scalar,1,1,0,
-						&basis[0],1,numdof,0,
+						basis,1,numnodes,0,
 						&Ke->values[0],1);
 		}
 	}
+
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
 	delete gauss;
 	return Ke;
@@ -5706,21 +5827,20 @@
 ElementVector* Tria::CreatePVectorHydrologyShreve(void){
 
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
-
 	/*Intermediaries */
-	int        i,j;
-	IssmDouble Jdettria,dt;
+	int        i;
+	IssmDouble Jdet,dt;
 	IssmDouble basal_melting_g;
 	IssmDouble old_watercolumn_g;
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble basis[numdof];
-	GaussTria* gauss=NULL;
 
 	/*Skip if water or ice shelf element*/
-	if(IsOnWater() | IsFloating()) return NULL;
+	if(NoIceInElement() | IsFloating()) return NULL;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
 
 	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+	ElementVector* pe=new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNewZeroInit<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -5732,10 +5852,10 @@
 	/*Initialize basal_melting_correction_g to 0, do not forget!:*/
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
 
-		GetJacobianDeterminant(&Jdettria, &xyz_list[0][0],gauss);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
 		GetNodalFunctions(basis, gauss);
 
@@ -5743,9 +5863,14 @@
 		old_watercolumn_input->GetInputValue(&old_watercolumn_g,gauss);
 
-		if(reCast<int,IssmDouble>(dt))for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(old_watercolumn_g+dt*basal_melting_g)*basis[i];
-		else  for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*basal_melting_g*basis[i];
+		if(reCast<int,IssmDouble>(dt)){
+			for(i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(old_watercolumn_g+dt*basal_melting_g)*basis[i];
+		}
+		else{
+			for(i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*basal_melting_g*basis[i];
+		}
 	}
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
 	delete gauss;
 	return pe;
@@ -5754,7 +5879,4 @@
 /*FUNCTION Tria::CreatePVectorHydrologyDCInefficient {{{*/
 ElementVector* Tria::CreatePVectorHydrologyDCInefficient(void){
-
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
 
 	/*Intermediaries */
@@ -5764,9 +5886,11 @@
 	IssmDouble water_load,transfer;
 	IssmDouble sediment_storing;
-	IssmDouble basis[numdof];
-	GaussTria* gauss=NULL;
-
-	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -5783,5 +5907,5 @@
 
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
@@ -5795,5 +5919,5 @@
 		scalar = Jdet*gauss->weight*(water_load+transfer);
 		if(reCast<bool,IssmDouble>(dt)) scalar = scalar*dt;
-		for(int i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
+		for(int i=0;i<numnodes;i++) pe->values[i]+=scalar*basis[i];
 
 		/*Transient term*/
@@ -5801,8 +5925,10 @@
 			old_wh_input->GetInputValue(&water_head,gauss);
 			scalar = Jdet*gauss->weight*water_head*sediment_storing;
-			for(int i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
-		}
-	}
+			for(int i=0;i<numnodes;i++) pe->values[i]+=scalar*basis[i];
+		}
+	}
+
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
 	delete gauss;
 	return pe;
@@ -5811,7 +5937,4 @@
 /*FUNCTION Tria::CreatePVectorHydrologyDCEfficient {{{*/
 ElementVector* Tria::CreatePVectorHydrologyDCEfficient(void){
-
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
 
 	/*Intermediaries */
@@ -5822,6 +5945,5 @@
 	IssmDouble transfer,residual;
 	IssmDouble epl_storing;
-	IssmDouble basis[numdof];
-	GaussTria* gauss=NULL;
+	GaussTria* gauss = NULL;
 
 	/*Check that all nodes are active, else return empty matrix*/
@@ -5829,6 +5951,11 @@
 		return NULL;
 	}
-	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
@@ -5850,5 +5977,5 @@
 		gauss->GaussPoint(ig);
 		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
-		GetNodalFunctions(basis, gauss);
+		GetNodalFunctions(basis,gauss);
 
 		/*Loading term*/
@@ -5856,5 +5983,5 @@
 		scalar = Jdet*gauss->weight*(-transfer);
 		if(reCast<bool,IssmDouble>(dt)) scalar = scalar*dt;
-		for(int i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
+		for(int i=0;i<numnodes;i++) pe->values[i]+=scalar*basis[i];
 
 		/*Transient term*/
@@ -5862,9 +5989,9 @@
 			old_wh_input->GetInputValue(&water_head,gauss);
 			scalar = Jdet*gauss->weight*water_head*epl_storing;
-			for(int i=0;i<numdof;i++) pe->values[i]+=scalar*basis[i];
+			for(int i=0;i<numnodes;i++) pe->values[i]+=scalar*basis[i];
 		}
 	}
 	delete gauss;
-	
+
 	/*	Add residual if necessary*/
 	gauss=new GaussTria();
@@ -5872,9 +5999,11 @@
 		gauss->GaussVertex(iv);
 
-		connectivity = IssmDouble(nodes[iv]->GetConnectivity());
+		connectivity = IssmDouble(vertices[iv]->Connectivity());
 		residual_input->GetInputValue(&residual,gauss);
 		pe->values[iv]+=residual/connectivity;
 	}
+
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
 	delete gauss;
 	return pe;
@@ -5883,15 +6012,14 @@
 /*FUNCTION Tria::GetSolutionFromInputsOneDof{{{*/
 void  Tria::GetSolutionFromInputsOneDof(Vector<IssmDouble>* solution, int enum_type){
-	
-	const int    numdof=NDOF1*NUMVERTICES;
-
-	int         i;
+
 	int        *doflist = NULL;
-	IssmDouble  enum_value;
-	IssmDouble  values[numdof];
-	GaussTria  *gauss   = NULL;
-
-	/*Get dof list: */
+	IssmDouble  value;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Fetch dof list and allocate solution vector*/
 	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values = xNew<IssmDouble>(numnodes);
 
 	/*Get inputs*/
@@ -5899,20 +6027,18 @@
 
 	/*Ok, we have the values, fill in the array: */
-	/*P1 element only for now*/
-	gauss=new GaussTria();
-	for(i=0;i<NUMVERTICES;i++){
-
-		gauss->GaussVertex(i);
-
-		/*Recover dof values*/
-		enum_input->GetInputValue(&enum_value,gauss);
-		values[i]=enum_value;
-	}
-
-	solution->SetValues(numdof,doflist,values,INS_VAL);
+	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;
-	xDelete<int>(doflist);
 }
 /*}}}*/
@@ -5920,14 +6046,16 @@
 void  Tria::InputUpdateFromSolutionHydrologyShreve(IssmDouble* solution){
 
-	/*Intermediaries*/
-	const int   numdof         = NDOF1 *NUMVERTICES;
-	int        *doflist        = NULL;
-	IssmDouble  values[numdof];
-
-	/*Get dof list: */
+	/*Intermediary*/
+	int* doflist = NULL;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Fetch dof list and allocate solution vector*/
 	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values    = xNew<IssmDouble>(numnodes);
 
 	/*Use the dof list to index into the solution vector: */
-	for(int i=0;i<numdof;i++){
+	for(int i=0;i<numnodes;i++){
 		values[i]=solution[doflist[i]];
 		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
@@ -5939,4 +6067,5 @@
 
 	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
 	xDelete<int>(doflist);
 }
@@ -5946,17 +6075,19 @@
 
 	/*Intermediaries*/
-	const int   numdof   = NDOF1 *NUMVERTICES;
 	int        *doflist  = NULL;
 	bool        converged;
-	IssmDouble  values[numdof];
-	IssmDouble  residual[numdof];
 	IssmDouble  penalty_factor, dt;
 	IssmDouble  kmax, kappa, h_max;
 
-	/*Get dof list: */
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Fetch dof list and allocate solution vector*/
 	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
+	IssmDouble* values   = xNew<IssmDouble>(numnodes);
+	IssmDouble* residual = xNew<IssmDouble>(numnodes);
 
 	/*Use the dof list to index into the solution vector: */
-	for(int i=0;i<numdof;i++){
+	for(int i=0;i<numnodes;i++){
 		values[i]=solution[doflist[i]];
 		if(xIsNan<IssmDouble>(values[i])) _error_("NaN found in solution vector");
@@ -5970,8 +6101,8 @@
 		this->parameters->FindParam(&kmax,HydrologySedimentKmaxEnum);
 		this->parameters->FindParam(&penalty_factor,HydrologydcPenaltyFactorEnum);
-		
+
 		kappa=kmax*pow(10.,penalty_factor);
-		
-		for(int i=0;i<NUMVERTICES;i++){
+
+		for(int i=0;i<numnodes;i++){
 			this->GetHydrologyDCInefficientHmax(&h_max,nodes[i]);
 			if(values[i]>h_max){
@@ -5982,11 +6113,13 @@
 			}
 		}
+		this->inputs->AddInput(new TriaInput(SedimentHeadResidualEnum,residual,P1Enum));
 	}
 
 	/*Add input to the element: */
 	this->inputs->AddInput(new TriaInput(SedimentHeadEnum,values,P1Enum));
-	this->inputs->AddInput(new TriaInput(SedimentHeadResidualEnum,residual,P1Enum));
 
 	/*Free ressources:*/
+	xDelete<IssmDouble>(values);
+	xDelete<IssmDouble>(residual);
 	xDelete<int>(doflist);
 }
@@ -6030,6 +6163,6 @@
 void  Tria::GetHydrologyTransfer(Vector<IssmDouble>* transfer){
 
-	const int  numdof         = NDOF1 *NUMVERTICES;
-	int        *doflist       = NULL;
+	const int  numdof   = NDOF1 *NUMVERTICES;
+	int        *doflist = NULL;
 	bool       isefficientlayer;
 	int        transfermethod;
@@ -6042,8 +6175,8 @@
 
 	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
-	
+
 	/*Get the flag to know if the efficient layer is present*/
 	this->parameters->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
-	
+
 	if(isefficientlayer){
 		/*Also get the flag to the transfer method*/
@@ -6060,10 +6193,10 @@
 			GetInputListOnVertices(&sed_head[0],SedimentHeadEnum); 
 			GetInputListOnVertices(&epl_head[0],EplHeadEnum);
-			
+
 			this->parameters->FindParam(&leakage,HydrologydcLeakageFactorEnum);
 
 			sed_trans = matpar->GetSedimentTransmitivity();
 			sed_thick = matpar->GetSedimentThickness();
-			
+
 			for(int i=0;i<numdof;i++){
 				/*No transfer if the EPL is not active*/
@@ -6074,9 +6207,9 @@
 					eplstoring[i]=matpar->GetEplStoring();		
 					sedstoring[i]=matpar->GetSedimentStoring();
-					
+
 					/*EPL head higher than sediment head, transfer from the epl to the sediment*/
 					if(epl_head[i]>sed_head[i]){
 						wh_trans=eplstoring[i]*sed_trans*(epl_head[i]-sed_head[i])/(leakage*sed_thick);				
-						
+
 						/*No transfer if the sediment head is allready at the maximum*/
 						this->GetHydrologyDCInefficientHmax(&h_max,nodes[i]);
@@ -6084,5 +6217,5 @@
 					}
 					/*EPL head lower than sediment head, transfer from the sediment to the epl*/
-					else if(epl_head[i]<sed_head[i]){
+					else if(epl_head[i]<=sed_head[i]){
 						wh_trans=sedstoring[i]*sed_trans*(epl_head[i]-sed_head[i])/(leakage*sed_thick);				
 					}
@@ -6107,9 +6240,9 @@
 	IssmDouble flag     = 0.;
 	IssmDouble active[numnodes];
-	
+
 	GetInputListOnVertices(&active[0],HydrologydcMaskEplactiveEnum);
 
 	for(int i=0;i<numnodes;i++) flag+=active[i];
-	
+
 	if(flag>0.){
 		for(int i=0;i<numnodes;i++){
@@ -6120,5 +6253,5 @@
 		/*Do not do anything: at least one node is active for this element but this element is not solved for*/
 	}
-	
+
 }
 /*}}}*/
@@ -6144,5 +6277,5 @@
 	sedheadmin=sedhead[0];
 	for(i=1;i<numdof;i++) if(sedhead[i]<=sedheadmin)sedheadmin=sedhead[i];
-	
+
 	for(i=0;i<numdof;i++){
 		/*Activate EPL if residual is >0 */
@@ -6150,5 +6283,5 @@
 			vec_mask->SetValue(nodes[i]->Sid(),1.,INS_VAL);
 		}
-		
+
 		/*If mask was alread one, keep one*/
 		else if(old_active[i]>0.){
@@ -6175,13 +6308,13 @@
 #endif
 
-#ifdef _HAVE_PROGNOSTIC_
-/*FUNCTION Tria::CreateKMatrixPrognostic {{{*/
-ElementMatrix* Tria::CreateKMatrixPrognostic(void){
+#ifdef _HAVE_MASSTRANSPORT_
+/*FUNCTION Tria::CreateKMatrixMasstransport {{{*/
+ElementMatrix* Tria::CreateKMatrixMasstransport(void){
 
 	switch(GetElementType()){
-		case P1Enum:
-			return CreateKMatrixPrognostic_CG();
+		case P1Enum: case P2Enum:
+			return CreateKMatrixMasstransport_CG();
 		case P1DGEnum:
-			return CreateKMatrixPrognostic_DG();
+			return CreateKMatrixMasstransport_DG();
 		default:
 			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
@@ -6189,28 +6322,24 @@
 }
 /*}}}*/
-/*FUNCTION Tria::CreateKMatrixPrognostic_CG {{{*/
-ElementMatrix* Tria::CreateKMatrixPrognostic_CG(void){
-
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
+/*FUNCTION Tria::CreateKMatrixMasstransport_CG {{{*/
+ElementMatrix* Tria::CreateKMatrixMasstransport_CG(void){
 
 	/*Intermediaries */
 	int        stabilization;
 	int        dim;
-	IssmDouble Jdettria,DL_scalar,dt,h;
+	IssmDouble Jdet,D_scalar,dt,h;
 	IssmDouble vel,vx,vy,dvxdx,dvydy;
 	IssmDouble dvx[2],dvy[2];
-	IssmDouble v_gauss[2]={0.0};
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble basis[NUMVERTICES];
-	IssmDouble B[2][NUMVERTICES];
-	IssmDouble Bprime[2][NUMVERTICES];
-	IssmDouble K[2][2]                        ={0.0};
-	IssmDouble KDL[2][2]                      ={0.0};
-	IssmDouble DL[2][2]                        ={0.0};
-	IssmDouble DLprime[2][2]                   ={0.0};
-
-	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2];
 
 	/*Retrieve all inputs and parameters*/
@@ -6218,5 +6347,5 @@
 	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
 	this->parameters->FindParam(&dim,MeshDimensionEnum);
-	this->parameters->FindParam(&stabilization,PrognosticStabilizationEnum);
+	this->parameters->FindParam(&stabilization,MasstransportStabilizationEnum);
 	Input* vxaverage_input=NULL;
 	Input* vyaverage_input=NULL;
@@ -6237,6 +6366,6 @@
 		gauss->GaussPoint(ig);
 
-		GetJacobianDeterminant(&Jdettria, &xyz_list[0][0],gauss);
-		GetNodalFunctions(&basis[0],gauss);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
 
 		vxaverage_input->GetInputValue(&vx,gauss);
@@ -6245,31 +6374,32 @@
 		vyaverage_input->GetInputDerivativeValue(&dvy[0],&xyz_list[0][0],gauss);
 
-		DL_scalar=gauss->weight*Jdettria;
-
-		TripleMultiply(&basis[0],1,numdof,1,
-					&DL_scalar,1,1,0,
-					&basis[0],1,numdof,0,
+		D_scalar=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
 					&Ke->values[0],1);
 
-		GetBPrognostic(&B[0][0], &xyz_list[0][0], gauss);
-		GetBprimePrognostic(&Bprime[0][0], &xyz_list[0][0], gauss);
+		GetBMasstransport(B,&xyz_list[0][0],gauss);
+		GetBprimeMasstransport(Bprime,&xyz_list[0][0],gauss);
 
 		dvxdx=dvx[0];
 		dvydy=dvy[1];
-		DL_scalar=dt*gauss->weight*Jdettria;
-
-		DL[0][0]=DL_scalar*dvxdx;
-		DL[1][1]=DL_scalar*dvydy;
-		DLprime[0][0]=DL_scalar*vx;
-		DLprime[1][1]=DL_scalar*vy;
-
-		TripleMultiply( &B[0][0],2,numdof,1,
-					&DL[0][0],2,2,0,
-					&B[0][0],2,numdof,0,
+		D_scalar=dt*gauss->weight*Jdet;
+
+		D[0][0]=D_scalar*dvxdx;
+		D[0][1]=0.;
+		D[1][0]=0.;
+		D[1][1]=D_scalar*dvydy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					B,2,numnodes,0,
 					&Ke->values[0],1);
 
-		TripleMultiply( &B[0][0],2,numdof,1,
-					&DLprime[0][0],2,2,0,
-					&Bprime[0][0],2,numdof,0,
+		D[0][0]=D_scalar*vx;
+		D[1][1]=D_scalar*vy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
 					&Ke->values[0],1);
 
@@ -6277,26 +6407,26 @@
 			/*Streamline upwinding*/
 			vel=sqrt(vx*vx+vy*vy)+1.e-8;
-			K[0][0]=h/(2*vel)*vx*vx;
-			K[1][0]=h/(2*vel)*vy*vx;
-			K[0][1]=h/(2*vel)*vx*vy;
-			K[1][1]=h/(2*vel)*vy*vy;
+			D[0][0]=h/(2*vel)*vx*vx;
+			D[1][0]=h/(2*vel)*vy*vx;
+			D[0][1]=h/(2*vel)*vx*vy;
+			D[1][1]=h/(2*vel)*vy*vy;
 		}
 		else if(stabilization==1){
-			/*MacAyeal*/
+			/*SSA*/
 			vxaverage_input->GetInputAverage(&vx);
 			vyaverage_input->GetInputAverage(&vy);
-			K[0][0]=h/2.0*fabs(vx);
-			K[0][1]=0.;
-			K[1][0]=0.;
-			K[1][1]=h/2.0*fabs(vy);
+			D[0][0]=h/2.0*fabs(vx);
+			D[0][1]=0.;
+			D[1][0]=0.;
+			D[1][1]=h/2.0*fabs(vy);
 		}
 		if(stabilization==1 || stabilization==2){
-			KDL[0][0]=DL_scalar*K[0][0];
-			KDL[1][0]=DL_scalar*K[1][0];
-			KDL[0][1]=DL_scalar*K[0][1];
-			KDL[1][1]=DL_scalar*K[1][1];
-			TripleMultiply( &Bprime[0][0],2,numdof,1,
-						&KDL[0][0],2,2,0,
-						&Bprime[0][0],2,numdof,0,
+			D[0][0]=D_scalar*D[0][0];
+			D[1][0]=D_scalar*D[1][0];
+			D[0][1]=D_scalar*D[0][1];
+			D[1][1]=D_scalar*D[1][1];
+			TripleMultiply(Bprime,2,numnodes,1,
+						&D[0][0],2,2,0,
+						Bprime,2,numnodes,0,
 						&Ke->values[0],1);
 		}
@@ -6304,28 +6434,28 @@
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
 	delete gauss;
 	return Ke;
 }
 /*}}}*/
-/*FUNCTION Tria::CreateKMatrixPrognostic_DG {{{*/
-ElementMatrix* Tria::CreateKMatrixPrognostic_DG(void){
-
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
+/*FUNCTION Tria::CreateKMatrixMasstransport_DG {{{*/
+ElementMatrix* Tria::CreateKMatrixMasstransport_DG(void){
 
 	/*Intermediaries */
 	int        dim;
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble Jdettria,dt,vx,vy;
-	IssmDouble basis[NUMVERTICES];
-	IssmDouble B[2][NUMVERTICES];
-	IssmDouble Bprime[2][NUMVERTICES];
-	IssmDouble DL[2][2]={0.0};
-	IssmDouble DLprime[2][2]={0.0};
-	IssmDouble DL_scalar;
-	GaussTria  *gauss=NULL;
-
-	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+	IssmDouble Jdet,D_scalar,dt,vx,vy;
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2];
 
 	/*Retrieve all inputs and parameters*/
@@ -6345,5 +6475,5 @@
 
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
@@ -6353,137 +6483,432 @@
 		vyaverage_input->GetInputValue(&vy,gauss);
 
-		GetJacobianDeterminant(&Jdettria, &xyz_list[0][0],gauss);
-		GetNodalFunctions(&basis[0],gauss);
-
-		DL_scalar=gauss->weight*Jdettria;
-
-		TripleMultiply(&basis[0],1,numdof,1,
-					&DL_scalar,1,1,0,
-					&basis[0],1,numdof,0,
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		D_scalar=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
 					&Ke->values[0],1);
 
-		/*WARNING: B and Bprime are inverted compared to usual prognostic!!!!*/
-		GetBPrognostic(&Bprime[0][0], &xyz_list[0][0], gauss);
-		GetBprimePrognostic(&B[0][0], &xyz_list[0][0], gauss);
-
-		DL_scalar=-dt*gauss->weight*Jdettria;
-
-		DLprime[0][0]=DL_scalar*vx;
-		DLprime[1][1]=DL_scalar*vy;
-
-		TripleMultiply( &B[0][0],2,numdof,1,
-					&DLprime[0][0],2,2,0,
-					&Bprime[0][0],2,numdof,0,
+		/*WARNING: B and Bprime are inverted compared to usual masstransport!!!!*/
+		GetBMasstransport(Bprime, &xyz_list[0][0], gauss);
+		GetBprimeMasstransport(B, &xyz_list[0][0], gauss);
+
+		D_scalar=-dt*gauss->weight*Jdet;
+		D[0][0]=D_scalar*vx;
+		D[0][1]=0.;
+		D[1][0]=0.;
+		D[1][1]=D_scalar*vy;
+
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
 					&Ke->values[0],1);
 	}
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
 	delete gauss;
 	return Ke;
 }
 /*}}}*/
-/*FUNCTION Tria::CreatePVectorPrognostic{{{*/
-ElementVector* Tria::CreatePVectorPrognostic(void){
-
-	switch(GetElementType()){
-		case P1Enum:
-			return CreatePVectorPrognostic_CG();
-		case P1DGEnum:
-			return CreatePVectorPrognostic_DG();
-		default:
-			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
-	}
-}
-/*}}}*/
-/*FUNCTION Tria::CreatePVectorPrognostic_CG {{{*/
-ElementVector* Tria::CreatePVectorPrognostic_CG(void){
-
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
+/*FUNCTION Tria::CreateKMatrixFreeSurfaceTop {{{*/
+ElementMatrix* Tria::CreateKMatrixFreeSurfaceTop(void){
 
 	/*Intermediaries */
-	IssmDouble Jdettria,dt;
-	IssmDouble surface_mass_balance_g,basal_melting_g,basal_melting_correction_g,thickness_g;
+	int        stabilization;
+	int        dim;
+	IssmDouble Jdet,D_scalar,dt,h;
+	IssmDouble vel,vx,vy;
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble basis[NUMVERTICES];
-	GaussTria* gauss=NULL;
-
-	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2];
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
 	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
-	Input* surface_mass_balance_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(surface_mass_balance_input);
-	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum);          _assert_(basal_melting_input);
-	Input* basal_melting_correction_input=inputs->GetInput(BasalforcingsMeltingRateCorrectionEnum);
-	Input* thickness_input=inputs->GetInput(ThicknessEnum);                             _assert_(thickness_input);
-
-	/*Initialize basal_melting_correction_g to 0, do not forget!:*/
+	this->parameters->FindParam(&stabilization,MasstransportStabilizationEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	h=sqrt(2*this->GetArea());
+
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria *gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
 
-		GetJacobianDeterminant(&Jdettria, &xyz_list[0][0],gauss);
-		GetNodalFunctions(&basis[0],gauss);
-
-		surface_mass_balance_input->GetInputValue(&surface_mass_balance_g,gauss);
-		basal_melting_input->GetInputValue(&basal_melting_g,gauss);
-		thickness_input->GetInputValue(&thickness_g,gauss);
-		if(basal_melting_correction_input)
-		 basal_melting_correction_input->GetInputValue(&basal_melting_correction_g,gauss);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+
+		D_scalar=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+		GetBMasstransport(B,&xyz_list[0][0],gauss);
+		GetBprimeMasstransport(Bprime,&xyz_list[0][0],gauss);
+
+		D_scalar=dt*gauss->weight*Jdet;
+
+		D[0][0]=D_scalar*vx;
+		D[0][1]=0.;
+		D[1][0]=0.;
+		D[1][1]=D_scalar*vy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
+					&Ke->values[0],1);
+
+		if(stabilization==2){
+			/*Streamline upwinding*/
+			vel=sqrt(vx*vx+vy*vy)+1.e-8;
+			D[0][0]=h/(2*vel)*vx*vx;
+			D[1][0]=h/(2*vel)*vy*vx;
+			D[0][1]=h/(2*vel)*vx*vy;
+			D[1][1]=h/(2*vel)*vy*vy;
+		}
+		else if(stabilization==1){
+			/*SSA*/
+			vx_input->GetInputAverage(&vx);
+			vy_input->GetInputAverage(&vy);
+			D[0][0]=h/2.0*fabs(vx);
+			D[0][1]=0.;
+			D[1][0]=0.;
+			D[1][1]=h/2.0*fabs(vy);
+		}
+		if(stabilization==1 || stabilization==2){
+			D[0][0]=D_scalar*D[0][0];
+			D[1][0]=D_scalar*D[1][0];
+			D[0][1]=D_scalar*D[0][1];
+			D[1][1]=D_scalar*D[1][1];
+			TripleMultiply(Bprime,2,numnodes,1,
+						&D[0][0],2,2,0,
+						Bprime,2,numnodes,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixFreeSurfaceBase {{{*/
+ElementMatrix* Tria::CreateKMatrixFreeSurfaceBase(void){
+
+	/*Intermediaries */
+	int        stabilization;
+	int        dim;
+	IssmDouble Jdet,D_scalar,dt,h;
+	IssmDouble vel,vx,vy;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2];
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	this->parameters->FindParam(&stabilization,MasstransportStabilizationEnum);
+	Input* vx_input=inputs->GetInput(VxEnum); _assert_(vx_input);
+	Input* vy_input=inputs->GetInput(VyEnum); _assert_(vy_input);
+	h=sqrt(2*this->GetArea());
+
+	/* Start  looping on the number of gaussian points: */
+	GaussTria *gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		vx_input->GetInputValue(&vx,gauss);
+		vy_input->GetInputValue(&vy,gauss);
+
+		D_scalar=gauss->weight*Jdet;
+
+		TripleMultiply(basis,1,numnodes,1,
+					&D_scalar,1,1,0,
+					basis,1,numnodes,0,
+					&Ke->values[0],1);
+
+		GetBMasstransport(B,&xyz_list[0][0],gauss);
+		GetBprimeMasstransport(Bprime,&xyz_list[0][0],gauss);
+
+		D_scalar=dt*gauss->weight*Jdet;
+
+		D[0][0]=D_scalar*vx;
+		D[0][1]=0.;
+		D[1][0]=0.;
+		D[1][1]=D_scalar*vy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
+					&Ke->values[0],1);
+
+		if(stabilization==2){
+			/*Streamline upwinding*/
+			vel=sqrt(vx*vx+vy*vy)+1.e-8;
+			D[0][0]=h/(2*vel)*vx*vx;
+			D[1][0]=h/(2*vel)*vy*vx;
+			D[0][1]=h/(2*vel)*vx*vy;
+			D[1][1]=h/(2*vel)*vy*vy;
+		}
+		else if(stabilization==1){
+			/*SSA*/
+			vx_input->GetInputAverage(&vx);
+			vy_input->GetInputAverage(&vy);
+			D[0][0]=h/2.0*fabs(vx);
+			D[0][1]=0.;
+			D[1][0]=0.;
+			D[1][1]=h/2.0*fabs(vy);
+		}
+		if(stabilization==1 || stabilization==2){
+			D[0][0]=D_scalar*D[0][0];
+			D[1][0]=D_scalar*D[1][0];
+			D[0][1]=D_scalar*D[0][1];
+			D[1][1]=D_scalar*D[1][1];
+			TripleMultiply(Bprime,2,numnodes,1,
+						&D[0][0],2,2,0,
+						Bprime,2,numnodes,0,
+						&Ke->values[0],1);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorMasstransport{{{*/
+ElementVector* Tria::CreatePVectorMasstransport(void){
+
+	switch(GetElementType()){
+		case P1Enum: case P2Enum:
+			return CreatePVectorMasstransport_CG();
+		case P1DGEnum:
+			return CreatePVectorMasstransport_DG();
+		default:
+			_error_("Element type " << EnumToStringx(GetElementType()) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorMasstransport_CG {{{*/
+ElementVector* Tria::CreatePVectorMasstransport_CG(void){
+
+	/*Intermediaries */
+	IssmDouble Jdet,dt;
+	IssmDouble ms,mb,mb_correction,thickness;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* ms_input     = inputs->GetInput(SurfaceforcingsMassBalanceEnum);      _assert_(ms_input);
+	Input* mb_input     = inputs->GetInput(BasalforcingsMeltingRateEnum); _assert_(mb_input);
+	Input* mb_correction_input = inputs->GetInput(BasalforcingsMeltingRateCorrectionEnum);
+	Input* thickness_input  = inputs->GetInput(ThicknessEnum);     _assert_(thickness_input);
+
+	/*Initialize mb_correction to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	GaussTria* gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		ms_input->GetInputValue(&ms,gauss);
+		mb_input->GetInputValue(&mb,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+		if(mb_correction_input)
+		 mb_correction_input->GetInputValue(&mb_correction,gauss);
 		else
-		 basal_melting_correction_g=0.;
-
-		for(int i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(thickness_g+dt*(surface_mass_balance_g-basal_melting_g-basal_melting_correction_g))*basis[i];
+		 mb_correction=0.;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(thickness+dt*(ms-mb-mb_correction))*basis[i];
 	}
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
 	delete gauss;
 	return pe;
 }
 /*}}}*/
-/*FUNCTION Tria::CreatePVectorPrognostic_DG {{{*/
-ElementVector* Tria::CreatePVectorPrognostic_DG(void){
-
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
+/*FUNCTION Tria::CreatePVectorMasstransport_DG {{{*/
+ElementVector* Tria::CreatePVectorMasstransport_DG(void){
 
 	/*Intermediaries */
-	IssmDouble Jdettria,dt;
-	IssmDouble surface_mass_balance_g,basal_melting_g,thickness_g;
+	IssmDouble Jdet,dt;
+	IssmDouble ms,mb,thickness;
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble basis[NUMVERTICES];
-	GaussTria* gauss=NULL;
-
-	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
 	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	Input* surface_mass_balance_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(surface_mass_balance_input);
-	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum);          _assert_(basal_melting_input);
-	Input* thickness_input=inputs->GetInput(ThicknessEnum);                             _assert_(thickness_input);
+	Input* ms_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(ms_input);
+	Input* mb_input=inputs->GetInput(BasalforcingsMeltingRateEnum);   _assert_(mb_input);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum);           _assert_(thickness_input);
 
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
 
-		GetJacobianDeterminant(&Jdettria, &xyz_list[0][0],gauss);
-		GetNodalFunctions(&basis[0],gauss);
-
-		surface_mass_balance_input->GetInputValue(&surface_mass_balance_g,gauss);
-		basal_melting_input->GetInputValue(&basal_melting_g,gauss);
-		thickness_input->GetInputValue(&thickness_g,gauss);
-
-		for(int i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(thickness_g+dt*(surface_mass_balance_g-basal_melting_g))*basis[i];
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		ms_input->GetInputValue(&ms,gauss);
+		mb_input->GetInputValue(&mb,gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(thickness+dt*(ms-mb))*basis[i];
 	}
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorFreeSurfaceTop {{{*/
+ElementVector* Tria::CreatePVectorFreeSurfaceTop(void){
+
+	/*Intermediaries */
+	IssmDouble Jdet,dt;
+	IssmDouble ms,surface,vz;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vz_input     = inputs->GetInput(VzEnum);                         _assert_(vz_input);
+	Input* ms_input     = inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(ms_input);
+	Input* surface_input= inputs->GetInput(SurfaceEnum);                    _assert_(surface_input);
+
+	/*Initialize mb_correction to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	GaussTria* gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		vz_input->GetInputValue(&vz,gauss);
+		ms_input->GetInputValue(&ms,gauss);
+		surface_input->GetInputValue(&surface,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(surface + dt*ms + dt*vz)*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorFreeSurfaceBase {{{*/
+ElementVector* Tria::CreatePVectorFreeSurfaceBase(void){
+
+	/*Intermediaries */
+	IssmDouble Jdet,dt;
+	IssmDouble mb,mb_correction,bed,vz;
+	IssmDouble xyz_list[NUMVERTICES][3];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	this->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
+	Input* vz_input  = inputs->GetInput(VzEnum);                         _assert_(vz_input);
+	Input* mb_input  = inputs->GetInput(BasalforcingsMeltingRateEnum);   _assert_(mb_input);
+	Input* mb_correction_input = inputs->GetInput(BasalforcingsMeltingRateCorrectionEnum);
+	Input* bed_input = inputs->GetInput(BedEnum);                        _assert_(bed_input);
+
+	/*Initialize mb_correction to 0, do not forget!:*/
+	/* Start  looping on the number of gaussian points: */
+	GaussTria* gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		vz_input->GetInputValue(&vz,gauss);
+		mb_input->GetInputValue(&mb,gauss);
+		bed_input->GetInputValue(&bed,gauss);
+		if(mb_correction_input)
+		 mb_correction_input->GetInputValue(&mb_correction,gauss);
+		else
+		 mb_correction=0.;
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(bed+dt*(mb-mb_correction) + dt*vz)*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
 	delete gauss;
 	return pe;
@@ -6582,23 +7007,11 @@
 }
 /*}}}*/
-/*FUNCTION Tria::InputUpdateFromVectorDakota(int* vector, int name, int type);{{{*/
-void  Tria::InputUpdateFromVectorDakota(int* vector, int name, int type){
-	_error_("not supported yet!");
-}
-/*}}}*/
-/*FUNCTION Tria::InputUpdateFromVectorDakota(bool* vector, int name, int type);{{{*/
-void  Tria::InputUpdateFromVectorDakota(bool* vector, int name, int type){
-	_error_("not supported yet!");
-}
-/*}}}*/
 /*FUNCTION Tria::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type);{{{*/
 void  Tria::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){
 
-	int i,j,t;
-	TransientInput* transientinput=NULL;
-	IssmDouble values[3];
-	IssmDouble time;
-	int row;
-	IssmDouble yts;
+	int             i,t,row;
+	IssmDouble      time;
+	TransientInput *transientinput = NULL;
+	IssmDouble      values[3];
 
 	/*Check that name is an element input*/
@@ -6608,8 +7021,5 @@
 
 		case VertexEnum:
-
 			/*Create transient input: */
-
-			parameters->FindParam(&yts,ConstantsYtsEnum);
 			for(t=0;t<ncols;t++){ //ncols is the number of times
 
@@ -6617,9 +7027,9 @@
 				for(i=0;i<3;i++){
 					row=this->vertices[i]->Sid();
-					values[i]=(IssmDouble)matrix[ncols*row+t];
+					values[i]=matrix[ncols*row+t];
 				}
 
-				/*time? :*/
-				time=(IssmDouble)matrix[(nrows-1)*ncols+t]*yts;
+				/*time:*/
+				time=matrix[(nrows-1)*ncols+t];
 
 				if(t==0) transientinput=new TransientInput(name);
@@ -6656,25 +7066,21 @@
 ElementMatrix* Tria::CreateKMatrixBalancethickness_CG(void){
 
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
-
 	/*Intermediaries */
 	int        stabilization;
 	int        i,j,dim;
-	IssmDouble Jdettria,vx,vy,dvxdx,dvydy,vel,h;
+	IssmDouble Jdet,vx,vy,dvxdx,dvydy,vel,h;
+	IssmDouble D_scalar;
 	IssmDouble dvx[2],dvy[2];
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble L[NUMVERTICES];
-	IssmDouble B[2][NUMVERTICES];
-	IssmDouble Bprime[2][NUMVERTICES];
-	IssmDouble K[2][2]                          = {0.0};
-	IssmDouble KDL[2][2]                        = {0.0};
-	IssmDouble DL[2][2]                         = {0.0};
-	IssmDouble DLprime[2][2]                    = {0.0};
-	IssmDouble DL_scalar;
-	GaussTria *gauss                            = NULL;
-
-	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2];
 
 	/*Retrieve all Inputs and parameters: */
@@ -6692,15 +7098,15 @@
 		vyaverage_input=inputs->GetInput(VyAverageEnum); _assert_(vyaverage_input);
 	}
-	h=sqrt(2*this->GetArea());
+	h=sqrt(2.*this->GetArea());
 
 	/*Start looping on the number of gaussian points:*/
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
 
-		GetJacobianDeterminant(&Jdettria, &xyz_list[0][0],gauss);
-		GetBPrognostic(&B[0][0], &xyz_list[0][0], gauss);
-		GetBprimePrognostic(&Bprime[0][0], &xyz_list[0][0], gauss);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetBMasstransport(B,&xyz_list[0][0],gauss);
+		GetBprimeMasstransport(Bprime,&xyz_list[0][0],gauss);
 
 		vxaverage_input->GetInputValue(&vx,gauss);
@@ -6711,20 +7117,20 @@
 		dvxdx=dvx[0];
 		dvydy=dvy[1];
-		DL_scalar=gauss->weight*Jdettria;
-
-		DL[0][0]=DL_scalar*dvxdx;
-		DL[1][1]=DL_scalar*dvydy;
-
-		DLprime[0][0]=DL_scalar*vx;
-		DLprime[1][1]=DL_scalar*vy;
-
-		TripleMultiply( &B[0][0],2,numdof,1,
-					&DL[0][0],2,2,0,
-					&B[0][0],2,numdof,0,
+		D_scalar=gauss->weight*Jdet;
+
+		D[0][0]=D_scalar*dvxdx;
+		D[0][1]=0.;
+		D[1][0]=0.;
+		D[1][1]=D_scalar*dvydy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					B,2,numnodes,0,
 					&Ke->values[0],1);
 
-		TripleMultiply( &B[0][0],2,numdof,1,
-					&DLprime[0][0],2,2,0,
-					&Bprime[0][0],2,numdof,0,
+		D[0][0]=D_scalar*vx;
+		D[1][1]=D_scalar*vy;
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
 					&Ke->values[0],1);
 
@@ -6732,26 +7138,26 @@
 			/*Streamline upwinding*/
 			vel=sqrt(vx*vx+vy*vy);
-			K[0][0]=h/(2*vel)*vx*vx;
-			K[1][0]=h/(2*vel)*vy*vx;
-			K[0][1]=h/(2*vel)*vx*vy;
-			K[1][1]=h/(2*vel)*vy*vy;
+			D[0][0]=h/(2*vel)*vx*vx;
+			D[1][0]=h/(2*vel)*vy*vx;
+			D[0][1]=h/(2*vel)*vx*vy;
+			D[1][1]=h/(2*vel)*vy*vy;
 		}
 		else if(stabilization==2){
-			/*MacAyeal*/
+			/*SSA*/
 			vxaverage_input->GetInputAverage(&vx);
 			vyaverage_input->GetInputAverage(&vy);
-			K[0][0]=h/2.0*fabs(vx);
-			K[0][1]=0.;
-			K[1][0]=0.;
-			K[1][1]=h/2.0*fabs(vy);
+			D[0][0]=h/2.0*fabs(vx);
+			D[0][1]=0.;
+			D[1][0]=0.;
+			D[1][1]=h/2.0*fabs(vy);
 		}
 		if(stabilization==1 || stabilization==2){
-			KDL[0][0]=DL_scalar*K[0][0];
-			KDL[1][0]=DL_scalar*K[1][0];
-			KDL[0][1]=DL_scalar*K[0][1];
-			KDL[1][1]=DL_scalar*K[1][1];
-			TripleMultiply( &Bprime[0][0],2,numdof,1,
-						&KDL[0][0],2,2,0,
-						&Bprime[0][0],2,numdof,0,
+			D[0][0]=D_scalar*D[0][0];
+			D[1][0]=D_scalar*D[1][0];
+			D[0][1]=D_scalar*D[0][1];
+			D[1][1]=D_scalar*D[1][1];
+			TripleMultiply(Bprime,2,numnodes,1,
+						&D[0][0],2,2,0,
+						Bprime,2,numnodes,0,
 						&Ke->values[0],1);
 		}
@@ -6759,4 +7165,7 @@
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
 	delete gauss;
 	return Ke;
@@ -6766,19 +7175,18 @@
 ElementMatrix* Tria::CreateKMatrixBalancethickness_DG(void){
 
-	/*Constants*/
-	const int  numdof=NDOF1*NUMVERTICES;
-
 	/*Intermediaries*/
-	int        i,j,dim;
-	IssmDouble vx,vy,Jdettria;
+	int        dim;
+	IssmDouble vx,vy,D_scalar,Jdet;
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble B[2][NUMVERTICES];
-	IssmDouble Bprime[2][NUMVERTICES];
-	IssmDouble DL[2][2]={0.0};
-	IssmDouble DL_scalar;
-	GaussTria  *gauss=NULL;
-
-	/*Initialize Element matrix*/
-	ElementMatrix* Ke=new ElementMatrix(nodes,NUMVERTICES,this->parameters,NoneApproximationEnum);
+
+	/*Fetch number of nodes for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    Bprime = xNew<IssmDouble>(2*numnodes);
+	IssmDouble     D[2][2];
 
 	/*Retrieve all inputs and parameters*/
@@ -6789,29 +7197,165 @@
 
 	/*Start looping on the number of gaussian points:*/
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
 
-		GetJacobianDeterminant(&Jdettria, &xyz_list[0][0],gauss);
-		/*WARNING: B and Bprime are inverted compared to usual prognostic!!!!*/
-		GetBPrognostic(&Bprime[0][0], &xyz_list[0][0], gauss);
-		GetBprimePrognostic(&B[0][0], &xyz_list[0][0], gauss);
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		/*WARNING: B and Bprime are inverted compared to usual masstransport!!!!*/
+		GetBMasstransport(Bprime,&xyz_list[0][0],gauss);
+		GetBprimeMasstransport(B,&xyz_list[0][0],gauss);
 
 		vx_input->GetInputValue(&vx,gauss);
 		vy_input->GetInputValue(&vy,gauss);
 
-		DL_scalar=-gauss->weight*Jdettria;
-		DL[0][0]=DL_scalar*vx;
-		DL[1][1]=DL_scalar*vy;
-
-		TripleMultiply( &B[0][0],2,numdof,1,
-					&DL[0][0],2,2,0,
-					&Bprime[0][0],2,numdof,0,
+		D_scalar=-gauss->weight*Jdet;
+		D[0][0]=D_scalar*vx;
+		D[0][1]=0.;
+		D[1][0]=0.;
+		D[1][1]=D_scalar*vy;
+
+		TripleMultiply(B,2,numnodes,1,
+					&D[0][0],2,2,0,
+					Bprime,2,numnodes,0,
 					&Ke->values[0],1);
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(Bprime);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixBalancevelocity{{{*/
+ElementMatrix* Tria::CreateKMatrixBalancevelocity(void){
+
+	/*Intermediaries */
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dhdt_g,mb_g,ms_g,Jdet;
+	IssmDouble h,gamma,thickness;
+	IssmDouble hnx,hny,dhnx[2],dhny[2];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters,NoneApproximationEnum);
+	IssmDouble*    B      = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    HNx    = xNew<IssmDouble>(numnodes);
+	IssmDouble*    HNy    = xNew<IssmDouble>(numnodes);
+	IssmDouble*    H      = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Nx     = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Ny     = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all Inputs and parameters: */
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* H_input =inputs->GetInput(ThicknessEnum); _assert_(H_input);
+	h=sqrt(2.*this->GetArea());
+
+	/*Get vector N for all nodes and build HNx and HNy*/
+	GetInputListOnNodes(Nx,SurfaceSlopeXEnum);
+	GetInputListOnNodes(Ny,SurfaceSlopeYEnum);
+	GetInputListOnNodes(H,ThicknessEnum);
+	for(int i=0;i<numnodes;i++){
+		IssmDouble norm=sqrt(Nx[i]*Nx[i]+Ny[i]*Ny[i]+1.e-10);
+		HNx[i] = -H[i]*Nx[i]/norm;
+		HNy[i] = -H[i]*Ny[i]/norm;
+	}
+
+	/*Start looping on the number of gaussian points:*/
+	GaussTria* gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		H_input->GetInputValue(&thickness,gauss);
+		if(thickness<50.) thickness=50.;
+		TriaRef::GetInputDerivativeValue(&dhnx[0],HNx,&xyz_list[0][0],gauss);
+		TriaRef::GetInputDerivativeValue(&dhny[0],HNy,&xyz_list[0][0],gauss);
+		TriaRef::GetInputValue(&hnx,HNx,gauss);
+		TriaRef::GetInputValue(&hny,HNy,gauss);
+
+		gamma=h/(2.*thickness+1.e-10);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+		GetNodalFunctionsDerivatives(dbasis,&xyz_list[0][0],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]+gamma*(basis[i]*(dhnx[0]+dhny[1]) + dbasis[0*numnodes+i]*hnx + dbasis[1*numnodes+i]*hny))*
+							(basis[j]*(dhnx[0]+dhny[1])  + dbasis[0*numnodes+j]*hnx + dbasis[1*numnodes+j]*hny)
+							);
+			}
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(H);
+	xDelete<IssmDouble>(Nx);
+	xDelete<IssmDouble>(Ny);
+	xDelete<IssmDouble>(HNx);
+	xDelete<IssmDouble>(HNy);
+	xDelete<IssmDouble>(B);
+	delete gauss;
+	return Ke;
+}
+/*}}}*/
+/*FUNCTION Tria::CreateKMatrixSmoothedSlope {{{*/
+ElementMatrix* Tria::CreateKMatrixSmoothedSlope(void){
+
+	/* Intermediaries */
+	IssmDouble D_scalar,Jdet,thickness;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble D[2][2];
+	IssmDouble l=8.;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element matrix and vectors*/
+	ElementMatrix* Ke     = new ElementMatrix(nodes,numnodes,this->parameters);
+	IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* thickness_input=inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
+
+	/* Start looping on the number of gaussian points: */
+	GaussTria* gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		thickness_input->GetInputValue(&thickness,gauss);
+		if(thickness<50.) thickness=50.;
+
+		GetNodalFunctions(basis,gauss);
+		GetNodalFunctionsDerivatives(dbasis,&xyz_list[0][0],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);
 	return Ke;
 }
@@ -6834,40 +7378,39 @@
 ElementVector* Tria::CreatePVectorBalancethickness_CG(void){
 
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
-
 	/*Intermediaries */
-	int        i,j;
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble dhdt_g,basal_melting_g,surface_mass_balance_g,Jdettria;
-	IssmDouble basis[NUMVERTICES];
-	GaussTria* gauss=NULL;
-
-	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+	IssmDouble dhdt_g,mb_g,ms_g,Jdet;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	Input* surface_mass_balance_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(surface_mass_balance_input);
-	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum);          _assert_(basal_melting_input);
-	Input* dhdt_input=inputs->GetInput(BalancethicknessThickeningRateEnum);             _assert_(dhdt_input);
+	Input* ms_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(ms_input);
+	Input* mb_input=inputs->GetInput(BasalforcingsMeltingRateEnum);   _assert_(mb_input);
+	Input* dhdt_input=inputs->GetInput(BalancethicknessThickeningRateEnum); _assert_(dhdt_input);
 
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
 
-		surface_mass_balance_input->GetInputValue(&surface_mass_balance_g,gauss);
-		basal_melting_input->GetInputValue(&basal_melting_g,gauss);
+		ms_input->GetInputValue(&ms_g,gauss);
+		mb_input->GetInputValue(&mb_g,gauss);
 		dhdt_input->GetInputValue(&dhdt_g,gauss);
 
-		GetJacobianDeterminant(&Jdettria, &xyz_list[0][0],gauss);
-		GetNodalFunctions(&basis[0],gauss);
-
-		for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(surface_mass_balance_g-basal_melting_g-dhdt_g)*basis[i];
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(ms_g-mb_g-dhdt_g)*basis[i];
 	}
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
 	delete gauss;
 	return pe;
@@ -6877,57 +7420,246 @@
 ElementVector* Tria::CreatePVectorBalancethickness_DG(void){
 
-	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
-
 	/*Intermediaries */
-	int        i,j;
 	IssmDouble xyz_list[NUMVERTICES][3];
-	IssmDouble basal_melting_g,surface_mass_balance_g,dhdt_g,Jdettria;
-	IssmDouble basis[NUMVERTICES];
-	GaussTria* gauss=NULL;
-
-	/*Initialize Element vector*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICES,this->parameters);
+	IssmDouble mb_g,ms_g,dhdt_g,Jdet;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
 
 	/*Retrieve all inputs and parameters*/
 	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
-	Input* surface_mass_balance_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(surface_mass_balance_input);
-	Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum);          _assert_(basal_melting_input);
-	Input* dhdt_input=inputs->GetInput(BalancethicknessThickeningRateEnum);                                       _assert_(dhdt_input);
+	Input* ms_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(ms_input);
+	Input* mb_input=inputs->GetInput(BasalforcingsMeltingRateEnum);   _assert_(mb_input);
+	Input* dhdt_input=inputs->GetInput(BalancethicknessThickeningRateEnum);_assert_(dhdt_input);
 
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
+	GaussTria* gauss=new GaussTria(2);
 	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
 
-		surface_mass_balance_input->GetInputValue(&surface_mass_balance_g,gauss);
-		basal_melting_input->GetInputValue(&basal_melting_g,gauss);
+		ms_input->GetInputValue(&ms_g,gauss);
+		mb_input->GetInputValue(&mb_g,gauss);
 		dhdt_input->GetInputValue(&dhdt_g,gauss);
 
-		GetJacobianDeterminant(&Jdettria, &xyz_list[0][0],gauss);
-		GetNodalFunctions(&basis[0],gauss);
-
-		for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(surface_mass_balance_g-basal_melting_g-dhdt_g)*basis[i];
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(ms_g-mb_g-dhdt_g)*basis[i];
 	}
 
 	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
 	delete gauss;
 	return pe;
 }
 /*}}}*/
+/*FUNCTION Tria::CreatePVectorBalancevelocity{{{*/
+ElementVector* Tria::CreatePVectorBalancevelocity(void){
+
+	/*Intermediaries */
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dhdt_g,mb_g,ms_g,Jdet;
+	IssmDouble h,gamma,thickness;
+	IssmDouble hnx,hny,dhnx[2],dhny[2];
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    dbasis = xNew<IssmDouble>(numnodes*2);
+	IssmDouble*    HNx    = xNew<IssmDouble>(numnodes);
+	IssmDouble*    HNy    = xNew<IssmDouble>(numnodes);
+	IssmDouble*    H      = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Nx     = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Ny     = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* ms_input=inputs->GetInput(SurfaceforcingsMassBalanceEnum); _assert_(ms_input);
+	Input* mb_input=inputs->GetInput(BasalforcingsMeltingRateEnum);   _assert_(mb_input);
+	Input* dhdt_input=inputs->GetInput(BalancethicknessThickeningRateEnum); _assert_(dhdt_input);
+	Input* H_input=inputs->GetInput(ThicknessEnum); _assert_(H_input);
+	h=sqrt(2.*this->GetArea());
+
+	/*Get vector N for all nodes*/
+	GetInputListOnNodes(Nx,SurfaceSlopeXEnum);
+	GetInputListOnNodes(Ny,SurfaceSlopeYEnum);
+	GetInputListOnNodes(H,ThicknessEnum);
+	for(int i=0;i<numnodes;i++){
+		IssmDouble norm=sqrt(Nx[i]*Nx[i]+Ny[i]*Ny[i]+1.e-10);
+		Nx[i] = -H[i]*Nx[i]/norm;
+		Ny[i] = -H[i]*Ny[i]/norm;
+	}
+
+	/* Start  looping on the number of gaussian points: */
+	GaussTria* gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		ms_input->GetInputValue(&ms_g,gauss);
+		mb_input->GetInputValue(&mb_g,gauss);
+		dhdt_input->GetInputValue(&dhdt_g,gauss);
+		H_input->GetInputValue(&thickness,gauss);
+		if(thickness<50.) thickness=50.;
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+		GetNodalFunctionsDerivatives(dbasis,&xyz_list[0][0],gauss);
+
+		TriaRef::GetInputDerivativeValue(&dhnx[0],HNx,&xyz_list[0][0],gauss);
+		TriaRef::GetInputDerivativeValue(&dhny[0],HNy,&xyz_list[0][0],gauss);
+		TriaRef::GetInputValue(&hnx,HNx,gauss);
+		TriaRef::GetInputValue(&hny,HNy,gauss);
+
+		gamma=h/(2.*thickness+1.e-10);
+
+		for(int i=0;i<numnodes;i++){
+			pe->values[i]+=Jdet*gauss->weight*(ms_g-mb_g-dhdt_g)*(
+						basis[i] + gamma*(basis[i]*(dhnx[0]+dhny[1])+hnx*dbasis[0*numnodes+i] + hny*dbasis[1*numnodes+i])
+						);
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	xDelete<IssmDouble>(dbasis);
+	xDelete<IssmDouble>(H);
+	xDelete<IssmDouble>(Nx);
+	xDelete<IssmDouble>(Ny);
+	xDelete<IssmDouble>(HNx);
+	xDelete<IssmDouble>(HNy);
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorSmoothedSlopeX{{{*/
+ElementVector* Tria::CreatePVectorSmoothedSlopeX(void){
+
+	/*Intermediaries */
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble Jdet;
+	IssmDouble thickness,slope[2];
+	IssmDouble taud_x,norms,normv,vx,vy;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Vx     = xNew<IssmDouble>(numnodes);
+	IssmDouble*    Vy     = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* H_input       = inputs->GetInput(ThicknessEnum); _assert_(H_input);
+	Input* surface_input = inputs->GetInput(SurfaceEnum);   _assert_(surface_input);
+	Input* vx_input      = inputs->GetInput(VxEnum);
+	Input* vy_input      = inputs->GetInput(VyEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	GaussTria* gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		H_input->GetInputValue(&thickness,gauss);
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],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 = matpar->GetRhoIce()*matpar->GetG()*thickness*slope[0];
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*taud_x*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}
+/*}}}*/
+/*FUNCTION Tria::CreatePVectorSmoothedSlopeY{{{*/
+ElementVector* Tria::CreatePVectorSmoothedSlopeY(void){
+
+	/*Intermediaries */
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble Jdet;
+	IssmDouble thickness,slope[2];
+	IssmDouble taud_y,norms,normv,vx,vy;
+
+	/*Fetch number of nodes and dof for this finite element*/
+	int numnodes = this->NumberofNodes();
+
+	/*Initialize Element vector and other vectors*/
+	ElementVector* pe    = new ElementVector(nodes,numnodes,this->parameters);
+	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
+
+	/*Retrieve all inputs and parameters*/
+	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
+	Input* H_input       = inputs->GetInput(ThicknessEnum); _assert_(H_input);
+	Input* surface_input = inputs->GetInput(SurfaceEnum);   _assert_(surface_input);
+	Input* vx_input      = inputs->GetInput(VxEnum);
+	Input* vy_input      = inputs->GetInput(VyEnum);
+
+	/* Start  looping on the number of gaussian points: */
+	GaussTria* gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
+
+		gauss->GaussPoint(ig);
+
+		H_input->GetInputValue(&thickness,gauss);
+		surface_input->GetInputDerivativeValue(&slope[0],&xyz_list[0][0],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 = matpar->GetRhoIce()*matpar->GetG()*thickness*slope[1];
+
+		GetJacobianDeterminant(&Jdet, &xyz_list[0][0],gauss);
+		GetNodalFunctions(basis,gauss);
+
+		for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*taud_y*basis[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(basis);
+	delete gauss;
+	return pe;
+}
+/*}}}*/
 #endif
 
 #ifdef _HAVE_GROUNDINGLINE_
 /*FUNCTION Tria::MigrateGroundingLine{{{*/
-void  Tria::MigrateGroundingLine(IssmDouble* old_floating_ice,IssmDouble* sheet_ungrounding){
-
-	int     i,migration_style;
-	bool    floatingelement = false;
-	bool    groundedelement = false;
-	IssmDouble  bed_hydro,yts,gl_melting_rate;
-	IssmDouble  rho_water,rho_ice,density;
-	IssmDouble  melting[NUMVERTICES],phi[NUMVERTICES];;
-	IssmDouble  h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],ba[NUMVERTICES];
+void  Tria::MigrateGroundingLine(IssmDouble* phi_ungrounding){
+
+	int        i,migration_style;
+	bool       oldfloating;
+	bool       floatingelement = false;
+	bool       groundedelement = false;
+	IssmDouble bed_hydro,yts,gl_melting_rate;
+	IssmDouble rho_water,rho_ice,density;
+	IssmDouble melting[NUMVERTICES],phi[NUMVERTICES];;
+	IssmDouble h[NUMVERTICES],s[NUMVERTICES],b[NUMVERTICES],r[NUMVERTICES];
+	bool       grounded[NUMVERTICES],floating[NUMVERTICES];
 
 	/*Recover info at the vertices: */
@@ -6938,38 +7670,39 @@
 	GetInputListOnVertices(&s[0],SurfaceEnum);
 	GetInputListOnVertices(&b[0],BedEnum);
-	GetInputListOnVertices(&ba[0],BathymetryEnum);
-	if(migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum) GetInputListOnVertices(&phi[0],GLlevelsetEnum);
-	rho_water=matpar->GetRhoWater();
-	rho_ice=matpar->GetRhoIce();
-	density=rho_ice/rho_water;
+	GetInputListOnVertices(&r[0],BathymetryEnum);
+	GetInputListOnVertices(&phi[0],MaskGroundediceLevelsetEnum);
+	rho_water   = matpar->GetRhoWater();
+	rho_ice     = matpar->GetRhoIce();
+	density     = rho_ice/rho_water;
+	oldfloating = this->IsFloating(); //figure out if element is floating before we start to change everything
 
 	/*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(reCast<bool>(old_floating_ice[nodes[i]->Sid()])){
-			if(b[i]<=ba[i]){ 
-				b[i]=ba[i];
-				s[i]=b[i]+h[i];
-				nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,false));
-				nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,true));
+		if(phi[i]<=0.){
+			if(b[i]<=r[i]){ 
+				b[i]        = r[i];
+				s[i]        = b[i]+h[i];
+				floating[i] = false;
+				grounded[i] = true;
 			}
 		}
 		/*Ice sheet: if hydrostatic bed above bathymetry, ice sheet starts to unground, elso do nothing */
 		/*Change only if AgressiveMigration or if the ice sheet is in contact with the ocean*/
-		else{
+		else{ // phi>0
 			bed_hydro=-density*h[i];
-			if (bed_hydro>ba[i]){
+			if (bed_hydro>r[i]){
 				/*Unground only if the element is connected to the ice shelf*/
 				if(migration_style==AgressiveMigrationEnum || migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
-					s[i]=(1-density)*h[i];
-					b[i]=-density*h[i];
-					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,true));
-					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,false));
+					s[i]        = (1-density)*h[i];
+					b[i]        = -density*h[i];
+					floating[i] = true;
+					grounded[i] = false;
 				}
-				else if(migration_style==SoftMigrationEnum && reCast<bool>(sheet_ungrounding[nodes[i]->Sid()])){
-					s[i]=(1-density)*h[i];
-					b[i]=-density*h[i];
-					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,true));
-					nodes[i]->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,false));
+				else if(migration_style==SoftMigrationEnum && phi_ungrounding[vertices[i]->Pid()]<0.){
+					s[i]        = (1-density)*h[i];
+					b[i]        = -density*h[i];
+					floating[i] = true;
+					grounded[i] = false;
 				}
 				else{
@@ -6980,8 +7713,20 @@
 	}
 
+	/*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));
+
 	/*SubelementMigrationEnum: if one grounded, all grounded*/
 	if(migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
 		for(i=0;i<NUMVERTICES;i++){
-			if(nodes[i]->IsGrounded()){
+			if(phi[i]>0.){
 				groundedelement=true;
 				break;
@@ -6993,5 +7738,5 @@
 		/*Otherwise: if one floating, all floating*/
 		for(i=0;i<NUMVERTICES;i++){
-			if(nodes[i]->IsFloating()){
+			if(phi[i]<=0.){
 				floatingelement=true;
 				break;
@@ -7001,5 +7746,5 @@
 
    /*Add basal melting rate if element just ungrounded*/
-	if(!this->IsFloating() && floatingelement==true){
+	if(!oldfloating && floatingelement==true){
 		for(i=0;i<NUMVERTICES;i++)melting[i]=gl_melting_rate/yts;
 		this->inputs->AddInput(new TriaInput(BasalforcingsMeltingRateEnum,&melting[0],P1Enum));
@@ -7007,13 +7752,7 @@
 
 	/*Update inputs*/
-   this->inputs->AddInput(new BoolInput(MaskElementonfloatingiceEnum,floatingelement));
 	this->inputs->AddInput(new TriaInput(SurfaceEnum,&s[0],P1Enum));
 	this->inputs->AddInput(new TriaInput(BedEnum,&b[0],P1Enum));
 
-	/*Recalculate phi*/
-	if(migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum){
-		for(i=0;i<NUMVERTICES;i++) phi[i]=h[i]+ba[i]/density;
-		this->inputs->AddInput(new TriaInput(GLlevelsetEnum,&phi[0],P1Enum));
-	}
 }
 /*}}}*/
@@ -7021,6 +7760,5 @@
 void  Tria::PotentialUngrounding(Vector<IssmDouble>* potential_ungrounding){
 
-	int     i;
-	IssmDouble  h[NUMVERTICES],ba[NUMVERTICES];
+	IssmDouble  h[NUMVERTICES],r[NUMVERTICES],gl[NUMVERTICES];
 	IssmDouble  bed_hydro;
 	IssmDouble  rho_water,rho_ice,density;
@@ -7031,14 +7769,15 @@
 	density=rho_ice/rho_water;
 	GetInputListOnVertices(&h[0],ThicknessEnum);
-	GetInputListOnVertices(&ba[0],BathymetryEnum);
+	GetInputListOnVertices(&r[0],BathymetryEnum);
+	GetInputListOnVertices(&gl[0],MaskGroundediceLevelsetEnum);
 
 	/*go through vertices, and figure out which ones are grounded and want to unground: */
-	for(i=0;i<NUMVERTICES;i++){
+	for(int i=0;i<NUMVERTICES;i++){
 		/*Find if grounded vertices want to start floating*/
-		if (!nodes[i]->IsFloating()){
+		if (gl[i]>0.){
 			bed_hydro=-density*h[i];
-			if (bed_hydro>ba[i]){
+			if(bed_hydro>r[i]){
 				/*Vertex that could potentially unground, flag it*/
-				potential_ungrounding->SetValue(nodes[i]->Sid(),1,INS_VAL);
+				potential_ungrounding->SetValue(vertices[i]->Pid(),1,INS_VAL);
 			}
 		}
@@ -7054,9 +7793,9 @@
 	/*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[nodes[i]->Sid()])){
-			vec_nodes_on_iceshelf->SetValue(nodes[i]->Sid(),1,INS_VAL);
+		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[nodes[i]->Sid()]==0){
+			if(nodes_on_iceshelf[vertices[i]->Pid()]>=0.){
 				nflipped++;
 			}
Index: /issm/trunk/src/c/classes/Elements/Tria.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/Tria.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Elements/Tria.h	(revision 16137)
@@ -37,5 +37,4 @@
 		Material    *material;                    // 1 material ice
 		Matpar      *matpar;                      // 1 material parameter
-		int          horizontalneighborsids[3];
 
 		Parameters  *parameters;                  //pointer to solution parameters
@@ -58,10 +57,6 @@
 		void  InputUpdateFromSolution(IssmDouble* solutiong);
 		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVector(int* vector, int name, int type);
-		void  InputUpdateFromVector(bool* vector, int name, int type);
 		#ifdef _HAVE_DAKOTA_
 		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
 		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nows, int ncols, int name, int type);
 		#endif
@@ -72,66 +67,65 @@
 		/*}}}*/
 		/*Element virtual functions definitions: {{{*/
-		void   ComputeBasalStress(Vector<IssmDouble>* sigma_b);
-		void   ComputeStrainRate(Vector<IssmDouble>* eps);
-		void   ComputeStressTensor();
-		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   SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
-		void   CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
-		void   CreateDVector(Vector<IssmDouble>* df);
-		void   CreatePVector(Vector<IssmDouble>* pf);
-		void   CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
-		void   Delta18oParameterization(void);
-		int    GetNodeIndex(Node* node);
-		int    GetNumberOfNodes(void);
-		void   GetNodesSidList(int* sidlist);
-		int    Sid();
-		bool   IsOnBed();
-		bool   IsFloating();
-		bool   IsNodeOnShelf(); 
-		bool   IsNodeOnShelfFromFlags(IssmDouble* flags);
-		bool   IsOnWater();
-		void   GetSolutionFromInputs(Vector<IssmDouble>* solution);
-		void   GetVectorFromInputs(Vector<IssmDouble>* vector, int name_enum);
-		void   GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int enum_in,int interp);
-		void   InputArtificialNoise(int enum_type,IssmDouble min, IssmDouble max);
-		void   InputCreate(IssmDouble scalar,int name,int code);
-		void   InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
-		void   InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum=MeshElementsEnum);
-		void   InputDuplicate(int original_enum,int new_enum);
-		void   InputScale(int enum_type,IssmDouble scale_factor);
-		void   InputToResult(int enum_type,int step,IssmDouble time);
-		void   DeleteResults(void);
-		void   MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
-		int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum);
-		void   PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm);
-		void   RequestedOutput(int output_enum,int step,IssmDouble time);
-		void   ListResultsInfo(int** results_enums,int** results_size,IssmDouble** results_times,int** results_steps,int* num_results);
-		void   PatchFill(int* pcount, Patch* patch);
-		void   PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes);
-		void   ResetCoordinateSystem(void){_error_("not implemented yet");};
-		void	 SmbGradients();
-		IssmDouble SurfaceArea(void);
-		void   Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type);
-		IssmDouble TimeAdapt();
-		int*   GetHorizontalNeighboorSids(void);
+		void        ComputeBasalStress(Vector<IssmDouble>* sigma_b);
+		void        ComputeStrainRate(Vector<IssmDouble>* eps);
+		void        ComputeStressTensor();
+		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        SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum);
+		void        CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
+		void        CreateDVector(Vector<IssmDouble>* df);
+		void        CreatePVector(Vector<IssmDouble>* pf);
+		void        CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
+		void        Delta18oParameterization(void);
+		int         GetNodeIndex(Node* node);
+		void        GetNodesSidList(int* sidlist);
+		void        GetNodesLidList(int* lidlist);
+		int         GetNumberOfNodes(void);
+		int         Sid();
+		bool        IsOnBed();
+		bool        IsFloating();
+		bool        IsNodeOnShelfFromFlags(IssmDouble* flags);
+		bool        NoIceInElement();
+		void        GetSolutionFromInputs(Vector<IssmDouble>* solution);
+		void        GetVectorFromInputs(Vector<IssmDouble>* vector, int name_enum);
+		void        GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int enum_in,int interp);
+		void        InputArtificialNoise(int enum_type,IssmDouble min, IssmDouble max);
+		void        InputCreate(IssmDouble scalar,int name,int code);
+		void        InputCreate(IssmDouble* vector, int index,IoModel* iomodel,int M,int N,int vector_type,int vector_enum,int code);
+		void        InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum=MeshElementsEnum);
+		void        InputDuplicate(int original_enum,int new_enum);
+		void        InputScale(int enum_type,IssmDouble scale_factor);
+		void        InputToResult(int enum_type,int step,IssmDouble time);
+		void        DeleteResults(void);
+		void        MaterialUpdateFromTemperature(void){_error_("not implemented yet");};
+		int         NodalValue(IssmDouble* pvalue, int index, int natureofdataenum);
+		void        PositiveDegreeDay(IssmDouble* pdds,IssmDouble* pds,IssmDouble signorm);
+		void        RequestedOutput(int output_enum,int step,IssmDouble time);
+		void        ListResultsInfo(int** results_enums,int** results_size,IssmDouble** results_times,int** results_steps,int* num_results);
+		void        PatchFill(int* pcount, Patch* patch);
+		void        PatchSize(int* pnumrows, int* pnumvertices,int* pnumnodes);
+		void        ResetCoordinateSystem(void){_error_("not implemented yet");};
+		void	      SmbGradients();
+		IssmDouble  SurfaceArea(void);
+		void        Update(int index, IoModel* iomodel,int analysis_counter,int analysis_type,int finitelement);
+		IssmDouble  TimeAdapt();
 
 		#ifdef _HAVE_RESPONSES_
-		void   AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
+		void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
 		IssmDouble IceVolume(void);
 		IssmDouble TotalSmb(void);
-		void   MinVel(IssmDouble* pminvel);
-		void   MinVx(IssmDouble* pminvx);
-		void   MinVy(IssmDouble* pminvy);
-		void   MinVz(IssmDouble* pminvz);
+		void       MinVel(IssmDouble* pminvel);
+		void       MinVx(IssmDouble* pminvx);
+		void       MinVy(IssmDouble* pminvy);
+		void       MinVz(IssmDouble* pminvz);
 		IssmDouble MassFlux(IssmDouble* segment);
-		void   MaxAbsVx(IssmDouble* pmaxabsvx);
-		void   MaxAbsVy(IssmDouble* pmaxabsvy);
-		void   MaxAbsVz(IssmDouble* pmaxabsvz);
-		void   ElementResponse(IssmDouble* presponse,int response_enum);
-		void   MaxVel(IssmDouble* pmaxvel);
-		void   MaxVx(IssmDouble* pmaxvx);
-		void   MaxVy(IssmDouble* pmaxvy);
-		void   MaxVz(IssmDouble* pmaxvz);
+		void       MaxAbsVx(IssmDouble* pmaxabsvx);
+		void       MaxAbsVy(IssmDouble* pmaxabsvy);
+		void       MaxAbsVz(IssmDouble* pmaxabsvz);
+		void       ElementResponse(IssmDouble* presponse,int response_enum);
+		void       MaxVel(IssmDouble* pmaxvel);
+		void       MaxVx(IssmDouble* pmaxvx);
+		void       MaxVy(IssmDouble* pmaxvy);
+		void       MaxVz(IssmDouble* pmaxvz);
 		#endif
 
@@ -142,22 +136,22 @@
 		#ifdef _HAVE_CONTROL_
 		IssmDouble DragCoefficientAbsGradient(int weight_index);
-		void   GradientIndexing(int* indexing,int control_index);
-		void   Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index);
-		void   GradjBGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
-		void   GradjZGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
-		void   GradjBMacAyeal(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjZMacAyeal(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjDragMacAyeal(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjDragStokes(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjDragGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
-		void   GradjDhDtBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjVxBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjVyBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
-		void   GradjThicknessBalancethicknessSoft(Vector<IssmDouble>* gradient,int control_index);
-		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   ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index);
-		void   ControlInputScaleGradient(int enum_type,IssmDouble scale);
-		void   ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
+		void       GradientIndexing(int* indexing,int control_index);
+		void       Gradj(Vector<IssmDouble>* gradient,int control_type,int control_index);
+		void       GradjBGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
+		void       GradjZGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
+		void       GradjBSSA(Vector<IssmDouble>* gradient,int control_index);
+		void       GradjZSSA(Vector<IssmDouble>* gradient,int control_index);
+		void       GradjDragSSA(Vector<IssmDouble>* gradient,int control_index);
+		void       GradjDragFS(Vector<IssmDouble>* gradient,int control_index);
+		void       GradjDragGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index);
+		void       GradjDhDtBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
+		void       GradjVxBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
+		void       GradjVyBalancedthickness(Vector<IssmDouble>* gradient,int control_index);
+		void       GradjThicknessBalancethicknessSoft(Vector<IssmDouble>* gradient,int control_index);
+		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       ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index);
+		void       ControlInputScaleGradient(int enum_type,IssmDouble scale);
+		void       ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index);
 		IssmDouble RheologyBbarAbsGradient(int weight_index);
 		IssmDouble ThicknessAbsMisfit(     int weight_index);
@@ -171,9 +165,10 @@
 		IssmDouble SurfaceLogVxVyMisfit(   int weight_index);
 		IssmDouble SurfaceAverageVelMisfit(int weight_index);
-		void   InputControlUpdate(IssmDouble scalar,bool save_parameter);
-		#endif
+		void       InputControlUpdate(IssmDouble scalar,bool save_parameter);
+		#endif
+
 		#ifdef _HAVE_GROUNDINGLINE_
 		void   PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding);
-		void   MigrateGroundingLine(IssmDouble* oldfloating,IssmDouble* sheet_ungrounding);
+		void   MigrateGroundingLine(IssmDouble* sheet_ungrounding);
 		int    UpdatePotentialUngrounding(IssmDouble* vertices_potentially_ungrounding,Vector<IssmDouble>* vec_nodes_on_iceshelf,IssmDouble* nodes_on_iceshelf);
 		#endif
@@ -181,20 +176,32 @@
 		/*}}}*/
 		/*Tria specific routines:{{{*/
+		ElementMatrix* CreateKMatrix(void);
 		ElementMatrix* CreateKMatrixBalancethickness(void);
 		ElementMatrix* CreateKMatrixBalancethickness_DG(void);
 		ElementMatrix* CreateKMatrixBalancethickness_CG(void);
+		ElementMatrix* CreateKMatrixBalancevelocity(void);
+		ElementMatrix* CreateKMatrixSmoothedSlope(void);
 		ElementMatrix* CreateKMatrixMelting(void);
-		ElementMatrix* CreateKMatrixPrognostic(void);
-		ElementMatrix* CreateKMatrixPrognostic_CG(void);
-		ElementMatrix* CreateKMatrixPrognostic_DG(void);
+		ElementMatrix* CreateKMatrixMasstransport(void);
+		ElementMatrix* CreateKMatrixMasstransport_CG(void);
+		ElementMatrix* CreateKMatrixMasstransport_DG(void);
+		ElementMatrix* CreateKMatrixFreeSurfaceTop(void);
+		ElementMatrix* CreateKMatrixFreeSurfaceBase(void);
 		ElementMatrix* CreateMassMatrix(void);
+		ElementVector* CreatePVector(void);
 		ElementVector* CreatePVectorBalancethickness(void);
 		ElementVector* CreatePVectorBalancethickness_DG(void);
 		ElementVector* CreatePVectorBalancethickness_CG(void);
-		ElementVector* CreatePVectorPrognostic(void);
-		ElementVector* CreatePVectorPrognostic_CG(void);
-		ElementVector* CreatePVectorPrognostic_DG(void);
+		ElementVector* CreatePVectorBalancevelocity(void);
+		ElementVector* CreatePVectorSmoothedSlopeX(void);
+		ElementVector* CreatePVectorSmoothedSlopeY(void);
+		ElementVector* CreatePVectorMasstransport(void);
+		ElementVector* CreatePVectorMasstransport_CG(void);
+		ElementVector* CreatePVectorMasstransport_DG(void);
+		ElementVector* CreatePVectorFreeSurfaceTop(void);
+		ElementVector* CreatePVectorFreeSurfaceBase(void);
 		ElementVector* CreatePVectorSlope(void);
 		IssmDouble     GetArea(void);
+		void           GetAreaCoordinates(IssmDouble *area_coordinates,IssmDouble xyz_zero[3][3],IssmDouble xyz_list[3][3],int numpoints);
 		int            GetElementType(void);
 		void	         GetDofList(int** pdoflist,int approximation_enum,int setenum);
@@ -202,6 +209,8 @@
 		void           GetVertexSidList(int* sidlist);
 		void           GetConnectivityList(int* connectivity);
+		void           GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating);
 		IssmDouble     GetGroundedPortion(IssmDouble* xyz_list);
-		void           GetGroundedPart(int* point1,IssmDouble* fraction1, IssmDouble* fraction2,bool* mainlyfloating);
+		void           GetSegmentNormal(IssmDouble* normal,IssmDouble xyz_list[2][3]);
+		void           GetZeroLevelsetCoordinates(IssmDouble* xyz_zero,IssmDouble xyz_list[3][3],int levelsetenum);
 		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype);
 		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue);
@@ -212,32 +221,37 @@
 		void           GetStrainRate2d(IssmDouble* epsilon,IssmDouble* xyz_list, GaussTria* gauss, Input* vx_input, Input* vy_input);
 		void	         InputUpdateFromSolutionOneDof(IssmDouble* solution,int enum_type);
-		void	         InputUpdateFromSolutionPrognostic(IssmDouble* solution);
+		void	         InputUpdateFromSolutionMasstransport(IssmDouble* solution);
 		bool	         IsInput(int name);
 		void	         SetClone(int* minranks);
 		void	         SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]);
-		void             UpdateConstraints(void);
-
-		#ifdef _HAVE_DIAGNOSTIC_
-		ElementMatrix* CreateKMatrixDiagnosticMacAyeal(void);
-		ElementMatrix* CreateKMatrixDiagnosticMacAyealViscous(void);
-		ElementMatrix* CreateKMatrixDiagnosticMacAyealFriction(void);
-		ElementMatrix* CreateKMatrixDiagnosticHutter(void);
-		ElementVector* CreatePVectorDiagnosticMacAyeal(void);
-		ElementVector* CreatePVectorDiagnosticHutter(void);
-		ElementMatrix* CreateJacobianDiagnosticMacayeal(void);
-		void	  GetSolutionFromInputsDiagnosticHoriz(Vector<IssmDouble>* solution);
-		void	  GetSolutionFromInputsDiagnosticHutter(Vector<IssmDouble>* solution);
-		void	  InputUpdateFromSolutionDiagnosticHoriz( IssmDouble* solution);
-		void	  InputUpdateFromSolutionDiagnosticHutter( IssmDouble* solution);
+
+		#ifdef _HAVE_STRESSBALANCE_
+		ElementMatrix* CreateKMatrixStressbalanceSSA(void);
+		ElementMatrix* CreateKMatrixStressbalanceSSAViscous(void);
+		ElementMatrix* CreateKMatrixStressbalanceSSAFriction(void);
+		ElementMatrix* CreateKMatrixStressbalanceSIA(void);
+		ElementVector* CreatePVectorStressbalanceSSA(void);
+		ElementVector* CreatePVectorStressbalanceSSADrivingStress(void);
+		ElementVector* CreatePVectorStressbalanceSSAFront(void);
+		ElementVector* CreatePVectorStressbalanceSIA(void);
+		ElementMatrix* CreateJacobianStressbalanceSSA(void);
+		void	  GetSolutionFromInputsStressbalanceHoriz(Vector<IssmDouble>* solution);
+		void	  GetSolutionFromInputsStressbalanceSIA(Vector<IssmDouble>* solution);
+		void	  InputUpdateFromSolutionStressbalanceHoriz( IssmDouble* solution);
+		void	  InputUpdateFromSolutionStressbalanceSIA( IssmDouble* solution);
 		#endif
 
 		#ifdef _HAVE_CONTROL_
 		ElementMatrix* CreateKMatrixAdjointBalancethickness(void);
-		ElementMatrix* CreateKMatrixAdjointMacAyeal(void);
+		ElementMatrix* CreateKMatrixAdjointSSA(void);
 		ElementVector* CreatePVectorAdjointHoriz(void);
-		ElementVector* CreatePVectorAdjointStokes(void);
 		ElementVector* CreatePVectorAdjointBalancethickness(void);
-		void	  InputUpdateFromSolutionAdjointBalancethickness( IssmDouble* solution);
-		void	  InputUpdateFromSolutionAdjointHoriz( IssmDouble* solution);
+		void	         InputUpdateFromSolutionAdjointHoriz( IssmDouble* solution);
+		#endif
+
+		#ifdef _HAVE_THERMAL_
+		void UpdateThermalBasalConstraints(void){_error_("not implemented yet");};
+		void ComputeBasalMeltingrate(void){_error_("not implemented yet");};
+	        void DrainWaterfraction(void){_error_("not implemented yet");};
 		#endif
 
Index: /issm/trunk/src/c/classes/Elements/TriaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/Elements/TriaRef.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Elements/TriaRef.cpp	(revision 16137)
@@ -16,6 +16,7 @@
 
 /*Element macros*/
-#define NUMNODESP1 3
-#define NUMNODESP2 6
+#define NUMNODESP1  3
+#define NUMNODESP1b 4
+#define NUMNODESP2  6
 
 /*Object constructors and destructor*/
@@ -43,5 +44,5 @@
 void TriaRef::SetElementType(int type,int type_counter){
 
-	_assert_(type==P1Enum || type==P1DGEnum);
+	_assert_(type==P1Enum || type==P1DGEnum || type==P1bubbleEnum || type==P1bubblecondensedEnum || type==P2Enum);
 
 	/*initialize element type*/
@@ -72,6 +73,6 @@
 	/*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*0+i] = dbasis[0*numnodes+i];
+		B[numnodes*1+i] = dbasis[1*numnodes+i];
 	}
 
@@ -80,6 +81,6 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::GetBMacAyeal {{{*/
-void TriaRef::GetBMacAyeal(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss){
+/*FUNCTION TriaRef::GetBSSA {{{*/
+void TriaRef::GetBSSA(IssmDouble* B, IssmDouble* xyz_list, GaussTria* 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
@@ -102,10 +103,10 @@
 	/*Build B: */
 	for(int i=0;i<numnodes;i++){
-		B[NDOF2*numnodes*0+NDOF2*i+0]=dbasis[0*numnodes+i];
-		B[NDOF2*numnodes*0+NDOF2*i+1]=0.;
-		B[NDOF2*numnodes*1+NDOF2*i+0]=0.;
-		B[NDOF2*numnodes*1+NDOF2*i+1]=dbasis[1*numnodes+i];
-		B[NDOF2*numnodes*2+NDOF2*i+0]=.5*dbasis[1*numnodes+i]; 
-		B[NDOF2*numnodes*2+NDOF2*i+1]=.5*dbasis[0*numnodes+i]; 
+		B[NDOF2*numnodes*0+NDOF2*i+0] = dbasis[0*numnodes+i];
+		B[NDOF2*numnodes*0+NDOF2*i+1] = 0.;
+		B[NDOF2*numnodes*1+NDOF2*i+0] = 0.;
+		B[NDOF2*numnodes*1+NDOF2*i+1] = dbasis[1*numnodes+i];
+		B[NDOF2*numnodes*2+NDOF2*i+0] = .5*dbasis[1*numnodes+i];
+		B[NDOF2*numnodes*2+NDOF2*i+1] = .5*dbasis[0*numnodes+i];
 	}
 
@@ -114,6 +115,6 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::GetBMacAyealStokes {{{*/
-void TriaRef::GetBMacAyealStokes(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss){
+/*FUNCTION TriaRef::GetBSSAFS {{{*/
+void TriaRef::GetBSSAFS(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss){
 
 	/*Compute B  matrix. B=[B1 B2 B3] where Bi is of size 3*NDOF2. 
@@ -136,11 +137,11 @@
 
 	/*Build B': */
-	for (int i=0;i<numnodes;i++){
-		B[NDOF2*numnodes*0+NDOF2*i+0]=dbasis[0*numnodes+i]; 
-		B[NDOF2*numnodes*0+NDOF2*i+1]=0.; 
-		B[NDOF2*numnodes*1+NDOF2*i+0]=0.; 
-		B[NDOF2*numnodes*1+NDOF2*i+1]=dbasis[1*numnodes+i]; 
-		B[NDOF2*numnodes*2+NDOF2*i+0]=0.5*dbasis[1*numnodes+i]; 
-		B[NDOF2*numnodes*2+NDOF2*i+1]=0.5*dbasis[0*numnodes+i]; 
+	for(int i=0;i<numnodes;i++){
+		B[NDOF2*numnodes*0+NDOF2*i+0] = dbasis[0*numnodes+i];
+		B[NDOF2*numnodes*0+NDOF2*i+1] = 0.;
+		B[NDOF2*numnodes*1+NDOF2*i+0] = 0.;
+		B[NDOF2*numnodes*1+NDOF2*i+1] = dbasis[1*numnodes+i];
+		B[NDOF2*numnodes*2+NDOF2*i+0] = 0.5*dbasis[1*numnodes+i];
+		B[NDOF2*numnodes*2+NDOF2*i+1] = 0.5*dbasis[0*numnodes+i];
 	}
 
@@ -201,6 +202,6 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::GetBPrognostic{{{*/
-void TriaRef::GetBPrognostic(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss){
+/*FUNCTION TriaRef::GetBMasstransport{{{*/
+void TriaRef::GetBMasstransport(IssmDouble* B, IssmDouble* xyz_list, GaussTria* 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
@@ -221,7 +222,7 @@
 
 	/*Build B: */
-	for (int i=0;i<numnodes;i++){
-		B[numnodes*0+i]=basis[i];
-		B[numnodes*1+i]=basis[i];
+	for(int i=0;i<numnodes;i++){
+		B[numnodes*0+i] = basis[i];
+		B[numnodes*1+i] = basis[i];
 	}
 
@@ -230,6 +231,6 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::GetBprimeMacAyeal {{{*/
-void TriaRef::GetBprimeMacAyeal(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss){
+/*FUNCTION TriaRef::GetBprimeSSA {{{*/
+void TriaRef::GetBprimeSSA(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss){
 
 	/*Compute B'  matrix. B'=[B1' B2' B3'] where Bi' is of size 3*NDOF2. 
@@ -252,5 +253,5 @@
 
 	/*Build B': */
-	for (int i=0;i<numnodes;i++){
+	for(int i=0;i<numnodes;i++){
 		Bprime[NDOF2*numnodes*0+NDOF2*i+0] = 2.*dbasis[0*numnodes+i];
 		Bprime[NDOF2*numnodes*0+NDOF2*i+1] =    dbasis[1*numnodes+i];
@@ -265,6 +266,6 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::GetBprimeMacAyealStokes {{{*/
-void TriaRef::GetBprimeMacAyealStokes(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss){
+/*FUNCTION TriaRef::GetBprimeSSAFS {{{*/
+void TriaRef::GetBprimeSSAFS(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* 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
@@ -288,12 +289,12 @@
 	/*Build Bprime: */
 	for(int i=0;i<numnodes;i++){
-		Bprime[NDOF2*numnodes*0+NDOF2*i+0]=dbasis[0*numnodes+i]; 
-		Bprime[NDOF2*numnodes*0+NDOF2*i+1]=0.; 
-		Bprime[NDOF2*numnodes*1+NDOF2*i+0]=0.; 
-		Bprime[NDOF2*numnodes*1+NDOF2*i+1]=dbasis[1*numnodes+i]; 
-		Bprime[NDOF2*numnodes*2+NDOF2*i+0]=dbasis[1*numnodes+i]; 
-		Bprime[NDOF2*numnodes*2+NDOF2*i+1]=dbasis[0*numnodes+i]; 
-		Bprime[NDOF2*numnodes*3+NDOF2*i+0]=dbasis[0*numnodes+i]; 
-		Bprime[NDOF2*numnodes*3+NDOF2*i+1]=dbasis[1*numnodes+i]; 
+		Bprime[NDOF2*numnodes*0+NDOF2*i+0] = dbasis[0*numnodes+i];
+		Bprime[NDOF2*numnodes*0+NDOF2*i+1] = 0.;
+		Bprime[NDOF2*numnodes*1+NDOF2*i+0] = 0.;
+		Bprime[NDOF2*numnodes*1+NDOF2*i+1] = dbasis[1*numnodes+i];
+		Bprime[NDOF2*numnodes*2+NDOF2*i+0] = dbasis[1*numnodes+i];
+		Bprime[NDOF2*numnodes*2+NDOF2*i+1] = dbasis[0*numnodes+i];
+		Bprime[NDOF2*numnodes*3+NDOF2*i+0] = dbasis[0*numnodes+i];
+		Bprime[NDOF2*numnodes*3+NDOF2*i+1] = dbasis[1*numnodes+i];
 	}
 
@@ -302,6 +303,6 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::GetBprimePrognostic{{{*/
-void TriaRef::GetBprimePrognostic(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss){
+/*FUNCTION TriaRef::GetBprimeMasstransport{{{*/
+void TriaRef::GetBprimeMasstransport(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* 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
@@ -323,6 +324,6 @@
 	/*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]; 
+		Bprime[numnodes*0+i] = dbasis[0*numnodes+i];
+		Bprime[numnodes*1+i] = dbasis[1*numnodes+i];
 	}
 
@@ -331,6 +332,6 @@
 }
 /*}}}*/
-/*FUNCTION TriaRef::GetBMacAyealFriction{{{*/
-void TriaRef::GetBMacAyealFriction(IssmDouble* B, IssmDouble* xyz_list,GaussTria* gauss){
+/*FUNCTION TriaRef::GetBSSAFriction{{{*/
+void TriaRef::GetBSSAFriction(IssmDouble* B, IssmDouble* xyz_list,GaussTria* 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
@@ -352,8 +353,8 @@
 	/*Build L: */
 	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];
+		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];
 	}
 
@@ -431,14 +432,23 @@
 
 	switch(this->element_type){
-		case P1Enum:
-		case P1DGEnum:
+		case P1Enum: case P1DGEnum:
 			basis[0]=gauss->coord1;
 			basis[1]=gauss->coord2;
 			basis[2]=gauss->coord3;
 			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			/*Corner nodes*/
+			basis[0]=gauss->coord1;
+			basis[1]=gauss->coord2;
+			basis[2]=gauss->coord3;
+			/*bubble*/
+			basis[3]=27.*gauss->coord1*gauss->coord2*gauss->coord3;
+			return;
 		case P2Enum:
+			/*Corner nodes*/
 			basis[0]=gauss->coord1*(2.*gauss->coord1-1.);
 			basis[1]=gauss->coord2*(2.*gauss->coord2-1.);
 			basis[2]=gauss->coord3*(2.*gauss->coord3-1.);
+			/*Mid-sides*/
 			basis[3]=4.*gauss->coord3*gauss->coord2;
 			basis[4]=4.*gauss->coord3*gauss->coord1;
@@ -465,6 +475,10 @@
 
 	switch(this->element_type){
-		case P1Enum:
-		case P1DGEnum:
+		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];
@@ -508,6 +522,6 @@
 	 */
 	for(int i=0;i<numnodes;i++){
-		dbasis[numnodes*0+i]=Jinv[0][0]*dbasis_ref[0*numnodes+i]+Jinv[0][1]*dbasis_ref[1*numnodes+i];
-		dbasis[numnodes*1+i]=Jinv[1][0]*dbasis_ref[0*numnodes+i]+Jinv[1][1]*dbasis_ref[1*numnodes+i];
+		dbasis[numnodes*0+i] = Jinv[0][0]*dbasis_ref[0*numnodes+i]+Jinv[0][1]*dbasis_ref[1*numnodes+i];
+		dbasis[numnodes*1+i] = Jinv[1][0]*dbasis_ref[0*numnodes+i]+Jinv[1][1]*dbasis_ref[1*numnodes+i];
 	}
 
@@ -527,32 +541,46 @@
 		case P1Enum: case P1DGEnum:
 			/*Nodal function 1*/
-			dbasis[NUMNODESP1*0+0]=-0.5; 
-			dbasis[NUMNODESP1*1+0]=-1.0/(2.0*SQRT3);
+			dbasis[NUMNODESP1*0+0] = -0.5;
+			dbasis[NUMNODESP1*1+0] = -SQRT3/6.;
 			/*Nodal function 2*/
-			dbasis[NUMNODESP1*0+1]=0.5;
-			dbasis[NUMNODESP1*1+1]=-1.0/(2.0*SQRT3);
+			dbasis[NUMNODESP1*0+1] = 0.5;
+			dbasis[NUMNODESP1*1+1] = -SQRT3/6.;
 			/*Nodal function 3*/
-			dbasis[NUMNODESP1*0+2]=0;
-			dbasis[NUMNODESP1*1+2]=1.0/SQRT3;
+			dbasis[NUMNODESP1*0+2] = 0;
+			dbasis[NUMNODESP1*1+2] = SQRT3/3.;
+			return;
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			/*Nodal function 1*/
+			dbasis[NUMNODESP1b*0+0] = -0.5;
+			dbasis[NUMNODESP1b*1+0] = -SQRT3/6.;
+			/*Nodal function 2*/
+			dbasis[NUMNODESP1b*0+1] = 0.5;
+			dbasis[NUMNODESP1b*1+1] = -SQRT3/6.;
+			/*Nodal function 3*/
+			dbasis[NUMNODESP1b*0+2] = 0;
+			dbasis[NUMNODESP1b*1+2] = SQRT3/3.;
+			/*Nodal function 4*/
+			dbasis[NUMNODESP1b*0+3] = 27.*(-.5*gauss->coord2*gauss->coord3 + .5*gauss->coord1*gauss->coord3);
+			dbasis[NUMNODESP1b*1+3] = 27.*SQRT3*(-1./6.*gauss->coord2*gauss->coord3 - 1./6.*gauss->coord1*gauss->coord3 +1./3.*gauss->coord1*gauss->coord2);
 			return;
 		case P2Enum:
 			/*Nodal function 1*/
-			dbasis[NUMNODESP2*0+0]=-2.*gauss->coord1 + 0.5;
-			dbasis[NUMNODESP2*1+0]=-2.*SQRT3/3.*gauss->coord1 + SQRT3/6.;
+			dbasis[NUMNODESP2*0+0] = -2.*gauss->coord1 + 0.5;
+			dbasis[NUMNODESP2*1+0] = -2.*SQRT3/3.*gauss->coord1 + SQRT3/6.;
 			/*Nodal function 2*/
-			dbasis[NUMNODESP2*0+1]=+2.*gauss->coord2 + 0.5;
-			dbasis[NUMNODESP2*1+1]=-2.*SQRT3/3.*gauss->coord2 + SQRT3/6.;
+			dbasis[NUMNODESP2*0+1] = +2.*gauss->coord2 - 0.5;
+			dbasis[NUMNODESP2*1+1] = -2.*SQRT3/3.*gauss->coord2 + SQRT3/6.;
 			/*Nodal function 3*/
-			dbasis[NUMNODESP2*0+2]=0.;
-			dbasis[NUMNODESP2*1+2]=+4.*SQRT3/3.*gauss->coord3 - SQRT3/3.;
+			dbasis[NUMNODESP2*0+2] = 0.;
+			dbasis[NUMNODESP2*1+2] = +4.*SQRT3/3.*gauss->coord3 - SQRT3/3.;
 			/*Nodal function 4*/
-			dbasis[NUMNODESP2*0+3]=+2.*gauss->coord3;
-			dbasis[NUMNODESP2*1+3]=+4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3;
+			dbasis[NUMNODESP2*0+3] = +2.*gauss->coord3;
+			dbasis[NUMNODESP2*1+3] = +4.*SQRT3/3.*gauss->coord2 - 2.*SQRT3/3.*gauss->coord3;
 			/*Nodal function 5*/
-			dbasis[NUMNODESP2*0+4]=-2.*gauss->coord3;
-			dbasis[NUMNODESP2*1+4]=+4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3;
+			dbasis[NUMNODESP2*0+4] = -2.*gauss->coord3;
+			dbasis[NUMNODESP2*1+4] = +4.*SQRT3/3.*gauss->coord1 - 2.*SQRT3/3.*gauss->coord3;
 			/*Nodal function 6*/
-			dbasis[NUMNODESP2*0+5]=2.*(gauss->coord1-gauss->coord2);
-			dbasis[NUMNODESP2*1+5]=-2.*SQRT3/3.*(gauss->coord1+gauss->coord2);
+			dbasis[NUMNODESP2*0+5] = 2.*(gauss->coord1-gauss->coord2);
+			dbasis[NUMNODESP2*1+5] = -2.*SQRT3/3.*(gauss->coord1+gauss->coord2);
 			return;
 		default:
@@ -590,6 +618,6 @@
 	/*Assign values*/
 	xDelete<IssmDouble>(dbasis);
-	*(p+0)=dpx;
-	*(p+1)=dpy;
+	p[0]=dpx;
+	p[1]=dpy;
 
 }
@@ -620,7 +648,9 @@
 
 	switch(this->element_type){
-		case P1Enum:   return NUMNODESP1;
-		case P1DGEnum: return NUMNODESP1;
-		case P2Enum:   return NUMNODESP2;
+		case P1Enum:                return NUMNODESP1;
+		case P1DGEnum:              return NUMNODESP1;
+		case P1bubbleEnum:          return NUMNODESP1b;
+		case P1bubblecondensedEnum: return NUMNODESP1b;
+		case P2Enum:                return NUMNODESP2;
 		default: _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
 	}
Index: /issm/trunk/src/c/classes/Elements/TriaRef.h
===================================================================
--- /issm/trunk/src/c/classes/Elements/TriaRef.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Elements/TriaRef.h	(revision 16137)
@@ -23,12 +23,12 @@
 
 		/*Numerics*/
-		void GetBMacAyeal(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss);
-		void GetBMacAyealStokes(IssmDouble* B , IssmDouble* xyz_list, GaussTria* gauss);
-		void GetBprimeMacAyeal(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss);
-		void GetBprimeMacAyealStokes(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss);
-		void GetBprimePrognostic(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss);
-		void GetBPrognostic(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetBSSA(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetBSSAFS(IssmDouble* B , IssmDouble* xyz_list, GaussTria* gauss);
+		void GetBprimeSSA(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetBprimeSSAFS(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetBprimeMasstransport(IssmDouble* Bprime, IssmDouble* xyz_list, GaussTria* gauss);
+		void GetBMasstransport(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss);
 		void GetBHydro(IssmDouble* B, IssmDouble* xyz_list, GaussTria* gauss);
-		void GetBMacAyealFriction(IssmDouble* L, IssmDouble* xyz_list,GaussTria* gauss);
+		void GetBSSAFriction(IssmDouble* L, IssmDouble* xyz_list,GaussTria* gauss);
 		void GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussTria* gauss);
 		void GetSegmentJacobianDeterminant(IssmDouble* Jdet, IssmDouble* xyz_list,GaussTria* gauss);
Index: sm/trunk/src/c/classes/ExternalResults/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/objects/ExternalResults)
-# }}}
Index: /issm/trunk/src/c/classes/ExternalResults/Results.cpp
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/Results.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/ExternalResults/Results.cpp	(revision 16137)
@@ -34,30 +34,4 @@
 
 /*Object management*/
-/*FUNCTION Results::SpawnTriaResults{{{*/
-Results* Results::SpawnTriaResults(int* indices){
-
-	/*Intermediary*/
-	vector<Object*>::iterator object;
-	ElementResult* resultin=NULL;
-	ElementResult* resultout=NULL;
-
-	/*Output*/
-	Results* newresults=new Results();
-
-	/*Go through results and call Spawn function*/
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		/*Create new result*/
-		resultin=(ElementResult*)(*object); 
-		resultout=resultin->SpawnTriaElementResult(indices);
-
-		/*Add result to new results*/
-		newresults->AddObject((Object*)resultout);
-	}
-
-	/*Assign output pointer*/
-	return newresults;
-}
-/*}}}*/
 /*FUNCTION Results::Write{{{*/
 void Results::Write(Parameters* parameters){
@@ -80,2 +54,30 @@
 }
 /*}}}*/
+/*FUNCTION Results::Write{{{*/
+int Results::AddResult(ElementResult* in_result){
+
+	/*First, go through dataset of inputs and check whether any input 
+	 * with the same name is already in. If so, erase the corresponding 
+	 * object before adding this new one: */
+	vector<Object*>::iterator object;
+	ElementResult* result=NULL;
+
+	/*In debugging mode, check that the input is not a NULL pointer*/
+	_assert_(in_result);
+
+	for(object=objects.begin() ; object<objects.end(); object++){
+
+		result=dynamic_cast<ElementResult*>(*object);
+
+		if(result->InstanceEnum()==in_result->InstanceEnum()){
+			if(result->GetStep()==in_result->GetStep()){
+				this->DeleteObject(result);
+				break;
+			}
+		}
+	}
+	this->AddObject(in_result);
+
+	return 1;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/ExternalResults/Results.h
===================================================================
--- /issm/trunk/src/c/classes/ExternalResults/Results.h	(revision 16136)
+++ /issm/trunk/src/c/classes/ExternalResults/Results.h	(revision 16137)
@@ -1,4 +1,4 @@
 #ifndef _CONTAINER_RESULTS_H_
-#define  _CONTAINER_RESULTS_H_
+#define _CONTAINER_RESULTS_H_
 
 #include "../../datastructures/datastructures.h"
@@ -6,4 +6,5 @@
 /*forward declarations */
 class Parameters;
+class ElementResult;
 
 /*!\brief Declaration of Results class.
@@ -19,7 +20,7 @@
 		~Results();
 
-		/*numerics*/
-		Results* SpawnTriaResults(int* indices);
-		void     Write(Parameters* parameters);
+		/*Mehthos*/
+		int AddResult(ElementResult* result);
+		void Write(Parameters* parameters);
 };
 #endif //ifndef _RESULTS_H_
Index: /issm/trunk/src/c/classes/FemModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/FemModel.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/FemModel.cpp	(revision 16137)
@@ -41,6 +41,6 @@
 
 /*Object constructors and destructor*/
-/*FUNCTION FemModel::FemModel(int argc,char** argv,COMM incomm){{{*/
-FemModel::FemModel(int argc,char** argv,COMM incomm){
+/*FUNCTION FemModel::FemModel(int argc,char** argv,ISSM_MPI_Comm incomm){{{*/
+FemModel::FemModel(int argc,char** argv,ISSM_MPI_Comm incomm){
 
 	/*configuration: */
@@ -153,5 +153,5 @@
 	/*Finalize PETSC for this model: */
 	#ifdef _HAVE_PETSC_
-	_printf0_("closing Petsc\n");
+	_printf0_("closing PETSc\n");
 	PetscFinalize(); 
 	#endif
@@ -188,5 +188,5 @@
 
 	/*Open input file on cpu 0: */
-	if(my_rank==0) IOMODEL = pfopen(inputfilename ,"rb");
+	if(my_rank==0) IOMODEL = pfopen0(inputfilename ,"rb");
 
 	/*Initialize internal data: */
@@ -288,5 +288,4 @@
 	/*configure elements, loads and nodes, for this new analysis: */
 	this->elements->SetCurrentConfiguration(elements,loads, nodes,vertices, materials,parameters);
-	this->nodes->SetCurrentConfiguration(elements,loads, nodes,vertices, materials,parameters);
 	this->loads->SetCurrentConfiguration(elements, loads, nodes,vertices, materials,parameters);
 
@@ -343,8 +342,8 @@
 		solution_memory=profiler->Memory(FinishCore);
 
-		_printf0_("Solution elapsed time    : " << solution_time   << " Seconds\n");
-		_printf0_("Solution number of flops : " << solution_flops  << " Flops\n");
-		_printf0_("Solution memory used     : " << solution_memory << " Bytes\n");
-		
+		_printf0_("Core solution elapsed time    : " << solution_time   << " Seconds\n");
+		_printf0_("Core solution number of flops : " << solution_flops  << " Flops\n");
+		_printf0_("Core solution memory used     : " << solution_memory << " Bytes\n");
+
 		/*Add to results: */
 		results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingSolutionTimeEnum, solution_time, 1, 0));
@@ -361,5 +360,4 @@
 		_printf0_("AD Solution memory used     : " << solution_memory << " Bytes\n");
 
-
 		#endif
 
@@ -367,293 +365,14 @@
 }
 /*}}}*/
-
 /*Modules:*/
-void FemModel::AllocateSystemMatrices(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,Vector<IssmDouble>** pdf,Vector<IssmDouble>** ppf){ /*{{{*/
-
-	/*Intermediary*/
-	int  fsize,ssize,flocalsize,slocalsize;
-	int  connectivity, numberofdofspernode;
-	int  configuration_type;
-	int  m,n,M,N;
-	int *d_nnz = NULL;
-	int *o_nnz = NULL;
-
-	/*output*/
-	Matrix<IssmDouble> *Kff  = NULL;
-	Matrix<IssmDouble> *Kfs  = NULL;
-	Vector<IssmDouble> *pf   = NULL;
-	Vector<IssmDouble> *df   = NULL;
-
-	bool oldalloc=false;
-
-	/*retrieve parameters: */
-	this->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-	this->parameters->FindParam(&connectivity,MeshAverageVertexConnectivityEnum);
-
-	/*retrieve node info*/
-	fsize      = this->nodes->NumberOfDofs(configuration_type,FsetEnum);
-	ssize      = this->nodes->NumberOfDofs(configuration_type,SsetEnum);
-	flocalsize = this->nodes->NumberOfDofsLocal(configuration_type,FsetEnum);
-	slocalsize = this->nodes->NumberOfDofsLocal(configuration_type,SsetEnum);
-
-	numberofdofspernode=this->nodes->MaxNumDofs(configuration_type,GsetEnum);
-
-	if(oldalloc){
-		if(pKff) Kff=new Matrix<IssmDouble>(fsize,fsize,connectivity,numberofdofspernode);
-		if(pKfs) Kfs=new Matrix<IssmDouble>(fsize,ssize,connectivity,numberofdofspernode);
-		if(pdf)  df =new Vector<IssmDouble>(fsize);
-		if(ppf)  pf =new Vector<IssmDouble>(fsize);
-	}
-	else{
-		if(pKff){
-			m=flocalsize; n=flocalsize; /*local  sizes*/
-			M=fsize;      N=fsize;      /*global sizes*/
-			this->MatrixNonzeros(&d_nnz,&o_nnz,FsetEnum,FsetEnum);
-			Kff=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
-			xDelete<int>(d_nnz);
-			xDelete<int>(o_nnz);
-		}
-		if(pKfs){
-			m=flocalsize; n=slocalsize; /*local  sizes*/
-			M=fsize;      N=ssize;      /*global sizes*/
-			this->MatrixNonzeros(&d_nnz,&o_nnz,FsetEnum,SsetEnum);
-			Kfs=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
-			xDelete<int>(d_nnz);
-			xDelete<int>(o_nnz);
-		}
-		if(pdf) df =new Vector<IssmDouble>(flocalsize,fsize);
-		if(ppf) pf =new Vector<IssmDouble>(flocalsize,fsize);
-	}
-
-	/*Allocate output pointers*/
-	if(pKff) *pKff = Kff;
-	if(pKfs) *pKfs = Kfs;
-	if(pdf)  *pdf  = df;
-	if(ppf)  *ppf  = pf;
-}
-/*}}}*/
-void FemModel::MatrixNonzeros(int** pd_nnz,int** po_nnz,int set1enum,int set2enum){/*{{{*/
-
-	/*Intermediary*/
-	int      i,j,k,index,offset,count;
-	int      configuration_type;
-	int      d_nz,o_nz;
-	Element *element            = NULL;
-	Load    *load               = NULL;
-	int     *head_e             = NULL;
-	int     *next_e             = NULL;
-	int     *count2offset_e     = NULL;
-	int     *head_l             = NULL;
-	int     *next_l             = NULL;
-	int     *count2offset_l     = NULL;
-	int     *sidlist            = NULL;
-
-	/*output*/
-	int *d_nnz = NULL;
-	int *o_nnz = NULL;
-
-	/*retrive parameters: */
-	this->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-
-	/*Get vector size and number of nodes*/
-	int numnodes            = nodes->NumberOfNodes(configuration_type);
-	int numberofdofspernode = nodes->MaxNumDofs(configuration_type,GsetEnum);
-	int M                   = nodes->NumberOfDofs(configuration_type,set1enum);
-	int N                   = nodes->NumberOfDofs(configuration_type,set2enum);
-	int m                   = nodes->NumberOfDofsLocal(configuration_type,set1enum);
-	int n                   = nodes->NumberOfDofsLocal(configuration_type,set2enum);
-	int numnodesperelement  = elements->MaxNumNodes();
-	int numnodesperload     = loads->MaxNumNodes(configuration_type);
-
-	/*First, we are building chaining vectors so that we know what nodes are
-	 * connected to what elements. These vectors are such that:
-	 *   for(int i=head[id];i!=-1;i=next[i])
-	 * will loop over all the elements that are connected to the node number
-	 * id*/
-	head_e         = xNew<int>(numnodes); for(i=0;i<numnodes;i++) head_e[i]=-1;
-	next_e         = xNew<int>(elements->Size()*numnodesperelement);
-	count2offset_e = xNew<int>(elements->Size()*numnodesperelement);
-
-	k=0;
-	for(i=0;i<elements->Size();i++){
-		element = dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		sidlist = xNew<int>(element->GetNumberOfNodes());
-		element->GetNodesSidList(sidlist);
-
-		for(j=0;j<element->GetNumberOfNodes();j++){
-			index = sidlist[j];
-			_assert_(index>=0 && index<numnodes);
-
-			count2offset_e[k]=i;
-			next_e[k]=head_e[index];
-			head_e[index]=k++;
-		}
-		for(j=0;j<numnodesperelement-element->GetNumberOfNodes();j++) k++;
-
-		xDelete<int>(sidlist);
-	}
-
-	/*Chain for loads*/
-	head_l         = xNew<int>(numnodes); for(i=0;i<numnodes;i++) head_l[i]=-1;
-	next_l         = xNew<int>(loads->Size(configuration_type)*numnodesperload);
-	count2offset_l = xNew<int>(loads->Size(configuration_type)*numnodesperload);
-	k=0;
-	for(i=0;i<loads->Size();i++){
-		load = dynamic_cast<Load*>(loads->GetObjectByOffset(i));
-		if(!load->InAnalysis(configuration_type)) continue;
-		sidlist = xNew<int>(load->GetNumberOfNodes());
-		load->GetNodesSidList(sidlist);
-
-		for(j=0;j<load->GetNumberOfNodes();j++){
-			index = sidlist[j];
-			_assert_(index>=0 && index<numnodes);
-
-			count2offset_l[k]=i;
-			next_l[k]=head_l[index];
-			head_l[index]=k++;
-		}
-		for(j=0;j<numnodesperload-load->GetNumberOfNodes();j++) k++;
-
-		xDelete<int>(sidlist);
-	}
-
-	/*OK now count number of dofs and flag each nodes for each node i*/
-	bool *flags                  = xNew<bool>(numnodes);
-	int  *d_connectivity         = xNewZeroInit<int>(numnodes);
-	int  *o_connectivity         = xNewZeroInit<int>(numnodes);
-	int  *connectivity_clone     = xNewZeroInit<int>(numnodes);
-	int  *all_connectivity_clone = xNewZeroInit<int>(numnodes);
-
-	/*Create connectivity vector*/
-	for(i=0;i<nodes->Size();i++){
-		Node* node=dynamic_cast<Node*>(nodes->GetObjectByOffset(i));
-		if(node->InAnalysis(configuration_type)){
-
-			/*Reinitialize flags to 0*/
-			for(j=0;j<numnodes;j++) flags[j]=false;
-
-			/*Loop over elements that hold node number i*/
-			//if(head_e[node->Sid()]==-1 && head_l[node->Sid()]==-1){
-			//	printf("[%i] vertex %i\n",IssmComm::GetRank(),node->Sid()+1);
-			//}
-			for(j=head_e[node->Sid()];j!=-1;j=next_e[j]){
-				offset=count2offset_e[j];
-				element=dynamic_cast<Element*>(elements->GetObjectByOffset(offset));
-				element->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,set1enum,set2enum);
-				if(node->IsClone()){
-					connectivity_clone[node->Sid()]+=d_nz+o_nz;
-				}
-				else{
-					d_connectivity[node->Sid()]+=d_nz;
-					o_connectivity[node->Sid()]+=o_nz;
-				}
-			}
-			for(j=head_l[node->Sid()];j!=-1;j=next_l[j]){
-				offset=count2offset_l[j];
-				load=dynamic_cast<Load*>(loads->GetObjectByOffset(offset));
-				load->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,set1enum,set2enum);
-				if(node->IsClone()){
-					connectivity_clone[node->Sid()]+=d_nz+o_nz;
-				}
-				else{
-					d_connectivity[node->Sid()]+=d_nz;
-					o_connectivity[node->Sid()]+=o_nz;
-				}
-			}
-		}
-	}
-	xDelete<bool>(flags);
-	xDelete<int>(count2offset_e);
-	xDelete<int>(head_e);
-	xDelete<int>(next_e);
-	xDelete<int>(count2offset_l);
-	xDelete<int>(head_l);
-	xDelete<int>(next_l);
-
-	/*sum over all cpus*/
-#ifdef _HAVE_MPI_
-	MPI_Allreduce((void*)connectivity_clone,(void*)all_connectivity_clone,numnodes,MPI_INT,MPI_SUM,IssmComm::GetComm());
-#endif
-	xDelete<int>(connectivity_clone);
-
-	if(set1enum==FsetEnum){
-		count=0;
-		d_nnz=xNew<int>(m);
-		o_nnz=xNew<int>(m);
-		for(i=0;i<nodes->Size();i++){
-			Node* node=dynamic_cast<Node*>(nodes->GetObjectByOffset(i));
-			if(node->InAnalysis(configuration_type) && !node->IsClone()){
-				for(j=0;j<node->indexing.fsize;j++){
-					_assert_(count<m);
-					d_nnz[count]=numberofdofspernode*(d_connectivity[node->Sid()] + all_connectivity_clone[node->Sid()]);
-					o_nnz[count]=numberofdofspernode*(o_connectivity[node->Sid()] + all_connectivity_clone[node->Sid()]);
-					if(d_nnz[count]>n)   d_nnz[count]=n;
-					if(o_nnz[count]>N-n) o_nnz[count]=N-n;
-					count++;
-				}
-			}
-		}
-		_assert_(m==count);
-	}
-	else{
-		_error_("STOP not implemented");
-	}
-	xDelete<int>(d_connectivity);
-	xDelete<int>(o_connectivity);
-	xDelete<int>(all_connectivity_clone);
-
-	/*Allocate ouptput pointer*/
-	*pd_nnz=d_nnz;
-	*po_nnz=o_nnz;
-
-}/*}}}*/
-void FemModel::CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,IssmDouble kmax){/*{{{*/
-
-	int      i,connectivity;
-	int      numberofdofspernode;
-	int      fsize,configuration_type;
-	Element *element = NULL;
-	Load    *load    = NULL;
-	Matrix<IssmDouble>* Jff = NULL;
-
-	/*Checks*/
-	_assert_(nodes && elements);
-
-	/*Recover some parameters*/
-	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-	parameters->FindParam(&connectivity,MeshAverageVertexConnectivityEnum);
-	fsize=nodes->NumberOfDofs(configuration_type,FsetEnum);
-	numberofdofspernode=nodes->MaxNumDofs(configuration_type,GsetEnum);
-
-	/*Initialize Jacobian Matrix*/
-	this->AllocateSystemMatrices(&Jff,NULL,NULL,NULL);
-
-	/*Create and assemble matrix*/
-	for(i=0;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		element->CreateJacobianMatrix(Jff);
-	}
-	for (i=0;i<loads->Size();i++){
-		load=(Load*)loads->GetObjectByOffset(i);
-		if(load->InAnalysis(configuration_type)) load->CreateJacobianMatrix(Jff);
-		if(load->InAnalysis(configuration_type)) load->PenaltyCreateJacobianMatrix(Jff,kmax);
-	}
-	Jff->Assemble();
-
-	/*Assign output pointer*/
-	*pJff=Jff;
-
-}/*}}}*/
 int  FemModel::UpdateVertexPositionsx(void){ /*{{{*/
 
-	int     i;
-	Vector<IssmDouble>*     vz        = NULL;
-	Vertex *vertex    = NULL;
-	IssmDouble *thickness = NULL;
-	IssmDouble *bed       = NULL;
+	Vector<IssmDouble> *vz        = NULL;
+	IssmDouble         *thickness = NULL;
+	IssmDouble         *bed       = NULL;
 
 	/*get vertex vectors for bed and thickness: */
-	GetVectorFromInputsx(&thickness,elements,nodes, vertices, loads, materials, parameters, ThicknessEnum,VertexEnum);
-	GetVectorFromInputsx(&bed      ,elements,nodes, vertices, loads, materials, parameters, BedEnum,      VertexEnum);
+	GetVectorFromInputsx(&thickness,this, ThicknessEnum,VertexEnum);
+	GetVectorFromInputsx(&bed      ,this, BedEnum,      VertexEnum);
 
 	/*Allocate vector*/
@@ -661,6 +380,6 @@
 
 	/*Update verices new geometry: */
-	for (i=0;i<vertices->Size();i++){
-		vertex=(Vertex*)vertices->GetObjectByOffset(i);
+	for(int i=0;i<vertices->Size();i++){
+		Vertex* vertex=(Vertex*)vertices->GetObjectByOffset(i);
 		vertex->UpdatePosition(vz,parameters,thickness,bed);
 	}
@@ -670,10 +389,10 @@
 
 	/*Update element inputs*/
-	InputUpdateFromVectorx(elements,nodes,vertices,loads,materials,parameters,vz,VzMeshEnum,VertexPIdEnum);
+	InputUpdateFromVectorx(this,vz,VzMeshEnum,VertexPIdEnum);
 
 	/*Free ressources:*/
+	delete vz;
+	xDelete<IssmDouble>(bed);
 	xDelete<IssmDouble>(thickness);
-	xDelete<IssmDouble>(bed);
-	delete vz;
 	return 1;
 }
@@ -691,10 +410,4 @@
 	/*start module: */
 	if(VerboseModule()) _printf0_("   Updating constraints for time: " << time << "\n");
-
-	/*First, Nodes might be activated/deactivated by element*/
-	for(int i=0;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		element->UpdateConstraints();
-	}
 
 	/*Second, constraints might be time dependent: */
@@ -736,5 +449,5 @@
 		case SurfaceLogVelMisfitEnum:    SurfaceLogVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
 		case SurfaceLogVxVyMisfitEnum:   SurfaceLogVxVyMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
-		case SurfaceAverageVelMisfitEnum:SurfaceAverageVelMisfitx( responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
+		case SurfaceAverageVelMisfitEnum:SurfaceAverageVelMisfitx(responses,this,weight_index); break;
 		case ThicknessAbsMisfitEnum:     ThicknessAbsMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,weight_index); break;
 		case ThicknessAbsGradientEnum:   this->ThicknessAbsGradientx(responses,weight_index); break;
@@ -808,4 +521,5 @@
 	IssmPDouble *dependents;
 	DataSet*    dependent_objects=NULL;
+	int my_rank=IssmComm::GetRank();
 
 	/*AD mode on?: */
@@ -823,5 +537,7 @@
 				DependentObject* dep=(DependentObject*)dependent_objects->GetObjectByOffset(i);
 				dep->Responsex(&output_value,this);
-				output_value>>=dependents[i];
+				if (my_rank==0) {
+					output_value>>=dependents[i];
+				}
 			}
 		}
@@ -833,111 +549,4 @@
 }
 /*}}}*/
-void FemModel::SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** pdf, IssmDouble* pkmax){/*{{{*/
-
-	/*intermediary: */
-	int      i;
-	int      configuration_type;
-	Element *element = NULL;
-	Load    *load    = NULL;
-
-	/*output: */
-	Matrix<IssmDouble> *Kff  = NULL;
-	Matrix<IssmDouble> *Kfs  = NULL;
-	Vector<IssmDouble> *pf   = NULL;
-	Vector<IssmDouble> *df   = NULL;
-	IssmDouble          kmax = 0;
-
-	/*Display message*/
-	if(VerboseModule()) _printf0_("   Generating matrices\n");
-
-	/*retrive parameters: */
-	this->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-
-	/*First, we might need to do a dry run to get kmax if penalties are employed*/
-	if(loads->IsPenalty(configuration_type)){
-
-		/*Allocate Kff_temp*/
-		Matrix<IssmDouble> *Kff_temp = NULL;
-		this->AllocateSystemMatrices(&Kff_temp,NULL,NULL,NULL);
-
-		/*Get complete stiffness matrix without penalties*/
-		for (i=0;i<this->elements->Size();i++){
-			element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
-			element->CreateKMatrix(Kff_temp,NULL);
-		}
-
-		for (i=0;i<this->loads->Size();i++){
-			load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
-			if(load->InAnalysis(configuration_type)) load->CreateKMatrix(Kff_temp,NULL);
-		}
-		Kff_temp->Assemble();
-
-		/*Now, figure out maximum value of stiffness matrix, so that we can penalize it correctly: */
-		kmax=Kff_temp->Norm(NORM_INF);
-		delete Kff_temp;
-	}
-
-	/*Allocate stiffness matrices and load vector*/
-	this->AllocateSystemMatrices(&Kff,&Kfs,&df,&pf);
-
-	/*Fill stiffness matrix from elements and loads */
-	for (i=0;i<this->elements->Size();i++){
-		element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
-		element->CreateKMatrix(Kff,Kfs);
-	}
-	
-	for (i=0;i<this->loads->Size();i++){
-		load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
-		if(load->InAnalysis(configuration_type)) load->CreateKMatrix(Kff,Kfs);
-	}
-
-	/*Fill right hand side vector, from elements and loads */
-	for (i=0;i<this->elements->Size();i++){
-		element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
-		element->CreatePVector(pf);
-	}
-	for (i=0;i<this->loads->Size();i++){
-		load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
-		if(load->InAnalysis(configuration_type)) load->CreatePVector(pf);
-	}
-
-	/*Now deal with penalties (only in loads)*/
-	if(loads->IsPenalty(configuration_type)){
-		for (i=0;i<this->loads->Size();i++){
-			load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
-			if(load->InAnalysis(configuration_type)) load->PenaltyCreateKMatrix(Kff,Kfs,kmax);
-		}
-		for (i=0;i<this->loads->Size();i++){
-			load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
-			if(load->InAnalysis(configuration_type)) load->PenaltyCreatePVector(pf,kmax);
-		}
-	}
-
-	/*Create dof vector for stiffness matrix preconditioning*/
-	for (i=0;i<this->elements->Size();i++){
-		element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
-		element->CreateDVector(df);
-	}
-
-	/*Assemble matrices and vector*/
-	Kff->Assemble();
-	Kfs->Assemble();
-	pf->Assemble();
-	df->Assemble();
-	//Kff->AllocationInfo();
-	//Kfs->AllocationInfo();
-
-	/*Assign output pointers: */
-	if(pKff) *pKff=Kff;
-	else      delete Kff;
-	if(pKfs) *pKfs=Kfs;
-	else      delete Kfs;
-	if(ppf)  *ppf=pf;
-	else      delete pf;
-	if(pdf)  *pdf=df;
-	else      delete df;
-	if(pkmax) *pkmax=kmax;
-}
-/*}}}*/
 void FemModel::TimeAdaptx(IssmDouble* pdt){/*{{{*/
 
@@ -962,9 +571,7 @@
 
 	/*Figure out minimum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce (&min_dt,&node_min_dt,1,MPI_DOUBLE,MPI_MIN,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_min_dt,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	ISSM_MPI_Reduce (&min_dt,&node_min_dt,1,ISSM_MPI_DOUBLE,ISSM_MPI_MIN,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_min_dt,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
 	min_dt=node_min_dt;
-#endif
 
 	/*Assign output pointers:*/
@@ -1015,8 +622,6 @@
 	}
 
-#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)&mass_flux,(void*)&all_mass_flux,1,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
+	ISSM_MPI_Allreduce ( (void*)&mass_flux,(void*)&all_mass_flux,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
 	mass_flux=all_mass_flux;
-#endif
 
 	/*Free ressources:*/
@@ -1049,9 +654,7 @@
 
 	/*Figure out maximum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&maxabsvx,&node_maxabsvx,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_maxabsvx,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	ISSM_MPI_Reduce(&maxabsvx,&node_maxabsvx,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxabsvx,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
 	maxabsvx=node_maxabsvx;
-#endif
 
 	/*Assign output pointers:*/
@@ -1075,9 +678,7 @@
 
 	/*Figure out maximum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&maxabsvy,&node_maxabsvy,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_maxabsvy,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	ISSM_MPI_Reduce(&maxabsvy,&node_maxabsvy,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxabsvy,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
 	maxabsvy=node_maxabsvy;
-#endif
 
 	/*Assign output pointers:*/
@@ -1101,9 +702,7 @@
 
 	/*Figure out maximum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&maxabsvz,&node_maxabsvz,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_maxabsvz,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	ISSM_MPI_Reduce(&maxabsvz,&node_maxabsvz,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxabsvz,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
 	maxabsvz=node_maxabsvz;
-#endif
 
 	/*Assign output pointers:*/
@@ -1127,9 +726,7 @@
 
 	/*Figure out maximum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&maxvel,&node_maxvel,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_maxvel,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	ISSM_MPI_Reduce(&maxvel,&node_maxvel,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxvel,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
 	maxvel=node_maxvel;
-#endif
 
 	/*Assign output pointers:*/
@@ -1153,9 +750,7 @@
 
 	/*Figure out maximum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&maxvx,&node_maxvx,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_maxvx,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	ISSM_MPI_Reduce(&maxvx,&node_maxvx,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxvx,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
 	maxvx=node_maxvx;
-#endif
 
 	/*Assign output pointers:*/
@@ -1179,9 +774,7 @@
 
 	/*Figure out maximum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&maxvy,&node_maxvy,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_maxvy,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	ISSM_MPI_Reduce(&maxvy,&node_maxvy,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxvy,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
 	maxvy=node_maxvy;
-#endif
 
 	/*Assign output pointers:*/
@@ -1205,9 +798,7 @@
 
 	/*Figure out maximum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&maxvz,&node_maxvz,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_maxvz,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	ISSM_MPI_Reduce(&maxvz,&node_maxvz,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_maxvz,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
 	maxvz=node_maxvz;
-#endif
 
 	/*Assign output pointers:*/
@@ -1231,9 +822,7 @@
 
 	/*Figure out minimum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&minvel,&node_minvel,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_minvel,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	ISSM_MPI_Reduce(&minvel,&node_minvel,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_minvel,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
 	minvel=node_minvel;
-#endif
 
 	/*Assign output pointers:*/
@@ -1257,9 +846,7 @@
 
 	/*Figure out minimum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&minvx,&node_minvx,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_minvx,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	ISSM_MPI_Reduce(&minvx,&node_minvx,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_minvx,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
 	minvx=node_minvx;
-#endif
 
 	/*Assign output pointers:*/
@@ -1283,9 +870,7 @@
 
 	/*Figure out minimum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&minvy,&node_minvy,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_minvy,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	ISSM_MPI_Reduce(&minvy,&node_minvy,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_minvy,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
 	minvy=node_minvy;
-#endif
 
 	/*Assign output pointers:*/
@@ -1309,9 +894,7 @@
 
 	/*Figure out minimum across the cluster: */
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&minvz,&node_minvz,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_minvz,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	ISSM_MPI_Reduce(&minvz,&node_minvz,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_minvz,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());   
 	minvz=node_minvz;
-#endif
 
 	/*Assign output pointers:*/
@@ -1328,10 +911,6 @@
 		local_smb+=element->TotalSmb();
 	}
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&local_smb,&total_smb,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&total_smb,1,MPI_DOUBLE,0,IssmComm::GetComm());
-#else
-	total_smb=local_smb;
-#endif
+	ISSM_MPI_Reduce(&local_smb,&total_smb,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&total_smb,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
 
 	/*Assign output pointers: */
@@ -1348,10 +927,6 @@
 		local_ice_volume+=element->IceVolume();
 	}
-	#ifdef _HAVE_MPI_
-	MPI_Reduce(&local_ice_volume,&total_ice_volume,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&total_ice_volume,1,MPI_DOUBLE,0,IssmComm::GetComm());
-	#else
-	total_ice_volume=local_ice_volume;
-	#endif
+	ISSM_MPI_Reduce(&local_ice_volume,&total_ice_volume,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&total_ice_volume,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
 
 	/*Assign output pointers: */
@@ -1383,8 +958,6 @@
 
 	/*Broadcast whether we found the element: */
-#ifdef _HAVE_MPI_
-	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
+	ISSM_MPI_Allreduce ( &found,&sumfound,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
 	if(!sumfound)_error_("could not find material with id" << index << " to compute ElementResponse");
-#endif
 
 	/*Ok, we found the element, compute responseocity: */
@@ -1394,8 +967,6 @@
 
 	/*Broadcast and plug into response: */
-#ifdef _HAVE_MPI_
-	MPI_Allreduce ( &cpu_found,&cpu_found,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
-	MPI_Bcast(&response,1,MPI_DOUBLE,cpu_found,IssmComm::GetComm()); 
-#endif
+	ISSM_MPI_Allreduce ( &cpu_found,&cpu_found,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&response,1,ISSM_MPI_DOUBLE,cpu_found,IssmComm::GetComm()); 
 
 	/*Assign output pointers: */
@@ -1414,9 +985,7 @@
 		J+=element->BalancethicknessMisfit(weight_index);
 	}
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
@@ -1441,9 +1010,7 @@
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
@@ -1467,8 +1034,11 @@
 	/*Get response*/
 	J=0;
+	//_printf_(true,"list of misfits: ");
 	for(int i=0;i<num_responses;i++){
 		this->Responsex(&Jplus,EnumToStringx(responses[i]),i);
+		//_printf_(true," %12.7g ",Jplus);
 		J+=Jplus;
 	}
+	//_printf_(true," \n");
 
 	/*Assign output pointers: */
@@ -1511,5 +1081,5 @@
 
 			/*this response was scaled. pick up the response from the inputs: */
-			GetVectorFromInputsx(&vertex_response,elements,nodes, vertices, loads, materials, parameters, StringToEnumx(root),VertexEnum);
+			GetVectorFromInputsx(&vertex_response,this, StringToEnumx(root),VertexEnum);
 
 			/*Now, average it onto the partition nodes: */
@@ -1595,5 +1165,4 @@
 /*}}}*/
 #endif
-
 #ifdef _HAVE_HYDROLOGY_
 void FemModel::HydrologyEPLupdateDomainx(void){ /*{{{*/
@@ -1617,5 +1186,5 @@
 
 	/*Update Mask*/
-	InputUpdateFromVectorx(elements,nodes,vertices,loads,materials,parameters,serial_mask,HydrologydcMaskEplactiveEnum,NodeSIdEnum);
+	InputUpdateFromVectorx(this,serial_mask,HydrologydcMaskEplactiveEnum,NodeSIdEnum);
 	xDelete<IssmDouble>(serial_mask);
 
@@ -1647,10 +1216,8 @@
 	}
 	xDelete<IssmDouble>(serial_active);
-	#ifdef _HAVE_MPI_
 	int sum_counter;
-	MPI_Reduce(&counter,&sum_counter,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&sum_counter,1,MPI_INT,0,IssmComm::GetComm());                
+	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;
-	#endif
 	if(VerboseSolution()) _printf0_("   Number of active nodes in EPL layer: "<< counter <<"\n");
 
@@ -1675,8 +1242,18 @@
 
 	/*Update Inputs*/
-	InputUpdateFromVectorx(elements,nodes,vertices,loads,materials,parameters,transferg,WaterTransferEnum,NodesEnum);
-
+	InputUpdateFromVectorx(this,transferg,WaterTransferEnum,NodesEnum);
 	delete transferg;
 }
 /*}}}*/
 #endif
+#ifdef _HAVE_THERMAL_
+void FemModel::UpdateThermalBasalConstraintsx(void){ /*{{{*/
+
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->UpdateThermalBasalConstraints();
+	}
+
+}
+/*}}}*/
+#endif
Index: /issm/trunk/src/c/classes/FemModel.h
===================================================================
--- /issm/trunk/src/c/classes/FemModel.h	(revision 16136)
+++ /issm/trunk/src/c/classes/FemModel.h	(revision 16137)
@@ -43,17 +43,14 @@
 		Parameters  *parameters;           //one set of parameters, independent of the analysis_type
 		Results     *results;              //results that cannot be fit into the elements 
-		COMM        comm;                  //communicator for this particular model
+		ISSM_MPI_Comm        comm;                  //communicator for this particular model
 
 		/*constructors, destructors: */
-		FemModel(int argc,char** argv,COMM comm_init);
+		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();
 
 		/*Methods:*/
-		void AllocateSystemMatrices(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,Vector<IssmDouble>** pdf,Vector<IssmDouble>** ppf);
-		void CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,IssmDouble kmax);
 		void Echo();
 		void InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int solution_type,const int* analyses,const int nummodels);
-		void MatrixNonzeros(int** pd_nnz,int** po_nnz,int set1enum,int set2enum);
 		void Solve(void);
 		void OutputResults(void);
@@ -95,11 +92,14 @@
 		void Deflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt, IssmDouble* x, IssmDouble* y);
 		#endif
-		void SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** pdf, IssmDouble* pkmax);
 		void TimeAdaptx(IssmDouble* pdt);
 		void UpdateConstraintsx(void);
 		int  UpdateVertexPositionsx(void);
-		void ParEplMask(void);		
+		#ifdef _HAVE_HYDROLOGY_
 		void HydrologyTransferx(void);
 		void HydrologyEPLupdateDomainx(void);
+		#endif
+		#ifdef _HAVE_THERMAL_
+		void UpdateThermalBasalConstraintsx(void);
+		#endif
 };
 
Index: /issm/trunk/src/c/classes/Hook.cpp
===================================================================
--- /issm/trunk/src/c/classes/Hook.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Hook.cpp	(revision 16137)
@@ -63,5 +63,5 @@
 /*FUNCTION Hook::Echo{{{*/
 void Hook::Echo(void){
-
+	_assert_(this);
 	int i;
 	if (num){
@@ -69,5 +69,5 @@
 		_printf_("      num=" << this->num << "\n");
 		_printf_("      ids: ");
-		for (i=0;i<this->num;i++) _printf_(this->ids[i] << " ");
+		for(i=0;i<this->num;i++) _printf_(this->ids[i] << " ");
 		_printf_("\n");
 		_printf_("      offsets: ");
Index: /issm/trunk/src/c/classes/IndependentObject.cpp
===================================================================
--- /issm/trunk/src/c/classes/IndependentObject.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/IndependentObject.cpp	(revision 16137)
@@ -106,12 +106,11 @@
 		if(my_rank==0){
 			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;
-
-		#ifdef _HAVE_MPI_
-		MPI_Bcast(&scalar,1,MPI_DOUBLE,0,IssmComm::GetComm()); 
-		#endif
+			
+			/*Now, before we even broadcast this to other nodes, declare the scalar  as an independent variable!: */
+			scalar<<=pscalar;
+		}
+
+		
+		ISSM_MPI_Bcast(&scalar,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm()); 
 
 		/*Ok, we are almost done. scalar is now an independent variable. We don't want this variable to be fetched again in the 
@@ -145,14 +144,10 @@
 			if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
 		}
-		#ifdef _HAVE_MPI_
-		MPI_Bcast(&M,1,MPI_INT,0,IssmComm::GetComm()); 
-		#endif
+		ISSM_MPI_Bcast(&M,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 		if(my_rank==0){  
 			if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
 		}
-		#ifdef _HAVE_MPI_
-		MPI_Bcast(&N,1,MPI_INT,0,IssmComm::GetComm()); 
-		#endif
+		ISSM_MPI_Bcast(&N,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 		/*Now allocate matrix: */
@@ -168,7 +163,5 @@
 				for (int i=0;i<M*N;++i) matrix[i]<<=buffer[i];  /*we use the <<= ADOLC overloaded operator to declare the independency*/
 			}
-			#ifdef _HAVE_MPI_
-			MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm()); 
-			#endif
+			ISSM_MPI_Bcast(matrix,M*N,ISSM_MPI_DOUBLE,0,IssmComm::GetComm()); 
 
 			xDelete<IssmPDouble>(buffer);
@@ -181,5 +174,5 @@
 		iomodel->data[name]=matrix;
 		iomodel->independents[name]=true;
-		
+
 		//Finally, record the number of independents created: 
 		this->numberofindependents=M*N;
Index: /issm/trunk/src/c/classes/Inputs/BoolInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/BoolInput.cpp	(revision 16137)
@@ -72,5 +72,5 @@
 /*}}}*/
 /*FUNCTION BoolInput::SpawnTriaInput{{{*/
-Input* BoolInput::SpawnTriaInput(int* indices){
+Input* BoolInput::SpawnTriaInput(int location){
 
 		/*output*/
Index: /issm/trunk/src/c/classes/Inputs/BoolInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/BoolInput.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/BoolInput.h	(revision 16137)
@@ -34,5 +34,5 @@
 		/*BoolInput management: {{{*/
 		int   InstanceEnum();
-		Input* SpawnTriaInput(int* indices);
+		Input* SpawnTriaInput(int location);
 		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
@@ -62,6 +62,6 @@
 		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype);
 		void SquareMin(IssmDouble* psquaremin, Parameters* parameters);
Index: sm/trunk/src/c/classes/Inputs/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Inputs/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,16 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/objects/Inputs)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/Inputs/BoolInput.cpp
-              $ENV{ISSM_DIR}/src/c/classes/objects/Inputs/DatasetInput.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/Inputs/DoubleInput.cpp
-                  $ENV{ISSM_DIR}/src/c/classes/objects/Inputs/IntInput.cpp
-            $ENV{ISSM_DIR}/src/c/classes/objects/Inputs/TransientInput.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/Inputs/TriaP1Input.cpp PARENT_SCOPE)
-# }}}
-# THREED_SOURCES {{{
-set(THREED_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/Inputs/PentaP1Input.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/classes/Inputs/ControlInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/ControlInput.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/ControlInput.cpp	(revision 16137)
@@ -36,9 +36,9 @@
 			maxvalues  =new TriaInput(enum_type,pmax,P1Enum);
 			break;
-		case PentaP1InputEnum:
-			values     =new PentaP1Input(enum_type,pvalues);
-			savedvalues=new PentaP1Input(enum_type,pvalues);
-			minvalues  =new PentaP1Input(enum_type,pmin);
-			maxvalues  =new PentaP1Input(enum_type,pmax);
+		case PentaInputEnum:
+			values     =new PentaInput(enum_type,pvalues,P1Enum);
+			savedvalues=new PentaInput(enum_type,pvalues,P1Enum);
+			minvalues  =new PentaInput(enum_type,pmin,P1Enum);
+			maxvalues  =new PentaInput(enum_type,pmax,P1Enum);
 			break;
 		default:
@@ -115,4 +115,8 @@
 
 /*Object functions*/
+/*FUNCTION ControlInput::AXPY(){{{*/
+void ControlInput::AXPY(Input* xinput,IssmDouble scalar){
+	values->AXPY(xinput,scalar);
+}/*}}}*/
 /*FUNCTION ControlInput::Constrain(){{{*/
 void ControlInput::Constrain(void){
@@ -179,6 +183,6 @@
 }/*}}}*/
 /*FUNCTION ControlInput::SpawnTriaInput{{{*/
-Input* ControlInput::SpawnTriaInput(int* indices){
-	return values->SpawnTriaInput(indices);
+Input* ControlInput::SpawnTriaInput(int location){
+	return values->SpawnTriaInput(location);
 }/*}}}*/
 /*FUNCTION ControlInput::SpawnGradient{{{*/
Index: /issm/trunk/src/c/classes/Inputs/ControlInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/ControlInput.h	(revision 16137)
@@ -38,5 +38,5 @@
 		/*ControlInput management: {{{*/
 		int    InstanceEnum();
-		Input* SpawnTriaInput(int* indices);
+		Input* SpawnTriaInput(int location);
 		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
@@ -67,6 +67,6 @@
 		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
 		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
@@ -74,5 +74,5 @@
 		void Scale(IssmDouble scale_factor){_error_("not implemented yet");};
 		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
-		void AXPY(Input* xinput,IssmDouble scalar){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar);
 		void Constrain(void);
 		void Constrain(IssmDouble min,IssmDouble max);
Index: /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/DatasetInput.cpp	(revision 16137)
@@ -70,5 +70,5 @@
 /*}}}*/
 /*FUNCTION DatasetInput::SpawnTriaInput{{{*/
-Input* DatasetInput::SpawnTriaInput(int* indices){
+Input* DatasetInput::SpawnTriaInput(int location){
 
 	/*output*/
@@ -78,5 +78,5 @@
 	outinput=new DatasetInput();
 	outinput->enum_type=this->enum_type;
-	outinput->inputs=dynamic_cast<Inputs*>(this->inputs->SpawnTriaInputs(indices));
+	outinput->inputs=dynamic_cast<Inputs*>(this->inputs->SpawnTriaInputs(location));
 
 	/*Assign output*/
@@ -110,2 +110,12 @@
 }
 /*}}}*/
+/*FUNCTION DatasetInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int index){{{*/
+void DatasetInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,int index){
+
+	/*Get requested input within dataset*/
+	if(index<0 || index > inputs->Size()-1) _error_("index requested (" << index << ") exceeds dataset size (" << inputs->Size() << ")");
+	Input* input=dynamic_cast<Input*>(this->inputs->GetObjectByOffset(index));
+
+	input->GetInputValue(pvalue,gauss);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/DatasetInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DatasetInput.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/DatasetInput.h	(revision 16137)
@@ -33,5 +33,5 @@
 		/*DatasetInput management: {{{*/
 		int    InstanceEnum();
-		Input* SpawnTriaInput(int* indices);
+		Input* SpawnTriaInput(int location);
 		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
@@ -50,5 +50,5 @@
 		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
 		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index);
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index);
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
 		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
@@ -61,6 +61,6 @@
 		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype){_error_("not implemented yet");};
 		void SquareMin(IssmDouble* psquaremin,Parameters* parameters){_error_("not implemented yet");};
Index: /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/DoubleInput.cpp	(revision 16137)
@@ -72,5 +72,5 @@
 /*}}}*/
 /*FUNCTION DoubleInput::SpawnTriaInput{{{*/
-Input* DoubleInput::SpawnTriaInput(int* indices){
+Input* DoubleInput::SpawnTriaInput(int location){
 
 	/*output*/
@@ -156,12 +156,12 @@
 }
 /*}}}*/
-/*FUNCTION DoubleInput::GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
-void DoubleInput::GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){
+/*FUNCTION DoubleInput::GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){
 	/*Epsilon is zero as vx is constant over the element*/
 	for(int i=0;i<5;i++) epsilonvx[i]=0;
 }
 /*}}}*/
-/*FUNCTION DoubleInput::GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
-void DoubleInput::GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){
+/*FUNCTION DoubleInput::GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void DoubleInput::GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){
 	/*Epsilon is zero as vy is constant over the element*/
 	for(int i=0;i<5;i++) epsilonvy[i]=0;
@@ -263,5 +263,5 @@
 	switch(thickness_input->ObjectEnum()){
 
-		case PentaP1InputEnum:
+		case PentaInputEnum:
 			thickness_input->GetInputAverage(&thickness_value);
 			this->value=this->value*thickness_value;
Index: /issm/trunk/src/c/classes/Inputs/DoubleInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/DoubleInput.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/DoubleInput.h	(revision 16137)
@@ -33,5 +33,5 @@
 		/*DoubleInput management: {{{*/
 		int   InstanceEnum();
-		Input* SpawnTriaInput(int* indices);
+		Input* SpawnTriaInput(int location);
 		Input* PointwiseDivide(Input* inputB);
 		Input* PointwiseMin(Input* inputB);
@@ -61,6 +61,6 @@
 		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss);
 		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss);
 		void ChangeEnum(int newenumtype);
 		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
Index: /issm/trunk/src/c/classes/Inputs/Input.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Input.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/Input.h	(revision 16137)
@@ -44,6 +44,6 @@
 		virtual void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss)=0;
 		virtual void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss)=0;
-		virtual void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss)=0;
-		virtual void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss)=0;
+		virtual void GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss)=0;
+		virtual void GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss)=0;
 		virtual void ChangeEnum(int newenumtype)=0;
 		virtual void Configure(Parameters* parameters)=0;
@@ -64,5 +64,5 @@
 		virtual void   GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist)=0;
 
-		virtual Input* SpawnTriaInput(int* indices)=0;
+		virtual Input* SpawnTriaInput(int location)=0;
 		virtual Input* PointwiseDivide(Input* inputB)=0;
 		virtual Input* PointwiseMax(Input* inputmax)=0;
Index: /issm/trunk/src/c/classes/Inputs/Inputs.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/Inputs.cpp	(revision 16137)
@@ -370,5 +370,5 @@
 /*}}}*/
 /*FUNCTION Inputs::SpawnTriaInputs{{{*/
-Inputs* Inputs::SpawnTriaInputs(int* indices){
+Inputs* Inputs::SpawnTriaInputs(int location){
 
 	/*Intermediary*/
@@ -385,5 +385,5 @@
 		/*Create new input*/
 		inputin=dynamic_cast<Input*>(*object);
-		inputout=inputin->SpawnTriaInput(indices);
+		inputout=inputin->SpawnTriaInput(location);
 
 		/*Add input to new inputs*/
Index: /issm/trunk/src/c/classes/Inputs/Inputs.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/Inputs.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/Inputs.h	(revision 16137)
@@ -28,5 +28,5 @@
 		void       DuplicateInput(int original_enum,int new_enum);
 		Input*     GetInput(int enum_name);
-		Inputs*    SpawnTriaInputs(int* indices);
+		Inputs*    SpawnTriaInputs(int position);
 		void       AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum);
 		IssmDouble  InfinityNorm(int enumtype);
Index: /issm/trunk/src/c/classes/Inputs/IntInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/IntInput.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/IntInput.cpp	(revision 16137)
@@ -72,5 +72,5 @@
 /*}}}*/
 /*FUNCTION IntInput::SpawnTriaInput{{{*/
-Input* IntInput::SpawnTriaInput(int* indices){
+Input* IntInput::SpawnTriaInput(int location){
 
 	/*output*/
Index: /issm/trunk/src/c/classes/Inputs/IntInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/IntInput.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/IntInput.h	(revision 16137)
@@ -34,5 +34,5 @@
 		/*IntInput management: {{{*/
 		int   InstanceEnum();
-		Input* SpawnTriaInput(int* indices);
+		Input* SpawnTriaInput(int location);
 		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* inputB){_error_("not implemented yet");};
@@ -63,6 +63,6 @@
 		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype);
 		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
Index: /issm/trunk/src/c/classes/Inputs/PentaInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaInput.cpp	(revision 16137)
+++ /issm/trunk/src/c/classes/Inputs/PentaInput.cpp	(revision 16137)
@@ -0,0 +1,561 @@
+/*!\file PentaInput.c
+ * \brief: implementation of the PentaInput object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes.h"
+#include "../../shared/shared.h"
+
+/*PentaInput constructors and destructor*/
+/*FUNCTION PentaInput::PentaInput(){{{*/
+PentaInput::PentaInput(){
+	values = NULL;
+}
+/*}}}*/
+/*FUNCTION PentaInput::PentaInput(int in_enum_type,IssmDouble* values,int element_type){{{*/
+PentaInput::PentaInput(int in_enum_type,IssmDouble* in_values,int element_type_in)
+		:PentaRef(1)
+{
+
+	/*Set PentaRef*/
+	this->SetElementType(element_type_in,0);
+	this->element_type=element_type_in;
+
+	/*Set Enum*/
+	enum_type=in_enum_type;
+
+	/*Set values*/
+	this->values=xNew<IssmDouble>(this->NumberofNodes());
+	for(int i=0;i<this->NumberofNodes();i++) values[i]=in_values[i];
+}
+/*}}}*/
+/*FUNCTION PentaInput::~PentaInput(){{{*/
+PentaInput::~PentaInput(){
+	xDelete<IssmDouble>(this->values);
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION PentaInput::Echo {{{*/
+void PentaInput::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION PentaInput::DeepEcho{{{*/
+void PentaInput::DeepEcho(void){
+
+	_printf_("PentaInput:\n");
+	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
+	_printf_("   values: [");
+	for(int i=0;i<this->NumberofNodes();i++) _printf_(" "<<this->values[i]);
+	_printf_("]\n");
+}
+/*}}}*/
+/*FUNCTION PentaInput::Id{{{*/
+int    PentaInput::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION PentaInput::ObjectEnum{{{*/
+int PentaInput::ObjectEnum(void){
+
+	return PentaInputEnum;
+
+}
+/*}}}*/
+/*FUNCTION PentaInput::copy{{{*/
+Object* PentaInput::copy() {
+
+	return new PentaInput(this->enum_type,this->values,this->element_type);
+
+}
+/*}}}*/
+
+/*PentaInput management*/
+/*FUNCTION PentaInput::InstanceEnum{{{*/
+int PentaInput::InstanceEnum(void){
+
+	return this->enum_type;
+
+}
+/*}}}*/
+/*FUNCTION PentaInput::SpawnTriaInput{{{*/
+Input* PentaInput::SpawnTriaInput(int location){
+
+	/*output*/
+	TriaInput* outinput=NULL;
+	IssmDouble newvalues[3]; //Assume P1 interpolation only for now
+
+	/*Create arrow of indices depending on location (0=base 1=surface)*/
+	int indices[3];
+	switch(location){
+		case 0:
+			indices[0] = 0;
+			indices[1] = 1;
+			indices[2] = 2;
+			break;
+		case 1:
+			indices[0] = 3;
+			indices[1] = 4;
+			indices[2] = 5;
+			break;
+		default:
+			_error_("case "<<location<<" not supported");
+	}
+
+	/*Loop over the new indices*/
+	for(int i=0;i<3;i++){
+
+		/*Check index value*/
+		_assert_(indices[i]>=0 && indices[i]<6);
+
+		/*Assign value to new input*/
+		newvalues[i]=this->values[indices[i]];
+	}
+
+	/*Create new Tria input*/
+	outinput=new TriaInput(this->enum_type,&newvalues[0],P1Enum);
+
+	/*Assign output*/
+	return outinput;
+}
+/*}}}*/
+/*FUNCTION PentaInput::SpawnResult{{{*/
+ElementResult* PentaInput::SpawnResult(int step, IssmDouble time){
+
+	return new PentaP1ElementResult(this->enum_type,this->values,step,time);
+
+}
+/*}}}*/
+
+/*Object functions*/
+/*FUNCTION PentaInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
+void PentaInput::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){
+
+	/*Call PentaRef function*/
+	PentaRef::GetInputValue(pvalue,&values[0],gauss);
+
+}
+/*}}}*/
+/*FUNCTION PentaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
+void PentaInput::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussPenta* gauss){
+
+	/*Call PentaRef function*/
+	PentaRef::GetInputDerivativeValue(p,&values[0],xyz_list,gauss);
+}
+/*}}}*/
+/*FUNCTION PentaInput::GetVxStrainRate3d{{{*/
+void PentaInput::GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){
+
+	/*Intermediary*/
+	int         numnodes=this->NumberofNodes();
+	IssmDouble* B=xNew<IssmDouble>(numnodes*(NDOF3*numnodes));
+	IssmDouble* velocity=xNew<IssmDouble>(numnodes*NDOF3);
+
+	/*Get B matrix: */
+	GetBFSstrainrate(B,xyz_list,gauss);
+
+	/*Here, we are computing the strain rate of (vx,0,0)*/
+	for(int i=0;i<numnodes;i++){
+		velocity[NDOF3*i+0]=this->values[i];
+		velocity[NDOF3*i+1]=0.;
+		velocity[NDOF3*i+2]=0.;
+	}
+	/*Multiply B by velocity, to get strain rate: */
+	MatrixMultiply(B,numnodes,NDOF3*numnodes,0,velocity,NDOF3*numnodes,1,0,epsilonvx,0);
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(velocity);
+
+}
+/*}}}*/
+/*FUNCTION PentaInput::GetVyStrainRate3d{{{*/
+void PentaInput::GetVyStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){
+
+	/*Intermediary*/
+	int         numnodes=this->NumberofNodes();
+	IssmDouble* B=xNew<IssmDouble>(numnodes*(NDOF3*numnodes));
+	IssmDouble* velocity=xNew<IssmDouble>(numnodes*NDOF3);
+
+	/*Get B matrix: */
+	GetBFSstrainrate(B,xyz_list,gauss);
+
+	/*Here, we are computing the strain rate of (0,vy,0)*/
+	for(int i=0;i<numnodes;i++){
+		velocity[NDOF3*i+0]=0.;
+		velocity[NDOF3*i+1]=this->values[i];
+		velocity[NDOF3*i+2]=0.;
+	}
+	/*Multiply B by velocity, to get strain rate: */
+	MatrixMultiply(B,numnodes,NDOF3*numnodes,0,velocity,NDOF3*numnodes,1,0,epsilonvx,0);
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(velocity);
+}
+/*}}}*/
+/*FUNCTION PentaInput::GetVzStrainRate3d{{{*/
+void PentaInput::GetVzStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){
+
+	/*Intermediary*/
+	int         numnodes=this->NumberofNodes();
+	IssmDouble* B=xNew<IssmDouble>(numnodes*(NDOF3*numnodes));
+	IssmDouble* velocity=xNew<IssmDouble>(numnodes*NDOF3);
+
+	/*Get B matrix: */
+	GetBFSstrainrate(B,xyz_list,gauss);
+
+	/*Here, we are computing the strain rate of (0,0,vz)*/
+	for(int i=0;i<numnodes;i++){
+		velocity[NDOF3*i+0]=0.;
+		velocity[NDOF3*i+1]=0.;
+		velocity[NDOF3*i+2]=this->values[i];
+	}
+	/*Multiply B by velocity, to get strain rate: */
+	MatrixMultiply(B,numnodes,NDOF3*numnodes,0,velocity,NDOF3*numnodes,1,0,epsilonvx,0);
+
+	/*Clean-up*/
+	xDelete<IssmDouble>(B);
+	xDelete<IssmDouble>(velocity);
+}
+/*}}}*/
+/*FUNCTION PentaInput::GetVxStrainRate3dHO{{{*/
+void PentaInput::GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){
+
+	int i;
+	const int numnodes=6;
+	IssmDouble B[5][NDOF2*numnodes];
+	IssmDouble velocity[numnodes][NDOF2];
+
+	/*Get B matrix: */
+	GetBHO(&B[0][0], xyz_list, gauss);
+
+	_assert_(this->NumberofNodes()==6); //Check Tria too
+
+	/*Here, we are computing the strain rate of (vx,0)*/
+	for(i=0;i<numnodes;i++){
+		velocity[i][0]=this->values[i];
+		velocity[i][1]=0.0;
+	}
+
+	/*Multiply B by velocity, to get strain rate: */
+	MatrixMultiply( &B[0][0],5,NDOF2*numnodes,0,
+				&velocity[0][0],NDOF2*numnodes,1,0,
+				epsilonvx,0);
+
+}
+/*}}}*/
+/*FUNCTION PentaInput::GetVyStrainRate3dHO{{{*/
+void PentaInput::GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){
+
+	int i;
+	const int numnodes=6;
+	IssmDouble B[5][NDOF2*numnodes];
+	IssmDouble velocity[numnodes][NDOF2];
+
+	/*Get B matrix: */
+	GetBHO(&B[0][0], xyz_list, gauss);
+	_assert_(this->NumberofNodes()==6); //Check Tria too
+
+	/*Here, we are computing the strain rate of (0,vy)*/
+	for(i=0;i<numnodes;i++){
+		velocity[i][0]=0.0;
+		velocity[i][1]=this->values[i];
+	}
+
+	/*Multiply B by velocity, to get strain rate: */
+	MatrixMultiply( &B[0][0],5,NDOF2*numnodes,0,
+				&velocity[0][0],NDOF2*numnodes,1,0,
+				epsilonvy,0);
+
+}
+/*}}}*/
+/*FUNCTION PentaInput::ChangeEnum{{{*/
+void PentaInput::ChangeEnum(int newenumtype){
+	this->enum_type=newenumtype;
+}
+/*}}}*/
+/*FUNCTION PentaInput::GetInputAverage{{{*/
+void PentaInput::GetInputAverage(IssmDouble* pvalue){
+
+	int        numnodes  = this->NumberofNodes();
+	IssmDouble numnodesd = reCast<int,IssmDouble>(numnodes);
+	IssmDouble value     = 0.;
+
+	for(int i=0;i<numnodes;i++) value+=values[i];
+	value = value/numnodesd;
+
+	*pvalue=value;
+}
+/*}}}*/
+
+/*Intermediary*/
+/*FUNCTION PentaInput::SquareMin{{{*/
+void PentaInput::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
+
+	int        numnodes=this->NumberofNodes();
+	IssmDouble squaremin;
+
+	/*Now, figure out minimum of valuescopy: */
+	squaremin=pow(this->values[0],2);
+	for(int i=1;i<numnodes;i++){
+		if(pow(this->values[i],2)<squaremin)squaremin=pow(this->values[i],2);
+	}
+	/*Assign output pointers:*/
+	*psquaremin=squaremin;
+}
+/*}}}*/
+/*FUNCTION PentaInput::ConstrainMin{{{*/
+void PentaInput::ConstrainMin(IssmDouble minimum){
+
+	int numnodes = this->NumberofNodes();
+	for(int i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
+}
+/*}}}*/
+/*FUNCTION PentaInput::InfinityNorm{{{*/
+IssmDouble PentaInput::InfinityNorm(void){
+
+	/*Output*/
+	IssmDouble norm=0.;
+	int numnodes=this->NumberofNodes();
+
+	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
+	return norm;
+}
+/*}}}*/
+/*FUNCTION PentaInput::Max{{{*/
+IssmDouble PentaInput::Max(void){
+
+	int  numnodes=this->NumberofNodes();
+	IssmDouble max=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]>max) max=values[i];
+	}
+	return max;
+}
+/*}}}*/
+/*FUNCTION PentaInput::MaxAbs{{{*/
+IssmDouble PentaInput::MaxAbs(void){
+
+	int  numnodes=this->NumberofNodes();
+	IssmDouble max=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])>max) max=fabs(values[i]);
+	}
+	return max;
+}
+/*}}}*/
+/*FUNCTION PentaInput::Min{{{*/
+IssmDouble PentaInput::Min(void){
+
+	const int  numnodes=this->NumberofNodes();
+	IssmDouble min=values[0];
+
+	for(int i=1;i<numnodes;i++){
+		if(values[i]<min) min=values[i];
+	}
+	return min;
+}
+/*}}}*/
+/*FUNCTION PentaInput::MinAbs{{{*/
+IssmDouble PentaInput::MinAbs(void){
+
+	const int  numnodes=this->NumberofNodes();
+	IssmDouble min=fabs(values[0]);
+
+	for(int i=1;i<numnodes;i++){
+		if(fabs(values[i])<min) min=fabs(values[i]);
+	}
+	return min;
+}
+/*}}}*/
+/*FUNCTION PentaInput::Scale{{{*/
+void PentaInput::Scale(IssmDouble scale_factor){
+
+	const int numnodes=this->NumberofNodes();
+	for(int i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
+}
+/*}}}*/
+/*FUNCTION PentaInput::AXPY{{{*/
+void PentaInput::AXPY(Input* xinput,IssmDouble scalar){
+
+	const int numnodes=this->NumberofNodes();
+	PentaInput* xpentainput=NULL;
+
+	/*If xinput is a ControlInput, take its values directly*/
+	if(xinput->ObjectEnum()==ControlInputEnum){
+		xinput=((ControlInput*)xinput)->values;
+	}
+
+	/*xinput is of the same type, so cast it: */
+	if(xinput->ObjectEnum()!=PentaInputEnum)
+	  _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
+	xpentainput=(PentaInput*)xinput;
+	if(xpentainput->element_type!=this->element_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xpentainput->element_type));
+
+	/*Carry out the AXPY operation depending on type:*/
+	for(int i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*xpentainput->values[i];
+
+}
+/*}}}*/
+/*FUNCTION PentaInput::Constrain{{{*/
+void PentaInput::Constrain(IssmDouble cm_min, IssmDouble cm_max){
+
+	int i;
+	const int numnodes=this->NumberofNodes();
+
+	if(!xIsNan<IssmDouble>(cm_min)) for(i=0;i<numnodes;i++)if (this->values[i]<cm_min)this->values[i]=cm_min;
+	if(!xIsNan<IssmDouble>(cm_max)) for(i=0;i<numnodes;i++)if (this->values[i]>cm_max)this->values[i]=cm_max;
+
+}
+/*}}}*/
+/*FUNCTION PentaInput::Extrude{{{*/
+void PentaInput::Extrude(void){
+
+	switch(this->element_type){
+		case P1Enum:
+			for(int i=0;i<3;i++) this->values[3+i]=this->values[i];
+			break;
+		default:
+			_error_("not supported yet for type "<<EnumToStringx(this->element_type));
+	}
+}
+/*}}}*/
+/*FUNCTION PentaInput::VerticallyIntegrate{{{*/
+void PentaInput::VerticallyIntegrate(Input* thickness_input){
+
+	IssmDouble thickness;
+
+	/*Check that input provided is a thickness*/
+	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
+
+	/*vertically integrate depending on type:*/
+	switch(this->element_type){
+		case P1Enum:{
+			GaussPenta *gauss=new GaussPenta();
+			for(int iv=0;iv<3;iv++){
+				gauss->GaussVertex(iv);
+				thickness_input->GetInputValue(&thickness,gauss);
+				this->values[iv]=0.5*(this->values[iv]+this->values[iv+3]) * thickness;
+				this->values[iv+3]=this->values[iv];
+			}
+			delete gauss;
+			return; }
+		default:
+			_error_("not supported yet for type "<<EnumToStringx(this->element_type));
+	}
+}
+/*}}}*/
+/*FUNCTION PentaInput::PointwiseDivide{{{*/
+Input* PentaInput::PointwiseDivide(Input* inputB){
+
+	/*Ouput*/
+	PentaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	PentaInput *xinputB  = NULL;
+	const int   numnodes = this->NumberofNodes();
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=PentaInputEnum)     _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaInput*)inputB;
+	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+
+	/*Allocate intermediary*/
+	IssmDouble* AdotBvalues=xNew<IssmDouble>(numnodes);
+
+	/*Create point wise sum*/
+	for(int i=0;i<numnodes;i++){
+		_assert_(xinputB->values[i]!=0);
+		AdotBvalues[i]=this->values[i]/xinputB->values[i];
+	}
+
+	/*Create new Penta vertex input (copy of current input)*/
+	outinput=new PentaInput(this->enum_type,AdotBvalues,this->element_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(AdotBvalues);
+	return outinput;
+
+}
+/*}}}*/
+/*FUNCTION PentaInput::PointwiseMin{{{*/
+Input* PentaInput::PointwiseMin(Input* inputB){
+
+	/*Ouput*/
+	PentaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	int         i;
+	PentaInput  *xinputB   = NULL;
+	const int   numnodes  = this->NumberofNodes();
+	IssmDouble *minvalues = xNew<IssmDouble>(numnodes);
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=PentaInputEnum)       _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaInput*)inputB;
+	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+
+	/*Create point wise min*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] > xinputB->values[i]) minvalues[i]=xinputB->values[i];
+		else minvalues[i]=this->values[i];
+	}
+
+	/*Create new Penta vertex input (copy of current input)*/
+	outinput=new PentaInput(this->enum_type,&minvalues[0],this->element_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(minvalues);
+	return outinput;
+}
+/*}}}*/
+/*FUNCTION PentaInput::PointwiseMax{{{*/
+Input* PentaInput::PointwiseMax(Input* inputB){
+
+	/*Ouput*/
+	PentaInput* outinput=NULL;
+
+	/*Intermediaries*/
+	int         i;
+	PentaInput  *xinputB   = NULL;
+	const int   numnodes  = this->NumberofNodes();
+	IssmDouble *maxvalues = xNew<IssmDouble>(numnodes);
+
+	/*Check that inputB is of the same type*/
+	if(inputB->ObjectEnum()!=PentaInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	xinputB=(PentaInput*)inputB;
+	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
+
+	/*Create point wise max*/
+	for(i=0;i<numnodes;i++){
+		if(this->values[i] < xinputB->values[i]) maxvalues[i]=xinputB->values[i];
+		else maxvalues[i]=this->values[i];
+	}
+
+	/*Create new Penta vertex input (copy of current input)*/
+	outinput=new PentaInput(this->enum_type,&maxvalues[0],this->element_type);
+
+	/*Return output pointer*/
+	xDelete<IssmDouble>(maxvalues);
+	return outinput;
+}
+/*}}}*/
+/*FUNCTION PentaInput::GetVectorFromInputs{{{*/
+void PentaInput::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
+
+	const int numnodes=this->NumberofNodes();
+	vector->SetValues(numnodes,doflist,this->values,INS_VAL);
+
+} /*}}}*/
+/*FUNCTION PentaInput::Configure{{{*/
+void PentaInput::Configure(Parameters* parameters){
+	/*do nothing: */
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Inputs/PentaInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaInput.h	(revision 16137)
+++ /issm/trunk/src/c/classes/Inputs/PentaInput.h	(revision 16137)
@@ -0,0 +1,84 @@
+/*! \file PentaInput.h 
+ *  \brief: header file for PentaInput object
+ */
+
+#ifndef _PENTAINPUT_H_
+#define _PENTAINPUT_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Input.h"
+#include "../Elements/PentaRef.h"
+class GaussTria;
+class GaussPenta;
+/*}}}*/
+
+class PentaInput: public Input, public PentaRef{
+
+	public:
+		int        enum_type;
+		IssmDouble* values;
+
+		/*PentaInput constructors, destructors*/
+		PentaInput();
+		PentaInput(int enum_type,IssmDouble* values,int element_type_in);
+		~PentaInput();
+
+		/*Object virtual functions definitions */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
+
+		/*PentaInput management*/
+		int   InstanceEnum();
+		Input* SpawnTriaInput(int location);
+		Input* PointwiseDivide(Input* inputB);
+		Input* PointwiseMin(Input* inputB);
+		Input* PointwiseMax(Input* inputB);
+		ElementResult* SpawnResult(int step, IssmDouble time);
+		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
+		void Configure(Parameters* parameters);
+		/*numerics*/
+		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,GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
+		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetInputAverage(IssmDouble* pvalue);
+		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
+		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
+
+		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss);
+		void GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss);
+		void ChangeEnum(int newenumtype);
+
+		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
+		void ConstrainMin(IssmDouble minimum);
+		void Scale(IssmDouble scale_factor);
+		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
+		void AXPY(Input* xinput,IssmDouble scalar);
+		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
+		IssmDouble InfinityNorm(void);
+		IssmDouble Max(void);
+		IssmDouble MaxAbs(void);
+		IssmDouble Min(void);
+		IssmDouble MinAbs(void);
+		void Extrude(void);
+		void VerticallyIntegrate(Input* thickness_input);
+		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
+
+};
+#endif  /* _PENTAINPUT_H */
Index: sm/trunk/src/c/classes/Inputs/PentaP1Input.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaP1Input.cpp	(revision 16136)
+++ 	(revision )
@@ -1,600 +1,0 @@
-/*!\file PentaP1Input.c
- * \brief: implementation of the PentaP1Input object
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "../classes.h"
-#include "../../shared/shared.h"
-
-/*PentaP1Input constructors and destructor*/
-/*FUNCTION PentaP1Input::PentaP1Input(){{{*/
-PentaP1Input::PentaP1Input(){
-	return;
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::PentaP1Input(int in_enum_type,IssmDouble* values){{{*/
-PentaP1Input::PentaP1Input(int in_enum_type,IssmDouble* in_values)
-		:PentaRef(1)
-{
-
-	/*Set PentaRef*/
-	this->SetElementType(P1Enum,0);
-	this->element_type=P1Enum;
-
-	enum_type=in_enum_type;
-	values[0]=in_values[0];
-	values[1]=in_values[1];
-	values[2]=in_values[2];
-	values[3]=in_values[3];
-	values[4]=in_values[4];
-	values[5]=in_values[5];
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::~PentaP1Input(){{{*/
-PentaP1Input::~PentaP1Input(){
-	return;
-}
-/*}}}*/
-
-/*Object virtual functions definitions:*/
-/*FUNCTION PentaP1Input::Echo {{{*/
-void PentaP1Input::Echo(void){
-	this->DeepEcho();
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::DeepEcho{{{*/
-void PentaP1Input::DeepEcho(void){
-
-	_printf_("PentaP1Input:\n");
-	_printf_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")\n");
-	_printf_("   values: [" << this->values[0] << " " << this->values[1] << " " << this->values[2] << " " << this->values[3] << " " << this->values[4] << " " << this->values[5] << "]\n");
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::Id{{{*/
-int    PentaP1Input::Id(void){ return -1; }
-/*}}}*/
-/*FUNCTION PentaP1Input::ObjectEnum{{{*/
-int PentaP1Input::ObjectEnum(void){
-
-	return PentaP1InputEnum;
-
-}
-/*}}}*/
-
-/*PentaP1Input management*/
-/*FUNCTION PentaP1Input::copy{{{*/
-Object* PentaP1Input::copy() {
-
-	return new PentaP1Input(this->enum_type,this->values);
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::InstanceEnum{{{*/
-int PentaP1Input::InstanceEnum(void){
-
-	return this->enum_type;
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::SpawnTriaInput{{{*/
-Input* PentaP1Input::SpawnTriaInput(int* indices){
-
-	/*output*/
-	TriaInput* outinput=NULL;
-	IssmDouble newvalues[3];
-
-	/*Loop over the new indices*/
-	for(int i=0;i<3;i++){
-
-		/*Check index value*/
-		_assert_(indices[i]>=0 && indices[i]<6);
-
-		/*Assign value to new input*/
-		newvalues[i]=this->values[indices[i]];
-	}
-
-	/*Create new Tria input*/
-	outinput=new TriaInput(this->enum_type,&newvalues[0],P1Enum);
-
-	/*Assign output*/
-	return outinput;
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::SpawnResult{{{*/
-ElementResult* PentaP1Input::SpawnResult(int step, IssmDouble time){
-
-	return new PentaP1ElementResult(this->enum_type,this->values,step,time);
-
-}
-/*}}}*/
-
-/*Object functions*/
-/*FUNCTION PentaP1Input::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){{{*/
-void PentaP1Input::GetInputValue(IssmDouble* pvalue,GaussPenta* gauss){
-
-	/*Call PentaRef function*/
-	PentaRef::GetInputValue(pvalue,&values[0],gauss);
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussPenta* gauss){{{*/
-void PentaP1Input::GetInputDerivativeValue(IssmDouble* p, IssmDouble* xyz_list, GaussPenta* gauss){
-
-	/*Call PentaRef function*/
-	PentaRef::GetInputDerivativeValue(p,&values[0],xyz_list,gauss);
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::GetVxStrainRate3d{{{*/
-void PentaP1Input::GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){
-	int i,j;
-
-	const int numnodes=6;
-	const int DOFVELOCITY=3;
-	IssmDouble B[8][27];
-	IssmDouble B_reduced[6][DOFVELOCITY*numnodes];
-	IssmDouble velocity[numnodes][DOFVELOCITY];
-
-	/*Get B matrix: */
-	GetBStokes(&B[0][0], xyz_list, gauss);
-	/*Create a reduced matrix of B to get rid of pressure */
-	for (i=0;i<6;i++){
-		for (j=0;j<3;j++){
-			B_reduced[i][j]=B[i][j];
-		}
-		for (j=4;j<7;j++){
-			B_reduced[i][j-1]=B[i][j];
-		}
-		for (j=8;j<11;j++){
-			B_reduced[i][j-2]=B[i][j];
-		}
-		for (j=12;j<15;j++){
-			B_reduced[i][j-3]=B[i][j];
-		}
-		for (j=16;j<19;j++){
-			B_reduced[i][j-4]=B[i][j];
-		}
-		for (j=20;j<23;j++){
-			B_reduced[i][j-5]=B[i][j];
-		}
-	}
-
-	/*Here, we are computing the strain rate of (vx,0,0)*/
-	for(i=0;i<numnodes;i++){
-		velocity[i][0]=this->values[i];
-		velocity[i][1]=0.0;
-		velocity[i][2]=0.0;
-	}
-	/*Multiply B by velocity, to get strain rate: */
-	MatrixMultiply(&B_reduced[0][0],6,DOFVELOCITY*numnodes,0,&velocity[0][0],DOFVELOCITY*numnodes,1,0,epsilonvx,0);
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::GetVyStrainRate3d{{{*/
-void PentaP1Input::GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){
-	int i,j;
-
-	const int numnodes=6;
-	const int DOFVELOCITY=3;
-	IssmDouble B[8][27];
-	IssmDouble B_reduced[6][DOFVELOCITY*numnodes];
-	IssmDouble velocity[numnodes][DOFVELOCITY];
-
-	/*Get B matrix: */
-	GetBStokes(&B[0][0], xyz_list, gauss);
-	/*Create a reduced matrix of B to get rid of pressure */
-	for (i=0;i<6;i++){
-		for (j=0;j<3;j++){
-			B_reduced[i][j]=B[i][j];
-		}
-		for (j=4;j<7;j++){
-			B_reduced[i][j-1]=B[i][j];
-		}
-		for (j=8;j<11;j++){
-			B_reduced[i][j-2]=B[i][j];
-		}
-		for (j=12;j<15;j++){
-			B_reduced[i][j-3]=B[i][j];
-		}
-		for (j=16;j<19;j++){
-			B_reduced[i][j-4]=B[i][j];
-		}
-		for (j=20;j<23;j++){
-			B_reduced[i][j-5]=B[i][j];
-		}
-	}
-
-	/*Here, we are computing the strain rate of (0,vy,0)*/
-	for(i=0;i<numnodes;i++){
-		velocity[i][0]=0.0;
-		velocity[i][1]=this->values[i];
-		velocity[i][2]=0.0;
-	}
-	/*Multiply B by velocity, to get strain rate: */
-	MatrixMultiply(&B_reduced[0][0],6,DOFVELOCITY*numnodes,0,&velocity[0][0],DOFVELOCITY*numnodes,1,0,epsilonvy,0);
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::GetVzStrainRate3d{{{*/
-void PentaP1Input::GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){
-	int i,j;
-
-	const int numnodes=6;
-	const int DOFVELOCITY=3;
-	IssmDouble B[8][27];
-	IssmDouble B_reduced[6][DOFVELOCITY*numnodes];
-	IssmDouble velocity[numnodes][DOFVELOCITY];
-
-	/*Get B matrix: */
-	GetBStokes(&B[0][0], xyz_list, gauss);
-	/*Create a reduced matrix of B to get rid of pressure */
-	for (i=0;i<6;i++){
-		for (j=0;j<3;j++){
-			B_reduced[i][j]=B[i][j];
-		}
-		for (j=4;j<7;j++){
-			B_reduced[i][j-1]=B[i][j];
-		}
-		for (j=8;j<11;j++){
-			B_reduced[i][j-2]=B[i][j];
-		}
-		for (j=12;j<15;j++){
-			B_reduced[i][j-3]=B[i][j];
-		}
-		for (j=16;j<19;j++){
-			B_reduced[i][j-4]=B[i][j];
-		}
-		for (j=20;j<23;j++){
-			B_reduced[i][j-5]=B[i][j];
-		}
-	}
-
-	/*Here, we are computing the strain rate of (0,0,vz)*/
-	for(i=0;i<numnodes;i++){
-		velocity[i][0]=0.0;
-		velocity[i][1]=0.0;
-		velocity[i][2]=this->values[i];
-	}
-
-	/*Multiply B by velocity, to get strain rate: */
-	MatrixMultiply(&B_reduced[0][0],6,DOFVELOCITY*numnodes,0,&velocity[0][0],DOFVELOCITY*numnodes,1,0,epsilonvz,0);
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::GetVxStrainRate3dPattyn{{{*/
-void PentaP1Input::GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){
-
-	int i;
-	const int numnodes=6;
-	IssmDouble B[5][NDOF2*numnodes];
-	IssmDouble velocity[numnodes][NDOF2];
-
-	/*Get B matrix: */
-	GetBPattyn(&B[0][0], xyz_list, gauss);
-
-	/*Here, we are computing the strain rate of (vx,0)*/
-	for(i=0;i<numnodes;i++){
-		velocity[i][0]=this->values[i];
-		velocity[i][1]=0.0;
-	}
-
-	/*Multiply B by velocity, to get strain rate: */
-	MatrixMultiply( &B[0][0],5,NDOF2*numnodes,0,
-				&velocity[0][0],NDOF2*numnodes,1,0,
-				epsilonvx,0);
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::GetVyStrainRate3dPattyn{{{*/
-void PentaP1Input::GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){
-
-	int i;
-	const int numnodes=6;
-	IssmDouble B[5][NDOF2*numnodes];
-	IssmDouble velocity[numnodes][NDOF2];
-
-	/*Get B matrix: */
-	GetBPattyn(&B[0][0], xyz_list, gauss);
-
-	/*Here, we are computing the strain rate of (0,vy)*/
-	for(i=0;i<numnodes;i++){
-		velocity[i][0]=0.0;
-		velocity[i][1]=this->values[i];
-	}
-
-	/*Multiply B by velocity, to get strain rate: */
-	MatrixMultiply( &B[0][0],5,NDOF2*numnodes,0,
-				&velocity[0][0],NDOF2*numnodes,1,0,
-				epsilonvy,0);
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::ChangeEnum{{{*/
-void PentaP1Input::ChangeEnum(int newenumtype){
-	this->enum_type=newenumtype;
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::GetInputAverage{{{*/
-void PentaP1Input::GetInputAverage(IssmDouble* pvalue){
-	*pvalue=1./6.*(values[0]+values[1]+values[2]+values[3]+values[4]+values[5]);
-}
-/*}}}*/
-
-/*Intermediary*/
-/*FUNCTION PentaP1Input::SquareMin{{{*/
-void PentaP1Input::SquareMin(IssmDouble* psquaremin,Parameters* parameters){
-
-	int i;
-	const int numnodes=6;
-	IssmDouble valuescopy[numnodes];
-	IssmDouble squaremin;
-
-	/*First,  copy values, to process units if requested: */
-	for(i=0;i<numnodes;i++)valuescopy[i]=this->values[i];
-
-	/*Now, figure out minimum of valuescopy: */
-	squaremin=pow(valuescopy[0],2);
-	for(i=1;i<numnodes;i++){
-		if(pow(valuescopy[i],2)<squaremin)squaremin=pow(valuescopy[i],2);
-	}
-	/*Assign output pointers:*/
-	*psquaremin=squaremin;
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::ConstrainMin{{{*/
-void PentaP1Input::ConstrainMin(IssmDouble minimum){
-
-	int i;
-	const int numnodes=6;
-
-	for(i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::InfinityNorm{{{*/
-IssmDouble PentaP1Input::InfinityNorm(void){
-
-	/*Output*/
-	const int numnodes=6;
-	IssmDouble norm=0;
-
-	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
-	return norm;
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::Max{{{*/
-IssmDouble PentaP1Input::Max(void){
-
-	const int numnodes=6;
-	IssmDouble    max=values[0];
-
-	for(int i=1;i<numnodes;i++){
-		if(values[i]>max) max=values[i];
-	}
-	return max;
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::MaxAbs{{{*/
-IssmDouble PentaP1Input::MaxAbs(void){
-
-	const int numnodes=6;
-	IssmDouble    max=fabs(values[0]);
-
-	for(int i=1;i<numnodes;i++){
-		if(fabs(values[i])>max) max=fabs(values[i]);
-	}
-	return max;
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::Min{{{*/
-IssmDouble PentaP1Input::Min(void){
-
-	const int numnodes=6;
-	IssmDouble    min=values[0];
-
-	for(int i=1;i<numnodes;i++){
-		if(values[i]<min) min=values[i];
-	}
-	return min;
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::MinAbs{{{*/
-IssmDouble PentaP1Input::MinAbs(void){
-
-	const int numnodes=6;
-	IssmDouble    min=fabs(values[0]);
-
-	for(int i=1;i<numnodes;i++){
-		if(fabs(values[i])<min) min=fabs(values[i]);
-	}
-	return min;
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::Scale{{{*/
-void PentaP1Input::Scale(IssmDouble scale_factor){
-
-	int i;
-	const int numnodes=6;
-
-	for(i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::AXPY{{{*/
-void PentaP1Input::AXPY(Input* xinput,IssmDouble scalar){
-
-	int i;
-	const int numnodes=6;
-
-	/*xinput is of the same type, so cast it: */
-
-	/*Carry out the AXPY operation depending on type:*/
-	switch(xinput->ObjectEnum()){
-
-		case PentaP1InputEnum:{
-			PentaP1Input* cast_input=(PentaP1Input*)xinput;
-			for(i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*(cast_input->values[i]);}
-			return;
-		case ControlInputEnum:{
-			ControlInput* cont_input=(ControlInput*)xinput;
-			if(cont_input->values->ObjectEnum()!=PentaP1InputEnum) _error_("not supported yet");
-			PentaP1Input* cast_input=(PentaP1Input*)cont_input->values;
-			for(i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*(cast_input->values[i]);}
-			return;
-		default:
-			_error_("not implemented yet");
-	}
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::Constrain{{{*/
-void PentaP1Input::Constrain(IssmDouble cm_min, IssmDouble cm_max){
-
-	int i;
-	const int numnodes=6;
-
-	if(!xIsNan<IssmDouble>(cm_min)) for(i=0;i<numnodes;i++)if (this->values[i]<cm_min)this->values[i]=cm_min;
-	if(!xIsNan<IssmDouble>(cm_max)) for(i=0;i<numnodes;i++)if (this->values[i]>cm_max)this->values[i]=cm_max;
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::Extrude{{{*/
-void PentaP1Input::Extrude(void){
-
-	int i;
-
-	/*First 3 values copied on 3 last values*/
-	for(i=0;i<3;i++) this->values[3+i]=this->values[i];
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::VerticallyIntegrate{{{*/
-void PentaP1Input::VerticallyIntegrate(Input* thickness_input){
-
-	IssmDouble thickness;
-
-	/*Check that input provided is a thickness*/
-	if (thickness_input->InstanceEnum()!=ThicknessEnum) _error_("Input provided is not a Thickness (enum_type is " << EnumToStringx(thickness_input->InstanceEnum()) << ")");
-
-	/*vertically integrate depending on type:*/
-	switch(thickness_input->ObjectEnum()){
-
-		case PentaP1InputEnum:{
-			GaussPenta *gauss=new GaussPenta();
-			for(int iv=0;iv<3;iv++){
-				gauss->GaussVertex(iv);
-				thickness_input->GetInputValue(&thickness,gauss);
-				this->values[iv]=0.5*(this->values[iv]+this->values[iv+3]) * thickness;
-				this->values[iv+3]=this->values[iv];
-			}
-			delete gauss;
-			return; }
-
-		default:
-			_error_("not implemented yet");
-	}
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::PointwiseDivide{{{*/
-Input* PentaP1Input::PointwiseDivide(Input* inputB){
-
-	/*Ouput*/
-	PentaP1Input* outinput=NULL;
-
-	/*Intermediaries*/
-	PentaP1Input *xinputB  = NULL;
-	const int     numnodes = 6;
-	IssmDouble    AdotBvalues[numnodes];
-
-	/*Check that inputB is of the same type*/
-	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(PentaP1Input*)inputB;
-
-	/*Create point wise sum*/
-	for(int i=0;i<numnodes;i++){
-		_assert_(xinputB->values[i]!=0);
-		AdotBvalues[i]=this->values[i]/xinputB->values[i];
-	}
-
-	/*Create new Penta vertex input (copy of current input)*/
-	outinput=new PentaP1Input(this->enum_type,&AdotBvalues[0]);
-
-	/*Return output pointer*/
-	return outinput;
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::PointwiseMin{{{*/
-Input* PentaP1Input::PointwiseMin(Input* inputB){
-
-	/*Ouput*/
-	PentaP1Input* outinput=NULL;
-
-	/*Intermediaries*/
-	int               i;
-	PentaP1Input *xinputB     = NULL;
-	const int         numnodes    = 6;
-	IssmDouble            minvalues[numnodes];
-
-	/*Check that inputB is of the same type*/
-	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(PentaP1Input*)inputB;
-
-	/*Create point wise min*/
-	for(i=0;i<numnodes;i++){
-		if(this->values[i] > xinputB->values[i]) minvalues[i]=xinputB->values[i];
-		else minvalues[i]=this->values[i];
-	}
-
-	/*Create new Penta vertex input (copy of current input)*/
-	outinput=new PentaP1Input(this->enum_type,&minvalues[0]);
-
-	/*Return output pointer*/
-	return outinput;
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::PointwiseMax{{{*/
-Input* PentaP1Input::PointwiseMax(Input* inputB){
-
-	/*Ouput*/
-	PentaP1Input* outinput=NULL;
-
-	/*Intermediaries*/
-	int               i;
-	PentaP1Input *xinputB     = NULL;
-	const int         numnodes    = 6;
-	IssmDouble            maxvalues[numnodes];
-
-	/*Check that inputB is of the same type*/
-	if (inputB->ObjectEnum()!=PentaP1InputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
-	xinputB=(PentaP1Input*)inputB;
-
-	/*Create point wise max*/
-	for(i=0;i<numnodes;i++){
-		if(this->values[i] < xinputB->values[i]) maxvalues[i]=xinputB->values[i];
-		else maxvalues[i]=this->values[i];
-	}
-
-	/*Create new Penta vertex input (copy of current input)*/
-	outinput=new PentaP1Input(this->enum_type,&maxvalues[0]);
-
-	/*Return output pointer*/
-	return outinput;
-
-}
-/*}}}*/
-/*FUNCTION PentaP1Input::GetVectorFromInputs{{{*/
-void PentaP1Input::GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist){
-
-	const int numvertices=6;
-	vector->SetValues(numvertices,doflist,this->values,INS_VAL);
-
-} /*}}}*/
-/*FUNCTION PentaP1Input::Configure{{{*/
-void PentaP1Input::Configure(Parameters* parameters){
-	/*do nothing: */
-}
-/*}}}*/
Index: sm/trunk/src/c/classes/Inputs/PentaP1Input.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/PentaP1Input.h	(revision 16136)
+++ 	(revision )
@@ -1,87 +1,0 @@
-/*! \file PentaP1Input.h 
- *  \brief: header file for PentaP1Input object
- */
-
-#ifndef _PENTAP1INPUT_H_
-#define _PENTAP1INPUT_H_
-
-/*Headers:*/
-/*{{{*/
-#include "./Input.h"
-#include "../Elements/PentaRef.h"
-class GaussTria;
-class GaussPenta;
-/*}}}*/
-
-class PentaP1Input: public Input, public PentaRef{
-
-	public:
-		/*just hold 6 values for 6 vertices: */
-		int        enum_type;
-		IssmDouble values[6];
-
-		/*PentaP1Input constructors, destructors: {{{*/
-		PentaP1Input();
-		PentaP1Input(int enum_type,IssmDouble* values);
-		~PentaP1Input();
-		/*}}}*/
-		/*Object virtual functions definitions:{{{ */
-		void    Echo();
-		void    DeepEcho();
-		int     Id();
-		int     ObjectEnum();
-		Object *copy();
-		/*}}}*/
-		/*PentaP1Input management: {{{*/
-		int   InstanceEnum();
-		Input* SpawnTriaInput(int* indices);
-		Input* PointwiseDivide(Input* inputB);
-		Input* PointwiseMin(Input* inputB);
-		Input* PointwiseMax(Input* inputB);
-		ElementResult* SpawnResult(int step, IssmDouble time);
-		void AddTimeValues(IssmDouble* values,int step,IssmDouble time){_error_("not supported yet");};
-		void Configure(Parameters* parameters);
-		/*}}}*/
-		/*numerics: {{{*/
-		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,GaussTria* gauss){_error_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss);
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss,IssmDouble time){_error_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss,IssmDouble time){_error_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussTria* gauss ,int index){_error_("not implemented yet");};
-		void GetInputValue(IssmDouble* pvalue,GaussPenta* gauss ,int index){_error_("not implemented yet");};
-		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
-		void GetInputDerivativeValue(IssmDouble* derivativevalues, IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetInputAverage(IssmDouble* pvalue);
-		void GetInputAllTimeAverages(IssmDouble** pvalues,IssmDouble** ptimes, int* pnumtimes){_error_("not implemented yet");};
-		void GetInputUpToCurrentTimeAverages(IssmDouble** pvalues, IssmDouble** ptimes, int* pnumtimes, IssmDouble currenttime){_error_("not implemented yet");};
-
-		void GetVxStrainRate2d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
-		void GetVyStrainRate2d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussTria* gauss){_error_("not implemented yet");};
-		void GetVxStrainRate3d(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss);
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss);
-		void ChangeEnum(int newenumtype);
-
-		void SquareMin(IssmDouble* psquaremin,Parameters* parameters);
-		void ConstrainMin(IssmDouble minimum);
-		void Scale(IssmDouble scale_factor);
-		void ArtificialNoise(IssmDouble min,IssmDouble max){_error_("not implemented yet");};
-		void AXPY(Input* xinput,IssmDouble scalar);
-		void Constrain(IssmDouble cm_min, IssmDouble cm_max);
-		IssmDouble InfinityNorm(void);
-		IssmDouble Max(void);
-		IssmDouble MaxAbs(void);
-		IssmDouble Min(void);
-		IssmDouble MinAbs(void);
-		void Extrude(void);
-		void VerticallyIntegrate(Input* thickness_input);
-		void GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist);
-		/*}}}*/
-
-};
-#endif  /* _PENTAP1INPUT_H */
Index: /issm/trunk/src/c/classes/Inputs/TransientInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/TransientInput.cpp	(revision 16137)
@@ -108,5 +108,5 @@
 /*}}}*/
 /*FUNCTION TransientInput::SpawnTriaInput{{{*/
-Input* TransientInput::SpawnTriaInput(int* indices){
+Input* TransientInput::SpawnTriaInput(int location){
 
 	/*output*/
@@ -119,5 +119,5 @@
 	outinput->timesteps=xNew<IssmDouble>(this->numtimesteps);
 	xMemCpy(outinput->timesteps,this->timesteps,this->numtimesteps);
-	outinput->inputs=(Inputs*)this->inputs->SpawnTriaInputs(indices);
+	outinput->inputs=(Inputs*)this->inputs->SpawnTriaInputs(location);
 	outinput->parameters=this->parameters;
 
Index: /issm/trunk/src/c/classes/Inputs/TransientInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TransientInput.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/TransientInput.h	(revision 16137)
@@ -38,5 +38,5 @@
 		/*TransientInput management: {{{*/
 		int    InstanceEnum();
-		Input* SpawnTriaInput(int* indices);
+		Input* SpawnTriaInput(int location);
 		Input* PointwiseDivide(Input* forcingB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* forcingB){_error_("not implemented yet");};
@@ -65,6 +65,6 @@
 		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype);
 
Index: /issm/trunk/src/c/classes/Inputs/TriaInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TriaInput.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/TriaInput.cpp	(revision 16137)
@@ -38,5 +38,4 @@
 TriaInput::~TriaInput(){
 	xDelete<IssmDouble>(this->values);
-	return;
 }
 /*}}}*/
@@ -85,5 +84,5 @@
 /*}}}*/
 /*FUNCTION TriaInput::SpawnTriaInput{{{*/
-Input* TriaInput::SpawnTriaInput(int* indices){
+Input* TriaInput::SpawnTriaInput(int location){
 
 	/*output*/
@@ -131,5 +130,5 @@
 
 	/*Get B matrix: */
-	GetBMacAyeal(&B[0],xyz_list,gauss);
+	GetBSSA(&B[0],xyz_list,gauss);
 
 	/*Here, we are computing the strain rate of (vx,0)*/
@@ -157,5 +156,5 @@
 
 	/*Get B matrix: */
-	GetBMacAyeal(&B[0],xyz_list,gauss);
+	GetBSSA(&B[0],xyz_list,gauss);
 
 	/*Here, we are computing the strain rate of (0,vy)*/
@@ -252,5 +251,5 @@
 void TriaInput::ConstrainMin(IssmDouble minimum){
 
-	const int numnodes = this->NumberofNodes();
+	int numnodes = this->NumberofNodes();
 	for(int i=0;i<numnodes;i++) if (values[i]<minimum) values[i]=minimum;
 }
@@ -260,6 +259,6 @@
 
 	/*Output*/
-	IssmDouble norm=0;
-	const int numnodes=this->NumberofNodes();
+	IssmDouble norm=0.;
+	int numnodes=this->NumberofNodes();
 
 	for(int i=0;i<numnodes;i++) if(fabs(values[i])>norm) norm=fabs(values[i]);
@@ -270,5 +269,5 @@
 IssmDouble TriaInput::Max(void){
 
-	const int  numnodes=this->NumberofNodes();
+	int  numnodes=this->NumberofNodes();
 	IssmDouble max=values[0];
 
@@ -282,5 +281,5 @@
 IssmDouble TriaInput::MaxAbs(void){
 
-	const int  numnodes=this->NumberofNodes();
+	int  numnodes=this->NumberofNodes();
 	IssmDouble max=fabs(values[0]);
 
@@ -319,5 +318,4 @@
 
 	const int numnodes=this->NumberofNodes();
-
 	for(int i=0;i<numnodes;i++)values[i]=values[i]*scale_factor;
 }
@@ -342,15 +340,14 @@
 void TriaInput::AXPY(Input* xinput,IssmDouble scalar){
 
-	int i;
 	const int numnodes=this->NumberofNodes();
-	TriaInput*  xtriavertexinput=NULL;
+	TriaInput*  xtriainput=NULL;
 
 	/*xinput is of the same type, so cast it: */
 	if(xinput->ObjectEnum()!=TriaInputEnum) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
-	xtriavertexinput=(TriaInput*)xinput;
-	if(xtriavertexinput->element_type!=this->element_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
+	xtriainput=(TriaInput*)xinput;
+	if(xtriainput->element_type!=this->element_type) _error_("Operation not permitted because xinput is of type " << EnumToStringx(xinput->ObjectEnum()));
 
 	/*Carry out the AXPY operation depending on type:*/
-	for(i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*xtriavertexinput->values[i];
+	for(int i=0;i<numnodes;i++)this->values[i]=this->values[i]+scalar*xtriainput->values[i];
 
 }
@@ -387,7 +384,7 @@
 
 	/*Check that inputB is of the same type*/
-	if(inputB->ObjectEnum()!=TriaInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	if(inputB->ObjectEnum()!=TriaInputEnum)       _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(TriaInput*)inputB;
-	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
 
 	/*Create point wise min*/
@@ -421,5 +418,5 @@
 	if(inputB->ObjectEnum()!=TriaInputEnum) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
 	xinputB=(TriaInput*)inputB;
-	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(inputB->ObjectEnum()));
+	if(xinputB->element_type!=this->element_type) _error_("Operation not permitted because inputB is of type " << EnumToStringx(xinputB->element_type));
 
 	/*Create point wise max*/
Index: /issm/trunk/src/c/classes/Inputs/TriaInput.h
===================================================================
--- /issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Inputs/TriaInput.h	(revision 16137)
@@ -34,5 +34,5 @@
 		/*TriaInput management:*/
 		int    InstanceEnum();
-		Input* SpawnTriaInput(int* indices);
+		Input* SpawnTriaInput(int location);
 		Input* PointwiseDivide(Input* inputB){_error_("not implemented yet");};
 		Input* PointwiseMin(Input* inputB);
@@ -62,6 +62,6 @@
 		void GetVyStrainRate3d(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void GetVzStrainRate3d(IssmDouble* epsilonvz,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVxStrainRate3dPattyn(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
-		void GetVyStrainRate3dPattyn(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVxStrainRate3dHO(IssmDouble* epsilonvx,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
+		void GetVyStrainRate3dHO(IssmDouble* epsilonvy,IssmDouble* xyz_list, GaussPenta* gauss){_error_("not implemented yet");};
 		void ChangeEnum(int newenumtype);
 
@@ -80,5 +80,4 @@
 		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 16136)
+++ /issm/trunk/src/c/classes/IoModel.cpp	(revision 16137)
@@ -28,7 +28,15 @@
 
 	this->my_elements=NULL;
-	this->my_nodes=NULL;
 	this->my_vertices=NULL;
 
+	this->dim=-1;
+	this->numberofvertices=-1;
+	this->numberofelements=-1;
+	this->numberoffaces=-1;
+	this->numberofedges=-1;
+	this->elements=NULL;
+	this->faces=NULL;
+	this->edges=NULL;
+	this->elementtoedgeconnectivity      =NULL;
 	this->singlenodetoelementconnectivity=NULL;
 	this->numbernodetoelementconnectivity=NULL;
@@ -49,6 +57,6 @@
 
 	/*Initialize data: */
-	this->data=xNew<IssmDouble*>(MaximumNumberOfEnums);
-	for(int i=0;i<MaximumNumberOfEnums;i++) this->data[i]=NULL;
+	this->data=xNew<IssmDouble*>(MaximumNumberOfDefinitionsEnum);
+	for(int i=0;i<MaximumNumberOfDefinitionsEnum;i++) this->data[i]=NULL;
 
 	/*If we are running in AD mode, we need to start the trace and declare our independent variables now, 
@@ -62,10 +70,16 @@
 
 	/*Initialize permanent data: */
-	this->my_elements=NULL;
-	this->my_nodes=NULL;
-	this->my_vertices=NULL;
-
-	this->singlenodetoelementconnectivity=NULL;
-	this->numbernodetoelementconnectivity=NULL;
+	this->my_elements = NULL;
+	this->my_vertices = NULL;
+
+	FetchData(&this->dim,MeshDimensionEnum);
+	FetchData(&this->numberofvertices,MeshNumberofverticesEnum);
+	FetchData(&this->numberofelements,MeshNumberofelementsEnum);
+	FetchData(&this->elements,NULL,NULL,MeshElementsEnum);
+	this->faces                           = NULL;
+	this->edges                           = NULL;
+	this->elementtoedgeconnectivity       = NULL;
+	this->singlenodetoelementconnectivity = NULL;
+	this->numbernodetoelementconnectivity = NULL;
 
 	this->nodecounter=0;
@@ -77,10 +91,8 @@
 IoModel::~IoModel(){
 
-	if(this->constants) delete this->constants;
-
 	/*Some checks in debugging mode*/
 	#ifdef _ISSM_DEBUG_
 	if(this->data){
-		for(int i=0;i<MaximumNumberOfEnums;i++){
+		for(int i=0;i<MaximumNumberOfDefinitionsEnum;i++){
 			if(this->data[i]){
 				_printf0_("Info: previous pointer of " << EnumToStringx(i) << " has not been freed (DeleteData has not been called)\n");
@@ -89,11 +101,18 @@
 	}
 	#endif
+
+	if(this->constants) delete this->constants;
 
 	xDelete<IssmDouble*>(this->data);
 	xDelete<bool>(this->independents);
 	if(this->independent_objects)delete this->independent_objects;
+
 	xDelete<bool>(this->my_elements);
-	xDelete<bool>(this->my_nodes);
 	xDelete<int>(this->my_vertices);
+
+	xDelete<int>(this->elements);
+	xDelete<int>(this->faces);
+	xDelete<int>(this->edges);
+	xDelete<int>(this->elementtoedgeconnectivity);
 	xDelete<int>(this->singlenodetoelementconnectivity);
 	xDelete<int>(this->numbernodetoelementconnectivity);
@@ -124,5 +143,5 @@
 		}
 		else{
-			if(record_enum!=MaximumNumberOfEnums){
+			if(record_enum!=MaximumNumberOfDefinitionsEnum){
 				_printf0_("\n");
 				_printf0_("=========================================================================\n");
@@ -196,5 +215,5 @@
 IssmDouble* IoModel::Data(int data_enum){
 
-	_assert_(data_enum<MaximumNumberOfEnums);
+	_assert_(data_enum<MaximumNumberOfDefinitionsEnum);
 	_assert_(data_enum>=0);
 
@@ -215,7 +234,9 @@
 	bool keep=false;
 
+	int my_rank=IssmComm::GetRank();
+
 	/*Initialize array detecting whether data[i] is an independent AD mode variable: */
-	this->independents=xNew<bool>(MaximumNumberOfEnums);
-	for(i=0;i<MaximumNumberOfEnums;i++) this->independents[i]=false;
+	this->independents=xNew<bool>(MaximumNumberOfDefinitionsEnum);
+	for(i=0;i<MaximumNumberOfDefinitionsEnum;i++) this->independents[i]=false;
 
 	this->FetchData(&autodiff,AutodiffIsautodiffEnum);
@@ -225,6 +246,6 @@
 		/*Start trace*/
 		this->FetchData(&keep,AutodiffKeepEnum);
-		if(keep)trace_on(1,1);
-		else    trace_on(1);
+		if(keep)trace_on(my_rank,1);
+		else    trace_on(my_rank);
 
 		/*build dataset made of independent objects:*/
@@ -273,5 +294,5 @@
 	for(i = 0; i <num; i++){
 		dataenum=va_arg(ap, int);
-		_assert_(dataenum<MaximumNumberOfEnums);
+		_assert_(dataenum<MaximumNumberOfDefinitionsEnum);
 
 		/*do not erase independent variables for the AD mode computations!: */
@@ -324,7 +345,5 @@
 				/*Ok, we have reached the end of the file. break: */
 				record_code=0; //0 means bailout
-				#ifdef _HAVE_MPI_
-				MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm());  /*tell others cpus we are bailing: */
-				#endif
+				ISSM_MPI_Bcast(&record_code,1,ISSM_MPI_INT,0,IssmComm::GetComm());  /*tell others cpus we are bailing: */
 				break;
 			}
@@ -335,12 +354,10 @@
 				if(fread(&record_code  ,sizeof(int),1,this->fid)!=1) _error_("Cound not read record_code");
 
-				#ifdef _HAVE_MPI_
 				/*Tell other cpus what we are doing: */
-				MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm());  /*tell other cpus what we are going to do: */
+				ISSM_MPI_Bcast(&record_code,1,ISSM_MPI_INT,0,IssmComm::GetComm());  /*tell other cpus what we are going to do: */
 
 				/*Tell other cpus the name of the data, then branch according to the data type: */
-				MPI_Bcast(&record_enum,1,MPI_INT,0,IssmComm::GetComm());  
-				MPI_Bcast(&record_length,1,MPI_INT,0,IssmComm::GetComm());  
-				#endif
+				ISSM_MPI_Bcast(&record_enum,1,ISSM_MPI_INT,0,IssmComm::GetComm());  
+				ISSM_MPI_Bcast(&record_length,1,ISSM_MPI_INT,0,IssmComm::GetComm());  
 
 				switch(record_code){
@@ -348,7 +365,5 @@
 						/*Read the boolean and broadcast it to other cpus:*/
 						if(fread(&booleanint,sizeof(int),1,this->fid)!=1) _error_("could not read boolean ");
-						#ifdef _HAVE_MPI_
-						MPI_Bcast(&booleanint,1,MPI_INT,0,IssmComm::GetComm()); 
-						#endif
+						ISSM_MPI_Bcast(&booleanint,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 						/*create BoolParam: */
@@ -359,7 +374,5 @@
 						/*Read the integer and broadcast it to other cpus:*/
 						if(fread(&integer,sizeof(int),1,this->fid)!=1) _error_("could not read integer ");
-						#ifdef _HAVE_MPI_
-						MPI_Bcast(&integer,1,MPI_INT,0,IssmComm::GetComm()); 
-						#endif
+						ISSM_MPI_Bcast(&integer,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 						/*create IntParam: */
@@ -376,8 +389,6 @@
 						else{
 							if(fread(&pscalar,sizeof(IssmPDouble),1,this->fid)!=1) _error_("could not read scalar ");
-							#ifdef _HAVE_MPI_
-							MPI_Bcast(&pscalar,1,MPI_DOUBLE,0,IssmComm::GetComm()); 
-							#endif
-							scalar=reCast<IssmDouble>(pscalar);
+							ISSM_MPI_Bcast(&pscalar,1,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
+							scalar=pscalar;
 						}
 
@@ -389,7 +400,5 @@
 						/*We have to read a string from disk. First read the dimensions of the string, then the string: */
 						if(fread(&string_size,sizeof(int),1,this->fid)!=1) _error_("could not read length of string ");
-						#ifdef _HAVE_MPI_
-						MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm()); 
-						#endif
+						ISSM_MPI_Bcast(&string_size,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 						if(string_size){
@@ -399,7 +408,5 @@
 							/*Read string, then broadcast: */
 							if(fread(string,string_size*sizeof(char),1,this->fid)!=1)_error_(" could not read string ");
-							#ifdef _HAVE_MPI_
-							MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm()); 
-							#endif
+							ISSM_MPI_Bcast(string,string_size,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
 						}
 						else{
@@ -455,18 +462,17 @@
 		}
 	} //}}}
-	#ifdef _HAVE_MPI_
 	else{ //cpu ~0 {{{
 		for(;;){ //wait on cpu 0
-			MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm());  /*get from cpu 0 what we are going to do: */
+			ISSM_MPI_Bcast(&record_code,1,ISSM_MPI_INT,0,IssmComm::GetComm());  /*get from cpu 0 what we are going to do: */
 			if(record_code==0){
 				break; //we are done, break from the loop
 			}
 			else{
-				MPI_Bcast(&record_enum,1,MPI_INT,0,IssmComm::GetComm());   //get from cpu 0 name of the data
-				MPI_Bcast(&record_length,1,MPI_INT,0,IssmComm::GetComm());  
+				ISSM_MPI_Bcast(&record_enum,1,ISSM_MPI_INT,0,IssmComm::GetComm());   //get from cpu 0 name of the data
+				ISSM_MPI_Bcast(&record_length,1,ISSM_MPI_INT,0,IssmComm::GetComm());  
 				switch(record_code){
 				case 1: 
 					/*boolean. get it from cpu 0 */
-					MPI_Bcast(&booleanint,1,MPI_INT,0,IssmComm::GetComm()); 
+					ISSM_MPI_Bcast(&booleanint,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 					/*create BoolParam: */
@@ -476,5 +482,5 @@
 				case 2:
 					/*integer. get it from cpu 0 */
-					MPI_Bcast(&integer,1,MPI_INT,0,IssmComm::GetComm()); 
+					ISSM_MPI_Bcast(&integer,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 					/*create IntParam: */
@@ -484,6 +490,6 @@
 				case 3:
 					/*scalar. get it from cpu 0 */
-					MPI_Bcast(&scalar,1,MPI_DOUBLE,0,IssmComm::GetComm()); 
-
+					ISSM_MPI_Bcast(&pscalar,1,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+					scalar=pscalar;
 					/*create DoubleParam: */
 					this->constants->AddObject(new DoubleParam(record_enum,scalar));
@@ -491,5 +497,5 @@
 					break;
 				case 4: 
-					MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm()); 
+					ISSM_MPI_Bcast(&string_size,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 					if(string_size){
 						string=xNew<char>((string_size+1));
@@ -497,5 +503,5 @@
 
 						/*Read string from cpu 0: */
-						MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm()); 
+						ISSM_MPI_Bcast(string,string_size,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
 					}
 					else{
@@ -524,5 +530,4 @@
 		}
 	} //}}}
-	#endif
 }
 /*}}}*/
@@ -548,7 +553,5 @@
 		if(fread(&booleanint,sizeof(int),1,fid)!=1) _error_("could not read boolean ");
 	}
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&booleanint,1,MPI_INT,0,IssmComm::GetComm()); 
-	#endif
+	ISSM_MPI_Bcast(&booleanint,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	/*cast to bool: */
@@ -580,7 +583,5 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&integer,1,MPI_INT,0,IssmComm::GetComm()); 
-	#endif
+	ISSM_MPI_Bcast(&integer,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	/*Assign output pointers: */
@@ -609,7 +610,5 @@
 		if(fread(&scalar,sizeof(IssmPDouble),1,fid)!=1)_error_("could not read scalar ");
 	}
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&scalar,1,MPI_DOUBLE,0,IssmComm::GetComm()); 
-	#endif
+	ISSM_MPI_Bcast(&scalar,1,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
 
 	/*Assign output pointers: */
@@ -643,7 +642,5 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm()); 
-	#endif
+	ISSM_MPI_Bcast(&string_size,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	/*Now allocate string: */
@@ -656,7 +653,5 @@
 			if(fread(string,string_size*sizeof(char),1,fid)!=1)_error_(" could not read string ");
 		}
-		#ifdef _HAVE_MPI_
-		MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm()); 
-		#endif
+		ISSM_MPI_Bcast(string,string_size,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
 	}
 	else{
@@ -697,14 +692,10 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&M,1,MPI_INT,0,IssmComm::GetComm()); 
-	#endif
+	ISSM_MPI_Bcast(&M,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	if(my_rank==0){  
 		if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
 	}
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&N,1,MPI_INT,0,IssmComm::GetComm());
-	#endif
+	ISSM_MPI_Bcast(&N,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 
 	/*Now allocate matrix: */
@@ -717,7 +708,5 @@
 		}
 
-		#ifdef _HAVE_MPI_
-		MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm()); 
-		#endif
+		ISSM_MPI_Bcast(matrix,M*N,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
 	}
 
@@ -768,14 +757,10 @@
 		if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
 	}
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&M,1,MPI_INT,0,IssmComm::GetComm()); 
-	#endif
+	ISSM_MPI_Bcast(&M,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	if(my_rank==0){  
 		if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
 	}
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&N,1,MPI_INT,0,IssmComm::GetComm()); 
-	#endif
+	ISSM_MPI_Bcast(&N,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	/*Now allocate matrix: */
@@ -787,7 +772,5 @@
 			if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
 		}
-		#ifdef _HAVE_MPI_
-		MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm()); 
-		#endif
+		ISSM_MPI_Bcast(matrix,M*N,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
 
 		_assert_(this->independents);
@@ -838,7 +821,5 @@
 		if(fread(&numstrings,sizeof(int),1,fid)!=1) _error_("could not read length of string array");
 	}
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&numstrings,1,MPI_INT,0,IssmComm::GetComm()); 
-	#endif
+	ISSM_MPI_Bcast(&numstrings,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	/*Now allocate string array: */
@@ -853,7 +834,5 @@
 				if(fread(&string_size,sizeof(int),1,fid)!=1) _error_("could not read length of string ");
 			}
-			#ifdef _HAVE_MPI_
-			MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm()); 
-			#endif
+			ISSM_MPI_Bcast(&string_size,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 			if(string_size){
 				string=xNew<char>((string_size+1));
@@ -864,7 +843,5 @@
 					if(fread(string,string_size*sizeof(char),1,fid)!=1)_error_(" could not read string ");
 				}
-				#ifdef _HAVE_MPI_
-				MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm()); 
-				#endif
+				ISSM_MPI_Bcast(string,string_size,ISSM_MPI_CHAR,0,IssmComm::GetComm()); 
 			}
 			else{
@@ -911,7 +888,5 @@
 		if(fread(&numrecords,sizeof(int),1,fid)!=1) _error_("could not read number of records in matrix array ");
 	}
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&numrecords,1,MPI_INT,0,IssmComm::GetComm()); 
-	#endif
+	ISSM_MPI_Bcast(&numrecords,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	if(numrecords){
@@ -934,14 +909,10 @@
 				if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows in " << i << "th matrix of matrix array");
 			}
-			#ifdef _HAVE_MPI_
-			MPI_Bcast(&M,1,MPI_INT,0,IssmComm::GetComm()); 
-			#endif
+			ISSM_MPI_Bcast(&M,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 			if(my_rank==0){  
 				if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns in " << i << "th matrix of matrix array");
 			}
-			#ifdef _HAVE_MPI_
-			MPI_Bcast(&N,1,MPI_INT,0,IssmComm::GetComm()); 
-			#endif
+			ISSM_MPI_Bcast(&N,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 			/*Now allocate matrix: */
@@ -954,7 +925,5 @@
 				}
 
-				#ifdef _HAVE_MPI_
-				MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm()); 
-				#endif
+				ISSM_MPI_Bcast(matrix,M*N,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm()); 
 				matrices[i]=xNew<IssmDouble>(M*N);
 				for (int j=0;j<M*N;++j) {matrices[i][j]=matrix[j];}
@@ -1025,9 +994,9 @@
 void  IoModel::FetchData(int num,...){
 
-	va_list ap;
-	int     dataenum;
-	IssmDouble* matrix=NULL;
-	int     M,N;
-	int     i;
+	va_list     ap;
+	int         dataenum;
+	IssmDouble *matrix   = NULL;
+	int         M,N;
+	int         i;
 
 	/*Go through the entire list of enums and fetch the corresponding data. Add it to the iomodel->data dataset. Everything
@@ -1038,4 +1007,6 @@
 
 		dataenum=va_arg(ap, int);
+		_assert_(dataenum<MaximumNumberOfDefinitionsEnum); 
+		_assert_(dataenum>=0);
 
 		if (this->independents[dataenum]){
@@ -1047,5 +1018,5 @@
 		/*{{{*/
 		#ifdef _ISSM_DEBUG_
-		_assert_(dataenum<MaximumNumberOfEnums);
+		_assert_(dataenum<MaximumNumberOfDefinitionsEnum);
 		if(this->data[dataenum]){
 			_error_("Info: trying to fetch " << EnumToStringx(dataenum) << " but previous pointer has not been freed (DeleteData has not been called)");
@@ -1077,10 +1048,10 @@
 
 	/*variables being fetched: */
-	bool    boolean;
-	int     integer;
+	bool        boolean;
+	int         integer;
 	IssmDouble  scalar;
-	char   *string        = NULL;
-	IssmDouble *IssmDoublevector  = NULL;
-	int     M,N;
+	char       *string           = NULL;
+	IssmDouble *IssmDoublevector = NULL;
+	int         M,N;
 
 	/*Fetch parameters: */
@@ -1286,7 +1257,5 @@
 	}
 	/*Broadcast code and vector type: */
-#ifdef _HAVE_MPI_
-	MPI_Bcast(&lastindex,1,MPI_INT,0,IssmComm::GetComm()); 
-#endif
+	ISSM_MPI_Bcast(&lastindex,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	/*Assign output pointers:*/
@@ -1344,15 +1313,11 @@
 		}
 	}
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&found,1,MPI_INT,0,IssmComm::GetComm()); 
+	ISSM_MPI_Bcast(&found,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 	if(!found)_error_("could not find data with name " << EnumToStringx(data_enum) << " in binary file");
-	#endif
 
 	/*Broadcast code and vector type: */
-	#ifdef _HAVE_MPI_
-	MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm()); 
-	MPI_Bcast(&vector_type,1,MPI_INT,0,IssmComm::GetComm()); 
-	if(record_code==5) MPI_Bcast(&vector_type,1,MPI_INT,0,IssmComm::GetComm()); 
-	#endif
+	ISSM_MPI_Bcast(&record_code,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+	ISSM_MPI_Bcast(&vector_type,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
+	if(record_code==5) ISSM_MPI_Bcast(&vector_type,1,ISSM_MPI_INT,0,IssmComm::GetComm()); 
 
 	/*Assign output pointers:*/
Index: /issm/trunk/src/c/classes/IoModel.h
===================================================================
--- /issm/trunk/src/c/classes/IoModel.h	(revision 16136)
+++ /issm/trunk/src/c/classes/IoModel.h	(revision 16137)
@@ -28,8 +28,16 @@
 		/*Partitioning*/
 		bool *my_elements;
-		bool *my_nodes;
 		int  *my_vertices;
 
-		/*Connectivity tables*/
+		/*Mesh properties and connectivity tables*/
+		int   dim;
+		int   numberofvertices;
+		int   numberofelements;
+		int   numberoffaces;
+		int   numberofedges;
+		int  *elements;
+		int  *faces;
+		int  *edges;
+		int  *elementtoedgeconnectivity;
 		int  *singlenodetoelementconnectivity;
 		int  *numbernodetoelementconnectivity;
Index: sm/trunk/src/c/classes/Loads/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Loads/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,15 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/objects/Loads)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/Loads/Friction.cpp
-                 $ENV{ISSM_DIR}/src/c/classes/objects/Loads/Icefront.cpp
-            $ENV{ISSM_DIR}/src/c/classes/objects/Loads/Numericalflux.cpp
-                  $ENV{ISSM_DIR}/src/c/classes/objects/Loads/Pengrid.cpp
-                  $ENV{ISSM_DIR}/src/c/classes/objects/Loads/Penpair.cpp PARENT_SCOPE)
-# }}}
-# RIFTS_SOURCES {{{
-set(RIFTS_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/Loads/Riftfront.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/classes/Loads/Icefront.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Icefront.cpp	(revision 16136)
+++ 	(revision )
@@ -1,856 +1,0 @@
-/*!\file Icefront.c
- * \brief: implementation of the Icefront object
- */
-
-/*Headers:*/
-/*{{{*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "../classes.h"
-#include "shared/shared.h"
-/*}}}*/	
-
-/*Load macros*/
-#define NUMVERTICESSEG 2
-#define NUMVERTICESQUA 4
-
-/*Icefront constructors and destructor*/
-/*FUNCTION Icefront::Icefront() {{{*/
-Icefront::Icefront(){
-
-	this->inputs=NULL;
-	this->parameters=NULL;
-
-	this->hnodes=NULL;
-	this->nodes= NULL;
-	this->hvertices=NULL;
-	this->vertices= NULL;
-	this->helement=NULL;
-	this->element= NULL;
-	this->hmatpar=NULL;
-	this->matpar= NULL;
-}
-/*}}}*/
-/*FUNCTION Icefront::Icefront(int id, int i, IoModel* iomodel,int analysis_type) {{{*/
-Icefront::Icefront(int icefront_id,int i, IoModel* iomodel,int in_icefront_type, int in_analysis_type){
-
-	int segment_width;
-	int element;
-	int numnodes; 
-	int numvertices; 
-	int dim;
-	int numberofelements;
-
-	/*icefront constructor data: */
-	int  icefront_eid;
-	int  icefront_mparid;
-	int  icefront_node_ids[NUMVERTICESQUA]; //initialize with largest size
-	int  icefront_vertex_ids[NUMVERTICESQUA]; //initialize with largest size
-	int  icefront_fill;
-
-	/*find parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-
-	/*First, retrieve element index and element type: */
-	if (dim==2){
-		segment_width=4;
-	}
-	else{
-		segment_width=6;
-	}
-	_assert_(iomodel->Data(DiagnosticIcefrontEnum));
-	element=reCast<int,IssmDouble>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+segment_width-2)-1); //element is in the penultimate column (node1 node2 ... elem fill)
-
-	/*Build ids for hook constructors: */
-	icefront_eid=reCast<int,IssmDouble>( *(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+segment_width-2)); //matlab indexing
-	icefront_mparid=numberofelements+1; //matlab indexing
-
-	if (in_icefront_type==MacAyeal2dIceFrontEnum || in_icefront_type==MacAyeal3dIceFrontEnum){
-		icefront_node_ids[0]=iomodel->nodecounter+reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+0));
-		icefront_node_ids[1]=iomodel->nodecounter+reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+1));
-		icefront_vertex_ids[0]=reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+0));
-		icefront_vertex_ids[1]=reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+1));
-	}
-	else if (in_icefront_type==PattynIceFrontEnum || in_icefront_type==StokesIceFrontEnum){
-		icefront_node_ids[0]=iomodel->nodecounter+reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+0));
-		icefront_node_ids[1]=iomodel->nodecounter+reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+1));
-		icefront_node_ids[2]=iomodel->nodecounter+reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+2));
-		icefront_node_ids[3]=iomodel->nodecounter+reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+3));
-		icefront_vertex_ids[0]=reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+0));
-		icefront_vertex_ids[1]=reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+1));
-		icefront_vertex_ids[2]=reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+2));
-		icefront_vertex_ids[3]=reCast<int>(*(iomodel->Data(DiagnosticIcefrontEnum)+segment_width*i+3));
-	}
-	else _error_("in_icefront_type " << EnumToStringx(in_icefront_type) << " not supported yet!");
-
-	if (in_icefront_type==PattynIceFrontEnum || in_icefront_type==StokesIceFrontEnum){
-		numnodes=4;
-		numvertices=4;
-	}
-	else{
-		numnodes=2;
-		numvertices=2;
-	}
-
-	/*Fill*/
-	icefront_fill=reCast<int>(iomodel->Data(DiagnosticIcefrontEnum)[segment_width*i+segment_width-1]);
-
-	/*Ok, we have everything to build the object: */
-	this->id=icefront_id;
-	this->analysis_type=in_analysis_type;
-
-	/*Hooks: */
-	this->hnodes=new Hook(icefront_node_ids,numnodes);
-	this->hvertices=new Hook(icefront_vertex_ids,numvertices);
-	this->helement=new Hook(&icefront_eid,1);
-	this->hmatpar=new Hook(&icefront_mparid,1);
-
-	//intialize  and add as many inputs per element as requested: 
-	this->inputs=new Inputs();
-	this->inputs->AddInput(new IntInput(FillEnum,icefront_fill));
-	this->inputs->AddInput(new IntInput(IceFrontTypeEnum,in_icefront_type));
-
-	//parameters and hooked fields: we still can't point to them, they may not even exist. Configure will handle this.
-	this->parameters = NULL;
-	this->nodes      = NULL;
-	this->vertices   = NULL;
-	this->element    = NULL;
-	this->matpar     = NULL;
-}
-
-/*}}}*/
-/*FUNCTION Icefront::~Icefront() {{{*/
-Icefront::~Icefront(){
-	delete inputs;
-	this->parameters=NULL;
-	delete hnodes;
-	delete hvertices;
-	delete helement;
-	delete hmatpar;
-}
-/*}}}*/
-
-/*Object virtual functions definitions:*/
-/*FUNCTION Icefront::Echo {{{*/
-void Icefront::Echo(void){
-	_printf_("Icefront:\n");
-	_printf_("   id: " << id << "\n");
-	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
-	hnodes->Echo();
-	hvertices->Echo();
-	helement->Echo();
-	hmatpar->Echo();
-	_printf_("   parameters: " << parameters << "\n");
-	if(parameters)parameters->Echo();
-	_printf_("   inputs: " << inputs << "\n");
-	if(inputs)inputs->Echo();
-}
-/*}}}*/
-/*FUNCTION Icefront::DeepEcho{{{*/
-void Icefront::DeepEcho(void){
-
-	_printf_("Icefront:\n");
-	_printf_("   id: " << id << "\n");
-	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
-	hnodes->DeepEcho();
-	hvertices->DeepEcho();
-	helement->DeepEcho();
-	hmatpar->DeepEcho();
-	_printf_("   parameters: " << parameters << "\n");
-	if(parameters)parameters->DeepEcho();
-	_printf_("   inputs: " << inputs << "\n");
-	if(inputs)inputs->DeepEcho();
-}
-/*}}}*/
-/*FUNCTION Icefront::Id {{{*/
-int    Icefront::Id(void){ return id; }
-/*}}}*/
-/*FUNCTION Icefront::ObjectEnum{{{*/
-int Icefront::ObjectEnum(void){
-
-	return IcefrontEnum;
-
-}
-/*}}}*/
-/*FUNCTION Icefront::copy {{{*/
-Object* Icefront::copy() {
-
-	Icefront* icefront=NULL;
-
-	icefront=new Icefront();
-
-	/*copy fields: */
-	icefront->id=this->id;
-	icefront->analysis_type=this->analysis_type;
-	if(this->inputs){
-		icefront->inputs=(Inputs*)this->inputs->Copy();
-	}
-	else{
-		icefront->inputs=new Inputs();
-	}
-	/*point parameters: */
-	icefront->parameters=this->parameters;
-
-	/*now deal with hooks and objects: */
-	icefront->hnodes    = (Hook*)this->hnodes->copy();
-	icefront->hvertices = (Hook*)this->hvertices->copy();
-	icefront->helement  = (Hook*)this->helement->copy();
-	icefront->hmatpar   = (Hook*)this->hmatpar->copy();
-
-	/*corresponding fields*/
-	icefront->nodes    = (Node**)icefront->hnodes->deliverp();
-	icefront->vertices = (Vertex**)icefront->hvertices->deliverp();
-	icefront->element  = (Element*)icefront->helement->delivers();
-	icefront->matpar   = (Matpar*)icefront->hmatpar->delivers();
-
-	return icefront;
-
-}
-/*}}}*/
-
-/*Load virtual functions definitions:*/
-/*FUNCTION Icefront::Configure {{{*/
-void  Icefront::Configure(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
-
-	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
-	 * datasets, using internal ids and offsets hidden in hooks: */
-	hnodes->configure((DataSet*)nodesin);
-	hvertices->configure((DataSet*)verticesin);
-	helement->configure((DataSet*)elementsin);
-	hmatpar->configure((DataSet*)materialsin);
-
-	/*Initialize hooked fields*/
-	this->nodes    = (Node**)hnodes->deliverp();
-	this->vertices = (Vertex**)hvertices->deliverp();
-	this->element  = (Element*)helement->delivers();
-	this->matpar   = (Matpar*)hmatpar->delivers();
-
-	/*point parameters to real dataset: */
-	this->parameters=parametersin;
-}
-/*}}}*/
-/*FUNCTION Icefront::SetCurrentConfiguration {{{*/
-void  Icefront::SetCurrentConfiguration(Elements* elementsin,Loads* loadsin,Nodes* nodesin,Vertices* verticesin,Materials* materialsin,Parameters* parametersin){
-}
-/*}}}*/
-/*FUNCTION Icefront::CreateKMatrix {{{*/
-void  Icefront::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs){
-
-	/*No stiffness loads applied, do nothing: */
-	return;
-
-}
-/*}}}*/
-/*FUNCTION Icefront::CreatePVector {{{*/
-void  Icefront::CreatePVector(Vector<IssmDouble>* pf){
-
-	/*Checks in debugging mode*/
-	_assert_(nodes);
-	_assert_(element);
-	_assert_(matpar);
-
-	/*Retrieve parameters: */
-	ElementVector* pe=NULL;
-	int analysis_type;
-	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-
-	/*Just branch to the correct element icefront vector generator, according to the type of analysis we are carrying out: */
-	switch(analysis_type){
-		#ifdef _HAVE_DIAGNOSTIC_
-		case DiagnosticHorizAnalysisEnum:
-			pe=CreatePVectorDiagnosticHoriz();
-			break;
-		#endif
-		#ifdef _HAVE_CONTROL_
-		case AdjointHorizAnalysisEnum:
-			pe=CreatePVectorAdjointHoriz();
-			break;
-		#endif
-		default:
-			_error_("analysis " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not supported yet");
-	}
-
-	/*Add to global Vector*/
-	if(pe){
-		pe->AddToGlobal(pf);
-		delete pe;
-	}
-}
-/*}}}*/
-/*FUNCTION Icefront::CreateJacobianMatrix{{{*/
-void  Icefront::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){
-	this->CreateKMatrix(Jff,NULL);
-}
-/*}}}*/
-/*FUNCTION Icefront::GetNodesSidList{{{*/
-void Icefront::GetNodesSidList(int* sidlist){
-
-	int type;
-	inputs->GetInputValue(&type,IceFrontTypeEnum);
-	_assert_(sidlist);
-	_assert_(nodes);
-
-	switch(type){
-		case MacAyeal2dIceFrontEnum:
-		case MacAyeal3dIceFrontEnum:
-			for(int i=0;i<NUMVERTICESSEG;i++) sidlist[i]=nodes[i]->Sid();
-			return;
-#ifdef _HAVE_3D_
-		case PattynIceFrontEnum:
-		case StokesIceFrontEnum:
-			for(int i=0;i<NUMVERTICESQUA;i++) sidlist[i]=nodes[i]->Sid();
-			return;
-#endif
-		default:
-			_error_("Icefront type " << EnumToStringx(type) << " not supported yet");
-	}
-}
-/*}}}*/
-/*FUNCTION Icefront::GetNumberOfNodes{{{*/
-int Icefront::GetNumberOfNodes(void){
-
-	int type;
-	inputs->GetInputValue(&type,IceFrontTypeEnum);
-
-	switch(type){
-		case MacAyeal2dIceFrontEnum:
-			return NUMVERTICESSEG;
-#ifdef _HAVE_3D_
-		case MacAyeal3dIceFrontEnum:
-			return NUMVERTICESSEG;
-		case PattynIceFrontEnum:
-			return NUMVERTICESQUA;
-		case StokesIceFrontEnum:
-			return NUMVERTICESQUA;
-#endif
-		default:
-			_error_("Icefront type " << EnumToStringx(type) << " not supported yet");
-	}
-
-}
-/*}}}*/
-/*FUNCTION Icefront::IsPenalty{{{*/
-bool Icefront::IsPenalty(void){
-	return false;
-}
-/*}}}*/
-/*FUNCTION Icefront::PenaltyCreateKMatrix {{{*/
-void  Icefront::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs, IssmDouble kmax){
-	/*do nothing: */
-	return;
-}
-/*}}}*/
-/*FUNCTION Icefront::PenaltyCreatePVector{{{*/
-void  Icefront::PenaltyCreatePVector(Vector<IssmDouble>* pf,IssmDouble kmax){
-	/*do nothing: */
-	return;
-}
-/*}}}*/
-/*FUNCTION Icefront::PenaltyCreateJacobianMatrix{{{*/
-void  Icefront::PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){
-	this->PenaltyCreateKMatrix(Jff,NULL,kmax);
-}
-/*}}}*/
-/*FUNCTION Icefront::SetwiseNodeConnectivity{{{*/
-void Icefront::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
-
-	/*Output */
-	int d_nz = 0;
-	int o_nz = 0;
-
-	/*Loop over all nodes*/
-	for(int i=0;i<this->GetNumberOfNodes();i++){
-
-		if(!flags[this->nodes[i]->Sid()]){
-
-			/*flag current node so that no other element processes it*/
-			flags[this->nodes[i]->Sid()]=true;
-
-			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
-			switch(set2_enum){
-				case FsetEnum:
-					if(nodes[i]->indexing.fsize){
-						if(this->nodes[i]->IsClone())
-						 o_nz += 1;
-						else
-						 d_nz += 1;
-					}
-					break;
-				case GsetEnum:
-					if(nodes[i]->indexing.gsize){
-						if(this->nodes[i]->IsClone())
-						 o_nz += 1;
-						else
-						 d_nz += 1;
-					}
-					break;
-				case SsetEnum:
-					if(nodes[i]->indexing.ssize){
-						if(this->nodes[i]->IsClone())
-						 o_nz += 1;
-						else
-						 d_nz += 1;
-					}
-					break;
-				default: _error_("not supported");
-			}
-		}
-	}
-
-	/*Assign output pointers: */
-	*pd_nz=d_nz;
-	*po_nz=o_nz;
-}
-/*}}}*/
-/*FUNCTION Icefront::InAnalysis{{{*/
-bool Icefront::InAnalysis(int in_analysis_type){
-	if (in_analysis_type==this->analysis_type)return true;
-	else return false;
-}
-/*}}}*/
-
-/*Update virtual functions definitions:*/
-/*FUNCTION Icefront::InputUpdateFromVector(IssmDouble* vector, int name, int type) {{{*/
-void  Icefront::InputUpdateFromVector(IssmDouble* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Icefront::InputUpdateFromVector(int* vector, int name, int type) {{{*/
-void  Icefront::InputUpdateFromVector(int* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Icefront::InputUpdateFromVector(bool* vector, int name, int type) {{{*/
-void  Icefront::InputUpdateFromVector(bool* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Icefront::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type) {{{*/
-void  Icefront::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Icefront::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type) {{{*/
-void  Icefront::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Icefront::InputUpdateFromVectorDakota(int* vector, int name, int type) {{{*/
-void  Icefront::InputUpdateFromVectorDakota(int* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Icefront::InputUpdateFromVectorDakota(bool* vector, int name, int type) {{{*/
-void  Icefront::InputUpdateFromVectorDakota(bool* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Icefront::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
-void  Icefront::InputUpdateFromConstant(IssmDouble constant, int name){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Icefront::InputUpdateFromConstant(int constant, int name) {{{*/
-void  Icefront::InputUpdateFromConstant(int constant, int name){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Icefront::InputUpdateFromConstant(bool constant, int name) {{{*/
-void  Icefront::InputUpdateFromConstant(bool constant, int name){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Icefront::InputUpdateFromSolution{{{*/
-void  Icefront::InputUpdateFromSolution(IssmDouble* solution){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-
-/*Icefront numerics: */
-#ifdef _HAVE_DIAGNOSTIC_
-/*FUNCTION Icefront::CreatePVectorDiagnosticHoriz {{{*/
-ElementVector* Icefront::CreatePVectorDiagnosticHoriz(void){
-
-	int type;
-	inputs->GetInputValue(&type,IceFrontTypeEnum);
-
-	switch(type){
-		case MacAyeal2dIceFrontEnum:
-			return CreatePVectorDiagnosticMacAyeal2d();
-        #ifdef _HAVE_3D_
-		case MacAyeal3dIceFrontEnum:
-			return CreatePVectorDiagnosticMacAyeal3d();
-		case PattynIceFrontEnum:
-			return CreatePVectorDiagnosticPattyn();
-		case StokesIceFrontEnum:
-			return CreatePVectorDiagnosticStokes();
-	    #endif
-		default:
-			_error_("Icefront type " << EnumToStringx(type) << " not supported yet");
-	}
-}
-/*}}}*/
-/*FUNCTION Icefront::CreatePVectorDiagnosticMacAyeal2d{{{*/
-ElementVector* Icefront::CreatePVectorDiagnosticMacAyeal2d(void){
-
-	/*Intermediary*/
-	int         ig,index1,index2,fill;
-	IssmDouble  Jdet;
-	IssmDouble  thickness,bed,pressure,ice_pressure,rho_water,rho_ice,gravity;
-	IssmDouble  water_pressure,air_pressure,surface_under_water,base_under_water;
-	IssmDouble  xyz_list[NUMVERTICESSEG][3];
-	IssmDouble  normal[2];
-	GaussTria *gauss;
-
-	/*return of element is on water*/
-	Tria* tria=((Tria*)element);
-	if(tria->IsOnWater()) return NULL;
-
-	/*Fetch number of nodes and dof for this finite element*/
-	//int numnodes = this->NumberofNodes();
-	int numnodes = 2; 
-	int numdof   = numnodes*NDOF2;
-
-	/*Initialize Element vector and vectors*/
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICESSEG,this->parameters,MacAyealApproximationEnum);
-	IssmDouble*    basis = xNew<IssmDouble>(numnodes);
-
-	/*Retrieve all inputs and parameters*/
-	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICESSEG);
-	Input* thickness_input=tria->inputs->GetInput(ThicknessEnum); _assert_(thickness_input);
-	Input* bed_input      =tria->inputs->GetInput(BedEnum);       _assert_(bed_input);
-	inputs->GetInputValue(&fill,FillEnum);
-	rho_water=matpar->GetRhoWater();
-	rho_ice  =matpar->GetRhoIce();
-	gravity  =matpar->GetG();
-	GetSegmentNormal(&normal[0],xyz_list);
-
-	/*Start looping on Gaussian points*/
-	index1=tria->GetNodeIndex(nodes[0]);
-	index2=tria->GetNodeIndex(nodes[1]);
-	gauss=new GaussTria(index1,index2,3);
-
-	for(ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		thickness_input->GetInputValue(&thickness,gauss);
-		bed_input->GetInputValue(&bed,gauss);
-
-		switch(fill){
-			case WaterEnum:
-				surface_under_water=min(0.,thickness+bed); // 0 if the top of the glacier is above water level
-				base_under_water=min(0.,bed);              // 0 if the bottom of the glacier is above water level
-				water_pressure=1.0/2.0*gravity*rho_water*(pow(surface_under_water,2) - pow(base_under_water,2));
-				break;
-			case AirEnum:
-				water_pressure=0;
-				break;
-			case IceEnum:
-				water_pressure=-1.0/2.0*gravity*rho_ice*pow(thickness,2); // we are facing a wall of ice. use water_pressure to cancel the lithostatic pressure.
-				break;
-			default:
-				_error_("fill type " << EnumToStringx(fill) << " not supported yet");
-		}
-		ice_pressure=1.0/2.0*gravity*rho_ice*pow(thickness,2);
-		air_pressure=0;
-		pressure = ice_pressure + water_pressure + air_pressure;
-
-		tria->GetSegmentJacobianDeterminant(&Jdet,&xyz_list[0][0],gauss);
-		tria->GetSegmentNodalFunctions(&basis[0],gauss,index1,index2);
-
-		for (int i=0;i<numnodes;i++){
-			pe->values[2*i+0]+= pressure*Jdet*gauss->weight*normal[0]*basis[i];
-			pe->values[2*i+1]+= pressure*Jdet*gauss->weight*normal[1]*basis[i];
-		}
-	}
-
-	/*Transform load vector*/
-	TransformLoadVectorCoord(pe,nodes,NUMVERTICESSEG,XYEnum);
-
-	/*Clean up and return*/
-	xDelete<IssmDouble>(basis);
-	delete gauss;
-	return pe;
-}
-/*}}}*/
-#endif
-
-#ifdef _HAVE_CONTROL_
-/*FUNCTION Icefront::CreatePVectorAdjointHoriz {{{*/
-ElementVector* Icefront::CreatePVectorAdjointHoriz(void){
-
-	/*No load vector applied to the adjoint*/
-	return NULL;
-}
-/*}}}*/
-#endif
-#ifdef _HAVE_3D_
-/*FUNCTION Icefront::CreatePVectorDiagnosticMacAyeal3d{{{*/
-ElementVector* Icefront::CreatePVectorDiagnosticMacAyeal3d(void){
-
-	Icefront *icefront = NULL;
-	Penta    *penta    = NULL;
-	Tria     *tria     = NULL;
-
-	/*Cast element onto Penta*/
-	penta   =(Penta*)this->element;
-
-	/*Return if not on bed*/
-	if(!penta->IsOnBed() || penta->IsOnWater()) return NULL;
-
-	/*Spawn Tria and call MacAyeal2d*/
-	tria    =(Tria*)penta->SpawnTria(0,1,2);
-	icefront=(Icefront*)this->copy();
-	icefront->element=tria;
-	icefront->inputs->AddInput(new IntInput(IceFrontTypeEnum,MacAyeal2dIceFrontEnum));
-	ElementVector* pe=icefront->CreatePVectorDiagnosticMacAyeal2d();
-
-	/*clean-up and return*/
-	delete tria->material;
-	delete tria;
-	delete icefront;
-	return pe;
-}
-/*}}}*/
-/*FUNCTION Icefront::CreatePVectorDiagnosticPattyn{{{*/
-ElementVector* Icefront::CreatePVectorDiagnosticPattyn(void){
-
-	/*Constants*/
-	const int numdofs = NUMVERTICESQUA *NDOF2;
-
-	/*Intermediaries*/
-	int         i,j,ig,index1,index2,index3,index4;
-	int         fill;
-	IssmDouble      surface,pressure,ice_pressure,rho_water,rho_ice,gravity;
-	IssmDouble      water_pressure,air_pressure;
-	IssmDouble      Jdet,z_g;
-	IssmDouble      xyz_list[NUMVERTICESQUA][3];
-	IssmDouble      normal[3];
-	IssmDouble      l1l4[4];
-	GaussPenta *gauss = NULL;
-
-	Penta* penta=(Penta*)element;
-
-	/*Initialize Element vector and return if necessary*/
-	if(penta->IsOnWater()) return NULL;
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICESQUA,this->parameters,PattynApproximationEnum);
-
-	/*Retrieve all inputs and parameters*/
-	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICESQUA);
-	Input* surface_input  =penta->inputs->GetInput(SurfaceEnum);   _assert_(surface_input);
-	inputs->GetInputValue(&fill,FillEnum);
-	rho_water=matpar->GetRhoWater();
-	rho_ice  =matpar->GetRhoIce();
-	gravity  =matpar->GetG();
-	GetQuadNormal(&normal[0],xyz_list);
-
-	/*Identify which nodes are in the quad: */
-	index1=element->GetNodeIndex(nodes[0]);
-	index2=element->GetNodeIndex(nodes[1]);
-	index3=element->GetNodeIndex(nodes[2]);
-	index4=element->GetNodeIndex(nodes[3]);
-
-	/* Start  looping on the number of gaussian points: */
-	IssmDouble zmax=xyz_list[0][2]; for(i=1;i<NUMVERTICESQUA;i++) if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
-	IssmDouble zmin=xyz_list[0][2]; for(i=1;i<NUMVERTICESQUA;i++) if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
-	if(zmax>0 && zmin<0) gauss=new GaussPenta(index1,index2,index3,index4,3,10); //refined in vertical because of the sea level discontinuity
-	else                 gauss=new GaussPenta(index1,index2,index3,index4,3,3);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		penta->GetQuadNodalFunctions(l1l4,gauss,index1,index2,index3,index4);
-		penta->GetQuadJacobianDeterminant(&Jdet,xyz_list,gauss);
-		z_g=penta->GetZcoord(gauss);
-		surface_input->GetInputValue(&surface,gauss);
-
-		switch(fill){
-			case WaterEnum:
-				water_pressure=rho_water*gravity*min(0.,z_g);//0 if the gaussian point is above water level
-				break;
-			case AirEnum:
-				water_pressure=0;
-				break;
-			default:
-				_error_("fill type " << EnumToStringx(fill) << " not supported yet");
-		}
-		ice_pressure=rho_ice*gravity*(surface-z_g);
-		air_pressure=0;
-		pressure = ice_pressure + water_pressure + air_pressure;
-
-		for(i=0;i<NUMVERTICESQUA;i++) for(j=0;j<NDOF2;j++) pe->values[i*NDOF2+j]+=Jdet*gauss->weight*pressure*l1l4[i]*normal[j];
-	}
-
-	/*Transform load vector*/
-	TransformLoadVectorCoord(pe,nodes,NUMVERTICESQUA,XYEnum);
-
-	/*Clean up and return*/
-	delete gauss;
-	return pe;
-}
-/*}}}*/
-/*FUNCTION Icefront::CreatePVectorDiagnosticStokes{{{*/
-ElementVector* Icefront::CreatePVectorDiagnosticStokes(void){
-
-	/*Constants*/
-	const int numdofs = NUMVERTICESQUA *NDOF4;
-
-	/*Intermediaries*/
-	int         i,j,ig,index1,index2,index3,index4;
-	int         fill;
-	IssmDouble      pressure,rho_water,gravity;
-	IssmDouble      water_pressure,air_pressure;
-	IssmDouble      Jdet,z_g;
-	IssmDouble      xyz_list[NUMVERTICESQUA][3];
-	IssmDouble      normal[3];
-	IssmDouble      l1l4[4];
-	GaussPenta *gauss = NULL;
-
-	Penta* penta=(Penta*)element;
-
-	/*Initialize Element vector and return if necessary*/
-	if(penta->IsOnWater()) return NULL;
-	ElementVector* pe=new ElementVector(nodes,NUMVERTICESQUA,this->parameters,StokesApproximationEnum);
-
-	/*Retrieve all inputs and parameters*/
-	GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICESQUA);
-	inputs->GetInputValue(&fill,FillEnum);
-	rho_water=matpar->GetRhoWater();
-	gravity  =matpar->GetG();
-	GetQuadNormal(&normal[0],xyz_list);
-
-	/*Identify which nodes are in the quad: */
-	index1=element->GetNodeIndex(nodes[0]);
-	index2=element->GetNodeIndex(nodes[1]);
-	index3=element->GetNodeIndex(nodes[2]);
-	index4=element->GetNodeIndex(nodes[3]);
-
-	/* Start  looping on the number of gaussian points: */
-	IssmDouble zmax=xyz_list[0][2]; for(i=1;i<NUMVERTICESQUA;i++) if(xyz_list[i][2]>zmax) zmax=xyz_list[i][2];
-	IssmDouble zmin=xyz_list[0][2]; for(i=1;i<NUMVERTICESQUA;i++) if(xyz_list[i][2]<zmin) zmin=xyz_list[i][2];
-	if(zmax>0 && zmin<0) gauss=new GaussPenta(index1,index2,index3,index4,3,30); //refined in vertical because of the sea level discontinuity
-	else                 gauss=new GaussPenta(index1,index2,index3,index4,3,3);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
-
-		gauss->GaussPoint(ig);
-
-		penta->GetQuadNodalFunctions(l1l4,gauss,index1,index2,index3,index4);
-		penta->GetQuadJacobianDeterminant(&Jdet,xyz_list,gauss);
-		z_g=penta->GetZcoord(gauss);
-
-		switch(fill){
-			case WaterEnum:
-				water_pressure=rho_water*gravity*min(0.,z_g);//0 if the gaussian point is above water level
-				break;
-			case AirEnum:
-				water_pressure=0;
-				break;
-			default:
-				_error_("fill type " << EnumToStringx(fill) << " not supported yet");
-		}
-		air_pressure=0;
-		pressure = water_pressure + air_pressure; //no ice pressure fore Stokes
-
-		for(i=0;i<NUMVERTICESQUA;i++){
-			for(j=0;j<NDOF4;j++){
-				if(j<3)  pe->values[i*NDOF4+j]+=Jdet*gauss->weight*pressure*l1l4[i]*normal[j];
-				else     pe->values[i*NDOF4+j]+=0; //pressure term
-			}
-		}
-	}
-
-	/*Transform load vector*/
-	TransformLoadVectorCoord(pe,nodes,NUMVERTICESQUA,XYZPEnum);
-
-	/*Clean up and return*/
-	delete gauss;
-	return pe;
-}
-/*}}}*/
-#endif
-/*FUNCTION Icefront::GetDofList {{{*/
-void  Icefront::GetDofList(int** pdoflist,int approximation_enum,int setenum){
-
-	int numberofdofs=0;
-	int count=0;
-	int type;
-	int numberofnodes=2;
-
-	/*output: */
-	int* doflist=NULL;
-
-	/*recover type: */
-	inputs->GetInputValue(&type,IceFrontTypeEnum);
-
-	/*Some checks for debugging*/
-	_assert_(nodes);
-
-	/*How many nodes? :*/
-	if(type==MacAyeal2dIceFrontEnum || type==MacAyeal3dIceFrontEnum)
-	 numberofnodes=2;
-	else 
-	 numberofnodes=4;
-
-	/*Figure out size of doflist: */
-	for(int i=0;i<numberofnodes;i++){
-		numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
-	}
-
-	/*Allocate: */
-	doflist=xNew<int>(numberofdofs);
-
-	/*Populate: */
-	count=0;
-	for(int i=0;i<numberofnodes;i++){
-		nodes[i]->GetDofList(doflist+count,approximation_enum,setenum);
-		count+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
-	}
-
-	/*Assign output pointers:*/
-	*pdoflist=doflist;
-}
-/*}}}*/
-/*FUNCTION Icefront::GetSegmentNormal {{{*/
-void Icefront:: GetSegmentNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]){
-
-	/*Build unit outward pointing vector*/
-	const int numnodes=NUMVERTICESSEG;
-	IssmDouble vector[2];
-	IssmDouble norm;
-
-	vector[0]=xyz_list[1][0] - xyz_list[0][0];
-	vector[1]=xyz_list[1][1] - xyz_list[0][1];
-
-	norm=sqrt(pow(vector[0],2.0)+pow(vector[1],2.0));
-
-	normal[0]= + vector[1]/norm;
-	normal[1]= - vector[0]/norm;
-}
-/*}}}*/
-/*FUNCTION Icefront::GetQuadNormal {{{*/
-void Icefront:: GetQuadNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]){
-
-	/*Build unit outward pointing vector*/
-	IssmDouble AB[3];
-	IssmDouble AC[3];
-	IssmDouble norm;
-
-	AB[0]=xyz_list[1][0] - xyz_list[0][0];
-	AB[1]=xyz_list[1][1] - xyz_list[0][1];
-	AB[2]=xyz_list[1][2] - xyz_list[0][2];
-	AC[0]=xyz_list[2][0] - xyz_list[0][0];
-	AC[1]=xyz_list[2][1] - xyz_list[0][1];
-	AC[2]=xyz_list[2][2] - xyz_list[0][2];
-
-	cross(normal,AB,AC);
-	norm=sqrt(pow(normal[0],2.0)+pow(normal[1],2.0)+pow(normal[2],2.0));
-
-	for(int i=0;i<3;i++) normal[i]=normal[i]/norm;
-}
-/*}}}*/
Index: sm/trunk/src/c/classes/Loads/Icefront.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Icefront.h	(revision 16136)
+++ 	(revision )
@@ -1,104 +1,0 @@
-/*!\file Icefront.h
- * \brief: header file for icefront object
- */
-
-#ifndef _ICEFRONT_H_
-#define _ICEFRONT_H_
-
-/*Headers:*/
-/*{{{*/
-#include "./Load.h"
-class Hook;
-class Inputs;
-class Parameters;
-class Matpar;
-class Node;
-class Element;
-class IoModel;
-class ElementVector;
-class Vertex;
-/*}}}*/
-
-class Icefront: public Load {
-
-	public:
-		int id;
-		int analysis_type;
-
-		/*hooks: */
-		Hook *hnodes;
-		Hook *hvertices;
-		Hook *helement;
-		Hook *hmatpar;
-
-		/*Corresponding fields*/
-		Matpar   *matpar;
-		Node    **nodes;
-		Vertex  **vertices;
-		Element  *element;
-
-		/*inputs and parameters: */
-		Inputs     *inputs;
-		Parameters *parameters;
-
-		/*Icefront constructors, destructors: {{{*/
-		Icefront();
-		Icefront(int icefront_id,int i, IoModel* iomodel,int in_icefront_type, int analysis_type);
-		~Icefront();
-		/*}}}*/
-		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   ObjectEnum();
-		Object* copy();
-		/*}}}*/
-		/*Update virtual functions definitions: {{{*/
-		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVector(int* vector, int name, int type);
-		void  InputUpdateFromVector(bool* vector, int name, int type);
-		void  InputUpdateFromMatrixDakota(IssmDouble* matrix,int ncols,int nrows, int name, int type);
-		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
-		void  InputUpdateFromConstant(IssmDouble constant, int name);
-		void  InputUpdateFromConstant(int constant, int name);
-		void  InputUpdateFromConstant(bool constant, int name);
-		void  InputUpdateFromSolution(IssmDouble* solution);
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("not implemented yet");};
-		/*}}}*/
-		/*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  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
-		void  CreatePVector(Vector<IssmDouble>* pf);
-		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
-		int   GetNumberOfNodes(void);
-		void  GetNodesSidList(int* sidlist);
-		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 set1_enum,int set2_enum);
-		bool  InAnalysis(int analysis_type);
-		/*}}}*/
-		/*Load management: {{{*/
-		void GetDofList(int** pdoflist,int approximation_enum,int setenum);
-		void GetSegmentNormal(IssmDouble* normal,IssmDouble xyz_list[2][3]);
-		void GetQuadNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]);
-		#ifdef _HAVE_CONTROL_
-		ElementVector* CreatePVectorAdjointHoriz(void);
-		#endif
-		#ifdef _HAVE_DIAGNOSTIC_
-		ElementVector* CreatePVectorDiagnosticHoriz(void);
-		ElementVector* CreatePVectorDiagnosticMacAyeal2d(void);
-		#endif
-        #ifdef _HAVE_3D_
-		ElementVector* CreatePVectorDiagnosticMacAyeal3d(void);
-		ElementVector* CreatePVectorDiagnosticPattyn(void);
-		ElementVector* CreatePVectorDiagnosticStokes(void);
-	    #endif
-		/*}}}*/
-};
-
-#endif  /* _ICEFRONT_H_ */
Index: /issm/trunk/src/c/classes/Loads/Load.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Load.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Loads/Load.h	(revision 16137)
@@ -9,5 +9,4 @@
 
 /*Headers:*/
-/*{{{*/
 class Node;
 template <class doublematrix> class Matrix;
@@ -19,9 +18,6 @@
 class Materials;
 class Parameters;
-
 #include "../../datastructures/datastructures.h"
 #include "../Update.h"
-
-/*}}}*/
 
 class Load: public Object,public Update{
@@ -34,4 +30,5 @@
 		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  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs)=0;
@@ -42,5 +39,5 @@
 		virtual void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax)=0;
 		virtual bool  InAnalysis(int analysis_type)=0;
-		virtual void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum)=0;
+		virtual void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum)=0;
 };
 #endif
Index: /issm/trunk/src/c/classes/Loads/Loads.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Loads.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Loads/Loads.cpp	(revision 16137)
@@ -67,8 +67,6 @@
 
 	/*Grab sum of all cpus: */
-#ifdef _HAVE_MPI_
-	MPI_Allreduce((void*)&ispenalty,(void*)&allispenalty,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
+	ISSM_MPI_Allreduce((void*)&ispenalty,(void*)&allispenalty,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
 	ispenalty=allispenalty;
-#endif
 
 	if(ispenalty)
@@ -96,8 +94,6 @@
 
 	/*Grab max of all cpus: */
-#ifdef _HAVE_MPI_
-	MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
+	ISSM_MPI_Allreduce((void*)&max,(void*)&allmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
 	max=allmax;
-#endif
 
 	return max;
@@ -114,10 +110,6 @@
 
 	/*figure out total number of loads combining all the cpus (no clones here)*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce(&localloads,&numberofloads,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&numberofloads,1,MPI_INT,0,IssmComm::GetComm());
-	#else
-	numberofloads=localloads;
-	#endif
+	ISSM_MPI_Reduce(&localloads,&numberofloads,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&numberofloads,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 
 	return numberofloads;
@@ -140,10 +132,6 @@
 
 	/*figure out total number of loads combining all the cpus (no clones here)*/
-#ifdef _HAVE_MPI_
-	MPI_Reduce(&localloads,&numberofloads,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&numberofloads,1,MPI_INT,0,IssmComm::GetComm());
-#else
-	numberofloads=localloads;
-#endif
+	ISSM_MPI_Reduce(&localloads,&numberofloads,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&numberofloads,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 
 	return numberofloads;
Index: /issm/trunk/src/c/classes/Loads/Numericalflux.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Numericalflux.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Loads/Numericalflux.cpp	(revision 16137)
@@ -33,9 +33,7 @@
 /*}}}*/
 /*FUNCTION Numericalflux::Numericalflux(int id, int i, IoModel* iomodel, int analysis_type) {{{*/
-Numericalflux::Numericalflux(int numericalflux_id,int i, IoModel* iomodel, int in_analysis_type){
+Numericalflux::Numericalflux(int numericalflux_id,int i,int index,IoModel* iomodel, int in_analysis_type){
 
 	/* Intermediary */
-	int  e1,e2;
-	int  i1,i2;
 	int  j;
 	int  pos1,pos2,pos3,pos4;
@@ -50,19 +48,17 @@
 	int   numericalflux_type;
 
-	int    numberofelements;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-
 	/* Get MatPar id */
-	numericalflux_mparid=numberofelements+1; //matlab indexing
+	numericalflux_mparid=iomodel->numberofelements+1; //matlab indexing
+
+	/*Get edge*/
+	int i1 = iomodel->faces[4*index+0];
+	int i2 = iomodel->faces[4*index+1];
+	int e1 = iomodel->faces[4*index+2];
+	int e2 = iomodel->faces[4*index+3];
 
 	/*First, see wether this is an internal or boundary edge (if e2=-1)*/
-	if (iomodel->Data(MeshEdgesEnum)[4*i+3]==-1.){ //edges are [node1 node2 elem1 elem2]
+	if(e2==-1){
 		/* Boundary edge, only one element */
-		e1=reCast<int>(iomodel->Data(MeshEdgesEnum)[4*i+2]);
-		e2=reCast<int>(UNDEF);
-		num_elems=1;
-		num_nodes=2;
+		num_elems=1; num_nodes=2;
 		numericalflux_type=BoundaryEnum;
 		numericalflux_elem_ids[0]=e1;
@@ -70,8 +66,5 @@
 	else{
 		/* internal edge: connected to 2 elements */
-		e1=reCast<int>(iomodel->Data(MeshEdgesEnum)[4*i+2]);
-		e2=reCast<int>(iomodel->Data(MeshEdgesEnum)[4*i+3]);
-		num_elems=2;
-		num_nodes=4;
+		num_elems=2; num_nodes=4;
 		numericalflux_type=InternalEnum;
 		numericalflux_elem_ids[0]=e1;
@@ -80,6 +73,4 @@
 
 	/*1: Get vertices ids*/
-	i1=reCast<int>(iomodel->Data(MeshEdgesEnum)[4*i+0]);
-	i2=reCast<int>(iomodel->Data(MeshEdgesEnum)[4*i+1]);
 	numericalflux_vertex_ids[0]=i1;
 	numericalflux_vertex_ids[1]=i2;
@@ -93,8 +84,8 @@
 		pos1=pos2=pos3=pos4=UNDEF;
 		for(j=0;j<3;j++){
-			if (iomodel->Data(MeshElementsEnum)[3*(e1-1)+j]==i1) pos1=j+1;
-			if (iomodel->Data(MeshElementsEnum)[3*(e1-1)+j]==i2) pos2=j+1;
-			if (iomodel->Data(MeshElementsEnum)[3*(e2-1)+j]==i1) pos3=j+1;
-			if (iomodel->Data(MeshElementsEnum)[3*(e2-1)+j]==i2) pos4=j+1;
+			if(iomodel->elements[3*(e1-1)+j]==i1) pos1=j+1;
+			if(iomodel->elements[3*(e1-1)+j]==i2) pos2=j+1;
+			if(iomodel->elements[3*(e2-1)+j]==i1) pos3=j+1;
+			if(iomodel->elements[3*(e2-1)+j]==i2) pos4=j+1;
 		}
 		_assert_(pos1!=UNDEF && pos2!=UNDEF && pos3!=UNDEF && pos4!=UNDEF);
@@ -112,6 +103,6 @@
 		pos1=pos2=UNDEF;
 		for(j=0;j<3;j++){
-			if (iomodel->Data(MeshElementsEnum)[3*(e1-1)+j]==i1) pos1=j+1;
-			if (iomodel->Data(MeshElementsEnum)[3*(e1-1)+j]==i2) pos2=j+1;
+			if(iomodel->elements[3*(e1-1)+j]==i1) pos1=j+1;
+			if(iomodel->elements[3*(e1-1)+j]==i2) pos2=j+1;
 		}
 		_assert_(pos1!=UNDEF && pos2!=UNDEF);
@@ -263,6 +254,6 @@
 	/*Just branch to the correct element stiffness matrix generator, according to the type of analysis we are carrying out: */
 	switch(analysis_type){
-		case PrognosticAnalysisEnum:
-			Ke=CreateKMatrixPrognostic();
+		case MasstransportAnalysisEnum:
+			Ke=CreateKMatrixMasstransport();
 			break;
 		case BalancethicknessAnalysisEnum:
@@ -293,6 +284,6 @@
 
 	switch(analysis_type){
-		case PrognosticAnalysisEnum:
-			pe=CreatePVectorPrognostic();
+		case MasstransportAnalysisEnum:
+			pe=CreatePVectorMasstransport();
 			break;
 		case BalancethicknessAnalysisEnum:
@@ -334,4 +325,24 @@
 }
 /*}}}*/
+/*FUNCTION Numericalflux::GetNodesLidList{{{*/
+void Numericalflux::GetNodesLidList(int* lidlist){
+
+	int type;
+	inputs->GetInputValue(&type,NumericalfluxTypeEnum);
+	_assert_(lidlist);
+	_assert_(nodes);
+
+	switch(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(type) << " not supported yet");
+	}
+}
+/*}}}*/
 /*FUNCTION Numericalflux::GetNumberOfNodes{{{*/
 int Numericalflux::GetNumberOfNodes(void){
@@ -379,5 +390,5 @@
 /*}}}*/
 /*FUNCTION Numericalflux::SetwiseNodeConnectivity{{{*/
-void Numericalflux::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+void Numericalflux::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){
 
 	/*Output */
@@ -388,8 +399,12 @@
 	for(int i=0;i<this->GetNumberOfNodes();i++){
 
-		if(!flags[this->nodes[i]->Sid()]){
+		if(!flags[this->nodes[i]->Lid()]){
 
 			/*flag current node so that no other element processes it*/
-			flags[this->nodes[i]->Sid()]=true;
+			flags[this->nodes[i]->Lid()]=true;
+
+			int counter=0;
+			while(flagsindices[counter]>=0) counter++;
+			flagsindices[counter]=this->nodes[i]->Lid();
 
 			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
@@ -431,6 +446,6 @@
 
 /*Numericalflux management*/
-/*FUNCTION Numericalflux::CreateKMatrixPrognostic{{{*/
-ElementMatrix* Numericalflux::CreateKMatrixPrognostic(void){
+/*FUNCTION Numericalflux::CreateKMatrixMasstransport{{{*/
+ElementMatrix* Numericalflux::CreateKMatrixMasstransport(void){
 
 	int type;
@@ -439,7 +454,7 @@
 	switch(type){
 		case InternalEnum:
-			return CreateKMatrixPrognosticInternal();
+			return CreateKMatrixMasstransportInternal();
 		case BoundaryEnum:
-			return CreateKMatrixPrognosticBoundary();
+			return CreateKMatrixMasstransportBoundary();
 		default:
 			_error_("type not supported yet");
@@ -447,6 +462,6 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreateKMatrixPrognosticInternal {{{*/
-ElementMatrix* Numericalflux::CreateKMatrixPrognosticInternal(void){
+/*FUNCTION Numericalflux::CreateKMatrixMasstransportInternal {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixMasstransportInternal(void){
 
 	/* constants*/
@@ -466,5 +481,5 @@
 	/*Initialize Element matrix and return if necessary*/
 	Tria*  tria=(Tria*)element;
-	if(tria->IsOnWater()) return NULL;
+	if(tria->NoIceInElement()) return NULL;
 	ElementMatrix* Ke=new ElementMatrix(nodes,NUMNODES_INTERNAL,this->parameters);
 
@@ -512,6 +527,6 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreateKMatrixPrognosticBoundary {{{*/
-ElementMatrix* Numericalflux::CreateKMatrixPrognosticBoundary(void){
+/*FUNCTION Numericalflux::CreateKMatrixMasstransportBoundary {{{*/
+ElementMatrix* Numericalflux::CreateKMatrixMasstransportBoundary(void){
 
 	/* constants*/
@@ -530,5 +545,5 @@
 	ElementMatrix* Ke = NULL;
 	Tria*  tria=(Tria*)element;
-	if(tria->IsOnWater()) return NULL;
+	if(tria->NoIceInElement()) return NULL;
 
 	/*Retrieve all inputs and parameters*/
@@ -619,5 +634,5 @@
 	/*Initialize Element matrix and return if necessary*/
 	Tria*  tria=(Tria*)element;
-	if(tria->IsOnWater()) return NULL;
+	if(tria->NoIceInElement()) return NULL;
 	ElementMatrix* Ke=new ElementMatrix(nodes,NUMNODES_INTERNAL,this->parameters);
 
@@ -682,5 +697,5 @@
 	ElementMatrix* Ke = NULL;
 	Tria*  tria=(Tria*)element;
-	if(tria->IsOnWater()) return NULL;
+	if(tria->NoIceInElement()) return NULL;
 
 	/*Retrieve all inputs and parameters*/
@@ -767,6 +782,6 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreatePVectorPrognostic{{{*/
-ElementVector* Numericalflux::CreatePVectorPrognostic(void){
+/*FUNCTION Numericalflux::CreatePVectorMasstransport{{{*/
+ElementVector* Numericalflux::CreatePVectorMasstransport(void){
 
 	int type;
@@ -775,7 +790,7 @@
 	switch(type){
 		case InternalEnum:
-			return CreatePVectorPrognosticInternal();
+			return CreatePVectorMasstransportInternal();
 		case BoundaryEnum:
-			return CreatePVectorPrognosticBoundary();
+			return CreatePVectorMasstransportBoundary();
 		default:
 			_error_("type not supported yet");
@@ -783,6 +798,6 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreatePVectorPrognosticInternal{{{*/
-ElementVector* Numericalflux::CreatePVectorPrognosticInternal(void){
+/*FUNCTION Numericalflux::CreatePVectorMasstransportInternal{{{*/
+ElementVector* Numericalflux::CreatePVectorMasstransportInternal(void){
 
 	/*Nothing added to PVector*/
@@ -791,6 +806,6 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::CreatePVectorPrognosticBoundary{{{*/
-ElementVector* Numericalflux::CreatePVectorPrognosticBoundary(void){
+/*FUNCTION Numericalflux::CreatePVectorMasstransportBoundary{{{*/
+ElementVector* Numericalflux::CreatePVectorMasstransportBoundary(void){
 
 	/* constants*/
@@ -808,5 +823,5 @@
 	ElementVector* pe = NULL;
 	Tria*  tria=(Tria*)element;
-	if(tria->IsOnWater()) return NULL;
+	if(tria->NoIceInElement()) return NULL;
 
 	/*Retrieve all inputs and parameters*/
@@ -815,5 +830,5 @@
 	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(PrognosticSpcthicknessEnum); _assert_(spcthickness_input);
+	Input* spcthickness_input=tria->inputs->GetInput(MasstransportSpcthicknessEnum); _assert_(spcthickness_input);
 	GetNormal(&normal[0],xyz_list);
 
@@ -902,5 +917,5 @@
 	ElementVector* pe = NULL;
 	Tria*  tria=(Tria*)element;
-	if(tria->IsOnWater()) return NULL;
+	if(tria->NoIceInElement()) return NULL;
 
 	/*Retrieve all inputs and parameters*/
Index: /issm/trunk/src/c/classes/Loads/Numericalflux.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Numericalflux.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Loads/Numericalflux.h	(revision 16137)
@@ -7,5 +7,4 @@
 
 /*Headers:*/
-/*{{{*/
 #include "./Load.h"
 class Hook;
@@ -13,7 +12,8 @@
 class Inputs;
 class IoModel;
+class Element;
+class Vertex;
 class ElementMatrix;
 class ElementVector;
-/*}}}*/
 
 class Numericalflux: public Load {
@@ -37,5 +37,5 @@
 		/*Numericalflux constructors,destructors {{{*/
 		Numericalflux();
-		Numericalflux(int numericalflux_id,int i, IoModel* iomodel,int analysis_type);
+		Numericalflux(int numericalflux_id,int i,int index,IoModel* iomodel,int analysis_type);
 		~Numericalflux();
 		/*}}}*/
@@ -49,10 +49,6 @@
 		/*Update virtual functions resolution: {{{*/
 		void InputUpdateFromVector(IssmDouble* vector, int name, int type){/*Do nothing*/}
-		void InputUpdateFromVector(int* vector, int name, int type){_error_("Not implemented yet!");}
-		void InputUpdateFromVector(bool* vector, int name, int type){_error_("Not implemented yet!");}
 		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 InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
-		void InputUpdateFromVectorDakota(bool* vector, int name, int type){_error_("Not implemented yet!");}
 		void InputUpdateFromConstant(IssmDouble constant, int name){/*Do nothing*/};
 		void InputUpdateFromConstant(int constant, int name){/*Do nothing*/};
@@ -67,4 +63,5 @@
 		void CreatePVector(Vector<IssmDouble>* pf);
 		void GetNodesSidList(int* sidlist);
+		void GetNodesLidList(int* lidlist);
 		int  GetNumberOfNodes(void);
 		void CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
@@ -73,12 +70,12 @@
 		void PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
 		void PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
-		void SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
+		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);
 		/*}}}*/
 		/*Numericalflux management:{{{*/
 		void           GetNormal(IssmDouble* normal,IssmDouble xyz_list[4][3]);
-		ElementMatrix* CreateKMatrixPrognostic(void);
-		ElementMatrix* CreateKMatrixPrognosticInternal(void);
-		ElementMatrix* CreateKMatrixPrognosticBoundary(void);
+		ElementMatrix* CreateKMatrixMasstransport(void);
+		ElementMatrix* CreateKMatrixMasstransportInternal(void);
+		ElementMatrix* CreateKMatrixMasstransportBoundary(void);
 		ElementMatrix* CreateKMatrixBalancethickness(void);
 		ElementMatrix* CreateKMatrixBalancethicknessInternal(void);
@@ -87,7 +84,7 @@
 		ElementMatrix* CreateKMatrixAdjointBalancethicknessInternal(void);
 		ElementMatrix* CreateKMatrixAdjointBalancethicknessBoundary(void);
-		ElementVector* CreatePVectorPrognostic(void);
-		ElementVector* CreatePVectorPrognosticInternal(void);
-		ElementVector* CreatePVectorPrognosticBoundary(void);
+		ElementVector* CreatePVectorMasstransport(void);
+		ElementVector* CreatePVectorMasstransportInternal(void);
+		ElementVector* CreatePVectorMasstransportBoundary(void);
 		ElementVector* CreatePVectorBalancethickness(void);
 		ElementVector* CreatePVectorBalancethicknessInternal(void);
Index: /issm/trunk/src/c/classes/Loads/Pengrid.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Pengrid.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Loads/Pengrid.cpp	(revision 16137)
@@ -43,14 +43,7 @@
 	int pengrid_element_id;
 
-	int numberofvertices;
-	int numberofelements;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-
 	/*Some checks if debugging activated*/
 	_assert_(iomodel->singlenodetoelementconnectivity);
-	_assert_(index>=0 && index<numberofvertices);
+	_assert_(index>=0 && index<iomodel->numberofvertices);
 	_assert_(id);
 
@@ -63,5 +56,5 @@
 	pengrid_element_id=iomodel->singlenodetoelementconnectivity[index];
 	_assert_(pengrid_element_id);
-	pengrid_matpar_id=numberofelements+1; //refers to the constant material parameters object
+	pengrid_matpar_id=iomodel->numberofelements+1; //refers to the constant material parameters object
 
 	this->hnode=new Hook(&pengrid_node_id,1);
@@ -213,4 +206,13 @@
 }
 /*}}}*/
+/*FUNCTION Pengrid::GetNodesLidList{{{*/
+void Pengrid::GetNodesLidList(int* lidlist){
+
+	_assert_(lidlist);
+	_assert_(node);
+
+	lidlist[0]=node->Lid();
+}
+/*}}}*/
 /*FUNCTION Pengrid::GetNumberOfNodes{{{*/
 int Pengrid::GetNumberOfNodes(void){
@@ -228,9 +230,4 @@
 
 	switch(analysis_type){
-		#ifdef _HAVE_DIAGNOSTIC_
-		case DiagnosticHorizAnalysisEnum: case AdjointHorizAnalysisEnum:
-			Ke=PenaltyCreateKMatrixDiagnosticStokes(kmax);
-			break;
-		#endif
 		#ifdef _HAVE_THERMAL_
 		case ThermalAnalysisEnum:
@@ -273,5 +270,5 @@
 			pe=PenaltyCreatePVectorMelting(kmax);
 			break;
-		case DiagnosticHorizAnalysisEnum: case AdjointHorizAnalysisEnum:
+		case StressbalanceAnalysisEnum: case AdjointHorizAnalysisEnum:
 			break;
 		#endif
@@ -304,5 +301,5 @@
 /*}}}*/
 /*FUNCTION Pengrid::SetwiseNodeConnectivity{{{*/
-void Pengrid::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+void Pengrid::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){
 
 	/*Output */
@@ -310,8 +307,12 @@
 	int o_nz = 0;
 
-	if(!flags[this->node->Sid()]){
+	if(!flags[this->node->Lid()]){
 
 		/*flag current node so that no other element processes it*/
-		flags[this->node->Sid()]=true;
+		flags[this->node->Lid()]=true;
+
+		int counter=0;
+		while(flagsindices[counter]>=0) counter++;
+		flagsindices[counter]=this->node->Lid();
 
 		/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
@@ -357,14 +358,4 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::InputUpdateFromVector(int* vector, int name, int type) {{{*/
-void  Pengrid::InputUpdateFromVector(int* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Pengrid::InputUpdateFromVector(bool* vector, int name, int type) {{{*/
-void  Pengrid::InputUpdateFromVector(bool* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
 /*FUNCTION Pengrid::InputUpdateFromMatrixDakota(IssmDouble* vector, int nrows, int ncols, int name, int type) {{{*/
 void  Pengrid::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){
@@ -377,14 +368,4 @@
 }
 /*}}}*/
-/*FUNCTION Pengrid::InputUpdateFromVectorDakota(int* vector, int name, int type) {{{*/
-void  Pengrid::InputUpdateFromVectorDakota(int* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Pengrid::InputUpdateFromVectorDakota(bool* vector, int name, int type) {{{*/
-void  Pengrid::InputUpdateFromVectorDakota(bool* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
 /*FUNCTION Pengrid::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
 void  Pengrid::InputUpdateFromConstant(IssmDouble constant, int name){
@@ -430,5 +411,5 @@
 	this->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 
-	if (analysis_type==DiagnosticHorizAnalysisEnum){
+	if (analysis_type==StressbalanceAnalysisEnum){
 		/*No penalty to check*/
 		return;
@@ -455,38 +436,4 @@
 }
 /*}}}*/
-#ifdef _HAVE_DIAGNOSTIC_
-/*FUNCTION Pengrid::PenaltyCreateKMatrixDiagnosticStokes {{{*/
-ElementMatrix* Pengrid::PenaltyCreateKMatrixDiagnosticStokes(IssmDouble kmax){
-
-	const int numdof = NUMVERTICES *NDOF4;
-	IssmDouble    slope[2];
-	IssmDouble    penalty_offset;
-	int       approximation;
-
-	Penta* penta=(Penta*)element;
-
-	/*Initialize Element vector and return if necessary*/
-	penta->inputs->GetInputValue(&approximation,ApproximationEnum);
-	if(approximation!=StokesApproximationEnum &&  approximation!=PattynStokesApproximationEnum) return NULL;
-	ElementMatrix* Ke=new ElementMatrix(&node,1,this->parameters,StokesApproximationEnum);
-
-	/*Retrieve all inputs and parameters*/
-	parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
-	penta->GetInputValue(&slope[0],node,BedSlopeXEnum);
-	penta->GetInputValue(&slope[1],node,BedSlopeYEnum);
-
-	/*Create elementary matrix: add penalty to constrain wb (wb=ub*db/dx+vb*db/dy)*/
-	Ke->values[2*NDOF4+0]=-slope[0]*kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[2*NDOF4+1]=-slope[1]*kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[2*NDOF4+2]= kmax*pow((IssmDouble)10,penalty_offset);
-
-	/*Transform Coordinate System*/
-	TransformStiffnessMatrixCoord(Ke,&node,NUMVERTICES,XYZPEnum);
-
-	/*Clean up and return*/
-	return Ke;
-}
-/*}}}*/
-#endif
 #ifdef _HAVE_THERMAL_
 /*FUNCTION Pengrid::ConstraintActivateThermal {{{*/
@@ -581,5 +528,5 @@
 	/*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((IssmDouble)10,penalty_factor);
+		Ke->values[0]=kmax*pow(10.,penalty_factor);
 	}
 
@@ -601,5 +548,5 @@
 	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
 
-	Ke->values[0]=kmax*pow((IssmDouble)10,penalty_factor);
+	Ke->values[0]=kmax*pow(10.,penalty_factor);
 
 	/*Clean up and return*/
@@ -642,6 +589,6 @@
 	}
 	else{
-		if (reCast<bool>(dt)) pe->values[0]=melting_offset*pow((IssmDouble)10,penalty_factor)*(temperature-t_pmp)/dt;
-		else    pe->values[0]=melting_offset*pow((IssmDouble)10,penalty_factor)*(temperature-t_pmp);
+		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);
 	}
 
@@ -671,5 +618,5 @@
 	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
 
-	pe->values[0]=kmax*pow((IssmDouble)10,penalty_factor)*t_pmp;
+	pe->values[0]=kmax*pow(10.,penalty_factor)*t_pmp;
 
 	/*Clean up and return*/
Index: /issm/trunk/src/c/classes/Loads/Pengrid.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Pengrid.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Loads/Pengrid.h	(revision 16137)
@@ -59,10 +59,6 @@
 		/*Update virtual functions resolution: {{{*/
 		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVector(int* vector, int name, int type);
-		void  InputUpdateFromVector(bool* vector, int name, int type);
 		void  InputUpdateFromMatrixDakota(IssmDouble* matrix ,int nrows, int ncols, int name, int type);
 		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
 		void  InputUpdateFromConstant(IssmDouble constant, int name);
 		void  InputUpdateFromConstant(int constant, int name);
@@ -78,4 +74,5 @@
 		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
 		void  GetNodesSidList(int* sidlist);
+		void  GetNodesLidList(int* lidlist);
 		int   GetNumberOfNodes(void);
 		bool  IsPenalty(void);
@@ -83,11 +80,8 @@
 		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
 		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
-		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
+		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);
 		/*}}}*/
 		/*Pengrid management {{{*/
-		#ifdef _HAVE_DIAGNOSTIC_
-		ElementMatrix* PenaltyCreateKMatrixDiagnosticStokes(IssmDouble kmax);
-		#endif
 		#ifdef _HAVE_THERMAL_
 		ElementMatrix* PenaltyCreateKMatrixThermal(IssmDouble kmax);
Index: /issm/trunk/src/c/classes/Loads/Penpair.cpp
===================================================================
--- /issm/trunk/src/c/classes/Loads/Penpair.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Loads/Penpair.cpp	(revision 16137)
@@ -153,4 +153,13 @@
 }
 /*}}}*/
+/*FUNCTION Penpair::GetNodesLidList{{{*/
+void Penpair::GetNodesLidList(int* lidlist){
+
+	_assert_(lidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) lidlist[i]=nodes[i]->Lid();
+}
+/*}}}*/
 /*FUNCTION Penpair::GetNumberOfNodes{{{*/
 int Penpair::GetNumberOfNodes(void){
@@ -173,9 +182,9 @@
 
 	switch(analysis_type){
-		case DiagnosticHorizAnalysisEnum:
-			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+		case StressbalanceAnalysisEnum:
+			Ke=PenaltyCreateKMatrixStressbalanceHoriz(kmax);
 			break;
-		case PrognosticAnalysisEnum:
-			Ke=PenaltyCreateKMatrixPrognostic(kmax);
+		case MasstransportAnalysisEnum:
+			Ke=PenaltyCreateKMatrixMasstransport(kmax);
 			break;
 		default:
@@ -208,5 +217,5 @@
 /*}}}*/
 /*FUNCTION Penpair::SetwiseNodeConnectivity{{{*/
-void Penpair::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+void Penpair::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){
 
 	/*Output */
@@ -217,8 +226,12 @@
 	for(int i=0;i<NUMVERTICES;i++){
 
-		if(!flags[this->nodes[i]->Sid()]){
+		if(!flags[this->nodes[i]->Lid()]){
 
 			/*flag current node so that no other element processes it*/
-			flags[this->nodes[i]->Sid()]=true;
+			flags[this->nodes[i]->Lid()]=true;
+
+			int counter=0;
+			while(flagsindices[counter]>=0) counter++;
+			flagsindices[counter]=this->nodes[i]->Lid();
 
 			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
@@ -280,18 +293,8 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::InputUpdateFromVector(int* vector, int name, int type) {{{*/
-void  Penpair::InputUpdateFromVector(int* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Penpair::InputUpdateFromVector(bool* vector, int name, int type) {{{*/
-void  Penpair::InputUpdateFromVector(bool* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
 
 /*Penpair management:*/
-/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticHoriz{{{*/
-ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticHoriz(IssmDouble kmax){
+/*FUNCTION Penpair::PenaltyCreateKMatrixStressbalanceHoriz{{{*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax){
 
 	int    approximation0=nodes[0]->GetApproximation();
@@ -299,34 +302,33 @@
 
 	switch(approximation0){
-		case MacAyealApproximationEnum:
+		case SSAApproximationEnum:
 			switch(approximation1){
-				case MacAyealApproximationEnum: return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
-				case PattynApproximationEnum:   return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
-				default: _error_("not supported yet");
+				case SSAApproximationEnum: return PenaltyCreateKMatrixStressbalanceSSAHO(kmax); 
+				case HOApproximationEnum:   return PenaltyCreateKMatrixStressbalanceSSAHO(kmax); 
+				default: _error_("Approximation "<<EnumToStringx(approximation1)<<" not supported yet");
 			}
-		case PattynApproximationEnum:
+		case HOApproximationEnum:
 			switch(approximation1){
-				case MacAyealApproximationEnum: return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
-				case PattynApproximationEnum:   return PenaltyCreateKMatrixDiagnosticMacAyealPattyn(kmax); 
-				default: _error_("not supported yet");
+				case SSAApproximationEnum: return PenaltyCreateKMatrixStressbalanceSSAHO(kmax); 
+				case HOApproximationEnum:   return PenaltyCreateKMatrixStressbalanceSSAHO(kmax); 
+				default: _error_("Approximation "<<EnumToStringx(approximation1)<<" not supported yet");
 			}
-		case StokesApproximationEnum:
+		case FSvelocityEnum:
 			switch(approximation1){
-				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
-				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
-				default: _error_("not supported yet");
+				case FSvelocityEnum: return PenaltyCreateKMatrixStressbalanceFS(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixStressbalanceFS(kmax); 
+				default: _error_("Approximation "<<EnumToStringx(approximation1)<<" not supported yet");
 			}
 		case NoneApproximationEnum:
 			switch(approximation1){
-				case StokesApproximationEnum: return PenaltyCreateKMatrixDiagnosticStokes(kmax); 
-				case NoneApproximationEnum: return   PenaltyCreateKMatrixDiagnosticStokes(kmax); 
-				default: _error_("not supported yet");
+				case FSvelocityEnum: return PenaltyCreateKMatrixStressbalanceFS(kmax); 
+				case NoneApproximationEnum: return   PenaltyCreateKMatrixStressbalanceFS(kmax); 
 			}
-		default: _error_("not supported yet");
+		default: _error_("Approximation "<<EnumToStringx(approximation0)<<" not supported yet");
 	}
 }
 /*}}}*/
-/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn {{{*/
-ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn(IssmDouble kmax){
+/*FUNCTION Penpair::PenaltyCreateKMatrixStressbalanceSSAHO {{{*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceSSAHO(IssmDouble kmax){
 
 	const int numdof=NUMVERTICES*NDOF2;
@@ -337,16 +339,16 @@
 
 	/*recover parameters: */
-	parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+	parameters->FindParam(&penalty_offset,StressbalancePenaltyFactorEnum);
 
 	//Create elementary matrix: add penalty to 
-	Ke->values[0*numdof+0]=+kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[0*numdof+2]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[2*numdof+0]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[2*numdof+2]=+kmax*pow((IssmDouble)10.0,penalty_offset);
-
-	Ke->values[1*numdof+1]=+kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[1*numdof+3]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[3*numdof+1]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[3*numdof+3]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+	Ke->values[0*numdof+0]=+kmax*pow(10.,penalty_offset);
+	Ke->values[0*numdof+2]=-kmax*pow(10.,penalty_offset);
+	Ke->values[2*numdof+0]=-kmax*pow(10.,penalty_offset);
+	Ke->values[2*numdof+2]=+kmax*pow(10.,penalty_offset);
+
+	Ke->values[1*numdof+1]=+kmax*pow(10.,penalty_offset);
+	Ke->values[1*numdof+3]=-kmax*pow(10.,penalty_offset);
+	Ke->values[3*numdof+1]=-kmax*pow(10.,penalty_offset);
+	Ke->values[3*numdof+3]=+kmax*pow(10.,penalty_offset);
 
 	/*Clean up and return*/
@@ -354,8 +356,8 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticStokes {{{*/
-ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticStokes(IssmDouble kmax){
-
-	const int numdof=NUMVERTICES*NDOF4;
+/*FUNCTION Penpair::PenaltyCreateKMatrixStressbalanceFS {{{*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixStressbalanceFS(IssmDouble kmax){
+
+	const int  numdof=NUMVERTICES*NDOF3;
 	IssmDouble penalty_offset;
 
@@ -364,26 +366,21 @@
 
 	/*recover parameters: */
-	parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+	parameters->FindParam(&penalty_offset,StressbalancePenaltyFactorEnum);
 
 	//Create elementary matrix: add penalty to 
-	Ke->values[0*numdof+0]=+kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[0*numdof+4]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[4*numdof+0]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[4*numdof+4]=+kmax*pow((IssmDouble)10.0,penalty_offset);
-
-	Ke->values[1*numdof+1]=+kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[1*numdof+5]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[5*numdof+1]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[5*numdof+5]=+kmax*pow((IssmDouble)10.0,penalty_offset);
-
-	Ke->values[2*numdof+2]=+kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[2*numdof+6]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[6*numdof+2]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[6*numdof+6]=+kmax*pow((IssmDouble)10.0,penalty_offset);
-
-	Ke->values[3*numdof+3]=+kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[3*numdof+7]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[7*numdof+3]=-kmax*pow((IssmDouble)10.0,penalty_offset);
-	Ke->values[7*numdof+7]=+kmax*pow((IssmDouble)10.0,penalty_offset);
+	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*/
@@ -391,6 +388,6 @@
 }
 /*}}}*/
-/*FUNCTION Penpair::PenaltyCreateKMatrixPrognostic {{{*/
-ElementMatrix* Penpair::PenaltyCreateKMatrixPrognostic(IssmDouble kmax){
+/*FUNCTION Penpair::PenaltyCreateKMatrixMasstransport {{{*/
+ElementMatrix* Penpair::PenaltyCreateKMatrixMasstransport(IssmDouble kmax){
 
 	const int numdof=NUMVERTICES*NDOF1;
@@ -401,11 +398,11 @@
 
 	/*recover parameters: */
-	parameters->FindParam(&penalty_factor,PrognosticPenaltyFactorEnum);
+	parameters->FindParam(&penalty_factor,MasstransportPenaltyFactorEnum);
 
 	//Create elementary matrix: add penalty to 
-	Ke->values[0*numdof+0]=+kmax*pow((IssmDouble)10.0,penalty_factor);
-	Ke->values[0*numdof+1]=-kmax*pow((IssmDouble)10.0,penalty_factor);
-	Ke->values[1*numdof+0]=-kmax*pow((IssmDouble)10.0,penalty_factor);
-	Ke->values[1*numdof+1]=+kmax*pow((IssmDouble)10.0,penalty_factor);
+	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*/
Index: /issm/trunk/src/c/classes/Loads/Penpair.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Penpair.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Loads/Penpair.h	(revision 16137)
@@ -39,10 +39,6 @@
 		/*Update virtual functions resolution: {{{*/
 		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVector(int* vector, int name, int type);
-		void  InputUpdateFromVector(bool* 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  InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
-		void  InputUpdateFromVectorDakota(bool* vector, int name, int type){_error_("Not implemented yet!");}
 		void  InputUpdateFromConstant(IssmDouble constant, int name);
 		void  InputUpdateFromConstant(int constant, int name);
@@ -58,4 +54,5 @@
 		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
 		void  GetNodesSidList(int* sidlist);
+		void  GetNodesLidList(int* lidlist);
 		int   GetNumberOfNodes(void);
 		bool  IsPenalty(void);
@@ -63,12 +60,12 @@
 		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 set1_enum,int set2_enum);
+		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* PenaltyCreateKMatrixDiagnosticHoriz(IssmDouble kmax);
-		ElementMatrix* PenaltyCreateKMatrixDiagnosticMacAyealPattyn(IssmDouble kmax);
-		ElementMatrix* PenaltyCreateKMatrixDiagnosticStokes(IssmDouble kmax);
-		ElementMatrix* PenaltyCreateKMatrixPrognostic(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 16136)
+++ /issm/trunk/src/c/classes/Loads/Riftfront.cpp	(revision 16137)
@@ -44,5 +44,4 @@
 	IssmDouble riftfront_fractionincrement;
 	bool   riftfront_shelf;
-	int    numberofelements;
 	int    penalty_lock;
 
@@ -52,6 +51,5 @@
 
 	/*Fetch parameters: */
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->Constant(&penalty_lock,DiagnosticRiftPenaltyLockEnum);
+	iomodel->Constant(&penalty_lock,StressbalanceRiftPenaltyLockEnum);
 
 	/*Ok, retrieve all the data needed to add a penalty between the two nodes: */
@@ -71,5 +69,5 @@
 	riftfront_elem_ids[0]=el1;
 	riftfront_elem_ids[1]=el2;
-	riftfront_matpar_id=numberofelements+1; //matlab indexing
+	riftfront_matpar_id=iomodel->numberofelements+1; //matlab indexing
 
 	/*Hooks: */
@@ -98,5 +96,5 @@
 	riftfront_friction=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+8);
 	riftfront_fractionincrement=*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+10);
-	riftfront_shelf=reCast<bool,IssmDouble>(iomodel->Data(MaskVertexonfloatingiceEnum)[node1-1]);
+	riftfront_shelf=reCast<bool,IssmDouble>(iomodel->Data(MaskGroundediceLevelsetEnum)[node1-1]<0.);
 
 	this->inputs->AddInput(new IntInput(RiftfrontTypeEnum,riftfront_type));
@@ -258,5 +256,5 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::InputUpdateFromConstant(IssmDouble* constant,int name) {{{*/
+/*FUNCTION Riftfront::InputUpdateFromVector(IssmDouble* constant,int name) {{{*/
 void    Riftfront::InputUpdateFromVector(IssmDouble* vector, int name, int type){
 
@@ -310,9 +308,9 @@
 
 	switch(analysis_type){
-		case DiagnosticHorizAnalysisEnum:
-			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+		case StressbalanceAnalysisEnum:
+			Ke=PenaltyCreateKMatrixStressbalanceHoriz(kmax);
 			break;
 		case AdjointHorizAnalysisEnum:
-			Ke=PenaltyCreateKMatrixDiagnosticHoriz(kmax);
+			Ke=PenaltyCreateKMatrixStressbalanceHoriz(kmax);
 			break;
 		default:
@@ -336,6 +334,6 @@
 
 	switch(analysis_type){
-		case DiagnosticHorizAnalysisEnum:
-			pe=PenaltyCreatePVectorDiagnosticHoriz(kmax);
+		case StressbalanceAnalysisEnum:
+			pe=PenaltyCreatePVectorStressbalanceHoriz(kmax);
 			break;
 		case AdjointHorizAnalysisEnum:
@@ -374,4 +372,13 @@
 }
 /*}}}*/
+/*FUNCTION Riftfront::GetNodesLidList{{{*/
+void Riftfront::GetNodesLidList(int* lidlist){
+
+	_assert_(lidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) lidlist[i]=nodes[i]->Lid();
+}
+/*}}}*/
 /*FUNCTION Riftfront::GetNumberOfNodes{{{*/
 int Riftfront::GetNumberOfNodes(void){
@@ -387,5 +394,5 @@
 /*}}}*/
 /*FUNCTION Riftfront::SetwiseNodeConnectivity{{{*/
-void Riftfront::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+void Riftfront::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int* flagsindices,int set1_enum,int set2_enum){
 
 	/*Output */
@@ -396,8 +403,12 @@
 	for(int i=0;i<NUMVERTICES;i++){
 
-		if(!flags[this->nodes[i]->Sid()]){
+		if(!flags[this->nodes[i]->Lid()]){
 
 			/*flag current node so that no other element processes it*/
-			flags[this->nodes[i]->Sid()]=true;
+			flags[this->nodes[i]->Lid()]=true;
+
+			int counter=0;
+			while(flagsindices[counter]>=0) counter++;
+			flagsindices[counter]=this->nodes[i]->Lid();
 
 			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
@@ -439,6 +450,6 @@
 
 /*Riftfront numerics*/
-/*FUNCTION Riftfront::PenaltyCreateKMatrixDiagnosticHoriz {{{*/
-ElementMatrix* Riftfront::PenaltyCreateKMatrixDiagnosticHoriz(IssmDouble kmax){
+/*FUNCTION Riftfront::PenaltyCreateKMatrixStressbalanceHoriz {{{*/
+ElementMatrix* Riftfront::PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax){
 
 	const int   numdof = NDOF2*NUMVERTICES;
@@ -463,5 +474,5 @@
 
 	/*Get some parameters: */
-	this->parameters->FindParam(&penalty_offset,DiagnosticPenaltyFactorEnum);
+	this->parameters->FindParam(&penalty_offset,StressbalancePenaltyFactorEnum);
 	this->inputs->GetInputValue(&friction,FrictionEnum);
 	tria1->GetInputValue(&h[0],nodes[0],ThicknessEnum);
@@ -520,6 +531,6 @@
 }
 /*}}}*/
-/*FUNCTION Riftfront::PenaltyCreatePVectorDiagnosticHoriz {{{*/
-ElementVector* Riftfront::PenaltyCreatePVectorDiagnosticHoriz(IssmDouble kmax){
+/*FUNCTION Riftfront::PenaltyCreatePVectorStressbalanceHoriz {{{*/
+ElementVector* Riftfront::PenaltyCreatePVectorStressbalanceHoriz(IssmDouble kmax){
 
 	const int  numdof = NDOF2*NUMVERTICES;
@@ -578,13 +589,13 @@
 		if(shelf){
 			/*We are on an ice shelf, hydrostatic equilibrium is used to determine the pressure for water fill: */
-			pressure=rho_ice*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2  - rho_water*gravity*pow(bed,(IssmDouble)2)/(IssmDouble)2; 
+			pressure=rho_ice*gravity*pow(thickness,2)/2.- rho_water*gravity*pow(bed,2)/2.; 
 		}
 		else{
 			//We are on an icesheet, we assume the water column fills the entire front: */
-			pressure=rho_ice*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2  - rho_water*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2; 
+			pressure=rho_ice*gravity*pow(thickness,2)/2.- rho_water*gravity*pow(thickness,2)/2.; 
 		}
 	}
 	else if(fill==AirEnum){
-		pressure=rho_ice*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2;   //icefront on an ice sheet, pressure imbalance ice vs air.
+		pressure=rho_ice*gravity*pow(thickness,2)/2.;   //icefront on an ice sheet, pressure imbalance ice vs air.
 	}
 	else if(fill==IceEnum){ //icefront finding itself against another icefront (pressure imbalance is fully compensated, ice vs ice)
@@ -595,7 +606,7 @@
 		if(!shelf) _error_("fill type " << fill << " not supported on ice sheets yet.");
 
-		pressure_litho=rho_ice*gravity*pow(thickness,(IssmDouble)2)/(IssmDouble)2;
+		pressure_litho=rho_ice*gravity*pow(thickness,2)/2.;
 		pressure_air=0;
-		pressure_melange=rho_ice*gravity*pow(fraction*thickness,(IssmDouble)2)/(IssmDouble)2;
+		pressure_melange=rho_ice*gravity*pow(fraction*thickness,2)/2.;
 		pressure_water=1.0/2.0*rho_water*gravity*  ( pow(bed,2.0)-pow(rho_ice/rho_water*fraction*thickness,2.0) );
 
@@ -686,5 +697,5 @@
 		/*increase melange fraction: */
 		this->fraction+=fractionincrement;
-		if (this->fraction>1)this->fraction=(IssmDouble)1.0;
+		if (this->fraction>1)this->fraction=1.;
 		//_printf_("riftfront " << this->Id() << " fraction: " << this->fraction << "\n");
 	}
Index: /issm/trunk/src/c/classes/Loads/Riftfront.h
===================================================================
--- /issm/trunk/src/c/classes/Loads/Riftfront.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Loads/Riftfront.h	(revision 16137)
@@ -60,10 +60,6 @@
 		/*Update virtual functions resolution: {{{*/
 		void    InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void    InputUpdateFromVector(int* vector, int name, int type){_error_("Not implemented yet!");}
-		void    InputUpdateFromVector(bool* vector, int name, int type){_error_("Not implemented yet!");}
 		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    InputUpdateFromVectorDakota(int* vector, int name, int type){_error_("Not implemented yet!");}
-		void    InputUpdateFromVectorDakota(bool* 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!");}
@@ -79,4 +75,5 @@
 		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
 		void  GetNodesSidList(int* sidlist);
+		void  GetNodesLidList(int* lidlist);
 		int   GetNumberOfNodes(void);
 		bool  IsPenalty(void);
@@ -84,11 +81,11 @@
 		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
 		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
-		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
+		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: {{{*/
 		bool  PreStable();
-		ElementMatrix* PenaltyCreateKMatrixDiagnosticHoriz(IssmDouble kmax);
-		ElementVector* PenaltyCreatePVectorDiagnosticHoriz(IssmDouble kmax);
+		ElementMatrix* PenaltyCreateKMatrixStressbalanceHoriz(IssmDouble kmax);
+		ElementVector* PenaltyCreatePVectorStressbalanceHoriz(IssmDouble kmax);
 		void  SetPreStable();
 		int   PreConstrain(int* punstable);
Index: sm/trunk/src/c/classes/Materials/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Materials/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,10 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/objects/Materials)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/Materials/Matdamageice.cpp
-                       $ENV{ISSM_DIR}/src/c/classes/objects/Materials/Matice.cpp
-                       $ENV{ISSM_DIR}/src/c/classes/objects/Materials/Matpar.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/classes/Materials/Matdamageice.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matdamageice.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Materials/Matdamageice.cpp	(revision 16137)
@@ -249,5 +249,5 @@
 	else{
 		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
-			viscosity=0.5*pow((IssmDouble)10,(IssmDouble)14);
+			viscosity=0.5*pow(10.,14);
 		}
 		else{
@@ -261,5 +261,5 @@
 			if(A==0){
 				/*Maxiviscositym viscosity for 0 shear areas: */
-				viscosity=2.5*pow(10.,17.);
+				viscosity=2.5*pow(10.,17);
 			}
 			else{
@@ -282,5 +282,5 @@
 void  Matdamageice::GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* epsilon){
 
-	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
 	 *
 	 *                                               B
@@ -317,5 +317,5 @@
 		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
 				(epsilon[3]==0) && (epsilon[4]==0)){
-			viscosity3d=0.5*pow((IssmDouble)10,(IssmDouble)14);
+			viscosity3d=0.5*pow(10.,14);
 		}
 		else{
@@ -332,5 +332,5 @@
 			if(A==0){
 				/*Maxiviscosity3dm viscosity for 0 shear areas: */
-				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+				viscosity3d=2.25*pow(10.,17);
 			}
 			else{
@@ -351,7 +351,7 @@
 }
 /*}}}*/
-/*FUNCTION Matdamageice::GetViscosity3dStokes {{{*/
-void  Matdamageice::GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon){
-	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+/*FUNCTION Matdamageice::GetViscosity3dFS {{{*/
+void  Matdamageice::GetViscosity3dFS(IssmDouble* pviscosity3d, IssmDouble* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
 	 *
 	 *                                          B
@@ -378,5 +378,5 @@
 
 	/*Get B and n*/
-	eps0=pow((IssmDouble)10,(IssmDouble)-27);
+	eps0=pow(10.,(IssmDouble)-27);
 	n=GetN();
 	Z=GetZ();
@@ -390,5 +390,5 @@
 		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
 				(epsilon[3]==0) && (epsilon[4]==0) && (epsilon[5]==0)){
-			viscosity3d=0.5*pow((IssmDouble)10,(IssmDouble)14);
+			viscosity3d=0.5*pow(10.,14);
 		}
 		else{
@@ -406,5 +406,5 @@
 			if(A==0){
 				/*Maxiviscosity3dm viscosity for 0 shear areas: */
-				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+				viscosity3d=2.25*pow(10.,17);
 			}
 			else{
@@ -426,5 +426,5 @@
 /*FUNCTION Matdamageice::GetViscosityComplement {{{*/
 void  Matdamageice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
-	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
 	 *
 	 *  										                1
@@ -459,5 +459,5 @@
 		if(A==0){
 			/*Maximum viscosity_complement for 0 shear areas: */
-			viscosity_complement=2.25*pow((IssmDouble)10,(IssmDouble)17);
+			viscosity_complement=2.25*pow(10.,17);
 		}
 		else{
@@ -468,5 +468,5 @@
 	}
 	else{
-		viscosity_complement=4.5*pow((IssmDouble)10,(IssmDouble)17);
+		viscosity_complement=4.5*pow(10.,17);
 	}
 
@@ -515,5 +515,5 @@
 		if(A==0){
 			/*Maximum viscosity_complement for 0 shear areas: */
-			viscosity_complement=2.25*pow((IssmDouble)10,(IssmDouble)17);
+			viscosity_complement=2.25*pow(10.,17);
 		}
 		else{
@@ -524,5 +524,5 @@
 	}
 	else{
-		viscosity_complement=4.5*pow((IssmDouble)10,(IssmDouble)17);
+		viscosity_complement=4.5*pow(10.,17);
 	}
 
@@ -552,5 +552,5 @@
 	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
 				(epsilon[3]==0) && (epsilon[4]==0)){
-		mu_prime=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		mu_prime=0.5*pow(10.,14);
 	}
 	else{
@@ -570,6 +570,6 @@
 }
 /*}}}*/
-/*FUNCTION Matdamageice::GetViscosity2dDerivativeEpsSquare{{{*/
-void  Matdamageice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+/*FUNCTION Matdamageice::GetViscosityDerivativeEpsSquareFS{{{*/
+void  Matdamageice::GetViscosityDerivativeEpsSquareFS(IssmDouble* pmu_prime, IssmDouble* epsilon){
 
 	/*output: */
@@ -578,4 +578,39 @@
 
 	/*input strain rate: */
+	IssmDouble exx,eyy,ezz,exy,exz,eyz;
+
+	/*Get visocisty and n*/
+	GetViscosity3d(&mu,epsilon);
+	n=GetN();
+
+	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0) && (epsilon[5]==0)){
+		mu_prime=0.5*pow(10.,14);
+	}
+	else{
+		/*Retrive strain rate components: */
+		exx=epsilon[0];
+		eyy=epsilon[1];
+		ezz=epsilon[2];
+		exy=epsilon[3];
+		exz=epsilon[4];
+		eyz=epsilon[5];
+		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy + exz*exz + eyz*eyz;
+
+		mu_prime=(1-n)/(2*n) * mu/eff2;
+	}
+
+	/*Assign output pointers:*/
+	*pmu_prime=mu_prime;
+}
+/*}}}*/
+/*FUNCTION Matdamageice::GetViscosity2dDerivativeEpsSquare{{{*/
+void  Matdamageice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+
+	/*output: */
+	IssmDouble mu_prime;
+	IssmDouble mu,n,eff2;
+
+	/*input strain rate: */
 	IssmDouble exx,eyy,exy;
 
@@ -585,5 +620,5 @@
 
 	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
-		mu_prime=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		mu_prime=0.5*pow(10.,14);
 	}
 	else{
@@ -639,14 +674,4 @@
 }
 /*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromVector(int* vector, int name, int type) {{{*/
-void  Matdamageice::InputUpdateFromVector(int* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromVector(bool* vector, int name, int type) {{{*/
-void  Matdamageice::InputUpdateFromVector(bool* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
 /*FUNCTION Matdamageice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type) {{{*/
 void  Matdamageice::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
@@ -670,25 +695,25 @@
 
 				case TriaEnum: {
-					IssmDouble values[3];
-					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->vertices[i]->Sid()]; //use sid list, to index into serial oriented vector 
-					this->inputs->AddInput(new TriaInput(name,values,P1Enum));
-					/*Special case for rheology B in 2D: Pourave land for this solution{{{*/
-					if(name==MaterialsRheologyBEnum){
-						/*Are we in 2D?:*/
-						if(element->ObjectEnum()==TriaEnum){
-							parameters=((Tria*)(element))->parameters;
-						}
-						else{
-							parameters=((Penta*)(element))->parameters;
-						}
-						parameters->FindParam(&dim,MeshDimensionEnum);
-						if(dim==2){
-							/*Dupliacte rheology input: */
-							this->inputs->AddInput(new TriaInput(MaterialsRheologyBbarEnum,values,P1Enum));
-						}
-					}
-					/*}}}*/
-					return;
-				}
+										IssmDouble values[3];
+										for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->vertices[i]->Sid()]; //use sid list, to index into serial oriented vector 
+										this->inputs->AddInput(new TriaInput(name,values,P1Enum));
+										/*Special case for rheology B in 2D: Pourave land for this solution{{{*/
+										if(name==MaterialsRheologyBEnum){
+											/*Are we in 2D?:*/
+											if(element->ObjectEnum()==TriaEnum){
+												parameters=((Tria*)(element))->parameters;
+											}
+											else{
+												parameters=((Penta*)(element))->parameters;
+											}
+											parameters->FindParam(&dim,MeshDimensionEnum);
+											if(dim==2){
+												/*Dupliacte rheology input: */
+												this->inputs->AddInput(new TriaInput(MaterialsRheologyBbarEnum,values,P1Enum));
+											}
+										}
+										/*}}}*/
+										return;
+									}
 				default: _error_("element " << EnumToStringx(element->ObjectEnum()) << " not implemented yet");
 			}
@@ -698,16 +723,6 @@
 }
 /*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromMatrixDakota(int* vector, int name, int type) {{{*/
+/*FUNCTION Matdamageice::InputUpdateFromMatrixDakota(IssmDouble* vector, int name, int type) {{{*/
 void  Matdamageice::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromVectorDakota(int* vector, int name, int type) {{{*/
-void  Matdamageice::InputUpdateFromVectorDakota(int* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matdamageice::InputUpdateFromVectorDakota(bool* vector, int name, int type) {{{*/
-void  Matdamageice::InputUpdateFromVectorDakota(bool* vector, int name, int type){
 	/*Nothing updated yet*/
 }
@@ -737,16 +752,12 @@
 
 	int i,j;
-
-	int    dim;
 	bool   control_analysis;
 	int    num_control_type;
 
 	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
 	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
 	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
 
-	/*if 2d*/
-	if(dim==2){
+	if(iomodel->dim==2){
 
 		/*Intermediaries*/
@@ -758,5 +769,5 @@
 		/*Get B*/
 		if (iomodel->Data(MaterialsRheologyBEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+i]-1];
 			this->inputs->AddInput(new TriaInput(MaterialsRheologyBbarEnum,nodeinputs,P1Enum));
 		}
@@ -770,5 +781,5 @@
 		/*Get Z*/
 		if (iomodel->Data(MaterialsRheologyZEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyZEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyZEnum)[iomodel->elements[num_vertices*index+i]-1];
 			this->inputs->AddInput(new TriaInput(MaterialsRheologyZbarEnum,nodeinputs,P1Enum));
 		}
@@ -782,7 +793,7 @@
 						if (iomodel->Data(MaterialsRheologyBEnum)){
 							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
-							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+j]-1];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
 							this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 						}
@@ -791,7 +802,7 @@
 						if (iomodel->Data(MaterialsRheologyZEnum)){
 							_assert_(iomodel->Data(MaterialsRheologyZEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
-							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyZEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyZEnum)[iomodel->elements[num_vertices*index+j]-1];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
 							this->inputs->AddInput(new ControlInput(MaterialsRheologyZbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 						}
@@ -806,5 +817,5 @@
 	/*if 3d*/
 	#ifdef _HAVE_3D_
-	else if(dim==3){
+	else if(iomodel->dim==3){
 
 		/*Intermediaries*/
@@ -816,6 +827,6 @@
 		/*Get B*/
 		if (iomodel->Data(MaterialsRheologyBEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
-			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,nodeinputs));
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+i]-1];
+			this->inputs->AddInput(new PentaInput(MaterialsRheologyBEnum,nodeinputs,P1Enum));
 		}
 
@@ -823,11 +834,11 @@
 		if (iomodel->Data(MaterialsRheologyNEnum)) {
 			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
-			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyNEnum,nodeinputs));
+			this->inputs->AddInput(new PentaInput(MaterialsRheologyNEnum,nodeinputs,P1Enum));
 		}
 
 		/*Get Z*/
 		if (iomodel->Data(MaterialsRheologyZEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyZEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
-			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyZEnum,nodeinputs));
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyZEnum)[iomodel->elements[num_vertices*index+i]-1];
+			this->inputs->AddInput(new PentaInput(MaterialsRheologyZEnum,nodeinputs,P1Enum));
 		}
 
@@ -840,8 +851,8 @@
 						if (iomodel->Data(MaterialsRheologyBEnum)){
 							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
-							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
-							this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+j]-1];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 						}
 						break;
@@ -849,8 +860,8 @@
 						if (iomodel->Data(MaterialsRheologyZEnum)){
 							_assert_(iomodel->Data(MaterialsRheologyZEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
-							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyZEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
-							this->inputs->AddInput(new ControlInput(MaterialsRheologyZEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyZEnum)[iomodel->elements[num_vertices*index+j]-1];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyZEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 						}
 						break;
Index: /issm/trunk/src/c/classes/Materials/Matdamageice.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matdamageice.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Materials/Matdamageice.h	(revision 16137)
@@ -33,10 +33,6 @@
 		/*Update virtual functions definitions: {{{*/
 		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVector(int* vector, int name, int type);
-		void  InputUpdateFromVector(bool* vector, int name, int type);
 		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrow, int ncols, int name, int type);
 		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
 		void  InputUpdateFromConstant(IssmDouble constant, int name);
 		void  InputUpdateFromConstant(int constant, int name);
@@ -52,8 +48,9 @@
 		void   GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon);
 		void   GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon);
-		void   GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon);
+		void   GetViscosity3dFS(IssmDouble* pviscosity3d, IssmDouble* epsilon);
 		void   GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
 		void   GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
 		void   GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		void   GetViscosityDerivativeEpsSquareFS(IssmDouble* pmu_prime, IssmDouble* pepsilon);
 		void   GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
 		IssmDouble GetA();
Index: /issm/trunk/src/c/classes/Materials/Material.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Material.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Materials/Material.h	(revision 16137)
@@ -28,8 +28,9 @@
 		virtual void       GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon)=0;
 		virtual void       GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon)=0;
-		virtual void       GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon)=0;
+		virtual void       GetViscosity3dFS(IssmDouble* pviscosity3d, IssmDouble* epsilon)=0;
 		virtual void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
 		virtual void       GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon)=0;
 		virtual void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
+		virtual void       GetViscosityDerivativeEpsSquareFS(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
 		virtual void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon)=0;
 		virtual IssmDouble GetA()=0;
Index: /issm/trunk/src/c/classes/Materials/Matice.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Materials/Matice.cpp	(revision 16137)
@@ -14,5 +14,5 @@
 #include "../Inputs/Inputs.h"
 #include "../Inputs/TriaInput.h"
-#include "../Inputs/PentaP1Input.h"
+#include "../Inputs/PentaInput.h"
 #include "../Inputs/ControlInput.h"
 #include "../Elements/Element.h"
@@ -241,5 +241,5 @@
 	else{
 		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
-			viscosity=0.5*pow((IssmDouble)10,(IssmDouble)14);
+			viscosity=0.5*pow(10.,14);
 		}
 		else{
@@ -253,5 +253,5 @@
 			if(A==0){
 				/*Maxiviscositym viscosity for 0 shear areas: */
-				viscosity=2.5*pow(10.,17.);
+				viscosity=2.5*pow(10.,17);
 			}
 			else{
@@ -274,5 +274,5 @@
 void  Matice::GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* epsilon){
 
-	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
 	 *
 	 *                                               B
@@ -308,5 +308,5 @@
 		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
 				(epsilon[3]==0) && (epsilon[4]==0)){
-			viscosity3d=0.5*pow((IssmDouble)10,(IssmDouble)14);
+			viscosity3d=0.5*pow(10.,14);
 		}
 		else{
@@ -323,5 +323,5 @@
 			if(A==0){
 				/*Maxiviscosity3dm viscosity for 0 shear areas: */
-				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+				viscosity3d=2.25*pow(10.,17);
 			}
 			else{
@@ -342,7 +342,7 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetViscosity3dStokes {{{*/
-void  Matice::GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon){
-	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+/*FUNCTION Matice::GetViscosity3dFS {{{*/
+void  Matice::GetViscosity3dFS(IssmDouble* pviscosity3d, IssmDouble* epsilon){
+	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
 	 *
 	 *                                          B
@@ -369,5 +369,5 @@
 
 	/*Get B and n*/
-	eps0=pow((IssmDouble)10,(IssmDouble)-27);
+	eps0=pow(10.,-27);
 	B=GetB();
 	n=GetN();
@@ -380,5 +380,5 @@
 		if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
 				(epsilon[3]==0) && (epsilon[4]==0) && (epsilon[5]==0)){
-			viscosity3d=0.5*pow((IssmDouble)10,(IssmDouble)14);
+			viscosity3d=0.5*pow(10.,14);
 		}
 		else{
@@ -396,5 +396,5 @@
 			if(A==0){
 				/*Maxiviscosity3dm viscosity for 0 shear areas: */
-				viscosity3d=2.25*pow((IssmDouble)10,(IssmDouble)17);
+				viscosity3d=2.25*pow(10.,17);
 			}
 			else{
@@ -416,5 +416,5 @@
 /*FUNCTION Matice::GetViscosityComplement {{{*/
 void  Matice::GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* epsilon){
-	/*Return viscosity accounting for steady state power law creep [Thomas and MacAyeal, 1982]: 
+	/*Return viscosity accounting for steady state power law creep [Thomas and SSA, 1982]: 
 	 *
 	 *  										                1
@@ -449,5 +449,5 @@
 		if(A==0){
 			/*Maximum viscosity_complement for 0 shear areas: */
-			viscosity_complement=2.25*pow((IssmDouble)10,(IssmDouble)17);
+			viscosity_complement=2.25*pow(10.,17);
 		}
 		else{
@@ -458,5 +458,5 @@
 	}
 	else{
-		viscosity_complement=4.5*pow((IssmDouble)10,(IssmDouble)17);
+		viscosity_complement=4.5*pow(10.,17);
 	}
 
@@ -486,5 +486,5 @@
 	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
 				(epsilon[3]==0) && (epsilon[4]==0)){
-		mu_prime=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		mu_prime=0.5*pow(10.,14);
 	}
 	else{
@@ -504,6 +504,6 @@
 }
 /*}}}*/
-/*FUNCTION Matice::GetViscosity2dDerivativeEpsSquare{{{*/
-void  Matice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+/*FUNCTION Matice::GetViscosityDerivativeEpsSquareFS{{{*/
+void  Matice::GetViscosityDerivativeEpsSquareFS(IssmDouble* pmu_prime, IssmDouble* epsilon){
 
 	/*output: */
@@ -512,4 +512,39 @@
 
 	/*input strain rate: */
+	IssmDouble exx,eyy,exy,exz,eyz,ezz;
+
+	/*Get visocisty and n*/
+	GetViscosity3d(&mu,epsilon);
+	n=GetN();
+
+	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0) && 
+				(epsilon[3]==0) && (epsilon[4]==0) && (epsilon[5]==0)){
+		mu_prime=0.5*pow(10.,14);
+	}
+	else{
+		/*Retrive strain rate components: */
+		exx=epsilon[0];
+		eyy=epsilon[1];
+		ezz=epsilon[2];
+		exy=epsilon[3];
+		exz=epsilon[4];
+		eyz=epsilon[5];
+		eff2 = exx*exx + eyy*eyy + exx*eyy + exy*exy + exz*exz + eyz*eyz;
+
+		mu_prime=(1-n)/(2*n) * mu/eff2;
+	}
+
+	/*Assign output pointers:*/
+	*pmu_prime=mu_prime;
+}
+/*}}}*/
+/*FUNCTION Matice::GetViscosity2dDerivativeEpsSquare{{{*/
+void  Matice::GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* epsilon){
+
+	/*output: */
+	IssmDouble mu_prime;
+	IssmDouble mu,n,eff2;
+
+	/*input strain rate: */
 	IssmDouble exx,eyy,exy;
 
@@ -519,5 +554,5 @@
 
 	if((epsilon[0]==0) && (epsilon[1]==0) && (epsilon[2]==0)){
-		mu_prime=0.5*pow((IssmDouble)10,(IssmDouble)14);
+		mu_prime=0.5*pow(10.,14);
 	}
 	else{
@@ -571,5 +606,5 @@
 					IssmDouble valuesp[6];
 					for (int i=0;i<6;i++) valuesp[i]=vector[((Penta*)element)->vertices[i]->Sid()]; //use sid list, to index into serial oriented vector
-					this->inputs->AddInput(new PentaP1Input(name,valuesp));
+					this->inputs->AddInput(new PentaInput(name,valuesp,P1Enum));
 					return;
 				}
@@ -579,14 +614,4 @@
 		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
 	}
-}
-/*}}}*/
-/*FUNCTION Matice::InputUpdateFromVector(int* vector, int name, int type) {{{*/
-void  Matice::InputUpdateFromVector(int* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matice::InputUpdateFromVector(bool* vector, int name, int type) {{{*/
-void  Matice::InputUpdateFromVector(bool* vector, int name, int type){
-	/*Nothing updated yet*/
 }
 /*}}}*/
@@ -637,5 +662,5 @@
 					IssmDouble valuesp[6];
 					for (int i=0;i<6;i++) valuesp[i]=vector[((Penta*)element)->vertices[i]->Sid()]; //use sid list, to index into serial oriented vector
-					this->inputs->AddInput(new PentaP1Input(name,valuesp));
+					this->inputs->AddInput(new PentaInput(name,valuesp,P1Enum));
 					return;
 				}
@@ -653,14 +678,4 @@
 }
 /*}}}*/
-/*FUNCTION Matice::InputUpdateFromVectorDakota(int* vector, int name, int type) {{{*/
-void  Matice::InputUpdateFromVectorDakota(int* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matice::InputUpdateFromVectorDakota(bool* vector, int name, int type) {{{*/
-void  Matice::InputUpdateFromVectorDakota(bool* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
 /*FUNCTION Matice::InputUpdateFromConstant(IssmDouble constant, int name) {{{*/
 void  Matice::InputUpdateFromConstant(IssmDouble constant, int name){
@@ -687,16 +702,12 @@
 
 	int i,j;
-
-	int    dim;
 	bool   control_analysis;
 	int    num_control_type;
 
 	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
 	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
 	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
 
-	/*if 2d*/
-	if(dim==2){
+	if(iomodel->dim==2){
 
 		/*Intermediaries*/
@@ -708,5 +719,5 @@
 		/*Get B*/
 		if (iomodel->Data(MaterialsRheologyBEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+i]-1];
 			this->inputs->AddInput(new TriaInput(MaterialsRheologyBbarEnum,nodeinputs,P1Enum));
 		}
@@ -726,7 +737,7 @@
 						if (iomodel->Data(MaterialsRheologyBEnum)){
 							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
-							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+j]-1];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
 							this->inputs->AddInput(new ControlInput(MaterialsRheologyBbarEnum,TriaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 						}
@@ -740,16 +751,16 @@
 	/*if 3d*/
 	#ifdef _HAVE_3D_
-	else if(dim==3){
+	else if(iomodel->dim==3){
 
 		/*Intermediaries*/
-		const int num_vertices = 6; //Penta has 6 vertices
-		IssmDouble    nodeinputs[num_vertices];
-		IssmDouble    cmmininputs[num_vertices];
-		IssmDouble    cmmaxinputs[num_vertices];
+		const int  num_vertices = 6; //Penta has 6 vertices
+		IssmDouble nodeinputs[num_vertices];
+		IssmDouble cmmininputs[num_vertices];
+		IssmDouble cmmaxinputs[num_vertices];
 
 		/*Get B*/
 		if (iomodel->Data(MaterialsRheologyBEnum)) {
-			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+i]-1)];
-			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyBEnum,nodeinputs));
+			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+i]-1];
+			this->inputs->AddInput(new PentaInput(MaterialsRheologyBEnum,nodeinputs,P1Enum));
 		}
 
@@ -757,5 +768,5 @@
 		if (iomodel->Data(MaterialsRheologyNEnum)) {
 			for(i=0;i<num_vertices;i++) nodeinputs[i]=iomodel->Data(MaterialsRheologyNEnum)[index];
-			this->inputs->AddInput(new PentaP1Input(MaterialsRheologyNEnum,nodeinputs));
+			this->inputs->AddInput(new PentaInput(MaterialsRheologyNEnum,nodeinputs,P1Enum));
 		}
 
@@ -768,8 +779,8 @@
 						if (iomodel->Data(MaterialsRheologyBEnum)){
 							_assert_(iomodel->Data(MaterialsRheologyBEnum));_assert_(iomodel->Data(InversionMinParametersEnum)); _assert_(iomodel->Data(InversionMaxParametersEnum)); 
-							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)];
-							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
-							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[reCast<int,IssmDouble>(iomodel->Data(MeshElementsEnum)[num_vertices*index+j]-1)*num_control_type+i];
-							this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaP1InputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
+							for(j=0;j<num_vertices;j++)nodeinputs[j]=iomodel->Data(MaterialsRheologyBEnum)[iomodel->elements[num_vertices*index+j]-1];
+							for(j=0;j<num_vertices;j++)cmmininputs[j]=iomodel->Data(InversionMinParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							for(j=0;j<num_vertices;j++)cmmaxinputs[j]=iomodel->Data(InversionMaxParametersEnum)[(iomodel->elements[num_vertices*index+j]-1)*num_control_type+i];
+							this->inputs->AddInput(new ControlInput(MaterialsRheologyBEnum,PentaInputEnum,nodeinputs,cmmininputs,cmmaxinputs,i+1));
 						}
 						break;
Index: /issm/trunk/src/c/classes/Materials/Matice.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matice.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Materials/Matice.h	(revision 16137)
@@ -40,10 +40,6 @@
 		/*Update virtual functions definitions: {{{*/
 		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVector(int* vector, int name, int type);
-		void  InputUpdateFromVector(bool* vector, int name, int type);
 		void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrow, int ncols, int name, int type);
 		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
 		void  InputUpdateFromConstant(IssmDouble constant, int name);
 		void  InputUpdateFromConstant(int constant, int name);
@@ -59,8 +55,9 @@
 		void       GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon);
 		void       GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon);
-		void       GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon);
+		void       GetViscosity3dFS(IssmDouble* pviscosity3d, IssmDouble* epsilon);
 		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon);
 		void GetViscosityZComplement(IssmDouble*, IssmDouble*){_error_("not supported");};
 		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
+		void       GetViscosityDerivativeEpsSquareFS(IssmDouble* pmu_prime, IssmDouble* pepsilon);
 		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon);
 		IssmDouble GetA();
Index: /issm/trunk/src/c/classes/Materials/Matpar.cpp
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Materials/Matpar.cpp	(revision 16137)
@@ -140,14 +140,4 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::InputUpdateFromVector(int* vector, int name, int type) {{{*/
-void   Matpar::InputUpdateFromVector(int* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matpar::InputUpdateFromVector(bool* vector, int name, int type) {{{*/
-void   Matpar::InputUpdateFromVector(bool* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
 /*FUNCTION Matpar::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type) {{{*/
 void   Matpar::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
@@ -155,15 +145,5 @@
 }
 /*}}}*/
-/*FUNCTION Matpar::InputUpdateFromVectorDakota(int* vector, int name, int type) {{{*/
-void   Matpar::InputUpdateFromVectorDakota(int* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matpar::InputUpdateFromVectorDakota(bool* vector, int name, int type) {{{*/
-void   Matpar::InputUpdateFromVectorDakota(bool* vector, int name, int type){
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Matpar::InputUpdateFromMatrixDakota(int* vector, int name, int type) {{{*/
+/*FUNCTION Matpar::InputUpdateFromMatrixDakota(IssmDouble* vector, int name, int type) {{{*/
 void  Matpar::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols,int name, int type){
 	/*Nothing updated yet*/
@@ -401,5 +381,5 @@
 	}
 	else{
-		return 0.1*thermalconductivity/(rho_ice*heatcapacity);
+		return 1.045*1.e-4/rho_ice; // K0=1.045*1e-4 from Aschwanden 2012. TODO: fetch K0 from model
 	}
 }
Index: /issm/trunk/src/c/classes/Materials/Matpar.h
===================================================================
--- /issm/trunk/src/c/classes/Materials/Matpar.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Materials/Matpar.h	(revision 16137)
@@ -71,10 +71,6 @@
 		/*Update virtual functions resolution: {{{*/
 		void   InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void   InputUpdateFromVector(int* vector, int name, int type);
-		void   InputUpdateFromVector(bool* vector, int name, int type);
 		void   InputUpdateFromMatrixDakota(IssmDouble* matrix,int nrows,int ncols, int name, int type);
 		void   InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
-		void   InputUpdateFromVectorDakota(int* vector, int name, int type);
-		void   InputUpdateFromVectorDakota(bool* vector, int name, int type);
 		void   InputUpdateFromConstant(IssmDouble constant, int name);
 		void   InputUpdateFromConstant(int constant, int name);
@@ -89,8 +85,9 @@
 		void       GetViscosity2d(IssmDouble* pviscosity, IssmDouble* pepsilon){_error_("not supported");};
 		void       GetViscosity3d(IssmDouble* pviscosity3d, IssmDouble* pepsilon){_error_("not supported");};
-		void       GetViscosity3dStokes(IssmDouble* pviscosity3d, IssmDouble* epsilon){_error_("not supported");};
+		void       GetViscosity3dFS(IssmDouble* pviscosity3d, IssmDouble* epsilon){_error_("not supported");};
 		void       GetViscosityComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
 		void       GetViscosityZComplement(IssmDouble* pviscosity_complement, IssmDouble* pepsilon){_error_("not supported");};
 		void       GetViscosityDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
+		void       GetViscosityDerivativeEpsSquareFS(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
 		void       GetViscosity2dDerivativeEpsSquare(IssmDouble* pmu_prime, IssmDouble* pepsilon){_error_("not supported");};
 		IssmDouble GetA(){_error_("not supported");};
Index: /issm/trunk/src/c/classes/Node.cpp
===================================================================
--- /issm/trunk/src/c/classes/Node.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Node.cpp	(revision 16137)
@@ -19,22 +19,17 @@
 Node::Node(){
 	this->approximation=0;
-	this->inputs=NULL;
-	this->hvertex=NULL;
-}
-/*}}}*/
-/*FUNCTION Node::Node(int node_id,int node_sid,int vertex_id,int io_index, IoModel* iomodel,int analysis_type) {{{*/
-Node::Node(int node_id,int node_sid,int vertex_id,int io_index, IoModel* iomodel,int analysis_type){
+}
+/*}}}*/
+/*FUNCTION Node::Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_type,int approximation) {{{*/
+Node::Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_type,int in_approximation){
 
 	/*Intermediary*/
 	int k,l;
 	int gsize;
-	int dim;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
 
 	/*id: */
 	this->id            = node_id;
 	this->sid           = node_sid;
+	this->lid           = node_lid;
 	this->analysis_type = analysis_type;
 
@@ -44,55 +39,38 @@
 
 	/*indexing:*/
-	DistributeNumDofs(&this->indexing,analysis_type,iomodel->Data(FlowequationVertexEquationEnum)+io_index); //number of dofs per node
+	this->indexingupdate = true;
+	DistributeNumDofs(&this->indexing,analysis_type,in_approximation); //number of dofs per node
 	gsize=this->indexing.gsize;
 
-	/*Hooks*/
-	this->hvertex=new Hook(&vertex_id,1); //node id is the same as the vertex id, continuous galerkin!
-
-	if (analysis_type==DiagnosticHorizAnalysisEnum)
-	 this->approximation=reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[io_index]);
+	if(analysis_type==StressbalanceAnalysisEnum)
+	 this->approximation=in_approximation;
 	else
 	 this->approximation=0;
 
-	//intialize inputs, and add as many inputs per element as requested: 
-	this->inputs=new Inputs();
-	if (iomodel->Data(MaskVertexonfloatingiceEnum))
-	 this->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,reCast<bool>(iomodel->Data(MaskVertexonfloatingiceEnum)[io_index])));
-	if (iomodel->Data(MaskVertexongroundediceEnum))
-	  this->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,reCast<bool>(iomodel->Data(MaskVertexongroundediceEnum)[io_index])));
-	if (analysis_type==DiagnosticHorizAnalysisEnum)
-	 this->approximation=reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[io_index]);
-	/*set single point constraints: */
-
-	/*spc all nodes on water*/
-	if (!iomodel->Data(MaskVertexonwaterEnum)) _error_("iomodel->nodeonwater is NULL");
-	if (reCast<bool>(iomodel->Data(MaskVertexonwaterEnum)[io_index])){
-		this->Deactivate();
-	}
-
-	/*Diagnostic Horiz*/
-	#ifdef _HAVE_DIAGNOSTIC_
-	if (analysis_type==DiagnosticHorizAnalysisEnum){
+	/*Stressbalance Horiz*/
+	#ifdef _HAVE_STRESSBALANCE_
+	if(analysis_type==StressbalanceAnalysisEnum){
 
 		/*Coordinate system provided, convert to coord_system matrix*/
-		_assert_(iomodel->Data(DiagnosticReferentialEnum)); 
-		XZvectorsToCoordinateSystem(&this->coord_system[0][0],iomodel->Data(DiagnosticReferentialEnum)+io_index*6);
-
-		if (dim==3){
+		_assert_(iomodel->Data(StressbalanceReferentialEnum)); 
+		XZvectorsToCoordinateSystem(&this->coord_system[0][0],&iomodel->Data(StressbalanceReferentialEnum)[io_index*6]);
+		_assert_(sqrt( coord_system[0][0]*coord_system[0][0] + coord_system[1][0]*coord_system[1][0]) >1.e-4);
+
+		if(iomodel->dim==3){
 			/*We have a  3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
 			_assert_(iomodel->Data(MeshVertexonbedEnum)); 
 			_assert_(iomodel->Data(FlowequationVertexEquationEnum));
-			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealApproximationEnum && !reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
+			if(in_approximation==SSAApproximationEnum && !reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
 				this->Deactivate();
 			}
-			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==L1L2ApproximationEnum && !reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
+			if(in_approximation==L1L2ApproximationEnum && !reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
 				this->Deactivate();
 			}
-			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealPattynApproximationEnum && reCast<int>(iomodel->Data(FlowequationBordermacayealEnum)[io_index])){
+			if(in_approximation==SSAHOApproximationEnum && reCast<int>(iomodel->Data(FlowequationBorderSSAEnum)[io_index])){
 				if(!reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
 					this->Deactivate();
 				}
 			}
-			if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==MacAyealStokesApproximationEnum && reCast<int>(iomodel->Data(FlowequationBordermacayealEnum)[io_index])){
+			if(in_approximation==SSAFSApproximationEnum && reCast<int>(iomodel->Data(FlowequationBorderSSAEnum)[io_index])){
 				if(!reCast<int>(iomodel->Data(MeshVertexonbedEnum)[io_index])){
 					for(k=1;k<=2;k++) this->FreezeDof(k);
@@ -100,6 +78,6 @@
 			}
 		}
-		/*spc all nodes on hutter*/
-		if (iomodel->Data(FlowequationVertexEquationEnum)[io_index]==HutterApproximationEnum){
+		/*spc all nodes on SIA*/
+		if(in_approximation==SIAApproximationEnum){
 			this->Deactivate();
 		}
@@ -107,16 +85,8 @@
 	#endif
 
-	/*Diagnostic Hutter*/
-	if (analysis_type==DiagnosticHutterAnalysisEnum){
-		_assert_(iomodel->Data(FlowequationVertexEquationEnum));
-		/*Constrain all nodes that are not Hutter*/
-		if (reCast<int>(iomodel->Data(FlowequationVertexEquationEnum)[io_index])!=HutterApproximationEnum){
-			this->Deactivate();
-		}
-	}
-
-	/*Prognostic/ Melting/ Slopecompute/ Balancethickness*/
-	if (
-				analysis_type==PrognosticAnalysisEnum || 
+	/*2d solutions in 3d, we need to constrain all the nodes that are not on base*/
+	if(
+				analysis_type==FreeSurfaceBaseAnalysisEnum || 
+				analysis_type==MasstransportAnalysisEnum || 
 				analysis_type==MeltingAnalysisEnum || 
 				analysis_type==BedSlopeAnalysisEnum || 
@@ -126,8 +96,17 @@
 				analysis_type==HydrologyDCEfficientAnalysisEnum
 				){
-		if (dim==3){
+		if(iomodel->dim==3){
 			/*On a 3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
 			_assert_(iomodel->Data(MeshVertexonbedEnum));
-			if (!(reCast<bool>(iomodel->Data(MeshVertexonbedEnum)[io_index]))){
+			if(!(reCast<bool>(iomodel->Data(MeshVertexonbedEnum)[io_index]))){
+				this->Deactivate();
+			}
+		}
+	}
+	if(analysis_type==FreeSurfaceTopAnalysisEnum){
+		if(iomodel->dim==3){
+			/*On a 3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
+			_assert_(iomodel->Data(MeshVertexonsurfaceEnum));
+			if(!(reCast<bool>(iomodel->Data(MeshVertexonsurfaceEnum)[io_index]))){
 				this->Deactivate();
 			}
@@ -139,6 +118,4 @@
 /*FUNCTION Node::~Node(){{{*/
 Node::~Node(){
-	delete inputs;
-	delete hvertex;
 	return;
 }
@@ -148,4 +125,17 @@
 /*FUNCTION Node::Echo{{{*/
 void Node::Echo(void){
+
+	_printf_("Node:\n");
+	_printf_("   id : " << id << "\n");
+	_printf_("   sid: " << sid << "\n");
+	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   approximation: " << EnumToStringx(approximation) << "\n");
+	_printf_("   indexingupdate: " << indexingupdate << "\n");
+	indexing.Echo();
+
+}
+/*}}}*/
+/*FUNCTION Node::DeepEcho{{{*/
+void Node::DeepEcho(void){
 
 	_printf_("Node:\n");
@@ -153,21 +143,7 @@
 	_printf_("   sid: " << sid << "\n");
 	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
-	indexing.Echo();
-	_printf_("   hvertex:     not displayed\n");
-	_printf_("   inputs:      " << inputs << "\n");
-
-}
-/*}}}*/
-/*FUNCTION Node::DeepEcho{{{*/
-void Node::DeepEcho(void){
-
-	_printf_("Node:\n");
-	_printf_("   id: " << id << "\n");
-	_printf_("   sid: " << sid << "\n");
-	_printf_("   analysis_type: " << EnumToStringx(analysis_type) << "\n");
+	_printf_("   approximation: " << EnumToStringx(approximation) << "\n");
+	_printf_("   indexingupdate: " << indexingupdate << "\n");
 	indexing.DeepEcho();
-	_printf_("Vertex:\n");
-	hvertex->DeepEcho();
-	_printf_("   inputs\n");
 
 }
@@ -185,19 +161,8 @@
 
 /*Node management:*/
-/*FUNCTION Node::Configure {{{*/
-void  Node::Configure(DataSet* nodesin,Vertices* verticesin){
-
-	/*Take care of hooking up all objects for this element, ie links the objects in the hooks to their respective 
-	 * datasets, using internal ids and off_sets hidden in hooks: */
-	hvertex->configure(verticesin);
-
-}/*}}}*/
-/*FUNCTION Node::SetCurrentConfiguration {{{*/
-void  Node::SetCurrentConfiguration(DataSet* nodesin,Vertices* verticesin){
-
-}/*}}}*/
 /*FUNCTION Node::GetDof {{{*/
 int   Node::GetDof(int dofindex,int setenum){
 
+	_assert_(!this->indexingupdate);
 	if(setenum==GsetEnum){
 		_assert_(dofindex>=0 && dofindex<indexing.gsize);
@@ -220,4 +185,6 @@
 	int count=0;
 	int count2=0;
+
+	_assert_(!this->indexingupdate);
 
 	if(approximation_enum==NoneApproximationEnum){
@@ -283,4 +250,6 @@
 	int count2=0;
 
+	_assert_(!this->indexingupdate);
+
 	if(approximation_enum==NoneApproximationEnum){
 		if(setenum==GsetEnum)for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=i;
@@ -377,7 +346,14 @@
 /*}}}*/
 /*FUNCTION Node::Sid{{{*/
-int    Node::Sid(void){ return sid; }
-/*}}}*/
-#ifdef _HAVE_DIAGNOSTIC_
+int Node::Sid(void){
+	return sid; 
+}
+/*}}}*/
+/*FUNCTION Node::Lid{{{*/
+int  Node::Lid(void){
+	return lid; 
+}
+/*}}}*/
+#ifdef _HAVE_STRESSBALANCE_
 /*FUNCTION Node::GetCoordinateSystem{{{*/
 void Node::GetCoordinateSystem(IssmDouble* coord_system_out){
@@ -406,4 +382,18 @@
 }
 /*}}}*/
+/*FUNCTION Node::RequiresDofReindexing{{{*/
+bool Node::RequiresDofReindexing(void){
+
+	return this->indexingupdate;
+
+}
+/*}}}*/
+/*FUNCTION Node::ReindexingDone{{{*/
+void Node::ReindexingDone(void){
+
+	this->indexingupdate = false;
+
+}
+/*}}}*/
 /*FUNCTION Node::RelaxConstraint{{{*/
 void  Node::RelaxConstraint(int dof){
@@ -411,5 +401,5 @@
 	/*Dof should be added to the f-set, and taken out of the s-set:*/
 	DofInFSet(dof-1);
-	this->indexing.svalues[dof-1]=NAN;
+	this->indexing.svalues[dof-1]=0.;
 }
 /*}}}*/
@@ -417,10 +407,8 @@
 void  Node::CreateVecSets(Vector<IssmDouble>* pv_g,Vector<IssmDouble>* pv_f,Vector<IssmDouble>* pv_s){
 
-	IssmDouble gvalue=1.0; //all nodes are in the g set;
+	IssmDouble gvalue=1.; //all nodes are in the g set;
 	IssmDouble value;
 
-	int i;
-
-	for(i=0;i<this->indexing.gsize;i++){
+	for(int i=0;i<this->indexing.gsize;i++){
 
 		/*g set: */
@@ -472,7 +460,11 @@
 	/*Put dof for this node into the s set (ie, this dof will be constrained 
 	 * to a fixed value during computations. */
-
-	this->indexing.f_set[dof]=0; //n splits into f (for which we solve) and s (single point constraints)
-	this->indexing.s_set[dof]=1;
+	_assert_(dof<this->indexing.gsize);
+
+	if(this->indexing.f_set[dof] == 1){
+		this->indexingupdate = true;
+		this->indexing.f_set[dof]=0; //n splits into f (for which we solve) and s (single point constraints)
+		this->indexing.s_set[dof]=1;
+	}
 }
 /*}}}*/
@@ -483,6 +475,9 @@
 	 * to a fixed value during computations. */
 
-	this->indexing.f_set[dof]=1; 
-	this->indexing.s_set[dof]=0;
+	if(this->indexing.f_set[dof] == 0){
+		this->indexingupdate = true;
+		this->indexing.f_set[dof]=1; 
+		this->indexing.s_set[dof]=0;
+	}
 }
 /*}}}*/
@@ -497,5 +492,8 @@
 void  Node::Deactivate(void){
 
-	indexing.Deactivate();
+	if(IsActive()){
+		this->indexingupdate = true;
+		indexing.Deactivate();
+	}
 
 }
@@ -504,5 +502,8 @@
 void  Node::Activate(void){
 
-	indexing.Activate();
+	if(!IsActive()){
+		this->indexingupdate = true;
+		indexing.Activate();
+	}
 
 }
@@ -521,12 +522,4 @@
 }
 /*}}}*/
-/*FUNCTION Node::GetConnectivity {{{*/
-int Node::GetConnectivity(){
-
-	Vertex*  vertex=NULL;
-	vertex=(Vertex*)hvertex->delivers();
-	return vertex->connectivity;
-}
-/*}}}*/
 /*FUNCTION Node::GetNumberOfDofs{{{*/
 int   Node::GetNumberOfDofs(int approximation_enum,int setenum){
@@ -539,5 +532,5 @@
 
 	if(approximation_enum==NoneApproximationEnum){
-		if (setenum==GsetEnum) numdofs=this->indexing.gsize;
+		if      (setenum==GsetEnum) numdofs=this->indexing.gsize;
 		else if (setenum==FsetEnum) numdofs=this->indexing.fsize;
 		else if (setenum==SsetEnum) numdofs=this->indexing.ssize;
@@ -584,94 +577,9 @@
 }
 /*}}}*/
-/*FUNCTION Node::IsGrounded {{{*/
-int   Node::IsGrounded(){
-
-	bool onsheet;
-
-	/*recover parameters: */
-	inputs->GetInputValue(&onsheet,MaskVertexongroundediceEnum);
-
-	return onsheet;
-}		
-/*}}}*/
-/*FUNCTION Node::IsFloating {{{*/
-int   Node::IsFloating(){
-
-	bool onshelf;
-
-	/*recover parameters: */
-	inputs->GetInputValue(&onshelf,MaskVertexonfloatingiceEnum);
-
-	return onshelf;
-}
-/*}}}*/
-/*FUNCTION Node::InputUpdateFromVector(IssmDouble* vector, int name, int type){{{*/
-void  Node::InputUpdateFromVector(IssmDouble* vector, int name, int type){
-
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Node::InputUpdateFromVector(int* vector, int name, int type){{{*/
-void  Node::InputUpdateFromVector(int* vector, int name, int type){
-
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Node::InputUpdateFromVector(bool* vector, int name, int type){{{*/
-void  Node::InputUpdateFromVector(bool* vector, int name, int type){
-
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Node::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){{{*/
-void  Node::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
-
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Node::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){{{*/
-void  Node::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){
-
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Node::InputUpdateFromVectorDakota(int* vector, int name, int type){{{*/
-void  Node::InputUpdateFromVectorDakota(int* vector, int name, int type){
-
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Node::InputUpdateFromVectorDakota(bool* vector, int name, int type){{{*/
-void  Node::InputUpdateFromVectorDakota(bool* vector, int name, int type){
-
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Node::InputUpdateFromConstant(IssmDouble constant, int name){{{*/
-void  Node::InputUpdateFromConstant(IssmDouble constant, int name){
-
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Node::InputUpdateFromConstant(int constant, int name){{{*/
-void  Node::InputUpdateFromConstant(int constant, int name){
-
-	/*Nothing updated yet*/
-}
-/*}}}*/
-/*FUNCTION Node::InputUpdateFromConstant(bool constant, int name){{{*/
-void  Node::InputUpdateFromConstant(bool constant, int name){
-
-	/*Nothing updated yet*/
-}
-/*}}}*/
 /*FUNCTION Node::UpdateSpcs {{{*/
 void   Node::UpdateSpcs(IssmDouble* ys){
 
-	int     count=0;
-	int     i;
-
-	count=0;
-	for(i=0;i<this->indexing.gsize;i++){
+	int count = 0;
+	for(int i=0;i<this->indexing.gsize;i++){
 		if(this->indexing.s_set[i]){
 			this->indexing.svalues[i]=ys[this->indexing.sdoflist[count]];
@@ -682,10 +590,10 @@
 /*}}}*/
 /*FUNCTION Node::VecMerge {{{*/
-void   Node::VecMerge(Vector<IssmDouble>* ug, IssmDouble* vector_serial,int setenum){
-
-	IssmDouble* values=NULL;
-	int*    indices=NULL;
-	int     count=0;
-	int     i;
+void Node::VecMerge(Vector<IssmDouble>* ug, IssmDouble* vector_serial,int setenum){
+
+	IssmDouble *values  = NULL;
+	int        *indices = NULL;
+	int         count   = 0;
+	int         i;
 
 	if(setenum==FsetEnum){
@@ -1020,5 +928,5 @@
 }
 /*}}}*/
-#ifdef _HAVE_DIAGNOSTIC_
+#ifdef _HAVE_STRESSBALANCE_
 void TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum){/*{{{*/
 
@@ -1046,6 +954,7 @@
 	for(i=0;i<numnodes;i++){
 		switch(cs_array[i]){
-			case XYEnum:   numdofs+=2; break;
-			case XYZPEnum: numdofs+=4; break;
+			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");
 		}
@@ -1095,6 +1004,7 @@
 	for(i=0;i<numnodes;i++){
 		switch(cs_array[i]){
-			case XYEnum:   numdofs+=2; break;
-			case XYZPEnum: numdofs+=4; break;
+			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");
 		}
@@ -1143,6 +1053,7 @@
 	for(i=0;i<numnodes;i++){
 		switch(cs_array[i]){
-			case XYEnum:   numdofs+=2; break;
-			case XYZPEnum: numdofs+=4; break;
+			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");
 		}
@@ -1183,14 +1094,14 @@
 void TransformStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array){/*{{{*/
 
-	int     i,j;
-	int     numdofs   = 0;
+	int         numdofs = 0;
 	IssmDouble *transform = NULL;
 	IssmDouble *values    = NULL;
 
 	/*Get total number of dofs*/
-	for(i=0;i<numnodes;i++){
+	for(int i=0;i<numnodes;i++){
 		switch(cs_array[i]){
-			case XYEnum:   numdofs+=2; break;
-			case XYZPEnum: numdofs+=4; break;
+			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");
 		}
@@ -1199,5 +1110,5 @@
 	/*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];
+	for(int i=0;i<Ke->nrows*Ke->ncols;i++) values[i]=Ke->values[i];
 
 	/*Get Coordinate Systems transform matrix*/
@@ -1230,6 +1141,7 @@
 	for(i=0;i<numnodes;i++){
 		switch(cs_array[i]){
-			case XYEnum:   numdofs+=2; break;
-			case XYZPEnum: numdofs+=4; break;
+			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");
 		}
@@ -1253,4 +1165,9 @@
 		nodes[i]->GetCoordinateSystem(&coord_system[0][0]);
 		switch(cs_array[i]){
+			case PressureEnum:
+				/*DO NOT change anything*/
+				transform[(numdofs)*(counter) + counter] = 1.;
+				counter+=1;
+				break;
 			case XYEnum:
 				/*We remove the z component, we need to renormalize x and y: x=[x1 x2 0] y=[-x2 x1 0]*/
@@ -1262,6 +1179,6 @@
 				counter+=2;
 				break;
-			case XYZPEnum:
-				/*Only the first 3 coordinates are changed (x,y,z), leave the others (P) unchanged*/
+			case XYZEnum:
+				/*The 3 coordinates are changed (x,y,z)*/
 				transform[(numdofs)*(counter+0) + counter+0] = coord_system[0][0];
 				transform[(numdofs)*(counter+0) + counter+1] = coord_system[0][1];
@@ -1273,6 +1190,5 @@
 				transform[(numdofs)*(counter+2) + counter+1] = coord_system[2][1];
 				transform[(numdofs)*(counter+2) + counter+2] = coord_system[2][2];
-				transform[(numdofs)*(counter+3) + counter+3] = 1.0;
-				counter+=4;
+				counter+=3;
 				break;
 			default:
Index: /issm/trunk/src/c/classes/Node.h
===================================================================
--- /issm/trunk/src/c/classes/Node.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Node.h	(revision 16137)
@@ -11,4 +11,5 @@
 #include "../shared/shared.h"
 #include "./DofIndexing.h"
+#include "./Update.h"
 class  Inputs;
 class  Hook;
@@ -20,8 +21,7 @@
 class ElementVector;
 class ElementMatrix;
-#include "Update.h"
 /*}}}*/
 
-class Node: public Object ,public Update{
+class Node: public Object{
 
 	private:
@@ -30,69 +30,56 @@
 	public: 
 
-		int id;    //unique arbitrary id.
-		int sid;   //"serial" id (rank of this node if the dataset was serial on 1 cpu)
+		int id;    // unique arbitrary id.
+		int sid;   // "serial" id (rank of this node if the dataset was serial on 1 cpu)
+		int lid;   // "local"  id (rank of this node in current partition)
 
+		bool         indexingupdate;
 		DofIndexing  indexing;
-		Hook        *hvertex;
-		Inputs      *inputs;               //properties of this node
 		int          analysis_type;
 		IssmDouble   coord_system[3][3];
 
-		/*Node constructors, destructors {{{*/
+		/*Node constructors, destructors*/
 		Node();
-		Node(int node_id,int node_sid, int vertex_id,int io_index, IoModel* iomodel,int analysis_type);
+		Node(int node_id,int node_sid,int node_lid,int io_index, IoModel* iomodel,int analysis_type,int approximation_in);
 		~Node();
-		/*}}}*/
-		/*Object virtual functions definitions:{{{ */
+
+		/*Object virtual functions definitions:*/
 		void    Echo();
 		void    DeepEcho();
 		int     Id();
 		int     ObjectEnum();
-		Object *copy()        {_error_("Not implemented yet (similar to Elements)"); };
-		/*}}}*/
-		/*Update virtual functions definitions: {{{*/
-		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVector(int* vector, int name, int type);
-		void  InputUpdateFromVector(bool* vector, int name, int type);
-		void  InputUpdateFromMatrixDakota(IssmDouble* matrix,int nrows, int ncols, int name, int type);
-		void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(int* vector, int name, int type);
-		void  InputUpdateFromVectorDakota(bool* vector, int name, int type);
-		void  InputUpdateFromConstant(IssmDouble constant, int name);
-		void  InputUpdateFromConstant(int constant, int name);
-		void  InputUpdateFromConstant(bool constant, int name);
-		void  InputUpdateFromSolution(IssmDouble* solution){_error_("Not implemented yet!");}
-		void  InputUpdateFromIoModel(int index, IoModel* iomodel){_error_("Not implemented yet!");}
-		/*}}}*/
-		/*Node numerical routines {{{*/
-		void   Configure(DataSet* nodes,Vertices* vertices);
-		void   CreateNodalConstraints(Vector<IssmDouble>* ys);
-		void   SetCurrentConfiguration(DataSet* nodes,Vertices* vertices);
-		int    Sid(void); 
-#ifdef _HAVE_DIAGNOSTIC_
-		void   GetCoordinateSystem(IssmDouble* coord_system_out);
+		Object *copy(){_error_("Not implemented yet (similar to Elements)"); };
+
+		/*Node numerical routines*/
+		void  CreateNodalConstraints(Vector<IssmDouble>* ys);
+		void  SetCurrentConfiguration(DataSet* nodes,Vertices* vertices);
+		int   Sid(void); 
+		int   Lid(void); 
+#ifdef _HAVE_STRESSBALANCE_
+		void  GetCoordinateSystem(IssmDouble* coord_system_out);
 #endif
-		bool   InAnalysis(int analysis_type);
-		int    GetApproximation();
-		int    GetNumberOfDofs(int approximation_enum,int setenum);
-		int    IsClone();
-		void   ApplyConstraint(int dof,IssmDouble value);
-		void   RelaxConstraint(int dof);
-		void   DofInSSet(int dof);
-		void   DofInFSet(int dof);
-		int    GetDof(int dofindex,int setenum);
-		void   CreateVecSets(Vector<IssmDouble>* pv_g,Vector<IssmDouble>* pv_f,Vector<IssmDouble>* pv_s);
-		int    GetConnectivity();
-		void   GetDofList(int* poutdoflist,int approximation_enum,int setenum);
-		void   GetLocalDofList(int* poutdoflist,int approximation_enum,int setenum);
-		void   FreezeDof(int dof);
-		bool   IsActive(void);
-		void   Activate(void);
-		void   Deactivate(void);
-		int    IsFloating();
-		int    IsGrounded();
-		void   UpdateSpcs(IssmDouble* ys);
-		void   VecMerge(Vector<IssmDouble>* ug, IssmDouble* vector_serial,int setenum);
-		void   VecReduce(Vector<IssmDouble>* vector, IssmDouble* ug_serial,int setnum);
+		bool  InAnalysis(int analysis_type);
+		int   GetApproximation();
+		int   GetNumberOfDofs(int approximation_enum,int setenum);
+		int   IsClone();
+		void  ApplyConstraint(int dof,IssmDouble value);
+		void  RelaxConstraint(int dof);
+		void  DofInSSet(int dof);
+		void  DofInFSet(int dof);
+		int   GetDof(int dofindex,int setenum);
+		void  CreateVecSets(Vector<IssmDouble>* pv_g,Vector<IssmDouble>* pv_f,Vector<IssmDouble>* pv_s);
+		void  GetDofList(int* poutdoflist,int approximation_enum,int setenum);
+		void  GetLocalDofList(int* poutdoflist,int approximation_enum,int setenum);
+		void  FreezeDof(int dof);
+		bool  IsActive(void);
+		void  Activate(void);
+		void  Deactivate(void);
+		void  UpdateSpcs(IssmDouble* ys);
+		void  ReindexingDone(void);
+		bool  RequiresDofReindexing(void);
+		int   IsFloating();
+		int   IsGrounded();
+		void  VecMerge(Vector<IssmDouble>* ug, IssmDouble* vector_serial,int setenum);
+		void  VecReduce(Vector<IssmDouble>* vector, IssmDouble* ug_serial,int setnum);
 		void  DistributeDofs(int* pdofcount,int setenum);
 		void  OffsetDofs(int dofcount,int setenum);
@@ -100,5 +87,4 @@
 		void  UpdateCloneDofs(int* alltruerows,int ncols,int setenum);
 		void  SetClone(int* minranks);
-		/*}}}*/
 };
 
@@ -107,5 +93,5 @@
 int* GetGlobalDofList(Node** nodes,int numnodes,int setenum,int approximation);
 int  GetNumberOfDofs(Node** nodes,int numnodes,int setenum,int approximation);
-#ifdef _HAVE_DIAGNOSTIC_
+#ifdef _HAVE_STRESSBALANCE_
 void TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int cs_enum);
 void TransformInvStiffnessMatrixCoord(ElementMatrix* Ke,Node** nodes,int numnodes,int* cs_array);
Index: /issm/trunk/src/c/classes/Nodes.cpp
===================================================================
--- /issm/trunk/src/c/classes/Nodes.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Nodes.cpp	(revision 16137)
@@ -32,19 +32,4 @@
 
 /*Numerics*/
-/*FUNCTION Nodes::Configure{{{*/
-void Nodes::Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
-
-	vector<Object*>::iterator object;
-	Node* node=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		node=dynamic_cast<Node*>(*object);
-		node->Configure(nodes,vertices);
-
-	}
-
-}
-/*}}}*/
 /*FUNCTION Nodes::DistributeDofs{{{*/
 void  Nodes::DistributeDofs(int analysis_type,int setenum){
@@ -66,9 +51,9 @@
 
 	/*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));
-
-		/*Check that this node corresponds to our analysis currently being carried out: */
-		if (node->InAnalysis(analysis_type)){
+	for(i=0;i<this->Size();i++){
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if(node->InAnalysis(analysis_type)){
 			node->DistributeDofs(&dofcount,setenum);
 		}
@@ -80,10 +65,6 @@
 	 * First: get number of dofs for each cpu*/
 	alldofcount=xNew<int>(num_procs);
-	#ifdef _HAVE_MPI_
-	MPI_Gather(&dofcount,1,MPI_INT,alldofcount,1,MPI_INT,0,IssmComm::GetComm());
-	MPI_Bcast(alldofcount,num_procs,MPI_INT,0,IssmComm::GetComm());
-	#else
-	alldofcount[0]=dofcount;
-	#endif
+	ISSM_MPI_Gather(&dofcount,1,ISSM_MPI_INT,alldofcount,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(alldofcount,num_procs,ISSM_MPI_INT,0,IssmComm::GetComm());
 
 	/* Every cpu should start its own dof count at the end of the dofcount from cpu-1*/
@@ -92,5 +73,5 @@
 		dofcount+=alldofcount[i];
 	}
-	for (i=0;i<this->Size();i++){
+	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));
@@ -110,5 +91,5 @@
 	}
 
-	for (i=0;i<this->Size();i++){
+	for(i=0;i<this->Size();i++){
 		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
 		if (node->InAnalysis(analysis_type)){
@@ -117,15 +98,19 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce((void*)truedofs,(void*)alltruedofs,numnodes*maxdofspernode,MPI_INT,MPI_MAX,IssmComm::GetComm());
-	#else
-	for(i=0;i<numnodes*maxdofspernode;i++)alltruedofs[i]=truedofs[i];
-	#endif
+	ISSM_MPI_Allreduce((void*)truedofs,(void*)alltruedofs,numnodes*maxdofspernode,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
 
 	/* Now every cpu knows the true dofs of everyone else that is not a clone*/
-	for (i=0;i<this->Size();i++){
+	for(i=0;i<this->Size();i++){
 		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
 		if (node->InAnalysis(analysis_type)){
 			node->UpdateCloneDofs(alltruedofs,maxdofspernode,setenum);
+		}
+	}
+
+	/*Update indexingupdateflag*/
+	for(i=0;i<this->Size();i++){
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+		if (node->InAnalysis(analysis_type)){
+			node->ReindexingDone();
 		}
 	}
@@ -162,9 +147,5 @@
 	 * dealt with by another cpu. We take the minimum because we are going to manage dof assignment in increasing 
 	 * order of cpu rank. This is also why we initialized this array to num_procs.*/
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce((void*)ranks,(void*)minranks,numnodes,MPI_INT,MPI_MIN,IssmComm::GetComm());
-	#else
-	for(i=0;i<numnodes;i++)minranks[i]=ranks[i];
-	#endif
+	ISSM_MPI_Allreduce((void*)ranks,(void*)minranks,numnodes,ISSM_MPI_INT,ISSM_MPI_MIN,IssmComm::GetComm());
 
 	/*Now go through all objects, and use minranks to flag which objects are cloned: */
@@ -190,11 +171,9 @@
 int   Nodes::MaxNumDofs(int analysis_type,int setenum){
 
-	int i;
 	int max=0;
-	int allmax;
-	int numdofs=0;
-
-	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
-	for(i=0;i<this->Size();i++){
+	int allmax,numdofs;
+
+	/*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));
@@ -209,8 +188,37 @@
 
 	/*Grab max of all cpus: */
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
+	ISSM_MPI_Allreduce((void*)&max,(void*)&allmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
 	max=allmax;
-	#endif
+
+	return max;
+}
+/*}}}*/
+/*FUNCTION Nodes::MaximymId{{{*/
+int Nodes::MaximumId(){
+
+	int max=-1;
+	int id,allmax;
+
+	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
+	if(!sorted){
+		for(int i=0;i<this->Size();i++){
+			Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+			id=node->Id();
+			if(id>max)max=id;
+		}
+	}
+	else{
+		if(this->Size()==0){
+			max = 0;
+		}
+		else{
+			Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(this->Size()-1));
+			max = node->Id();
+		}
+	}
+
+	/*Grab max of all cpus: */
+	ISSM_MPI_Allreduce((void*)&max,(void*)&allmax,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+	max=allmax;
 
 	return max;
@@ -226,9 +234,5 @@
 
 	/*Gather from all cpus: */
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)&numdofs,(void*)&allnumdofs,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
-	#else
-	allnumdofs=numdofs;
-	#endif
+	ISSM_MPI_Allreduce ( (void*)&numdofs,(void*)&allnumdofs,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
 	return allnumdofs;
 }
@@ -274,9 +278,5 @@
 
 	/*Gather from all cpus: */
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)&numnodes,(void*)&allnumnodes,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
-	#else
-	allnumnodes=numnodes;
-	#endif
+	ISSM_MPI_Allreduce ( (void*)&numnodes,(void*)&allnumnodes,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
 
 	return allnumnodes;
@@ -304,9 +304,7 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&max_sid,&node_max_sid,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&node_max_sid,1,MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Reduce (&max_sid,&node_max_sid,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&node_max_sid,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 	max_sid=node_max_sid;
-	#endif
 
 	/*sid starts at 0*/
@@ -340,16 +338,33 @@
 }
 /*}}}*/
-/*FUNCTION Nodes::SetCurrentConfiguration{{{*/
-void Nodes::SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters){
-
-	vector<Object*>::iterator object;
-	Node* node=NULL;
-
-	for (object=objects.begin() ; object < objects.end(); object++ ){
-
-		node=dynamic_cast<Node*>(*object);
-		node->SetCurrentConfiguration(nodes,vertices);
-
-	}
-}
-/*}}}*/
+/*FUNCTION Nodes::RequiresDofReindexing{{{*/
+bool Nodes::RequiresDofReindexing(int analysis_type){
+
+	int flag = 0;
+	int allflag;
+
+	/*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));
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if(node->InAnalysis(analysis_type)){
+			if(node->RequiresDofReindexing()){
+				flag = 1;
+				break;
+			}
+		}
+	}
+
+	/*Grab max of all cpus: */
+	ISSM_MPI_Allreduce((void*)&flag,(void*)&allflag,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+
+	if(allflag){
+		return true;
+	}
+	else{
+		return false;
+	}
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/Nodes.h
===================================================================
--- /issm/trunk/src/c/classes/Nodes.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Nodes.h	(revision 16137)
@@ -25,8 +25,9 @@
 
 		/*numerics*/
-		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
 		void  DistributeDofs(int analysis_type,int SETENUM);
 		void  FlagClones(int analysis_type);
+		bool  RequiresDofReindexing(int analysis_type);
 		int   MaxNumDofs(int analysis_type,int setenum);
+		int   MaximumId(void);
 		int   NumberOfDofs(int analysis_type,int setenum);
 		int   NumberOfDofsLocal(int analysis_type,int setenum);
@@ -34,5 +35,4 @@
 		int   NumberOfNodes(void);
 		void  Ranks(int* ranks,int analysis_type);
-		void  SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
 
 };
Index: sm/trunk/src/c/classes/Options/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Options/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/objects/Options)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/Options/OptionUtilities.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/classes/Params/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/Params/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,23 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/objects/Params)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/Params/BoolParam.cpp
-              $ENV{ISSM_DIR}/src/c/classes/objects/Params/DataSetParam.cpp
-       $ENV{ISSM_DIR}/src/c/classes/objects/Params/DoubleMatArrayParam.cpp
-            $ENV{ISSM_DIR}/src/c/classes/objects/Params/DoubleMatParam.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/Params/DoubleParam.cpp
-   $ENV{ISSM_DIR}/src/c/classes/objects/Params/DoubleTransientMatParam.cpp
-            $ENV{ISSM_DIR}/src/c/classes/objects/Params/DoubleVecParam.cpp
-                 $ENV{ISSM_DIR}/src/c/classes/objects/Params/FileParam.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/Params/IntMatParam.cpp
-                  $ENV{ISSM_DIR}/src/c/classes/objects/Params/IntParam.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/Params/IntVecParam.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/Params/MatrixParam.cpp
-          $ENV{ISSM_DIR}/src/c/classes/objects/Params/StringArrayParam.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/Params/StringParam.cpp
-            $ENV{ISSM_DIR}/src/c/classes/objects/Params/TransientParam.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/Params/VectorParam.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/classes/Patch.cpp
===================================================================
--- /issm/trunk/src/c/classes/Patch.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Patch.cpp	(revision 16137)
@@ -111,7 +111,5 @@
 	int         node_numrows;
 	IssmDouble     *total_values  = NULL;
-	#ifdef _HAVE_MPI_
-	MPI_Status  status;
-	#endif
+	ISSM_MPI_Status  status;
 
 	/*recover my_rank:*/
@@ -120,10 +118,6 @@
 
 	/*First, figure out total number of rows combining all the cpus: */
-	#ifdef _HAVE_MPI_
-	MPI_Reduce(&this->numrows,&total_numrows,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&total_numrows,1,MPI_INT,0,IssmComm::GetComm());
-	#else
-	total_numrows=this->numrows;
-	#endif
+	ISSM_MPI_Reduce(&this->numrows,&total_numrows,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&total_numrows,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 
 	/*return if patch empty*/
@@ -141,17 +135,15 @@
 
 	/*Now, ask other nodes to send their values: */
-	#ifdef _HAVE_MPI_
 	for(int i=1;i<num_procs;i++){
 		if (my_rank==i){ 
-			MPI_Send(&this->numrows,1,MPI_INT,0,1,IssmComm::GetComm());   
-			if (this->numrows)MPI_Send(this->values,this->numrows*this->numcols,MPI_DOUBLE,0,1,IssmComm::GetComm()); 
+			ISSM_MPI_Send(&this->numrows,1,ISSM_MPI_INT,0,1,IssmComm::GetComm());   
+			if (this->numrows)ISSM_MPI_Send(this->values,this->numrows*this->numcols,ISSM_MPI_DOUBLE,0,1,IssmComm::GetComm()); 
 		}
 		if (my_rank==0){
-			MPI_Recv(&node_numrows,1,MPI_INT,i,1,IssmComm::GetComm(),&status); 
-			if (node_numrows)MPI_Recv(total_values+count,node_numrows*this->numcols,MPI_DOUBLE,i,1,IssmComm::GetComm(),&status);
+			ISSM_MPI_Recv(&node_numrows,1,ISSM_MPI_INT,i,1,IssmComm::GetComm(),&status); 
+			if (node_numrows)ISSM_MPI_Recv(total_values+count,node_numrows*this->numcols,ISSM_MPI_DOUBLE,i,1,IssmComm::GetComm(),&status);
 			count+=node_numrows*this->numcols;
 		}
 	}	
-	#endif
 
 	/*Now, node 0 has total_values, of size total_numrows*this->numcols. Update the fields in the patch, to reflect this new 
@@ -162,9 +154,7 @@
 		this->values=total_values;
 	}
-	#ifdef _HAVE_MPI_
 	else{
 		this->numrows=0;
 		xDelete<IssmDouble>(this->values);
 	}
-	#endif
 }/*}}}*/
Index: /issm/trunk/src/c/classes/Profiler.cpp
===================================================================
--- /issm/trunk/src/c/classes/Profiler.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Profiler.cpp	(revision 16137)
@@ -73,12 +73,10 @@
 	 *in the execution: */
 	if(!dontmpisync){
-		#ifdef _HAVE_MPI_
-		MPI_Barrier(IssmComm::GetComm()); 
-		#endif
+		ISSM_MPI_Barrier(IssmComm::GetComm()); 
 	}
 
 	/*Capture time: */
 	#ifdef _HAVE_MPI_
-	t=MPI_Wtime();
+	t=ISSM_MPI_Wtime();
 	#else
 	t=(IssmPDouble)clock();
Index: /issm/trunk/src/c/classes/Update.h
===================================================================
--- /issm/trunk/src/c/classes/Update.h	(revision 16136)
+++ /issm/trunk/src/c/classes/Update.h	(revision 16137)
@@ -15,11 +15,7 @@
 
 		virtual void  InputUpdateFromVector(IssmDouble* vector, int name, int type)=0;
-		virtual void  InputUpdateFromVector(int* vector, int name, int type)=0;
-		virtual void  InputUpdateFromVector(bool* vector, int name, int type)=0; 
 		#ifdef _HAVE_DAKOTA_
 		virtual void  InputUpdateFromMatrixDakota(IssmDouble* matrix, int rows, int ncols, int name, int type)=0;
 		virtual void  InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type)=0;
-		virtual void  InputUpdateFromVectorDakota(int* vector, int name, int type)=0;
-		virtual void  InputUpdateFromVectorDakota(bool* vector, int name, int type)=0;
 		#endif
 		virtual void  InputUpdateFromConstant(IssmDouble constant, int name)=0;
Index: /issm/trunk/src/c/classes/Vertices.cpp
===================================================================
--- /issm/trunk/src/c/classes/Vertices.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/Vertices.cpp	(revision 16137)
@@ -64,10 +64,6 @@
 	 * First: get number of pids for each cpu*/
 	allpidcount=xNew<int>(num_procs);
-	#ifdef _HAVE_MPI_
-	MPI_Gather(&pidcount,1,MPI_INT,allpidcount,1,MPI_INT,0,IssmComm::GetComm());
-	MPI_Bcast(allpidcount,num_procs,MPI_INT,0,IssmComm::GetComm());
-	#else
-	allpidcount[0]=pidcount;
-	#endif
+	ISSM_MPI_Gather(&pidcount,1,ISSM_MPI_INT,allpidcount,1,ISSM_MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(allpidcount,num_procs,ISSM_MPI_INT,0,IssmComm::GetComm());
 
 	/* Every cpu should start its own pid count at the end of the pidcount from cpu-1*/
@@ -92,9 +88,5 @@
 		vertex->ShowTruePids(truepids);
 	}
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce((void*)truepids,(void*)alltruepids,numberofobjects,MPI_INT,MPI_MAX,IssmComm::GetComm());
-	#else
-	for(i=0;i<numberofobjects;i++)alltruepids[i]=truepids[i];
-	#endif
+	ISSM_MPI_Allreduce((void*)truepids,(void*)alltruepids,numberofobjects,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
 
 	/* Now every cpu knows the true pids of everyone else that is not a clone*/
@@ -135,9 +127,5 @@
 	 * dealt with by another cpu. We take the minimum because we are going to manage dof assignment in increasing 
 	 * order of cpu rank. This is also why we initialized this array to num_procs.*/
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)ranks,(void*)minranks,numberofobjects,MPI_INT,MPI_MIN,IssmComm::GetComm());
-	#else
-	for(i=0;i<numberofobjects;i++)minranks[i]=ranks[i];
-	#endif
+	ISSM_MPI_Allreduce ( (void*)ranks,(void*)minranks,numberofobjects,ISSM_MPI_INT,ISSM_MPI_MIN,IssmComm::GetComm());
 
 	/*Now go through all objects, and use minranks to flag which objects are cloned: */
@@ -167,9 +155,7 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&max_sid,&vertex_max_sid,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&vertex_max_sid,1,MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Reduce (&max_sid,&vertex_max_sid,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&vertex_max_sid,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 	max_sid=vertex_max_sid;
-	#endif
 
 	/*sid starts at 0*/
Index: /issm/trunk/src/c/classes/classes.h
===================================================================
--- /issm/trunk/src/c/classes/classes.h	(revision 16136)
+++ /issm/trunk/src/c/classes/classes.h	(revision 16137)
@@ -29,5 +29,4 @@
 #include "./Loads/Load.h"
 #include "./Loads/Friction.h"
-#include "./Loads/Icefront.h"
 #include "./Loads/Numericalflux.h"
 #include "./Loads/Riftfront.h"
@@ -56,5 +55,5 @@
 #include "./Inputs/DoubleInput.h"
 #include "./Inputs/IntInput.h"
-#include "./Inputs/PentaP1Input.h"
+#include "./Inputs/PentaInput.h"
 #include "./Inputs/TriaInput.h"
 #include "./Inputs/ControlInput.h"
Index: sm/trunk/src/c/classes/gauss/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/gauss/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/gauss)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/classes/gauss/GaussTria.cpp PARENT_SCOPE)
-# }}}
-# THREED_SOURCES {{{
-set(THREED_SOURCES $ENV{ISSM_DIR}/src/c/classes/gauss/GaussPenta.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/classes/gauss/GaussPenta.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/gauss/GaussPenta.cpp	(revision 16137)
@@ -8,4 +8,5 @@
 #include "../../shared/Exceptions/exceptions.h"
 #include "../../shared/MemOps/MemOps.h"
+#include "../../shared/Enum/Enum.h"
 #include "../../shared/Numerics/GaussPoints.h"
 #include "../../shared/Numerics/constants.h"
@@ -237,4 +238,205 @@
 }
 /*}}}*/
+/*FUNCTION GaussPenta::GaussPenta(int index,double r1,double r2,int order) {{{*/
+GaussPenta::GaussPenta(int index,IssmDouble r1,IssmDouble r2,bool mainlyfloating,int order){
+
+	/*
+	 *  ^ 
+	 *  |
+	 * 1|\
+	 *  |  \
+	 *  |    \
+	 *  |      \
+	 *  |        \
+	 *  |          \
+	 *  |    +(x,y)  \
+	 *  |              \
+	 *  +---------------+-->
+	 *  0               1
+	 *
+	 */
+	int         ig;
+	IssmDouble x,y;
+	IssmDouble xy_list[3][2];
+
+	if(mainlyfloating){
+		/*Get gauss points*/
+		GaussLegendreTria(&this->numgauss,&this->coords1,&this->coords2,&this->coords3,&this->weights,order);
+
+		xy_list[0][0]=0;  xy_list[0][1]=0; 
+		xy_list[1][0]=r1; xy_list[1][1]=0; 
+		xy_list[2][0]=0;  xy_list[2][1]=r2; 
+
+		for(ig=0;ig<this->numgauss;ig++){
+			x = this->coords1[ig]*xy_list[0][0] + this->coords2[ig]*xy_list[1][0] + this->coords3[ig]*xy_list[2][0];
+			y = this->coords1[ig]*xy_list[0][1] + this->coords2[ig]*xy_list[1][1] + this->coords3[ig]*xy_list[2][1];
+
+			switch(index){
+				case 0:
+					this->coords1[ig] = 1.-x-y;
+					this->coords2[ig] = x;
+					this->coords3[ig] = y;
+					break;
+				case 1:
+					this->coords1[ig] = y;
+					this->coords2[ig] = 1.-x-y;
+					this->coords3[ig] = x;
+					break;
+				case 2:
+					this->coords1[ig] = x;
+					this->coords2[ig] = y;
+					this->coords3[ig] = 1.-x-y;
+					break;
+				default:
+					_error_("index "<<index<<" not supported yet");
+			}
+			this->weights[ig] = this->weights[ig]*r1*r2;
+			this->coords4=xNew<IssmDouble>(numgauss);
+			for(ig=0;ig<numgauss;ig++) this->coords4[ig]=-1.0;
+		}
+	}
+	else{
+		/*Double number of gauss points*/
+		GaussPenta *gauss1    = NULL;
+		GaussPenta *gauss2    = NULL;
+		gauss1=new GaussPenta(0,1,2,order);
+		gauss2=new GaussPenta(0,1,2,order);
+
+		xy_list[0][0]=r1; xy_list[0][1]=0; 
+		xy_list[1][0]=0;  xy_list[1][1]=1.; 
+		xy_list[2][0]=0;  xy_list[2][1]=r2; 
+
+			//gauss1->Echo();
+		for(ig=0;ig<gauss1->numgauss;ig++){
+			x = gauss1->coords1[ig]*xy_list[0][0] + gauss1->coords2[ig]*xy_list[1][0] + gauss1->coords3[ig]*xy_list[2][0];
+			y = gauss1->coords1[ig]*xy_list[0][1] + gauss1->coords2[ig]*xy_list[1][1] + gauss1->coords3[ig]*xy_list[2][1];
+
+			switch(index){
+				case 0:
+					gauss1->coords1[ig] = 1.-x-y;
+					gauss1->coords2[ig] = x;
+					gauss1->coords3[ig] = y;
+					break;
+				case 1:
+					gauss1->coords1[ig] = y;
+					gauss1->coords2[ig] = 1.-x-y;
+					gauss1->coords3[ig] = x;
+					break;
+				case 2:
+					gauss1->coords1[ig] = x;
+					gauss1->coords2[ig] = y;
+					gauss1->coords3[ig] = 1.-x-y;
+					break;
+				default:
+					_error_("index "<<index<<" not supported yet");
+			}
+			gauss1->weights[ig] = gauss1->weights[ig]*r1*(1-r2);
+		}
+			//gauss1->Echo();
+		xy_list[0][0]=r1; xy_list[0][1]=0; 
+		xy_list[1][0]=1.; xy_list[1][1]=0; 
+		xy_list[2][0]=0;  xy_list[2][1]=1.; 
+
+			//gauss2->Echo();
+		for(ig=0;ig<gauss2->numgauss;ig++){
+			x = gauss2->coords1[ig]*xy_list[0][0] + gauss2->coords2[ig]*xy_list[1][0] + gauss2->coords3[ig]*xy_list[2][0];
+			y = gauss2->coords1[ig]*xy_list[0][1] + gauss2->coords2[ig]*xy_list[1][1] + gauss2->coords3[ig]*xy_list[2][1];
+
+			switch(index){
+				case 0:
+					gauss2->coords1[ig] = 1.-x-y;
+					gauss2->coords2[ig] = x;
+					gauss2->coords3[ig] = y;
+					break;
+				case 1:
+					gauss2->coords1[ig] = y;
+					gauss2->coords2[ig] = 1.-x-y;
+					gauss2->coords3[ig] = x;
+					break;
+				case 2:
+					gauss2->coords1[ig] = x;
+					gauss2->coords2[ig] = y;
+					gauss2->coords3[ig] = 1.-x-y;
+					break;
+				default:
+					_error_("index "<<index<<" not supported yet");
+			}
+			gauss2->weights[ig] = gauss2->weights[ig]*(1-r1);
+		}
+
+		this->numgauss = gauss1->numgauss + gauss2->numgauss;
+		this->coords1=xNew<IssmDouble>(this->numgauss);
+		this->coords2=xNew<IssmDouble>(this->numgauss);
+		this->coords3=xNew<IssmDouble>(this->numgauss);
+		this->coords4=xNew<IssmDouble>(this->numgauss);
+		this->weights=xNew<IssmDouble>(this->numgauss);
+
+		for(ig=0;ig<gauss1->numgauss;ig++){ // Add the first triangle gauss points
+			this->coords1[ig]=gauss1->coords1[ig];
+			this->coords2[ig]=gauss1->coords2[ig];
+			this->coords3[ig]=gauss1->coords3[ig];
+			this->coords4[ig]=gauss1->coords4[ig];
+			this->weights[ig]=gauss1->weights[ig];
+		}
+		for(ig=0;ig<gauss2->numgauss;ig++){ // Add the second triangle gauss points
+			this->coords1[gauss1->numgauss+ig]=gauss2->coords1[ig];
+			this->coords2[gauss1->numgauss+ig]=gauss2->coords2[ig];
+			this->coords3[gauss1->numgauss+ig]=gauss2->coords3[ig];
+			this->coords4[gauss1->numgauss+ig]=gauss2->coords4[ig];
+			this->weights[gauss1->numgauss+ig]=gauss2->weights[ig];
+		}
+
+		/*Delete gauss points*/
+		delete gauss1;
+		delete gauss2;
+	}
+
+	/*Initialize static fields as undefined*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+	coord4=UNDEF;
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussPenta(IssmDouble area_coordinates[4][3],int order_horiz,int order_vert){{{*/
+GaussPenta::GaussPenta(IssmDouble area_coordinates[4][3],int order_horiz,int order_vert){
+
+	/*Intermediaties*/
+	IssmPDouble *seg_horiz_coords  = NULL;
+	IssmPDouble *seg_horiz_weights = NULL;
+	IssmPDouble *seg_vert_coords   = NULL;
+	IssmPDouble *seg_vert_weights  = NULL;
+
+	/*get the gauss points using the product of two line rules*/
+	GaussLegendreLinear(&seg_horiz_coords,&seg_horiz_weights,order_horiz);
+	GaussLegendreLinear(&seg_vert_coords, &seg_vert_weights, order_vert);
+
+	/*Allocate GaussPenta fields*/
+	numgauss=order_horiz*order_vert;
+	coords1=xNew<IssmDouble>(numgauss);
+	coords2=xNew<IssmDouble>(numgauss);
+	coords3=xNew<IssmDouble>(numgauss);
+	coords4=xNew<IssmDouble>(numgauss);
+	weights=xNew<IssmDouble>(numgauss);
+
+	/*Quads: get the gauss points using the product of two line rules  */
+	for(int i=0;i<order_horiz;i++){
+		for(int j=0;j<order_vert;j++){
+			coords1[i*order_vert+j]=0.5*(area_coordinates[0][0]+area_coordinates[1][0]) + 0.5*seg_horiz_coords[i]*(area_coordinates[1][0]-area_coordinates[0][0]);
+			coords2[i*order_vert+j]=0.5*(area_coordinates[0][1]+area_coordinates[1][1]) + 0.5*seg_horiz_coords[i]*(area_coordinates[1][1]-area_coordinates[0][1]);
+			coords3[i*order_vert+j]=0.5*(area_coordinates[0][2]+area_coordinates[1][2]) + 0.5*seg_horiz_coords[i]*(area_coordinates[1][2]-area_coordinates[0][2]);
+			coords4[i*order_vert+j]=seg_vert_coords[j];
+			weights[i*order_vert+j]=seg_horiz_weights[i]*seg_vert_weights[j];
+		}
+	}
+
+	/*clean-up*/
+	xDelete<IssmPDouble>(seg_horiz_coords);
+	xDelete<IssmPDouble>(seg_horiz_weights);
+	xDelete<IssmPDouble>(seg_vert_coords);
+	xDelete<IssmPDouble>(seg_vert_weights);
+}
+/*}}}*/
 /*FUNCTION GaussPenta::~GaussPenta(){{{*/
 GaussPenta::~GaussPenta(){
@@ -327,24 +529,11 @@
 	/*update static arrays*/
 	switch(iv){
-		case 0:
-			coord1=1; coord2=0; coord3=0; coord4= -1;
-			break;
-		case 1:
-			coord1=0; coord2=1; coord3=0; coord4= -1;
-			break;
-		case 2:
-			coord1=0; coord2=0; coord3=1; coord4= -1;
-			break;
-		case 3:
-			coord1=1; coord2=0; coord3=0; coord4= +1;
-			break;
-		case 4:
-			coord1=0; coord2=1; coord3=0; coord4= +1;
-			break;
-		case 5:
-			coord1=0; coord2=0; coord3=1; coord4= +1;
-			break;
-		default:
-			_error_("vertex index should be in [0 5]");
+		case 0: coord1=1.; coord2=0.; coord3=0.; coord4= -1.; break;
+		case 1: coord1=0.; coord2=1.; coord3=0.; coord4= -1.; break;
+		case 2: coord1=0.; coord2=0.; coord3=1.; coord4= -1.; break;
+		case 3: coord1=1.; coord2=0.; coord3=0.; coord4= +1.; break;
+		case 4: coord1=0.; coord2=1.; coord3=0.; coord4= +1.; break;
+		case 5: coord1=0.; coord2=0.; coord3=1.; coord4= +1.; break;
+		default: _error_("vertex index should be in [0 5]");
 
 	}
@@ -366,4 +555,95 @@
 	else{
 		_error_("Tria not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION GaussPenta::GaussNode{{{*/
+void GaussPenta::GaussNode(int finiteelement,int iv){
+
+	/*in debugging mode: check that the default constructor has been called*/
+	_assert_(numgauss==-1);
+
+	/*update static arrays*/
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3: coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4: coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5: coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+				default: _error_("node index should be in [0 5]");
+			}
+			break;
+		case P1xP2Enum: 
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3: coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4: coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5: coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+
+				case 6: coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+				case 7: coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+				case 8: coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+				default: _error_("node index should be in [0 8]");
+			}
+			break;
+		case P2xP1Enum: 
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3: coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4: coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5: coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+
+				case  6: coord1=0.; coord2=.5; coord3=.5; coord4=-1.;break;
+				case  7: coord1=.5; coord2=0.; coord3=.5; coord4=-1.;break;
+				case  8: coord1=.5; coord2=.5; coord3=0.; coord4=-1.;break;
+				case  9: coord1=0.; coord2=.5; coord3=.5; coord4=+1.;break;
+				case 10: coord1=.5; coord2=0.; coord3=.5; coord4=+1.;break;
+				case 11: coord1=.5; coord2=.5; coord3=0.; coord4=+1.;break;
+				default: _error_("node index should be in [0 11]");
+			}
+			break;
+		case P1bubbleEnum:  case P1bubblecondensedEnum:
+			switch(iv){
+				case 0: coord1=1.;    coord2=0.;    coord3=0.;    coord4=-1.; break;
+				case 1: coord1=0.;    coord2=1.;    coord3=0.;    coord4=-1.; break;
+				case 2: coord1=0.;    coord2=0.;    coord3=1.;    coord4=-1.; break;
+				case 3: coord1=1.;    coord2=0.;    coord3=0.;    coord4=+1.; break;
+				case 4: coord1=0.;    coord2=1.;    coord3=0.;    coord4=+1.; break;
+				case 5: coord1=0.;    coord2=0.;    coord3=1.;    coord4=+1.; break;
+				case 6: coord1=1./3.; coord2=1./3.; coord3=1./3.; coord4=0.;  break;
+				default: _error_("node index should be in [0 6]");
+			}
+			break;
+		case P2Enum:
+			switch(iv){
+				case 0: coord1=1.; coord2=0.; coord3=0.; coord4=-1.; break;
+				case 1: coord1=0.; coord2=1.; coord3=0.; coord4=-1.; break;
+				case 2: coord1=0.; coord2=0.; coord3=1.; coord4=-1.; break;
+				case 3: coord1=1.; coord2=0.; coord3=0.; coord4=+1.; break;
+				case 4: coord1=0.; coord2=1.; coord3=0.; coord4=+1.; break;
+				case 5: coord1=0.; coord2=0.; coord3=1.; coord4=+1.; break;
+
+				case 6: coord1=1.; coord2=0.; coord3=0.; coord4=0.; break;
+				case 7: coord1=0.; coord2=1.; coord3=0.; coord4=0.; break;
+				case 8: coord1=0.; coord2=0.; coord3=1.; coord4=0.; break;
+
+				case  9: coord1=0.; coord2=.5; coord3=.5; coord4=-1.;break;
+				case 10: coord1=.5; coord2=0.; coord3=.5; coord4=-1.;break;
+				case 11: coord1=.5; coord2=.5; coord3=0.; coord4=-1.;break;
+				case 12: coord1=0.; coord2=.5; coord3=.5; coord4=+1.;break;
+				case 13: coord1=.5; coord2=0.; coord3=.5; coord4=+1.;break;
+				case 14: coord1=.5; coord2=.5; coord3=0.; coord4=+1.;break;
+				default: _error_("node index should be in [0 14]");
+			}
+			break;
+		default: _error_("Finite element "<<EnumToStringx(finiteelement)<<" not supported");
 	}
 
Index: /issm/trunk/src/c/classes/gauss/GaussPenta.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussPenta.h	(revision 16136)
+++ /issm/trunk/src/c/classes/gauss/GaussPenta.h	(revision 16137)
@@ -35,4 +35,6 @@
 		GaussPenta(int index1, int index2, int index3, int order);
 		GaussPenta(int index1, int index2, int index3, int index4,int order_horiz,int order_vert);
+		GaussPenta(int index,IssmDouble r1, IssmDouble r2,bool maintlyfloating,int order);
+		GaussPenta(IssmDouble area_coordinates[4][3],int order_horiz,int order_vert);
 		~GaussPenta();
 
@@ -43,4 +45,5 @@
 		void GaussPoint(int ig);
 		void GaussVertex(int iv);
+		void GaussNode(int finitelement,int iv);
 		void GaussFaceTria(int index1, int index2, int index3, int order);
 		void GaussCenter(void);
Index: /issm/trunk/src/c/classes/gauss/GaussTria.cpp
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/gauss/GaussTria.cpp	(revision 16137)
@@ -99,4 +99,41 @@
 	xDelete<double>(seg_coords);
 	xDelete<double>(seg_weights);
+}
+/*}}}*/
+/*FUNCTION GaussTria::GaussTria(IssmDouble area_coordinates,int order) {{{*/
+GaussTria::GaussTria(IssmDouble area_coordinates[2][3],int order){
+
+	/*Intermediaties*/
+	IssmPDouble *seg_coords  = NULL;
+	IssmPDouble *seg_weights = NULL;
+	int     i,index3;
+
+	/*Get Segment gauss points*/
+	numgauss=order;
+	GaussLegendreLinear(&seg_coords,&seg_weights,numgauss);
+
+	/*Allocate GaussTria fields*/
+	coords1=xNew<IssmDouble>(numgauss);
+	coords2=xNew<IssmDouble>(numgauss);
+	coords3=xNew<IssmDouble>(numgauss);
+	weights=xNew<IssmDouble>(numgauss);
+
+	/*Build Triangle Gauss point*/
+	for(i=0;i<numgauss;i++){
+		coords1[i]=0.5*(area_coordinates[0][0]+area_coordinates[1][0]) + 0.5*seg_coords[i]*(area_coordinates[1][0]-area_coordinates[0][0]);
+		coords2[i]=0.5*(area_coordinates[0][1]+area_coordinates[1][1]) + 0.5*seg_coords[i]*(area_coordinates[1][1]-area_coordinates[0][1]);
+		coords3[i]=0.5*(area_coordinates[0][2]+area_coordinates[1][2]) + 0.5*seg_coords[i]*(area_coordinates[1][2]-area_coordinates[0][2]);
+		weights[i]=seg_weights[i];
+	}
+
+	/*Initialize static fields as undefined*/
+	weight=UNDEF;
+	coord1=UNDEF;
+	coord2=UNDEF;
+	coord3=UNDEF;
+
+	/*clean up*/
+	xDelete<IssmPDouble>(seg_coords);
+	xDelete<IssmPDouble>(seg_weights);
 }
 /*}}}*/
@@ -260,7 +297,8 @@
 GaussTria::~GaussTria(){
 	xDelete<IssmDouble>(weights);
+	xDelete<IssmDouble>(coords3);
+	xDelete<IssmDouble>(coords2);
 	xDelete<IssmDouble>(coords1);
-	xDelete<IssmDouble>(coords2);
-	xDelete<IssmDouble>(coords3);
+
 }
 /*}}}*/
@@ -404,5 +442,5 @@
 /*}}}*/
 /*FUNCTION GaussTria::GaussNode{{{*/
-void GaussTria::GaussNode(int numnodes,int iv){
+void GaussTria::GaussNode(int finiteelement,int iv){
 
 	/*in debugging mode: check that the default constructor has been called*/
@@ -410,6 +448,6 @@
 
 	/*update static arrays*/
-	switch(numnodes){
-		case 3: //P1 Lagrange element
+	switch(finiteelement){
+		case P1Enum: case P1DGEnum:
 			switch(iv){
 				case 0: coord1=1.; coord2=0.; coord3=0.; break;
@@ -419,5 +457,14 @@
 			}
 			break;
-		case 6: //P2 Lagrange element
+		case P1bubbleEnum: case P1bubblecondensedEnum:
+			switch(iv){
+				case 0: coord1=1.;    coord2=0.;    coord3=0.;    break;
+				case 1: coord1=0.;    coord2=1.;    coord3=0.;    break;
+				case 2: coord1=0.;    coord2=0.;    coord3=1.;    break;
+				case 3: coord1=1./3.; coord2=1./3.; coord3=1./3.; break;
+				default: _error_("node index should be in [0 3]");
+			}
+			break;
+		case P2Enum:
 			switch(iv){
 				case 0: coord1=1.; coord2=0.; coord3=0.; break;
@@ -430,5 +477,5 @@
 			}
 			break;
-		default: _error_("supported number of nodes are 3 and 6");
+		default: _error_("Finite element "<<EnumToStringx(finiteelement)<<" not supported");
 	}
 
Index: /issm/trunk/src/c/classes/gauss/GaussTria.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 16136)
+++ /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 16137)
@@ -31,4 +31,5 @@
 		GaussTria(int index1,int index2,int order);
 		GaussTria(int index,IssmDouble r1, IssmDouble r2,bool maintlyfloating,int order);
+		GaussTria(IssmDouble area_coordinates[3][3],int order);
 		~GaussTria();
 
@@ -40,5 +41,5 @@
 		void GaussPoint(int ig);
 		void GaussVertex(int iv);
-		void GaussNode(int numnodes,int iv);
+		void GaussNode(int finitelement,int iv);
 		void GaussCenter(void);
 		void GaussEdgeCenter(int index1,int index2);
Index: sm/trunk/src/c/classes/kriging/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/kriging/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,21 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/kriging)
-# }}}
-# KRIGING_SOURCES {{{
-set(KRIGING_SOURCES $ENV{ISSM_DIR}/src/c/classes/kriging/ExponentialVariogram.cpp
-                       $ENV{ISSM_DIR}/src/c/classes/kriging/GaussianVariogram.cpp
-                             $ENV{ISSM_DIR}/src/c/classes/kriging/Observation.cpp
-                          $ENV{ISSM_DIR}/src/c/classes/kriging/PowerVariogram.cpp
-                                $ENV{ISSM_DIR}/src/c/classes/kriging/Quadtree.cpp
-                      $ENV{ISSM_DIR}/src/c/classes/kriging/SphericalVariogram.cpp PARENT_SCOPE)
-# }}}
-# PKRIGING_SOURCES {{{
-set(PKRIGING_SOURCES $ENV{ISSM_DIR}/src/c/classes/kriging/ExponentialVariogram.cpp
-                        $ENV{ISSM_DIR}/src/c/classes/kriging/GaussianVariogram.cpp
-                              $ENV{ISSM_DIR}/src/c/classes/kriging/Observation.cpp
-                           $ENV{ISSM_DIR}/src/c/classes/kriging/PowerVariogram.cpp
-                                 $ENV{ISSM_DIR}/src/c/classes/kriging/Quadtree.cpp
-                       $ENV{ISSM_DIR}/src/c/classes/kriging/SphericalVariogram.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 16137)
@@ -65,5 +65,5 @@
 
 	/*Calculate length*/
-	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+	h=sqrt(deltax*deltax + deltay*deltay);
 
 	/*If h is too small, return sill*/
@@ -82,5 +82,5 @@
 
 	/*Calculate length*/
-	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+	h=sqrt(deltax*deltax + deltay*deltay);
 
 	/*return semi-variogram*/
Index: /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp	(revision 16137)
@@ -65,5 +65,5 @@
 
 	/*Calculate length square*/
-	h2=pow(deltax,2.)+pow(deltay,2.);
+	h2=deltax*deltax + deltay*deltay;
 
 	/*If h is too small, return sill*/
@@ -83,5 +83,5 @@
 
 	/*Calculate length square*/
-	h2=pow(deltax,2.)+pow(deltay,2.);
+	h2=deltax*deltax + deltay*deltay;
 
 	/*return semi-variogram*/
Index: /issm/trunk/src/c/classes/kriging/Observations.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/kriging/Observations.cpp	(revision 16137)
@@ -563,5 +563,5 @@
 			observation2=dynamic_cast<Observation*>(this->GetObjectByOffset(j));
 
-			distance=sqrt(pow(observation1->x - observation2->x,2.) + pow(observation1->y - observation2->y,2.));
+			distance=sqrt(pow(observation1->x - observation2->x,2) + pow(observation1->y - observation2->y,2));
 			if(distance>x[n-1]) continue;
 
@@ -570,5 +570,5 @@
 			if(index<0)   index = 0;
 
-			gamma[index]   += 1./2.*pow(observation1->value - observation2->value,2.);
+			gamma[index]   += 1./2.*pow(observation1->value - observation2->value,2);
 			counter[index] += 1.;
 		}
Index: /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp	(revision 16137)
@@ -66,5 +66,5 @@
 
 	/*Calculate length square*/
-	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+	h=sqrt(deltax*deltax + deltay*deltay);
 
 	/*return covariance*/
@@ -80,5 +80,5 @@
 
 	/*Calculate length square*/
-	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+	h=sqrt(deltax*deltax + deltay*deltay);
 
 	/*return semi-variogram*/
Index: /issm/trunk/src/c/classes/kriging/Quadtree.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 16137)
@@ -230,7 +230,7 @@
 	if(box && box->nbitems==4){
 		index  = 0;
-		length = pow(box->obs[0]->x - x,2.) + pow(box->obs[0]->y - y,2.);
+		length = pow(box->obs[0]->x - x,2) + pow(box->obs[0]->y - y,2);
 		for(int i=1;i<4;i++){
-			length2 = pow(box->obs[i]->x - x,2.) + pow(box->obs[i]->y - y,2.);
+			length2 = pow(box->obs[i]->x - x,2) + pow(box->obs[i]->y - y,2);
 			if(length2<length){
 				index  = i;
@@ -282,7 +282,7 @@
 	if(box && box->nbitems>0){
 		index  = box->obs[0]->index;
-		length = pow(box->obs[0]->x - x,2.) + pow(box->obs[0]->y - y,2.);
+		length = pow(box->obs[0]->x - x,2) + pow(box->obs[0]->y - y,2);
 		for(int i=1;i<box->nbitems;i++){
-			length2 = pow(box->obs[i]->x - x,2.) + pow(box->obs[i]->y - y,2.);
+			length2 = pow(box->obs[i]->x - x,2) + pow(box->obs[i]->y - y,2);
 			if(length2<length){
 				index  = box->obs[i]->index;
Index: /issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp	(revision 16137)
@@ -65,9 +65,9 @@
 
 	/*Calculate length square*/
-	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+	h=sqrt(deltax*deltax + deltay*deltay);
 
 	/*return covariance*/
 	if(h<=range)
-	 cova = (sill-nugget)*(1 - (3*h)/(2*range) + pow(h,3.)/(2*pow(range,3.)) );
+	 cova = (sill-nugget)*(1 - (3*h)/(2*range) + pow(h,3)/(2*pow(range,3)) );
 	else
 	 cova = 0.;
@@ -82,9 +82,9 @@
 
 	/*Calculate length square*/
-	h=sqrt(pow(deltax,2.)+pow(deltay,2.));
+	h=sqrt(deltax*deltax + deltay*deltay);
 
 	/*return semi-variogram*/
 	if(h<=range)
-	 gamma = (sill-nugget)*( (3*h)/(2*range) - pow(h,3.)/(2*pow(range,3.)) ) + nugget;
+	 gamma = (sill-nugget)*( (3*h)/(2*range) - pow(h,3)/(2*pow(range,3)) ) + nugget;
 	else
 	 gamma = sill;
Index: sm/trunk/src/c/classes/matrix/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/classes/matrix/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,9 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/matrix)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/classes/matrix/ElementMatrix.cpp
-                 $ENV{ISSM_DIR}/src/c/classes/matrix/ElementVector.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 16137)
@@ -223,5 +223,4 @@
 	this->col_slocaldoflist=NULL;
 	this->col_sglobaldoflist=NULL;
-
 }
 /*}}}*/
@@ -373,4 +372,108 @@
 }
 /*}}}*/
+/*FUNCTION ElementMatrix::StaticCondensation{{{*/
+void ElementMatrix::StaticCondensation(int bsize,int* bindices){
+	/* 
+	 * | Kii  Kib | | Ui |    |Fi|
+	 * | Kbi  Kbb | | Ub |  = |Fb|
+	 *
+	 * Kii Ui + Kib Ub = Fi
+	 * Kbi Ui + Kbb Ub = Fb
+	 *
+	 * We want to remove Ub from the equation:
+	 *
+	 * Kii Ui + Kib inv(Kbb) (Fb - Kbi Ui) = Fi
+	 *
+	 * which gives:
+	 *
+	 * (Kii - Kib inv(Kbb) Kbi) Ui = Fi - Kib inv(Kbb) Fb
+	 */
+
+	/*Checks in debugging mode*/
+	_assert_(this->nrows==this->ncols && bsize>0 && bsize<this->ncols && this->values); 
+
+	/*Intermediaries*/
+	int         counter,i,j,isize;
+	IssmDouble *Kii         = NULL;
+	IssmDouble *Kib         = NULL;
+	IssmDouble *Kbi         = NULL;
+	IssmDouble *Kbb         = NULL;
+	IssmDouble *Kbbinv      = NULL;
+	IssmDouble *Ktemp       = NULL;
+	int        *iindices    = NULL;
+	bool        flag;
+
+	/*Get new sizes and indices*/
+	isize    = this->nrows - bsize;
+	iindices = xNew<int>(isize);
+	counter  = 0;
+	for(i=0;i<this->nrows;i++){
+		flag = true;
+		for(j=0;j<bsize;j++){
+			if(i==bindices[j]){
+				flag = false;
+				break;
+			}
+		}
+		if(flag){
+			_assert_(counter<isize);
+			iindices[counter++] = i;
+		}
+	}
+	_assert_(counter == isize);
+
+	/*Get submatrices*/
+	Kii = xNew<IssmDouble>(isize*isize);
+	Kib = xNew<IssmDouble>(isize*bsize);
+	Kbi = xNew<IssmDouble>(bsize*isize);
+	Kbb = xNew<IssmDouble>(bsize*bsize);
+	for(i=0;i<isize;i++) for(j=0;j<isize;j++) Kii[i*isize+j] = this->values[iindices[i]*this->ncols + iindices[j]];
+	for(i=0;i<isize;i++) for(j=0;j<bsize;j++) Kib[i*bsize+j] = this->values[iindices[i]*this->ncols + bindices[j]];
+	for(i=0;i<bsize;i++) for(j=0;j<isize;j++) Kbi[i*isize+j] = this->values[bindices[i]*this->ncols + iindices[j]];
+	for(i=0;i<bsize;i++) for(j=0;j<bsize;j++) Kbb[i*bsize+j] = this->values[bindices[i]*this->ncols + bindices[j]];
+
+	/*Invert Kbb*/
+	Kbbinv = xNew<IssmDouble>(bsize*bsize);
+	switch(bsize){
+		case 1:
+			Kbbinv[0] = 1./Kbb[0];
+			break;
+		case 2:
+			Matrix2x2Invert(Kbbinv,Kbb);
+			break;
+		case 3:
+			Matrix3x3Invert(Kbbinv,Kbb);
+			break;
+		default:
+			MatrixInverse(Kbbinv,bsize,bsize,NULL,0,NULL);
+			break;
+	}
+
+	/*Calculate  Kib inv(Kbb) Kbi*/
+	Ktemp = xNew<IssmDouble>(isize*isize);
+	TripleMultiply(Kib,isize,bsize,0, Kbbinv,bsize,bsize,0, Kbi,bsize,isize,0, Ktemp,0);
+
+	/*New Ke*/
+	for(i=0;i<isize*isize;i++) Ktemp[i] = Kii[i] - Ktemp[i];
+
+	/*Update matrix values*/
+	for(i=0;i<this->nrows*this->ncols;i++) this->values[i]=0.;
+	for(i=0;i<isize;i++){
+		for(j=0;j<isize;j++){
+			this->values[iindices[i]*this->ncols + iindices[j]] = Ktemp[i*isize+j];
+		}
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(Kii);
+	xDelete<IssmDouble>(Kib);
+	xDelete<IssmDouble>(Kbi);
+	xDelete<IssmDouble>(Kbb);
+	xDelete<IssmDouble>(Kbbinv);
+	xDelete<IssmDouble>(Ktemp);
+	xDelete<int>(iindices);
+	return;
+}
+/*}}}*/
 /*FUNCTION ElementMatrix::Echo{{{*/
 void ElementMatrix::Echo(void){
@@ -390,30 +493,30 @@
 
 	_printf_("   gglobaldoflist (" << gglobaldoflist << "): ");
-	if(gglobaldoflist) for(i=0;i<nrows;i++) _printf_(" " << gglobaldoflist[i] << "\n"); _printf_("\n");
+	if(gglobaldoflist) for(i=0;i<nrows;i++) _printf_(" " << gglobaldoflist[i]); _printf_("\n");
 
 	_printf_("   row_fsize: " << row_fsize << "\n");
 	_printf_("   row_flocaldoflist  (" << row_flocaldoflist << "): ");
-	if(row_flocaldoflist) for(i=0;i<row_fsize;i++) _printf_(" " << row_flocaldoflist[i] << "\n"); _printf_(" \n");
+	if(row_flocaldoflist) for(i=0;i<row_fsize;i++) _printf_(" " << row_flocaldoflist[i] ); _printf_(" \n");
 	_printf_("   row_fglobaldoflist  (" << row_fglobaldoflist << "): ");
-	if(row_fglobaldoflist) for(i=0;i<row_fsize;i++) _printf_(" " << row_fglobaldoflist[i] << "\n"); _printf_(" \n");
+	if(row_fglobaldoflist) for(i=0;i<row_fsize;i++)_printf_(" " << row_fglobaldoflist[i]); _printf_(" \n");
 
 	_printf_("   row_ssize: " << row_ssize << "\n");
 	_printf_("   row_slocaldoflist  (" << row_slocaldoflist << "): ");
-	if(row_slocaldoflist) for(i=0;i<row_ssize;i++) _printf_(" " << row_slocaldoflist[i] << "\n"); _printf_(" \n");
+	if(row_slocaldoflist) for(i=0;i<row_ssize;i++) _printf_(" " << row_slocaldoflist[i] ); _printf_(" \n");
 	_printf_("   row_sglobaldoflist  (" << row_sglobaldoflist << "): ");
-	if(row_sglobaldoflist) for(i=0;i<row_ssize;i++) _printf_(" " << row_sglobaldoflist[i] << "\n"); _printf_(" \n");
+	if(row_sglobaldoflist) for(i=0;i<row_ssize;i++)_printf_(" " << row_sglobaldoflist[i]); _printf_(" \n");
 
 	if(!dofsymmetrical){
 		_printf_("   col_fsize: " << col_fsize << "\n");
 		_printf_("   col_flocaldoflist  (" << col_flocaldoflist << "): ");
-		if(col_flocaldoflist) for(i=0;i<col_fsize;i++) _printf_(" " << col_flocaldoflist[i] << "\n"); _printf_(" \n");
+		if(col_flocaldoflist) for(i=0;i<col_fsize;i++) _printf_(" " << col_flocaldoflist[i] ); _printf_(" \n");
 		_printf_("   col_fglobaldoflist  (" << col_fglobaldoflist << "): ");
-		if(col_fglobaldoflist) for(i=0;i<col_fsize;i++) _printf_(" " << col_fglobaldoflist[i] << "\n"); _printf_(" \n");
+		if(col_fglobaldoflist) for(i=0;i<col_fsize;i++)_printf_(" " << col_fglobaldoflist[i]); _printf_(" \n");
 
 		_printf_("   col_ssize: " << col_ssize << "\n");
 		_printf_("   col_slocaldoflist  (" << col_slocaldoflist << "): ");
-		if(col_slocaldoflist) for(i=0;i<col_ssize;i++) _printf_(" " << col_slocaldoflist[i] << "\n"); _printf_(" \n");
+		if(col_slocaldoflist) for(i=0;i<col_ssize;i++) _printf_(" " << col_slocaldoflist[i] ); _printf_(" \n");
 		_printf_("   col_sglobaldoflist  (" << col_sglobaldoflist << "): ");
-		if(col_sglobaldoflist) for(i=0;i<col_ssize;i++) _printf_(" " << col_sglobaldoflist[i] << "\n"); _printf_(" \n");
+		if(col_sglobaldoflist) for(i=0;i<col_ssize;i++)_printf_(" " << col_sglobaldoflist[i]); _printf_(" \n");
 	}
 }
@@ -423,4 +526,5 @@
 
 	_assert_(Ke);
+	_assert_(this);
 
 	this->nrows =Ke->nrows;
Index: /issm/trunk/src/c/classes/matrix/ElementMatrix.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 16136)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 16137)
@@ -10,5 +10,4 @@
 
 /*Headers:*/
-/*{{{*/
 #include "../../datastructures/datastructures.h"
 #include "../../toolkits/toolkits.h"
@@ -17,5 +16,4 @@
 template <class doublematrix> class Matrix;
 class Parameters;
-/*}}}*/
 
 class ElementMatrix{
@@ -51,5 +49,5 @@
 		int*     col_sglobaldoflist;
 
-		/*ElementMatrix constructors, destructors {{{*/
+		/*ElementMatrix constructors, destructors*/
 		ElementMatrix();
 		ElementMatrix(ElementMatrix* Ke);
@@ -58,14 +56,14 @@
 		ElementMatrix(Node** nodes,int numnodes,Parameters* parameters,int approximation=NoneApproximationEnum);
 		~ElementMatrix();
-		/*}}}*/
-		/*ElementMatrix specific routines {{{*/
+
+		/*ElementMatrix specific routines*/
 		void AddToGlobal(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
 		void AddToGlobal(Matrix<IssmDouble>* Jff);
 		void Echo(void);
 		void CheckConsistency(void);
+		void StaticCondensation(int numindices,int* indices);
 		void Transpose(void);
 		void Init(ElementMatrix* Ke);
 		void SetDiag(IssmDouble scalar);
-		/*}}}*/
 };
 #endif //#ifndef _ELEMENT_MATRIX_H_
Index: /issm/trunk/src/c/classes/matrix/ElementVector.cpp
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementVector.cpp	(revision 16136)
+++ /issm/trunk/src/c/classes/matrix/ElementVector.cpp	(revision 16137)
@@ -274,2 +274,105 @@
 }
 /*}}}*/
+/*FUNCTION ElementVector::StaticCondensation{{{*/
+void ElementVector::StaticCondensation(ElementMatrix* Ke,int bsize,int* bindices){
+	/* 
+	 * | Kii  Kib | | Ui |    |Fi|
+	 * | Kbi  Kbb | | Ub |  = |Fb|
+	 *
+	 * Kii Ui + Kib Ub = Fi
+	 * Kbi Ui + Kbb Ub = Fb
+	 *
+	 * We want to remove Ub from the equation:
+	 *
+	 * Kii Ui + Kib inv(Kbb) (Fb - Kbi Ui) = Fi
+	 *
+	 * which gives:
+	 *
+	 * (Kii - Kib inv(Kbb) Kbi) Ui = Fi - Kib inv(Kbb) Fb
+	 */
+
+	/*Checks in debugging mode*/
+	_assert_(bsize>0 && bsize<this->nrows && this->values && Ke); 
+	_assert_(Ke->nrows==Ke->ncols && this->nrows==Ke->nrows);
+
+	/*Intermediaries*/
+	int         counter,i,j,isize;
+	IssmDouble *Fb          = NULL;
+	IssmDouble *Fi          = NULL;
+	IssmDouble *Kib         = NULL;
+	IssmDouble *Kbb         = NULL;
+	IssmDouble *Kbbinv      = NULL;
+	IssmDouble *Ftemp       = NULL;
+	int        *iindices    = NULL;
+	bool        flag;
+
+	/*Get new sizes and indices*/
+	isize    = this->nrows - bsize;
+	iindices = xNew<int>(isize);
+	counter  = 0;
+	for(i=0;i<this->nrows;i++){
+		flag = true;
+		for(j=0;j<bsize;j++){
+			if(i==bindices[j]){
+				flag = false;
+				break;
+			}
+		}
+		if(flag){
+			_assert_(counter<isize);
+			iindices[counter++] = i;
+		}
+	}
+	_assert_(counter == isize);
+
+	/*Get submatrices*/
+	Kib = xNew<IssmDouble>(isize*bsize);
+	Kbb = xNew<IssmDouble>(bsize*bsize);
+	Fb  = xNew<IssmDouble>(bsize);
+	Fi  = xNew<IssmDouble>(isize);
+	for(i=0;i<isize;i++) for(j=0;j<bsize;j++) Kib[i*bsize+j] = Ke->values[iindices[i]*Ke->ncols + bindices[j]];
+	for(i=0;i<bsize;i++) for(j=0;j<bsize;j++) Kbb[i*bsize+j] = Ke->values[bindices[i]*Ke->ncols + bindices[j]];
+	for(i=0;i<bsize;i++) Fb[i] = this->values[bindices[i]];
+	for(i=0;i<isize;i++) Fi[i] = this->values[iindices[i]];
+
+	/*Invert Kbb*/
+	Kbbinv = xNew<IssmDouble>(bsize*bsize);
+	switch(bsize){
+		case 1:
+			Kbbinv[0] = 1./Kbb[0];
+			break;
+		case 2:
+			Matrix2x2Invert(Kbbinv,Kbb);
+			break;
+		case 3:
+			Matrix3x3Invert(Kbbinv,Kbb);
+			break;
+		default:
+			MatrixInverse(Kbbinv,bsize,bsize,NULL,0,NULL);
+			break;
+	}
+
+	/*Calculate  Kib inv(Kbb) Fb*/
+	Ftemp = xNew<IssmDouble>(isize);
+	TripleMultiply(Kib,isize,bsize,0, Kbbinv,bsize,bsize,0, Fb,bsize,1,0, Ftemp,0);
+
+	/*New Pe*/
+	for(i=0;i<isize;i++) Ftemp[i] = Fi[i] - Ftemp[i];
+
+	/*Update matrix values*/
+	for(i=0;i<this->nrows;i++) this->values[i]=0.;
+	for(i=0;i<isize;i++){
+		this->values[iindices[i]] = Ftemp[i];
+	}
+
+	/*Clean up and return*/
+	xDelete<IssmDouble>(Kib);
+	xDelete<IssmDouble>(Kbb);
+	xDelete<IssmDouble>(Kbbinv);
+	xDelete<IssmDouble>(Fb);
+	xDelete<IssmDouble>(Fi);
+	xDelete<IssmDouble>(Ftemp);
+	xDelete<int>(iindices);
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/matrix/ElementVector.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementVector.h	(revision 16136)
+++ /issm/trunk/src/c/classes/matrix/ElementVector.h	(revision 16137)
@@ -10,5 +10,4 @@
 
 /*Headers:*/
-/*{{{*/
 #include "../../datastructures/datastructures.h"
 #include "../../toolkits/toolkits.h"
@@ -17,22 +16,21 @@
 template <class doubletype> class Vector;
 class Parameters;
-/*}}}*/
+class ElementMatrix;
 
 class ElementVector{
 
 	public:
-
-		int      nrows;
-		IssmDouble*  values;
+		int         nrows;
+		IssmDouble* values;
 
 		//gset
-		int*     gglobaldoflist;
+		int* gglobaldoflist;
 
 		//fset
-		int      fsize;
-		int*     flocaldoflist;
-		int*     fglobaldoflist;
+		int  fsize;
+		int* flocaldoflist;
+		int* fglobaldoflist;
 
-		/*ElementVector constructors, destructors {{{*/
+		/*ElementVector constructors, destructors*/
 		ElementVector();
 		ElementVector(ElementVector* pe1,ElementVector* pe2);
@@ -40,6 +38,6 @@
 		ElementVector(Node** nodes,int numnodes,Parameters* parameters,int approximation=NoneApproximationEnum);
 		~ElementVector();
-		/*}}}*/
-		/*ElementVector specific routines {{{*/
+
+		/*ElementVector specific routines*/
 		void AddToGlobal(Vector<IssmDouble>* pf);
 		void InsertIntoGlobal(Vector<IssmDouble>* pf);
@@ -48,5 +46,5 @@
 		void Init(ElementVector* pe);
 		void SetValue(IssmDouble scalar);
-		/*}}}*/
+		void StaticCondensation(ElementMatrix* Ke,int numindices,int* indices);
 };
 #endif //#ifndef _ELEMENT_VECTOR_H_
Index: sm/trunk/src/c/kml/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/kml/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,34 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/classes/objects/KML)
-# }}}
-# KML_SOURCES {{{
-set(KML_SOURCES $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Attribute.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_ColorStyle.cpp
-                  $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Comment.cpp
-                $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Container.cpp
-                 $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Document.cpp
-                  $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Feature.cpp
-                     $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_File.cpp
-                   $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Folder.cpp
-                 $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Geometry.cpp
-            $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_GroundOverlay.cpp
-                     $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Icon.cpp
-                $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_LatLonBox.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_LinearRing.cpp
-               $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_LineString.cpp
-                $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_LineStyle.cpp
-            $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_MultiGeometry.cpp
-                   $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Object.cpp
-                  $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Overlay.cpp
-                $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Placemark.cpp
-                    $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Point.cpp
-                  $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Polygon.cpp
-                $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_PolyStyle.cpp
-                    $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Style.cpp
-            $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_StyleSelector.cpp
-                 $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_SubStyle.cpp
-                  $ENV{ISSM_DIR}/src/c/classes/objects/KML/KML_Unknown.cpp
-             $ENV{ISSM_DIR}/src/c/classes/objects/KML/KMLFileReadUtils.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/kml/KMLFileReadUtils.cpp
===================================================================
--- /issm/trunk/src/c/kml/KMLFileReadUtils.cpp	(revision 16136)
+++ /issm/trunk/src/c/kml/KMLFileReadUtils.cpp	(revision 16137)
@@ -556,7 +556,7 @@
 	if (!*pdval)
 		if (maxlen)
-			*pdval=xNew<IssmDouble>(maxlen            );
-		else
-			*pdval=xNew<IssmDouble>((strlen(kstr)+1)/2);
+			*pdval=xNew<IssmPDouble>(maxlen            );
+		else
+			*pdval=xNew<IssmPDouble>((strlen(kstr)+1)/2);
 
 /*  loop through string to get all values  */
@@ -622,7 +622,7 @@
 	if (!*pdval)
 		if (maxlen)
-			*pdval=xNew<IssmDouble>(maxlen*n          );
-		else
-			*pdval=xNew<IssmDouble>((strlen(kstr)+1)/2);
+			*pdval=xNew<IssmPDouble>(maxlen*n          );
+		else
+			*pdval=xNew<IssmPDouble>((strlen(kstr)+1)/2);
 
 /*  loop through string to get all values  */
Index: /issm/trunk/src/c/kml/KML_LineString.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_LineString.cpp	(revision 16136)
+++ /issm/trunk/src/c/kml/KML_LineString.cpp	(revision 16137)
@@ -181,6 +181,6 @@
 /*  extract latitude and longitude into vectors  */
 
-	lat=xNew<IssmDouble>(ncoord);
-	lon=xNew<IssmDouble>(ncoord);
+	lat=xNew<IssmPDouble>(ncoord);
+	lon=xNew<IssmPDouble>(ncoord);
 	for (i=0; i<ncoord; i++) {
 		lon[i]=coords[3*i+0];
@@ -190,6 +190,6 @@
 /*  convert latitude and longitude to x and y  */
 
-	x  =xNew<IssmDouble>(ncoord);
-	y  =xNew<IssmDouble>(ncoord);
+	x  =xNew<IssmPDouble>(ncoord);
+	y  =xNew<IssmPDouble>(ncoord);
 	if (sgn) {
 		Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
@@ -222,10 +222,10 @@
 	fprintf(fid,"\n");
 
-	xDelete<IssmDouble>(y);
-	xDelete<IssmDouble>(x);
-	xDelete<IssmDouble>(lon);
-	xDelete<IssmDouble>(lat);
-
-	return;
-}
-/*}}}*/
+	xDelete<IssmPDouble>(y);
+	xDelete<IssmPDouble>(x);
+	xDelete<IssmPDouble>(lon);
+	xDelete<IssmPDouble>(lat);
+
+	return;
+}
+/*}}}*/
Index: /issm/trunk/src/c/kml/KML_LinearRing.cpp
===================================================================
--- /issm/trunk/src/c/kml/KML_LinearRing.cpp	(revision 16136)
+++ /issm/trunk/src/c/kml/KML_LinearRing.cpp	(revision 16137)
@@ -169,6 +169,6 @@
 /*  extract latitude and longitude into vectors  */
 
-	lat=xNew<IssmDouble>(ncoord);
-	lon=xNew<IssmDouble>(ncoord);
+	lat=xNew<IssmPDouble>(ncoord);
+	lon=xNew<IssmPDouble>(ncoord);
 	for (i=0; i<ncoord; i++) {
 		lon[i]=coords[3*i+0];
@@ -178,6 +178,6 @@
 /*  convert latitude and longitude to x and y  */
 
-	x  =xNew<IssmDouble>(ncoord);
-	y  =xNew<IssmDouble>(ncoord);
+	x  =xNew<IssmPDouble>(ncoord);
+	y  =xNew<IssmPDouble>(ncoord);
 	if (sgn) {
 		Ll2xyx(x,y,lat,lon,ncoord,sgn,cm,sp);
Index: /issm/trunk/src/c/main/globals.h
===================================================================
--- /issm/trunk/src/c/main/globals.h	(revision 16136)
+++ /issm/trunk/src/c/main/globals.h	(revision 16137)
@@ -6,12 +6,14 @@
 #define _GLOBALS_H_
 
-#include "../shared/io/Comm/Comm.h"
+#include "../shared/io/Comm/IssmComm.h"
 #include "../toolkits/ToolkitOptions.h"
 
 /*Communicators: */
-COMM IssmComm::comm;
+ISSM_MPI_Comm IssmComm::comm;
 bool IssmComm::parallel;
 
-/*String that is used to characterize our toolkits, ends up in Petsc Options database if we use Petsc. Can also be used to characterize the ISSM toolkit, often used when Petsc is not allowed*/
+/*String that is used to characterize our toolkits, ends up in Petsc Options
+ * database if we use Petsc. Can also be used to characterize the ISSM toolkit,
+ * often used when Petsc is not allowed*/
 char* ToolkitOptions::toolkitoptions;
 
Index: /issm/trunk/src/c/main/issm.cpp
===================================================================
--- /issm/trunk/src/c/main/issm.cpp	(revision 16136)
+++ /issm/trunk/src/c/main/issm.cpp	(revision 16137)
@@ -11,5 +11,5 @@
 
 	/*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
-	COMM comm_init=EnvironmentInit(argc,argv);
+	ISSM_MPI_Comm comm_init=EnvironmentInit(argc,argv);
 
 	/*Initialize femmodel from arguments provided command line: */
Index: /issm/trunk/src/c/main/kriging.cpp
===================================================================
--- /issm/trunk/src/c/main/kriging.cpp	(revision 16136)
+++ /issm/trunk/src/c/main/kriging.cpp	(revision 16137)
@@ -22,6 +22,4 @@
 	char *rootpath       = NULL;
 
-	MPI_Comm comm;
-
 	/*Input*/
 	int         ninterp,nobs;
@@ -41,5 +39,5 @@
 
 	/*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
-	comm=EnvironmentInit(argc,argv);
+	ISSM_MPI_Comm comm=EnvironmentInit(argc,argv);
 	IssmComm::SetComm(comm);
 
@@ -57,5 +55,5 @@
 	Results *results = new Results();
 	if(IssmComm::GetRank()==0){
-		output_fid=pfopen(outbinfilename,"wb");
+		output_fid=pfopen0(outbinfilename,"wb");
 		results->AddObject(new GenericExternalResult<double*>(results->Size()+1,0,predictions,ninterp,1,1,0));
 		results->AddObject(new GenericExternalResult<double*>(results->Size()+1,1,error,ninterp,1,1,0));
@@ -148,5 +146,5 @@
 	iomodel->fid=fid;
 	iomodel->CheckEnumSync();
-	iomodel->independents=xNew<bool>(MaximumNumberOfEnums); for(int i=0;i<MaximumNumberOfEnums;i++) iomodel->independents[i]=false;
+	iomodel->independents=xNew<bool>(MaximumNumberOfDefinitionsEnum); for(int i=0;i<MaximumNumberOfDefinitionsEnum;i++) iomodel->independents[i]=false;
 	iomodel->FetchData(&x,&M,&N,0);        nobs=M*N;
 	iomodel->FetchData(&y,&M,&N,1);        _assert_(M*N==nobs);
Index: /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.cpp	(revision 16137)
@@ -0,0 +1,264 @@
+/*!\file AllocateSystemMatricesx
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./AllocateSystemMatricesx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void AllocateSystemMatricesx(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,Vector<IssmDouble>** pdf,Vector<IssmDouble>** ppf,FemModel* femmodel){
+
+	/*Intermediary*/
+	int  fsize,ssize,flocalsize,slocalsize;
+	int  connectivity, numberofdofspernode;
+	int  configuration_type;
+	int  m,n,M,N;
+	int *d_nnz = NULL;
+	int *o_nnz = NULL;
+
+	/*output*/
+	Matrix<IssmDouble> *Kff  = NULL;
+	Matrix<IssmDouble> *Kfs  = NULL;
+	Vector<IssmDouble> *pf   = NULL;
+	Vector<IssmDouble> *df   = NULL;
+
+	bool oldalloc=false;
+
+	/*retrieve parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&connectivity,MeshAverageVertexConnectivityEnum);
+
+	/*retrieve node info*/
+	fsize      = femmodel->nodes->NumberOfDofs(configuration_type,FsetEnum);
+	ssize      = femmodel->nodes->NumberOfDofs(configuration_type,SsetEnum);
+	flocalsize = femmodel->nodes->NumberOfDofsLocal(configuration_type,FsetEnum);
+	slocalsize = femmodel->nodes->NumberOfDofsLocal(configuration_type,SsetEnum);
+
+	numberofdofspernode=femmodel->nodes->MaxNumDofs(configuration_type,GsetEnum);
+
+	if(oldalloc){
+		if(pKff) Kff=new Matrix<IssmDouble>(fsize,fsize,connectivity,numberofdofspernode);
+		if(pKfs) Kfs=new Matrix<IssmDouble>(fsize,ssize,connectivity,numberofdofspernode);
+		if(pdf)  df =new Vector<IssmDouble>(fsize);
+		if(ppf)  pf =new Vector<IssmDouble>(fsize);
+	}
+	else{
+		if(pKff){
+			m=flocalsize; n=flocalsize; /*local  sizes*/
+			M=fsize;      N=fsize;      /*global sizes*/
+			MatrixNonzeros(&d_nnz,&o_nnz,femmodel,FsetEnum,FsetEnum);
+			Kff=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
+			xDelete<int>(d_nnz);
+			xDelete<int>(o_nnz);
+		}
+		if(pKfs){
+			m=flocalsize; n=slocalsize; /*local  sizes*/
+			M=fsize;      N=ssize;      /*global sizes*/
+			MatrixNonzeros(&d_nnz,&o_nnz,femmodel,FsetEnum,SsetEnum);
+			Kfs=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
+			xDelete<int>(d_nnz);
+			xDelete<int>(o_nnz);
+		}
+		if(pdf) df =new Vector<IssmDouble>(flocalsize,fsize);
+		if(ppf) pf =new Vector<IssmDouble>(flocalsize,fsize);
+	}
+
+	/*Allocate output pointers*/
+	if(pKff) *pKff = Kff;
+	if(pKfs) *pKfs = Kfs;
+	if(pdf)  *pdf  = df;
+	if(ppf)  *ppf  = pf;
+}
+
+void MatrixNonzeros(int** pd_nnz,int** po_nnz,FemModel* femmodel,int set1enum,int set2enum){
+
+	/*Intermediary*/
+	int      i,j,k,index,offset,count;
+	int      configuration_type;
+	int      d_nz,o_nz;
+	Element *element            = NULL;
+	Load    *load               = NULL;
+	int     *head_e             = NULL;
+	int     *next_e             = NULL;
+	int     *count2offset_e     = NULL;
+	int     *head_l             = NULL;
+	int     *next_l             = NULL;
+	int     *count2offset_l     = NULL;
+	int     *lidlist            = NULL;
+
+	/*output*/
+	int *d_nnz = NULL;
+	int *o_nnz = NULL;
+
+	/*retrive parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	/*Get vector size and number of nodes*/
+	int numnodes            = femmodel->nodes->NumberOfNodes(configuration_type);
+	int localnumnodes       = femmodel->nodes->Size();
+	int numberofdofspernode = femmodel->nodes->MaxNumDofs(configuration_type,GsetEnum);
+	int M                   = femmodel->nodes->NumberOfDofs(configuration_type,set1enum);
+	int N                   = femmodel->nodes->NumberOfDofs(configuration_type,set2enum);
+	int m                   = femmodel->nodes->NumberOfDofsLocal(configuration_type,set1enum);
+	int n                   = femmodel->nodes->NumberOfDofsLocal(configuration_type,set2enum);
+	int numnodesperelement  = femmodel->elements->MaxNumNodes();
+	int numnodesperload     = femmodel->loads->MaxNumNodes(configuration_type);
+
+	/*First, we are building chaining vectors so that we know what nodes are
+	 * connected to what elements. These vectors are such that:
+	 *   for(int i=head[id];i!=-1;i=next[i])
+	 * will loop over all the elements that are connected to the node number
+	 * id*/
+	head_e         = xNew<int>(localnumnodes); for(i=0;i<localnumnodes;i++) head_e[i]=-1;
+	next_e         = xNew<int>(femmodel->elements->Size()*numnodesperelement);
+	count2offset_e = xNew<int>(femmodel->elements->Size()*numnodesperelement);
+
+	k=0;
+	for(i=0;i<femmodel->elements->Size();i++){
+		element = dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		lidlist = xNew<int>(element->GetNumberOfNodes());
+		element->GetNodesLidList(lidlist);
+
+		for(j=0;j<element->GetNumberOfNodes();j++){
+			index = lidlist[j];
+			_assert_(index>=0 && index<numnodes);
+
+			count2offset_e[k]=i;
+			next_e[k]=head_e[index];
+			head_e[index]=k++;
+		}
+		for(j=0;j<numnodesperelement-element->GetNumberOfNodes();j++) k++;
+
+		xDelete<int>(lidlist);
+	}
+
+	/*Chain for loads*/
+	head_l         = xNew<int>(localnumnodes); for(i=0;i<localnumnodes;i++) head_l[i]=-1;
+	next_l         = xNew<int>(femmodel->loads->Size(configuration_type)*numnodesperload);
+	count2offset_l = xNew<int>(femmodel->loads->Size(configuration_type)*numnodesperload);
+	k=0;
+	for(i=0;i<femmodel->loads->Size();i++){
+		load = dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+		if(!load->InAnalysis(configuration_type)) continue;
+		lidlist = xNew<int>(load->GetNumberOfNodes());
+		load->GetNodesLidList(lidlist);
+
+		for(j=0;j<load->GetNumberOfNodes();j++){
+			index = lidlist[j];
+			_assert_(index>=0 && index<numnodes);
+
+			count2offset_l[k]=i;
+			next_l[k]=head_l[index];
+			head_l[index]=k++;
+		}
+		for(j=0;j<numnodesperload-load->GetNumberOfNodes();j++) k++;
+
+		xDelete<int>(lidlist);
+	}
+
+	/*OK now count number of dofs and flag each nodes for each node i*/
+	bool *flags                  = xNew<bool>(localnumnodes);
+	int  *flagsindices           = xNew<int>(localnumnodes);
+	int  *d_connectivity         = xNewZeroInit<int>(numnodes);
+	int  *o_connectivity         = xNewZeroInit<int>(numnodes);
+	int  *connectivity_clone     = xNewZeroInit<int>(numnodes);
+	int  *all_connectivity_clone = xNewZeroInit<int>(numnodes);
+
+	/*Resetting flags to false at eahc iteration takes a lot of time, so we keep track of the flags
+	 * to reset in flagsindices, initialized with -1*/
+	for(i = 0;i<localnumnodes;i++) flags[i]        = false;
+	for(i = 0;i<localnumnodes;i++) flagsindices[i] = -1;
+
+	/*Create connectivity vector*/
+	for(i=0;i<femmodel->nodes->Size();i++){
+		Node* node=dynamic_cast<Node*>(femmodel->nodes->GetObjectByOffset(i));
+		if(node->InAnalysis(configuration_type)){
+
+			/*Reinitialize flags to false*/
+			j=0;
+			while(true){
+				if(flagsindices[j]>=0){
+					flags[flagsindices[j]] = false;
+					flagsindices[j]        = -1;
+					j++;
+				}
+				else{
+					break;
+				}
+			}
+
+			//for(j=0;j<localnumnodes;j++) flags[j]=false;
+
+			/*Loop over elements that hold node number i*/
+			//if(head_e[node->Lid()]==-1 && head_l[node->Lid()]==-1){
+			//	printf("[%i] vertex %i\n",IssmComm::GetRank(),node->Lid()+1);
+			//}
+			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->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,flagsindices,set1enum,set2enum);
+				if(node->IsClone()){
+					connectivity_clone[node->Sid()]+=d_nz+o_nz;
+				}
+				else{
+					d_connectivity[node->Sid()]+=d_nz;
+					o_connectivity[node->Sid()]+=o_nz;
+				}
+			}
+			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->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,flagsindices,set1enum,set2enum);
+				if(node->IsClone()){
+					connectivity_clone[node->Sid()]+=d_nz+o_nz;
+				}
+				else{
+					d_connectivity[node->Sid()]+=d_nz;
+					o_connectivity[node->Sid()]+=o_nz;
+				}
+			}
+		}
+	}
+	xDelete<bool>(flags);
+	xDelete<int>(flagsindices);
+	xDelete<int>(count2offset_e);
+	xDelete<int>(head_e);
+	xDelete<int>(next_e);
+	xDelete<int>(count2offset_l);
+	xDelete<int>(head_l);
+	xDelete<int>(next_l);
+
+	/*sum over all cpus*/
+	ISSM_MPI_Allreduce((void*)connectivity_clone,(void*)all_connectivity_clone,numnodes,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
+	xDelete<int>(connectivity_clone);
+
+	if(set1enum==FsetEnum){
+		count=0;
+		d_nnz=xNew<int>(m);
+		o_nnz=xNew<int>(m);
+		for(i=0;i<femmodel->nodes->Size();i++){
+			Node* node=dynamic_cast<Node*>(femmodel->nodes->GetObjectByOffset(i));
+			if(node->InAnalysis(configuration_type) && !node->IsClone()){
+				for(j=0;j<node->indexing.fsize;j++){
+					_assert_(count<m);
+					d_nnz[count]=numberofdofspernode*(d_connectivity[node->Sid()] + all_connectivity_clone[node->Sid()]);
+					o_nnz[count]=numberofdofspernode*(o_connectivity[node->Sid()] + all_connectivity_clone[node->Sid()]);
+					if(d_nnz[count]>n)   d_nnz[count]=n;
+					if(o_nnz[count]>N-n) o_nnz[count]=N-n;
+					count++;
+				}
+			}
+		}
+		_assert_(m==count);
+	}
+	else{
+		_error_("STOP not implemented");
+	}
+	xDelete<int>(d_connectivity);
+	xDelete<int>(o_connectivity);
+	xDelete<int>(all_connectivity_clone);
+
+	/*Allocate ouptput pointer*/
+	*pd_nnz=d_nnz;
+	*po_nnz=o_nnz;
+}
Index: /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.h
===================================================================
--- /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.h	(revision 16137)
+++ /issm/trunk/src/c/modules/AllocateSystemMatricesx/AllocateSystemMatricesx.h	(revision 16137)
@@ -0,0 +1,14 @@
+/*!\file:  AllocateSystemMatricesx.h
+*/ 
+
+#ifndef _ALLOCATESYSTEMMATRICESX_H
+#define _ALLOCATESYSTEMMATRICESX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void AllocateSystemMatricesx(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,Vector<IssmDouble>** pdf,Vector<IssmDouble>** ppf,FemModel* femmodel);
+void MatrixNonzeros(int** pd_nnz,int** po_nnz,FemModel* femmodel,int set1enum,int set2enum);
+
+
+#endif
Index: sm/trunk/src/c/modules/AverageFilterx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/AverageFilterx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/AverageFilterx)
-# }}}
Index: sm/trunk/src/c/modules/AverageOntoPartitionx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/AverageOntoPartitionx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/AverageOntoPartitionx)
-# }}}
-# DAKOTA_SOURCES {{{
-set(DAKOTA_SOURCES $ENV{ISSM_DIR}/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/BamgConvertMeshx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/BamgConvertMeshx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/BamgConvertMeshx)
-# }}}
-# BAMG_SOURCES {{{
-set(BAMG_SOURCES $ENV{ISSM_DIR}/src/c/modules/BamgConvertMeshx/BamgConvertMeshx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/BamgTriangulatex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/BamgTriangulatex/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/BamgTriangulatex)
-# }}}
-# BAMG_SOURCES {{{
-set(BAMG_SOURCES $ENV{ISSM_DIR}/src/c/modules/BamgTriangulatex/BamgTriangulatex.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/Bamgx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Bamgx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Bamgx)
-# }}}
-# BAMG_SOURCES {{{
-set(BAMG_SOURCES $ENV{ISSM_DIR}/src/c/modules/Bamgx/Bamgx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,99 +1,0 @@
-# Subdirectories {{{
-add_subdirectory(AverageFilterx)
-add_subdirectory(AverageOntoPartitionx)
-add_subdirectory(BamgConvertMeshx)
-add_subdirectory(BamgTriangulatex)
-add_subdirectory(Bamgx)
-add_subdirectory(Chacox)
-add_subdirectory(ComputeBasalStressx)
-add_subdirectory(ComputeStrainRatex)
-add_subdirectory(ConfigureObjectsx)
-add_subdirectory(ConstraintsStatex)
-add_subdirectory(ContourToMeshx)
-add_subdirectory(ContourToNodesx)
-add_subdirectory(ControlInputGetGradientx)
-add_subdirectory(ControlInputScaleGradientx)
-add_subdirectory(ControlInputSetGradientx)
-add_subdirectory(CreateNodalConstraintsx)
-add_subdirectory(Delta18oParameterizationx)
-add_subdirectory(DragCoefficientAbsGradientx)
-add_subdirectory(ElementConnectivityx)
-add_subdirectory(EnumToStringx)
-add_subdirectory(Exp2Kmlx)
-add_subdirectory(GetSolutionFromInputsx)
-add_subdirectory(GetVectorFromControlInputsx)
-add_subdirectory(GetVectorFromInputsx)
-add_subdirectory(Gradjx)
-add_subdirectory(GroundinglineMigrationx)
-add_subdirectory(HoleFillerx)
-add_subdirectory(InputArtificialNoisex)
-add_subdirectory(InputControlUpdatex)
-add_subdirectory(InputDuplicatex)
-add_subdirectory(InputScalex)
-add_subdirectory(InputToResultx)
-add_subdirectory(InputUpdateFromConstantx)
-add_subdirectory(InputUpdateFromDakotax)
-add_subdirectory(InputUpdateFromMatrixDakotax)
-add_subdirectory(InputUpdateFromSolutionx)
-add_subdirectory(InputUpdateFromVectorDakotax)
-add_subdirectory(InputUpdateFromVectorx)
-add_subdirectory(InterpFromGridToMeshx)
-add_subdirectory(InterpFromMesh2dx)
-add_subdirectory(InterpFromMeshToGridx)
-add_subdirectory(InterpFromMeshToMesh2dx)
-add_subdirectory(InterpFromMeshToMesh3dx)
-add_subdirectory(IoModelToConstraintsx)
-add_subdirectory(Kml2Expx)
-add_subdirectory(KMLFileReadx)
-add_subdirectory(KMLMeshWritex)
-add_subdirectory(KMLOverlayx)
-add_subdirectory(Krigingx)
-add_subdirectory(Ll2xyx)
-add_subdirectory(Mergesolutionfromftogx)
-add_subdirectory(MeshPartitionx)
-add_subdirectory(MeshProfileIntersectionx)
-add_subdirectory(ModelProcessorx)
-add_subdirectory(NodalValuex)
-add_subdirectory(NodeConnectivityx)
-add_subdirectory(NodesDofx)
-add_subdirectory(Orthx)
-add_subdirectory(OutputResultsx)
-add_subdirectory(OutputRiftsx)
-add_subdirectory(ParsePetscOptionsx)
-add_subdirectory(PointCloudFindNeighborsx)
-add_subdirectory(PositiveDegreeDayx)
-add_subdirectory(PropagateFlagsFromConnectivityx)
-add_subdirectory(Reduceloadx)
-add_subdirectory(Reducevectorgtofx)
-add_subdirectory(Reducevectorgtosx)
-add_subdirectory(ResetConstraintsx)
-add_subdirectory(ResetCoordinateSystemx)
-add_subdirectory(RheologyBbarAbsGradientx)
-add_subdirectory(Scotchx)
-add_subdirectory(SetControlInputsFromVectorx)
-add_subdirectory(Shp2Expx)
-add_subdirectory(Shp2Kmlx)
-add_subdirectory(SmbGradientsx)
-add_subdirectory(Solverx)
-add_subdirectory(SpcNodesx)
-add_subdirectory(StringToEnumx)
-add_subdirectory(SurfaceAbsVelMisfitx)
-add_subdirectory(SurfaceAreax)
-add_subdirectory(SurfaceAverageVelMisfitx)
-add_subdirectory(SurfaceLogVelMisfitx)
-add_subdirectory(SurfaceLogVxVyMisfitx)
-add_subdirectory(SurfaceRelVelMisfitx)
-add_subdirectory(ThicknessAbsMisfitx)
-add_subdirectory(ThicknessAcrossGradientx)
-add_subdirectory(ThicknessAlongGradientx)
-add_subdirectory(TriaSearchx)
-add_subdirectory(TriMeshProcessRiftsx)
-add_subdirectory(TriMeshx)
-add_subdirectory(UpdateDynamicConstraintsx)
-add_subdirectory(VecMergex)
-add_subdirectory(VerticesDofx)
-add_subdirectory(Xy2llx)
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules)
-# }}}
Index: sm/trunk/src/c/modules/Chacox/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Chacox/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Chacox)
-# }}}
Index: sm/trunk/src/c/modules/ComputeBasalStressx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ComputeBasalStressx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ComputeBasalStressx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/ComputeStrainRatex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ComputeStrainRatex/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ComputeStrainRatex)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/ConfigureObjectsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ConfigureObjectsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ConfigureObjectsx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 16137)
@@ -35,12 +35,4 @@
 		}
 	}
-	if(VerboseMProcessor()) _printf0_("      Configuring nodes...\n");
-	for (i=0;i<nodes->Size();i++){
-		node=(Node*)nodes->GetObjectByOffset(i);
-		if(node->InAnalysis(configuration_type)){
-			node->Configure(nodes,vertices);
-		}
-	}
-
 	if(VerboseMProcessor()) _printf0_("      Configuring materials...\n");
 	for (i=0;i<materials->Size();i++){
Index: sm/trunk/src/c/modules/ConstraintsStatex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,15 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ConstraintsStatex)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp PARENT_SCOPE)
-# }}}
-# THERMAL_SOURCES {{{
-set(THERMAL_SOURCES $ENV{ISSM_DIR}/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp
-                           $ENV{ISSM_DIR}/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp PARENT_SCOPE)
-# }}}
-# RIFTS_SOURCES {{{
-set(RIFTS_SOURCES $ENV{ISSM_DIR}/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 16137)
@@ -8,10 +8,10 @@
 #include "../../toolkits/toolkits.h"
 
-void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters){
+void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints,FemModel* femmodel){
 
 	/*output: */
-	int converged=0;
-	int num_unstable_constraints=0;
-	int min_mechanical_constraints=0; 
+	int converged                  = 0;
+	int num_unstable_constraints   = 0;
+	int min_mechanical_constraints = 0;
 	int analysis_type;
 
@@ -20,6 +20,6 @@
 
 	/*recover parameters: */
-	parameters->FindParam(&min_mechanical_constraints,DiagnosticRiftPenaltyThresholdEnum);
-	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	femmodel->parameters->FindParam(&min_mechanical_constraints,StressbalanceRiftPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 
 	/*Do we have penalties linked to rifts? In this case, run our special rifts penalty 
@@ -31,11 +31,11 @@
 
 	#ifdef _HAVE_RIFTS_
-	if (RiftIsPresent(loads,analysis_type)){
-		RiftConstraintsState(&converged,&num_unstable_constraints,loads,min_mechanical_constraints,analysis_type);
+	if(RiftIsPresent(femmodel->loads,analysis_type)){
+		RiftConstraintsState(&converged,&num_unstable_constraints,femmodel->loads,min_mechanical_constraints,analysis_type);
 	}
 	#endif
 	#ifdef _HAVE_THERMAL_
-	if(ThermalIsPresent(loads,analysis_type)){
-		ThermalConstraintsState(loads,&converged,&num_unstable_constraints,analysis_type);
+	if(ThermalIsPresent(femmodel->loads,analysis_type)){
+		ThermalConstraintsState(femmodel->loads,&converged,&num_unstable_constraints,analysis_type);
 	}
 	#endif
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 16136)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 16137)
@@ -9,7 +9,7 @@
 
 /* local prototypes: */
-int   ThermalIsPresent(Loads* loads,int analysis_type);
-int    RiftIsPresent(Loads* loads,int analysis_type);
-void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters); 
+int  ThermalIsPresent(Loads* loads,int analysis_type);
+int  RiftIsPresent(Loads* loads,int analysis_type);
+void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints,FemModel* femmodel);
 
 #endif  /* _CONSTRAINTSSTATEX_H */
Index: /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 16137)
@@ -28,9 +28,7 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());                
+	ISSM_MPI_Reduce (&found,&mpi_found,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&mpi_found,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
 	found=mpi_found;
-	#endif
 
 	return found;
@@ -90,9 +88,7 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());                
+	ISSM_MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&sum_num_unstable_constraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
 	num_unstable_constraints=sum_num_unstable_constraints;
-	#endif
 
 	/*Assign output pointers: */
@@ -130,9 +126,7 @@
 
 	/*Is there just one found? that would mean we have frozen! : */
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());                
+	ISSM_MPI_Reduce (&found,&mpi_found,1,ISSM_MPI_INT,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&mpi_found,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
 	found=mpi_found;
-	#endif
 
 	return found;
@@ -190,9 +184,7 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());                
+	ISSM_MPI_Reduce (&found,&mpi_found,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&mpi_found,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
 	found=mpi_found;
-	#endif
 
 	return found;
@@ -222,9 +214,7 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());                
+	ISSM_MPI_Reduce (&found,&mpi_found,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&mpi_found,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
 	found=mpi_found;
-	#endif
 
 	if (found){
@@ -282,9 +272,7 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());                
+	ISSM_MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&sum_num_unstable_constraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
 	num_unstable_constraints=sum_num_unstable_constraints;
-	#endif
 
 	/*Assign output pointers: */
@@ -322,9 +310,7 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&max_penetration,&mpi_max_penetration,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
-	MPI_Bcast(&mpi_max_penetration,1,MPI_DOUBLE,0,IssmComm::GetComm());                
+	ISSM_MPI_Reduce (&max_penetration,&mpi_max_penetration,1,ISSM_MPI_DOUBLE,ISSM_MPI_MAX,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&mpi_max_penetration,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());                
 	max_penetration=mpi_max_penetration;
-	#endif
 
 	/*feed max_penetration to inputs: */
@@ -361,9 +347,7 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());                
+	ISSM_MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&sum_num_unstable_constraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
 	num_unstable_constraints=sum_num_unstable_constraints;
-	#endif
 
 	return num_unstable_constraints;
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp	(revision 16137)
@@ -36,9 +36,7 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());                
+	ISSM_MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&sum_num_unstable_constraints,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
 	num_unstable_constraints=sum_num_unstable_constraints;
-	#endif
 
 	/*Have we converged? : */
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp	(revision 16137)
@@ -28,9 +28,7 @@
 	}
 
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());                
+	ISSM_MPI_Reduce (&found,&mpi_found,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&mpi_found,1,ISSM_MPI_INT,0,IssmComm::GetComm());                
 	found=mpi_found;
-	#endif
 
 	return found;
Index: sm/trunk/src/c/modules/ContourToMeshx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ContourToMeshx)
-# }}}
Index: sm/trunk/src/c/modules/ContourToNodesx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ContourToNodesx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ContourToNodesx)
-# }}}
Index: sm/trunk/src/c/modules/ControlInputGetGradientx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ControlInputGetGradientx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ControlInputGetGradientx)
-# }}}
Index: sm/trunk/src/c/modules/ControlInputScaleGradientx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ControlInputScaleGradientx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ControlInputScaleGradientx)
-# }}}
Index: sm/trunk/src/c/modules/ControlInputSetGradientx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ControlInputSetGradientx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ControlInputSetGradientx)
-# }}}
Index: /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp
===================================================================
--- /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp	(revision 16137)
@@ -0,0 +1,46 @@
+/*!\file CreateJacobianMatrixx
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./CreateJacobianMatrixx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../AllocateSystemMatricesx/AllocateSystemMatricesx.h"
+
+void CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,FemModel* femmodel,IssmDouble kmax){
+
+	int      i,connectivity;
+	int      numberofdofspernode;
+	int      fsize,configuration_type;
+	Element *element = NULL;
+	Load    *load    = NULL;
+	Matrix<IssmDouble>* Jff = NULL;
+
+	/*Checks*/
+	_assert_(femmodel && femmodel->nodes && femmodel->elements);
+
+	/*Recover some parameters*/
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&connectivity,MeshAverageVertexConnectivityEnum);
+	fsize=femmodel->nodes->NumberOfDofs(configuration_type,FsetEnum);
+	numberofdofspernode=femmodel->nodes->MaxNumDofs(configuration_type,GsetEnum);
+
+	/*Initialize Jacobian Matrix*/
+	AllocateSystemMatricesx(&Jff,NULL,NULL,NULL,femmodel);
+
+	/*Create and assemble matrix*/
+	for(i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->CreateJacobianMatrix(Jff);
+	}
+	for (i=0;i<femmodel->loads->Size();i++){
+		load=(Load*)femmodel->loads->GetObjectByOffset(i);
+		if(load->InAnalysis(configuration_type)) load->CreateJacobianMatrix(Jff);
+		if(load->InAnalysis(configuration_type)) load->PenaltyCreateJacobianMatrix(Jff,kmax);
+	}
+	Jff->Assemble();
+
+	/*Assign output pointer*/
+	*pJff=Jff;
+
+}
Index: /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h
===================================================================
--- /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h	(revision 16137)
+++ /issm/trunk/src/c/modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h	(revision 16137)
@@ -0,0 +1,12 @@
+/*!\file:  CreateJacobianMatrixx.h
+*/ 
+
+#ifndef _CREATEJACOBIANMATRIXX_H
+#define _CREATEJACOBIANMATRIXX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,FemModel* femmodel,IssmDouble kmax);
+
+#endif
Index: sm/trunk/src/c/modules/CreateNodalConstraintsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/CreateNodalConstraintsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/CreateNodalConstraintsx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/Delta18oParameterizationx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Delta18oParameterizationx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Delta18oParameterizationx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/DragCoefficientAbsGradientx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/DragCoefficientAbsGradientx)
-# }}}
Index: /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 16137)
@@ -25,9 +25,7 @@
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
Index: sm/trunk/src/c/modules/EdgeDetectionx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/EdgeDetectionx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/EdgeDetectionx)
-# }}}
Index: sm/trunk/src/c/modules/ElementConnectivityx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ElementConnectivityx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ElementConnectivityx)
-# }}}
Index: sm/trunk/src/c/modules/Exp2Kmlx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Exp2Kmlx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Exp2Kmlx)
-# }}}
-# KML_SOURCES {{{
-set(KML_SOURCES $ENV{ISSM_DIR}/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.h
===================================================================
--- /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.h	(revision 16137)
@@ -10,10 +10,6 @@
 
 /* local prototypes: */
-int Exp2Kmlx(char* filexp,char* filkml,
-			 int sgn,
-			 bool holes);
-int Exp2Kmlx(char* filexp,char* filkml,
-			 int sgn,double cm,double sp,
-			 bool holes);
+int Exp2Kmlx(char* filexp,char* filkml,int sgn,bool holes);
+int Exp2Kmlx(char* filexp,char* filkml,int sgn,double cm,double sp,bool holes);
 
 #endif  /* _EXP2KMLX_H */
Index: sm/trunk/src/c/modules/GetSolutionFromInputsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/GetSolutionFromInputsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/GetSolutionFromInputsx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 16137)
@@ -7,10 +7,9 @@
 #include "../../toolkits/toolkits.h"
 
-void	GetSolutionFromInputsx( Vector<IssmDouble>** psolution, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters){
+void GetSolutionFromInputsx(Vector<IssmDouble>** psolution,FemModel* femmodel){
 
 	/*intermediary: */
-	int gsize;
-	int i;
-	Element* element=NULL;
+	int      gsize;
+	Element* element = NULL;
 
 	int configuration_type;
@@ -22,9 +21,9 @@
 
 	/*retrive parameters: */
-	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
 
 	/*Get size of vector: */
-	gsize=nodes->NumberOfDofs(configuration_type,GsetEnum);
-	if (gsize==0) _error_("Allocating a Vec of size 0 as gsize=0 for configuration: " << EnumToStringx(configuration_type));
+	gsize=femmodel->nodes->NumberOfDofs(configuration_type,GsetEnum);
+	if(gsize==0) _error_("Allocating a Vec of size 0 as gsize=0 for configuration: " << EnumToStringx(configuration_type));
 
 	/*Initialize solution: */
@@ -32,6 +31,6 @@
 
 	/*Go through elements and plug solution: */
-	for (i=0;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(int i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->GetSolutionFromInputs(solution);
 	}
@@ -42,4 +41,3 @@
 	/*Assign output pointers:*/
 	*psolution=solution;
-
 }
Index: /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 16137)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void GetSolutionFromInputsx( Vector<IssmDouble>** psolution, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters);
+void GetSolutionFromInputsx(Vector<IssmDouble>** psolution,FemModel* femmodel);
 
 #endif  /* _GETSOLUTIONFROMINPUTSXX_H */
Index: sm/trunk/src/c/modules/GetVectorFromControlInputsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromControlInputsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/GetVectorFromControlInputsx)
-# }}}
Index: sm/trunk/src/c/modules/GetVectorFromInputsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/GetVectorFromInputsx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 16137)
@@ -7,5 +7,5 @@
 #include "../../toolkits/toolkits.h"
 
-void GetVectorFromInputsx( Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name, int type){
+void GetVectorFromInputsx( Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type){
 
 	int i;
@@ -15,15 +15,15 @@
 
 		/*Allocate vector*/
-		vector=new Vector<IssmDouble>(vertices->NumberOfVertices());
+		vector=new Vector<IssmDouble>(femmodel->vertices->NumberOfVertices());
 
 		/*Look up in elements*/
-		for(i=0;i<elements->Size();i++){
-			Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		for(i=0;i<femmodel->elements->Size();i++){
+			Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 			element->GetVectorFromInputs(vector,name);
 		}
 
 		/*Look up in materials*/
-		for(i=0;i<materials->Size();i++){
-			Material* material=(Material*)materials->GetObjectByOffset(i);
+		for(i=0;i<femmodel->materials->Size();i++){
+			Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
 			material->GetVectorFromInputs(vector,name);
 		}
@@ -39,5 +39,5 @@
 }
 
-void GetVectorFromInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name, int type){
+void GetVectorFromInputsx(IssmDouble** pvector,FemModel* femmodel,int name, int type){
 
 	/*output: */
@@ -47,5 +47,5 @@
 	Vector<IssmDouble>* vec_vector=NULL;
 
-	GetVectorFromInputsx( &vec_vector, elements,nodes, vertices, loads, materials, parameters, name, type);
+	GetVectorFromInputsx(&vec_vector,femmodel,name,type);
 	vector=vec_vector->ToMPISerial();
 
Index: /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 16137)
@@ -8,6 +8,6 @@
 
 /* local prototypes: */
-void	GetVectorFromInputsx( Vector<IssmDouble>** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,int type);
-void	GetVectorFromInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int name,int type);
+void	GetVectorFromInputsx( Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type);
+void	GetVectorFromInputsx( IssmDouble** pvector,FemModel* femmodel,int name,int type);
 
 #endif  /* _GETVECTORFROMINPUTSXX_H */
Index: sm/trunk/src/c/modules/GiaDeflectionCorex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/GiaDeflectionCorex/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/SurfaceAreax)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/GiaDeflectionCorex/GiaDeflectionCorex.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/Gradjx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Gradjx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Gradjx)
-# }}}
Index: sm/trunk/src/c/modules/GroundinglineMigrationx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/GroundinglineMigrationx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/GroundinglineMigrationx)
-# }}}
Index: /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 16137)
@@ -12,7 +12,5 @@
 	int                 migration_style,analysis_type;
 	IssmDouble         *vertices_potentially_ungrounding = NULL;
-	IssmDouble         *vertices_ungrounding             = NULL;
-	IssmDouble         *old_floatingice                  = NULL;
-	Vector<IssmDouble> *vec_old_floatingice              = NULL;
+	IssmDouble         *phi_ungrounding                  = NULL;
 	Element            *element                          = NULL;
 
@@ -39,58 +37,25 @@
 
 		/*propagate ice shelf into connex areas of the ice sheet that potentially want to unground: */
-		vertices_ungrounding=PropagateFloatingiceToGroundedNeighbors(elements,nodes,vertices,parameters,vertices_potentially_ungrounding);
+		phi_ungrounding=PropagateFloatingiceToGroundedNeighbors(elements,nodes,vertices,parameters,vertices_potentially_ungrounding);
 	}
-
-	/*Create vector with vertices initially floating and serialize*/
-	vec_old_floatingice=CreateNodesOnFloatingIce(nodes,analysis_type);
-	old_floatingice=vec_old_floatingice->ToMPISerial();
 
 	/*Migrate grounding line : */
 	for(int i=0;i<elements->Size();i++){
 		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		element->MigrateGroundingLine(old_floatingice,vertices_ungrounding);
+		element->MigrateGroundingLine(phi_ungrounding);
 	}
 
 	/*free ressouces: */
-	delete vec_old_floatingice;
 	xDelete<IssmDouble>(vertices_potentially_ungrounding);
-	xDelete<IssmDouble>(vertices_ungrounding);
-	xDelete<IssmDouble>(old_floatingice);
+	xDelete<IssmDouble>(phi_ungrounding);
 }
 
-/*FUNCTION CreateNodesOnFloatingIce {{{*/
-Vector<IssmDouble>* CreateNodesOnFloatingIce(Nodes* nodes,int configuration_type){ 
-
-	int     i,numnods;
-	Vector<IssmDouble>*   vec_nodes_on_floatingice = NULL;
-	Node *node                     = NULL;
-
-	/*First, initialize nodes_on_floatingice, which will track which nodes have changed status: */
-	numnods=nodes->NumberOfNodes(configuration_type);
-	vec_nodes_on_floatingice=new Vector<IssmDouble>(numnods);
-
-	/*Loop through nodes, and fill vec_nodes_on_floatingice: */
-	for(i=0;i<nodes->Size();i++){
-		node=(Node*)nodes->GetObjectByOffset(i);
-		if(node->InAnalysis(configuration_type)){
-			if(node->IsFloating()){
-				vec_nodes_on_floatingice->SetValue(node->Sid(),1.0,INS_VAL);
-			}
-		}
-	}
-
-	/*Assemble vector: */
-	vec_nodes_on_floatingice->Assemble();
-
-	return vec_nodes_on_floatingice;
-}
-/*%}}}*/
 /*FUNCTION PotentialUngrounding {{{*/
 IssmDouble*    PotentialUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters){ 
 
-	int      i,numberofvertices;
-	IssmDouble*  vertices_potentially_ungrounding      = NULL;
-	Vector<IssmDouble>*      vec_vertices_potentially_ungrounding  = NULL;
-	Element* element                               = NULL;
+	int                 i,numberofvertices;
+	IssmDouble*         vertices_potentially_ungrounding      = NULL;
+	Vector<IssmDouble>* vec_vertices_potentially_ungrounding  = NULL;
+	Element*            element                               = NULL;
 
 	/*Initialize vector with number of vertices*/
@@ -115,14 +80,12 @@
 /*FUNCTION PropagateFloatingiceToGroundedNeighbors {{{*/
 IssmDouble*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding){ 
-
-	int      i,analysis_type;
-	int      numberofvertices;
-	int      nflipped,local_nflipped;
-	IssmDouble*  nodes_on_floatingice                  = NULL;
-	IssmDouble*  elements_neighboring_floatingce      = NULL;
-	Vector<IssmDouble>*      vec_elements_neighboring_floatingice = NULL;
-	Vector<IssmDouble>*      vec_nodes_on_floatingice              = NULL;
-	Node*    node                                  = NULL;
-	Element* element                               = NULL;
+	int                 i,analysis_type,numberofvertices;
+	int                 nflipped,local_nflipped;
+	IssmDouble*         phi                                  = NULL;
+	IssmDouble*         elements_neighboring_floatingce      = NULL;
+	Vector<IssmDouble>* vec_elements_neighboring_floatingice = NULL;
+	Vector<IssmDouble>* vec_phi                              = NULL;
+	Node*               node                                  = NULL;
+	Element*            element                               = NULL;
 
 	/*recover parameters: */
@@ -130,7 +93,12 @@
 	numberofvertices=vertices->NumberOfVertices();
 
-	/*recover vec_nodes_on_floatingice*/
-	vec_nodes_on_floatingice=CreateNodesOnFloatingIce(nodes,analysis_type);
-	nodes_on_floatingice=vec_nodes_on_floatingice->ToMPISerial();
+	/*recover vec_phi*/
+	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);
+	}
+	vec_phi->Assemble();
+	phi=vec_phi->ToMPISerial();
 
 	nflipped=1; //bootstrap
@@ -143,5 +111,5 @@
 		for(i=0;i<elements->Size();i++){
 			element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-			vec_elements_neighboring_floatingice->SetValue(element->Sid(),element->IsNodeOnShelfFromFlags(nodes_on_floatingice)?1.0:0.0,INS_VAL);
+			vec_elements_neighboring_floatingice->SetValue(element->Sid(),element->IsNodeOnShelfFromFlags(phi)?1.0:0.0,INS_VAL);
 		}
 
@@ -155,30 +123,26 @@
 			element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 			if(reCast<int,IssmDouble>(elements_neighboring_floatingce[element->Sid()])){
-				local_nflipped+=element->UpdatePotentialUngrounding(vertices_potentially_ungrounding,vec_nodes_on_floatingice,nodes_on_floatingice);
+				local_nflipped+=element->UpdatePotentialUngrounding(vertices_potentially_ungrounding,vec_phi,phi);
 			}
 		}
-		vec_nodes_on_floatingice->Assemble();
+		vec_phi->Assemble();
 
-		#ifdef _HAVE_MPI_
-		MPI_Allreduce(&local_nflipped,&nflipped,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
+		ISSM_MPI_Allreduce(&local_nflipped,&nflipped,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
 		if(VerboseConvergence()) _printf0_("   Additional number of vertices allowed to unground: " << nflipped << "\n");
-		#else
-		nflipped=local_nflipped;
-		#endif
 
 		/*Avoid leaks: */
 		xDelete<IssmDouble>(elements_neighboring_floatingce);
-		xDelete<IssmDouble>(nodes_on_floatingice);
+		xDelete<IssmDouble>(phi);
 
 		/*Assemble and serialize:*/
 		delete vec_elements_neighboring_floatingice;
-		nodes_on_floatingice=vec_nodes_on_floatingice->ToMPISerial();
+		phi=vec_phi->ToMPISerial();
 	}
 
 	/*Free ressources:*/
-	delete vec_nodes_on_floatingice;
+	delete vec_phi;
 	xDelete<IssmDouble>(elements_neighboring_floatingce);
 
-	return nodes_on_floatingice;
+	return phi;
 }
 /*}}}*/
Index: /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h
===================================================================
--- /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.h	(revision 16137)
@@ -12,8 +12,6 @@
 
 /* local prototypes: */
-void       GroundinglineMigrationx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters);
-
-Vector<IssmDouble>* CreateNodesOnFloatingIce(Nodes* nodes,int configuration_type);
-IssmDouble*    PotentialUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters);
-IssmDouble*    PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding);
+void         GroundinglineMigrationx(Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads,Materials* materials, Parameters* parameters);
+IssmDouble*  PotentialUngrounding(Elements* elements,Vertices* vertices,Parameters* parameters);
+IssmDouble*  PropagateFloatingiceToGroundedNeighbors(Elements* elements,Nodes* nodes,Vertices* vertices,Parameters* parameters,IssmDouble* vertices_potentially_ungrounding);
 #endif  /* _GROUNDINGLINEMIGRATIONX_H */
Index: sm/trunk/src/c/modules/HoleFillerx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/HoleFillerx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/HoleFillerx)
-# }}}
Index: sm/trunk/src/c/modules/InputArtificialNoisex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InputArtificialNoisex/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InputArtificialNoisex)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/InputControlUpdatex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InputControlUpdatex/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InputControlUpdatex)
-# }}}
Index: sm/trunk/src/c/modules/InputDuplicatex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InputDuplicatex/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InputDuplicatex)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/InputDuplicatex/InputDuplicatex.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/InputScalex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InputScalex/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InputScalex)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/InputScalex/InputScalex.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/InputToResultx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InputToResultx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InputToResultx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/InputToResultx/InputToResultx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/InputToResultx/InputToResultx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputToResultx/InputToResultx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InputToResultx/InputToResultx.cpp	(revision 16137)
@@ -8,19 +8,18 @@
 #include "../../toolkits/toolkits.h"
 
-void InputToResultx(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type){
+void InputToResultx(FemModel* femmodel,int enum_type){
 
 	/*intermediary:*/
-	int      step;
-	IssmDouble   time;
-	Element *element = NULL;
+	int        step;
+	IssmDouble time;
+	Element   *element = NULL;
 
 	/*Get time and step*/
-	parameters->FindParam(&step,StepEnum);
-	parameters->FindParam(&time,TimeEnum);
+	femmodel->parameters->FindParam(&step,StepEnum);
+	femmodel->parameters->FindParam(&time,TimeEnum);
 
 	/*Go through elemnets, and ask each element to transfer the enum_type input into the results dataset, with step and time information: */
-	for(int i=0;i<elements->Size();i++){
-
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(int i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputToResult(enum_type,step,time);
 	}
Index: /issm/trunk/src/c/modules/InputToResultx/InputToResultx.h
===================================================================
--- /issm/trunk/src/c/modules/InputToResultx/InputToResultx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/InputToResultx/InputToResultx.h	(revision 16137)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void InputToResultx(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int enum_type);
+void InputToResultx(FemModel* femmodel,int enum_type);
 
 #endif  /* _INPUTTORESULTX_H */
Index: sm/trunk/src/c/modules/InputUpdateFromConstantx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromConstantx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromConstantx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 16137)
@@ -7,5 +7,5 @@
 #include "../../toolkits/toolkits.h"
 
-void InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool   constant, int name){
+void InputUpdateFromConstantx(FemModel* femmodel,bool constant, int name){
 
 	int i;
@@ -13,20 +13,20 @@
 
 	/*Elements and loads drive the update: */
-	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromConstant(constant,name);
 	}
 
-	for(i=0;i<loads->Size();i++){
-		Load* load=(Load*)loads->GetObjectByOffset(i);
+	for(i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
 		load->InputUpdateFromConstant(constant,name);
 	}
 
-	for(i=0;i<materials->Size();i++){
-		Material* material=(Material*)materials->GetObjectByOffset(i);
+	for(i=0;i<femmodel->materials->Size();i++){
+		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
 		material->InputUpdateFromConstant(constant,name);
 	}
 }
-void InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int    constant, int name){
+void InputUpdateFromConstantx(FemModel* femmodel,int constant, int name){
 
 	int i;
@@ -34,20 +34,20 @@
 
 	/*Elements and loads drive the update: */
-	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromConstant(constant,name);
 	}
 
-	for(i=0;i<loads->Size();i++){
-		Load* load=(Load*)loads->GetObjectByOffset(i);
+	for(i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
 		load->InputUpdateFromConstant(constant,name);
 	}
 
-	for(i=0;i<materials->Size();i++){
-		Material* material=(Material*)materials->GetObjectByOffset(i);
+	for(i=0;i<femmodel->materials->Size();i++){
+		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
 		material->InputUpdateFromConstant(constant,name);
 	}
 }
-void InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble constant, int name){
+void InputUpdateFromConstantx(FemModel* femmodel,IssmDouble constant, int name){
 
 	int i;
@@ -55,16 +55,16 @@
 
 	/*Elements and loads drive the update: */
-	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromConstant(constant,name);
 	}
 
-	for(i=0;i<loads->Size();i++){
-		Load* load=(Load*)loads->GetObjectByOffset(i);
+	for(i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
 		load->InputUpdateFromConstant(constant,name);
 	}
 
-	for(i=0;i<materials->Size();i++){
-		Material* material=(Material*)materials->GetObjectByOffset(i);
+	for(i=0;i<femmodel->materials->Size();i++){
+		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
 		material->InputUpdateFromConstant(constant,name);
 	}
Index: /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 16137)
@@ -9,7 +9,7 @@
 
 /* local prototypes: */
-void		InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters, bool   constant, int name);
-void		InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters, int    constant, int name);
-void		InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters, IssmDouble constant, int name);
+void InputUpdateFromConstantx(FemModel* femmode,bool   constant    ,int name);
+void InputUpdateFromConstantx(FemModel* femmode,int    constant    ,int name);
+void InputUpdateFromConstantx(FemModel* femmode,IssmDouble constant,int name);
 
 #endif  /* _UPDATEINPUTSFROMCONSTANTXX_H */
Index: sm/trunk/src/c/modules/InputUpdateFromDakotax/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromDakotax/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromDakotax)
-# }}}
-# DAKOTA_SOURCES {{{
-set(DAKOTA_SOURCES $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 16137)
@@ -10,5 +10,5 @@
 #include "../InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h"
 
-void  InputUpdateFromDakotax(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials*  materials,Parameters* parameters,double* variables,char* *variables_descriptors,int numvariables){
+void InputUpdateFromDakotax(FemModel* femmodel,double* variables,char* *variables_descriptors,int numvariables){
 
 	int     i,j,k,l;
@@ -27,7 +27,7 @@
 
 	/*retrieve parameters: */
-	parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
-	parameters->FindParam(&qmu_part,&dummy,QmuPartitionEnum);
-	numberofvertices=vertices->NumberOfVertices();
+	femmodel->parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
+	femmodel->parameters->FindParam(&qmu_part,&dummy,QmuPartitionEnum);
+	numberofvertices=femmodel->vertices->NumberOfVertices();
 
 	/*Go through all dakota descriptors, ex: "rho_ice","thermal_conductivity","thickness1","thickness2", etc ..., and 
@@ -54,5 +54,5 @@
 
 			/*Now, pick up the parameter corresponding to root: */
-			parameters->FindParam(&parameter,&nrows,&ncols,StringToEnumx(root));
+			femmodel->parameters->FindParam(&parameter,&nrows,&ncols,StringToEnumx(root));
 
 			/*We've got the parameter, we need to update it using qmu_part (a partitioning vector), 
@@ -83,5 +83,5 @@
 
 			/*Update inputs using the parameter matrix: */
-			InputUpdateFromMatrixDakotax( elements,nodes, vertices,loads, materials,  parameters, parameter, nrows,ncols,StringToEnumx(root), VertexEnum);
+			InputUpdateFromMatrixDakotax(femmodel, parameter, nrows,ncols,StringToEnumx(root), VertexEnum);
 
 			/*increment i to skip the distributed values just collected: */
@@ -100,5 +100,5 @@
 		else{
 			/*Ok, standard variable, just update inputs using the variable: */
-			InputUpdateFromConstantx( elements,nodes, vertices,loads, materials,  parameters, variables[i],StringToEnumx(descriptor));
+			InputUpdateFromConstantx(femmodel,variables[i],StringToEnumx(descriptor));
 		}
 	}
Index: /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 16137)
@@ -8,5 +8,5 @@
 #include "../../classes/classes.h"
 
-void  InputUpdateFromDakotax(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials*  materials,Parameters* parameters,double* variables,char* *variables_descriptors,int numvariables);
+void  InputUpdateFromDakotax(FemModel* femmodel,double* variables,char* *variables_descriptors,int numvariables);
 
 #endif  /* _INPUTUPDATEFROMDAKOTAXX_H */
Index: sm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromMatrixDakotax)
-# }}}
-# DAKOTA_SOURCES {{{
-set(DAKOTA_SOURCES $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 16137)
@@ -8,32 +8,27 @@
 #include "../InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h"
 
-void InputUpdateFromMatrixDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* matrix,int nrows,int ncols, int name, int type){
+void InputUpdateFromMatrixDakotax(FemModel* femmodel,double* matrix,int nrows,int ncols, int name, int type){
 
 	int i;
 	int numberofvertices;
 
-	numberofvertices=vertices->NumberOfVertices();
+	numberofvertices=femmodel->vertices->NumberOfVertices();
 
-	if((ncols==1) && (nrows==numberofvertices)) InputUpdateFromVectorDakotax( elements,nodes, vertices,loads, materials,  parameters,matrix, name,type);
+	if((ncols==1) && (nrows==numberofvertices)) InputUpdateFromVectorDakotax(femmodel,matrix,name,type);
 	else{
 
 		/*Update elements, nodes, loads and materials from inputs: */
-		for(i=0;i<elements->Size();i++){
-			Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		for(i=0;i<femmodel->elements->Size();i++){
+			Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 			element->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
 		}
-		for(i=0;i<nodes->Size();i++){
-			Node* node=(Node*)nodes->GetObjectByOffset(i);
-			node->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
-		}
-		for(i=0;i<loads->Size();i++){
-			Load* load=(Load*)loads->GetObjectByOffset(i);
+		for(i=0;i<femmodel->loads->Size();i++){
+			Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
 			load->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
 		}
-		for(i=0;i<materials->Size();i++){
-			Material* material=(Material*)materials->GetObjectByOffset(i);
+		for(i=0;i<femmodel->materials->Size();i++){
+			Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
 			material->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
 		}
 	}
-
 }
Index: /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 16137)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void InputUpdateFromMatrixDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* matrix,int nrows,int ncols, int name, int type);
+void InputUpdateFromMatrixDakotax(FemModel* femmodel,double* matrix,int nrows,int ncols, int name, int type);
 
 #endif  /* _UPDATEINPUTSFROMMATRIXDAKOTAXX_H */
Index: sm/trunk/src/c/modules/InputUpdateFromSolutionx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromSolutionx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromSolutionx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 16137)
@@ -7,27 +7,20 @@
 #include "../../toolkits/toolkits.h"
 
-void InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* solution){
-
-	IssmDouble* serial_solution=NULL;
+void InputUpdateFromSolutionx(FemModel* femmodel,Vector<IssmDouble>* solution){
 
 	/*Serialize solution, so that elements can index into it on every CPU: */
-	serial_solution=solution->ToMPISerial();
+	IssmDouble* serial_solution=solution->ToMPISerial();
 
 	/*Call overloaded form of InputUpdateFromSolutionx: */
-	InputUpdateFromSolutionx( elements, nodes,  vertices,  loads,  materials,  parameters,serial_solution);
+	InputUpdateFromSolutionx(femmodel,serial_solution);
 
-	/*Free ressources:*/
+	/*cleanup and return*/
 	xDelete<IssmDouble>(serial_solution);
 }
 
-void InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* solution){
+void InputUpdateFromSolutionx(FemModel* femmodel,IssmDouble* solution){
 
-	/*Intermediary*/
-	int i;
-	Element* element=NULL;
-
-	/*Elements drive the update: */
-	for (i=0;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(int i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromSolution(solution);
 	}
Index: /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 16137)
@@ -9,10 +9,6 @@
 
 /* local prototypes: */
-void		InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector<IssmDouble>* solution);
-void        InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* solution);
-
-//with timestep
-void		InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector<IssmDouble>* solution,int timestep);
-void        InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* solution, int timestep);
+void	InputUpdateFromSolutionx(FemModel* femmodel,Vector<IssmDouble>* solution);
+void  InputUpdateFromSolutionx(FemModel* femmodel,IssmDouble* solution);
 
 #endif  /* _UPDATEINPUTSFROMSOLUTIONXX_H */
Index: sm/trunk/src/c/modules/InputUpdateFromVectorDakotax/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromVectorDakotax)
-# }}}
-# DAKOTA_SOURCES {{{
-set(DAKOTA_SOURCES $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 16137)
@@ -7,11 +7,8 @@
 #include "../../toolkits/toolkits.h"
 
-void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* vector, int name, int type){
+void InputUpdateFromVectorDakotax(FemModel* femmodel,Vector<IssmDouble>* vector, int name, int type){
 
-	double* serial_vector=NULL;
-
-	serial_vector=vector->ToMPISerial();
-
-	InputUpdateFromVectorDakotax( elements,nodes, vertices, loads, materials, parameters,serial_vector,name, type);
+	IssmDouble* serial_vector=vector->ToMPISerial();
+	InputUpdateFromVectorDakotax(femmodel,serial_vector,name, type);
 
 	/*Free ressources:*/
@@ -19,70 +16,20 @@
 }
 
-void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vector, int name, int type){
+void InputUpdateFromVectorDakotax(FemModel* femmodel,IssmDouble* vector, int name, int type){
 
 	int i;
 
 	/*Update elements, nodes, loads and materials from inputs: */
-	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromVectorDakota(vector,name,type);
 	}
-	for(i=0;i<nodes->Size();i++){
-		Node* node=(Node*)nodes->GetObjectByOffset(i);
-		node->InputUpdateFromVectorDakota(vector,name,type);
-	}
-	for(i=0;i<loads->Size();i++){
-		Load* load=(Load*)loads->GetObjectByOffset(i);
+	for(i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
 		load->InputUpdateFromVectorDakota(vector,name,type);
 	}
-	for(i=0;i<materials->Size();i++){
-		Material* material=(Material*)materials->GetObjectByOffset(i);
+	for(i=0;i<femmodel->materials->Size();i++){
+		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
 		material->InputUpdateFromVectorDakota(vector,name,type);
 	}
 }
-
-void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int* vector, int name, int type){
-
-	int i;
-
-	/*Update elements, nodes, loads and materials from inputs: */
-	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		element->InputUpdateFromVectorDakota(vector,name,type);
-	}
-	for(i=0;i<nodes->Size();i++){
-		Node* node=(Node*)nodes->GetObjectByOffset(i);
-		node->InputUpdateFromVectorDakota(vector,name,type);
-	}
-	for(i=0;i<loads->Size();i++){
-		Load* load=(Load*)loads->GetObjectByOffset(i);
-		load->InputUpdateFromVectorDakota(vector,name,type);
-	}
-	for(i=0;i<materials->Size();i++){
-		Material* material=(Material*)materials->GetObjectByOffset(i);
-		material->InputUpdateFromVectorDakota(vector,name,type);
-	}
-}
-
-void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool* vector, int name, int type){
-
-	int i;
-
-	/*Update elements, nodes, loads and materials from inputs: */
-	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		element->InputUpdateFromVectorDakota(vector,name,type);
-	}
-	for(i=0;i<nodes->Size();i++){
-		Node* node=(Node*)nodes->GetObjectByOffset(i);
-		node->InputUpdateFromVectorDakota(vector,name,type);
-	}
-	for(i=0;i<loads->Size();i++){
-		Load* load=(Load*)loads->GetObjectByOffset(i);
-		load->InputUpdateFromVectorDakota(vector,name,type);
-	}
-	for(i=0;i<materials->Size();i++){
-		Material* material=(Material*)materials->GetObjectByOffset(i);
-		material->InputUpdateFromVectorDakota(vector,name,type);
-	}
-}
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 16137)
@@ -9,8 +9,6 @@
 
 /* local prototypes: */
-void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector<IssmDouble>* vector, int name,int type);
-void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,double* vector, int name,int type);
-void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int* vector, int name,int type);
-void	InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,bool* vector, int name,int type);
+void	InputUpdateFromVectorDakotax(FemModel* femmodel,Vector<IssmDouble>* vector, int name,int type);
+void	InputUpdateFromVectorDakotax(FemModel* femmodel,IssmDouble* vector, int name,int type);
 
 #endif  /* _UPDATEINPUTSFROMVECTORDAKOTAXX_H */
Index: sm/trunk/src/c/modules/InputUpdateFromVectorx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromVectorx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 16137)
@@ -7,82 +7,27 @@
 #include "../../toolkits/toolkits.h"
 
-void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* vector, int name, int type){
+void InputUpdateFromVectorx(FemModel* femmodel,Vector<IssmDouble>* vector, int name, int type){
 
-	IssmDouble* serial_vector=NULL;
-
-	serial_vector=vector->ToMPISerial();
-
-	InputUpdateFromVectorx( elements,nodes, vertices, loads, materials, parameters,serial_vector,name, type);
-
-	/*Free ressources:*/
+	IssmDouble* serial_vector=vector->ToMPISerial();
+	InputUpdateFromVectorx(femmodel,serial_vector,name,type);
 	xDelete<IssmDouble>(serial_vector);
 }
 
-void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* vector, int name, int type){
+void InputUpdateFromVectorx(FemModel* femmodel,IssmDouble* vector, int name, int type){
 
 	int i;
 
 	/*Update elements, nodes, loads and materials from inputs: */
-	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(i=0;i<femmodel->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		element->InputUpdateFromVector(vector,name,type);
 	}
-	for(i=0;i<nodes->Size();i++){
-		Node* node=(Node*)nodes->GetObjectByOffset(i);
-		node->InputUpdateFromVector(vector,name,type);
-	}
-	for(i=0;i<loads->Size();i++){
-		Load* load=(Load*)loads->GetObjectByOffset(i);
+	for(i=0;i<femmodel->loads->Size();i++){
+		Load* load=(Load*)femmodel->loads->GetObjectByOffset(i);
 		load->InputUpdateFromVector(vector,name,type);
 	}
-	for(i=0;i<materials->Size();i++){
-		Material* material=(Material*)materials->GetObjectByOffset(i);
+	for(i=0;i<femmodel->materials->Size();i++){
+		Material* material=(Material*)femmodel->materials->GetObjectByOffset(i);
 		material->InputUpdateFromVector(vector,name,type);
 	}
 }
-
-void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int* vector, int name, int type){
-
-	int i;
-
-	/*Update elements, nodes, loads and materials from inputs: */
-	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		element->InputUpdateFromVector(vector,name,type);
-	}
-	for(i=0;i<nodes->Size();i++){
-		Node* node=(Node*)nodes->GetObjectByOffset(i);
-		node->InputUpdateFromVector(vector,name,type);
-	}
-	for(i=0;i<loads->Size();i++){
-		Load* load=(Load*)loads->GetObjectByOffset(i);
-		load->InputUpdateFromVector(vector,name,type);
-	}
-	for(i=0;i<materials->Size();i++){
-		Material* material=(Material*)materials->GetObjectByOffset(i);
-		material->InputUpdateFromVector(vector,name,type);
-	}
-}
-
-void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool* vector, int name, int type){
-
-	int i;
-
-	/*Update elements, nodes, loads and materials from inputs: */
-	for(i=0;i<elements->Size();i++){
-		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-		element->InputUpdateFromVector(vector,name,type);
-	}
-	for(i=0;i<nodes->Size();i++){
-		Node* node=(Node*)nodes->GetObjectByOffset(i);
-		node->InputUpdateFromVector(vector,name,type);
-	}
-	for(i=0;i<loads->Size();i++){
-		Load* load=(Load*)loads->GetObjectByOffset(i);
-		load->InputUpdateFromVector(vector,name,type);
-	}
-	for(i=0;i<materials->Size();i++){
-		Material* material=(Material*)materials->GetObjectByOffset(i);
-		material->InputUpdateFromVector(vector,name,type);
-	}
-}
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 16137)
@@ -9,8 +9,6 @@
 
 /* local prototypes: */
-void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,Vector<IssmDouble>* vector, int name,int type);
-void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,IssmDouble* vector, int name,int type);
-void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,int* vector, int name,int type);
-void	InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices,Loads* loads, Materials* materials,  Parameters* parameters,bool* vector, int name,int type);
+void	InputUpdateFromVectorx(FemModel* femmodel,Vector<IssmDouble>* vector, int name,int type);
+void	InputUpdateFromVectorx(FemModel* femmodel,IssmDouble* vector, int name,int type);
 
 #endif  /* _UPDATEINPUTSFROMVECTORXX_H */
Index: sm/trunk/src/c/modules/InterpFromGridToMeshx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InterpFromGridToMeshx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InterpFromGridToMeshx)
-# }}}
Index: /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 16137)
@@ -87,5 +87,5 @@
 	/*launch the thread manager with InterpFromGridToMeshxt as a core: */
 	LaunchThread(InterpFromGridToMeshxt,(void*)&gate,num);
-	_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
+	_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 
 	/*Assign output pointers:*/
@@ -141,5 +141,5 @@
 
 		if(debug && my_thread==0)
-		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i-i0)/double(i1-i0)*100<<"%");
+		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i-i0)/double(i1-i0)*100<<"%   ");
 		x_grid=*(x_mesh+i);
 		y_grid=*(y_mesh+i);
Index: sm/trunk/src/c/modules/InterpFromMesh2dx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InterpFromMesh2dx)
-# }}}
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 16137)
@@ -47,5 +47,5 @@
 		/*display current iteration*/
 		if (debug && my_thread==0 && fmod((double)i,(double)100)==0)
-		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i-i0)/double(i1-i0)*100<<"%");
+		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i-i0)/double(i1-i0)*100<<"%   ");
 
 		/*if there is no point inside the domain, go to next iteration*/
@@ -99,5 +99,5 @@
 	}
 	if(debug && my_thread==0)
-	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
+	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 	return NULL;
 }
Index: sm/trunk/src/c/modules/InterpFromMeshToGridx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToGridx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InterpFromMeshToGridx)
-# }}}
Index: /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 16137)
@@ -63,6 +63,4 @@
 	else yflip=0;
 
-
-
 	/*Get extreme coordinates of the grid*/
 	if (xflip){
@@ -92,5 +90,5 @@
 		/*display current iteration*/
 		if (debug && fmod((double)n,(double)100)==0)
-		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(n)/double(nels)*100<<"%");
+		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(n)/double(nels)*100<<"%   ");
 
 		/*Get extrema coordinates of current elements*/
@@ -172,5 +170,5 @@
 	}
 	if (debug)
-	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
+	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 
 	/*Assign output pointers:*/
Index: sm/trunk/src/c/modules/InterpFromMeshToMesh2dx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InterpFromMeshToMesh2dx)
-# }}}
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 16137)
@@ -68,5 +68,5 @@
 	/*Loop over output nodes*/
 	for(i=0;i<N_interp;i++){
-		//if(i%100==0) _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i)/double(N_interp)*100.<<"%");
+		//if(i%100==0) _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i)/double(N_interp)*100.<<"%   ");
 
 		if(isdefault){
@@ -142,5 +142,5 @@
 		}
 	}
-	//if(N_interp>=100) _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
+	//if(N_interp>=100) _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 
 	/*clean-up and return*/
Index: sm/trunk/src/c/modules/InterpFromMeshToMesh3dx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/InterpFromMeshToMesh3dx)
-# }}}
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh3dx/InterpFromMeshToMesh3dx.cpp	(revision 16137)
@@ -61,5 +61,5 @@
 		/*display current iteration*/
 		if (debug && fmod((double)i,(double)100)==0)
-		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i)/double(nels_data)*100<<"%");
+		 _printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(i)/double(nels_data)*100<<"%   ");
 
 		/*Get extrema coordinates of current elements*/
@@ -132,5 +132,5 @@
 	}
 	if (debug)
-	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
+	 _printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 
 	/*Assign output pointers:*/
Index: sm/trunk/src/c/modules/IoModelToConstraintsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/IoModelToConstraintsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/IoModelToConstraintsx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 16137)
@@ -6,96 +6,343 @@
 #include "../../shared/shared.h"
 #include "../../toolkits/toolkits.h"
-
-void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,int vector_enum,int analysis_type){
+#include "../ModelProcessorx/ModelProcessorx.h"
+
+void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,int vector_enum,int analysis_type,int finite_element,int dof){
 
 	/*intermediary: */
-	int     i,j;
-	IssmDouble yts;
-	bool        transient        = false;
-	FILE       *fid              = NULL;
-	int         code             = 0;
-	int         vector_layout    = 0;
+	FILE       *fid = NULL;
+	int         code,vector_layout;
+	IssmDouble *spcdata = NULL;
+	int         M,N;
+
+	/*First of, find the record for the enum, and get code  of data type: */
+	fid=iomodel->SetFilePointerToData(&code, &vector_layout,vector_enum);
+	if(code!=7)_error_("expecting a IssmDouble vector for constraints with enum " << EnumToStringx(vector_enum));
+	if(vector_layout!=1)_error_("expecting a nodal vector for constraints with enum " << EnumToStringx(vector_enum));
+
+	/*Fetch vector:*/
+	iomodel->FetchData(&spcdata,&M,&N,vector_enum);
+
+	/*Call IoModelToConstraintsx*/
+	IoModelToConstraintsx(constraints,iomodel,spcdata,M,N,analysis_type,finite_element,dof);
+
+	/*Clean up*/
+	xDelete<IssmDouble>(spcdata);
+}
+
+void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,IssmDouble* spcdata,int M,int N,int analysis_type,int finite_element,int dof){
+
+	/*intermediary: */
+	int         i,j,count,elementnbv;
+	IssmDouble  value;
 	IssmDouble *times            = NULL;
 	IssmDouble *values           = NULL;
 	bool        spcpresent       = false;
-	int         count            = 0;
-	int         numberofvertices;
-
-	/*variables being fetched: */
-	IssmDouble *IssmDoublevector  = NULL;
-	int     M,N;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-	iomodel->Constant(&yts,ConstantsYtsEnum);
-
-	/*First of, find the record for the enum, and get code  of data type: */
-	fid=iomodel->SetFilePointerToData(&code, &vector_layout,vector_enum);
-
-	if(code!=7)_error_("expecting a IssmDouble vector for constraints with enum " << EnumToStringx(vector_enum));
-	if(vector_layout!=1)_error_("expecting a nodal vector for constraints with enum " << EnumToStringx(vector_enum));
-
-	/*Fetch vector:*/
-	iomodel->FetchData(&IssmDoublevector,&M,&N,vector_enum);
-
-	/*Transient or static?:*/
-	if(M==numberofvertices){
-		/*static: just create Constraints objects*/
-		count=0;
-
-		/*Create Constraints from x,y,z: */
-		for (i=0;i<numberofvertices;i++){
-
-			/*keep only this partition's nodes:*/
-			if((iomodel->my_vertices[i])){
-
-				if (!xIsNan<IssmDouble>(IssmDoublevector[i])){
-
-					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,IssmDoublevector[i],analysis_type));
-					count++;
-				}
+
+	/*P2 finite elements*/
+	int   v1,v2;
+	bool *my_edges = NULL;
+
+	switch(finite_element){
+		case P1Enum: 
+			/*Nothing else to do*/
+			break;
+		case P1bubbleEnum:
+			switch(iomodel->dim){
+				case 2: elementnbv = 3; break;
+				case 3: elementnbv = 6; break;
+				default: _error_("3d is the only supported dimension");
 			}
+			break;
+		case P1bubblecondensedEnum: 
+			/*Nothing else to do*/
+			break;
+		case P1xP2Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			break;
+		case P2xP1Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			break;
+		case P2Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			break;
+		default:
+			_error_("Finite element "<<EnumToStringx(finite_element)<<" not supported yet");
+	}
+
+	count=0;
+	if(M==iomodel->numberofvertices){
+		switch(finite_element){
+			case P1Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				break;
+			case P2Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(my_edges[i]){
+						v1 = iomodel->edges[3*i+0]-1;
+						v2 = iomodel->edges[3*i+1]-1;
+						if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,
+											dof,(spcdata[v1]+spcdata[v2])/2.,analysis_type));
+							count++;
+						}
+					}
+				}
+				break;
+			case P1bubbleEnum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofelements;i++){
+					if(iomodel->my_elements[i]){
+						value = spcdata[iomodel->elements[i*elementnbv+0]-1];
+						for(j=1;j<elementnbv;j++) value += spcdata[iomodel->elements[i*elementnbv+j]-1];
+						value = value/reCast<IssmDouble,int>(elementnbv+0);
+						if(!xIsNan<IssmDouble>(value)){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,
+											dof,value,analysis_type));
+							count++;
+						}
+					}
+				}
+				break;
+			case P1bubblecondensedEnum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				break;
+			case P1xP2Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(iomodel->edges[i*3+2]==2){
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,
+												dof,(spcdata[v1]+spcdata[v2])/2.,analysis_type));
+								count++;
+							}
+						}
+					}
+				}
+				break;
+			case P2xP1Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+						if (!xIsNan<IssmDouble>(spcdata[i])){
+							constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,dof,spcdata[i],analysis_type));
+							count++;
+						}
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(iomodel->edges[i*3+2]!=2){
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							if(!xIsNan<IssmDouble>(spcdata[v1]) && !xIsNan<IssmDouble>(spcdata[v2])){
+								constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+iomodel->numberofvertices+i+1,
+												dof,(spcdata[v1]+spcdata[v2])/2.,analysis_type));
+								count++;
+							}
+						}
+					}
+				}
+				break;
+			default:
+				_error_("Finite element "<<EnumToStringx(finite_element)<<" not supported yet");
 		}
 	}
-	else if (M==(numberofvertices+1)){
+	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(j=0;j<N;j++){
-			times[j]=IssmDoublevector[(M-1)*N+j]*yts;
-		}
-
-		/*Create constraints from x,y,z: */
-		for (i=0;i<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(j=0;j<N;j++){
-					values[j]=IssmDoublevector[i*N+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,N,times,values,analysis_type));
-					count++;
-				}
-				xDelete<IssmDouble>(values);
-			}
+		for(j=0;j<N;j++) times[j]=spcdata[(M-1)*N+j];
+
+		switch(finite_element){
+			case P1Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+
+						/*figure out times and values: */
+						values=xNew<IssmDouble>(N);
+						spcpresent=false;
+						for(j=0;j<N;j++){
+							values[j]=spcdata[i*N+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,dof,N,times,values,analysis_type));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+				}
+				break;
+			case P2Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+
+						/*figure out times and values: */
+						values=xNew<IssmDouble>(N);
+						spcpresent=false;
+						for(j=0;j<N;j++){
+							values[j]=spcdata[i*N+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,dof,N,times,values,analysis_type));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(my_edges[i]){
+						v1 = iomodel->edges[3*i+0]-1;
+						v2 = iomodel->edges[3*i+1]-1;
+						values=xNew<IssmDouble>(N);
+						spcpresent=false;
+						for(j=0;j<N;j++){
+							values[j]=(spcdata[v1*N+j]+spcdata[v2*N+j])/2.;
+							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+iomodel->numberofvertices+i+1,dof,
+											N,times,values,analysis_type));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+				}
+				break;
+			case P1xP2Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+
+						/*figure out times and values: */
+						values=xNew<IssmDouble>(N);
+						spcpresent=false;
+						for(j=0;j<N;j++){
+							values[j]=spcdata[i*N+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,dof,N,times,values,analysis_type));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(iomodel->edges[i*3+2]==2){
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							values=xNew<IssmDouble>(N);
+							spcpresent=false;
+							for(j=0;j<N;j++){
+								values[j]=(spcdata[v1*N+j]+spcdata[v2*N+j])/2.;
+								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+iomodel->numberofvertices+i+1,dof,
+												N,times,values,analysis_type));
+								count++;
+							}
+							xDelete<IssmDouble>(values);
+						}
+					}
+				}
+				break;
+			case P2xP1Enum:
+				for(i=0;i<iomodel->numberofvertices;i++){
+					if((iomodel->my_vertices[i])){
+
+						/*figure out times and values: */
+						values=xNew<IssmDouble>(N);
+						spcpresent=false;
+						for(j=0;j<N;j++){
+							values[j]=spcdata[i*N+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,dof,N,times,values,analysis_type));
+							count++;
+						}
+						xDelete<IssmDouble>(values);
+					}
+				}
+				for(i=0;i<iomodel->numberofedges;i++){
+					if(iomodel->edges[i*3+2]!=2){
+						if(my_edges[i]){
+							v1 = iomodel->edges[3*i+0]-1;
+							v2 = iomodel->edges[3*i+1]-1;
+							values=xNew<IssmDouble>(N);
+							spcpresent=false;
+							for(j=0;j<N;j++){
+								values[j]=(spcdata[v1*N+j]+spcdata[v2*N+j])/2.;
+								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+iomodel->numberofvertices+i+1,dof,
+												N,times,values,analysis_type));
+								count++;
+							}
+							xDelete<IssmDouble>(values);
+						}
+					}
+				}
+				break;
+			default:
+				_error_("Finite element "<<EnumToStringx(finite_element)<<" not supported yet");
 		}
 	}
 	else{
-		_error_("Size of field " << EnumToStringx(vector_enum) << " not supported");
+		_error_("Size of spc field not supported");
 	}
 
 	/*Free ressources:*/
-	xDelete<IssmDouble>(IssmDoublevector);
 	xDelete<IssmDouble>(times);
 	xDelete<IssmDouble>(values);
+	xDelete<bool>(my_edges);
 }
Index: /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.h	(revision 16137)
@@ -8,5 +8,6 @@
 
 /* local prototypes: */
-void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,int vector_enum,int analysis_type);
+void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,int vector_enum,int analysis_type,int finite_element,int dof=1);
+void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,IssmDouble* spcdata,int M,int N,int analysis_type,int finite_element,int dof=1);
 
 #endif  /* _IOMODELTOELEMENTINPUTX_H */
Index: sm/trunk/src/c/modules/KMLFileReadx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/KMLFileReadx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/KMLFileReadx)
-# }}}
-# KML_SOURCES {{{
-set(KML_SOURCES $ENV{ISSM_DIR}/src/c/modules/KMLFileReadx/KMLFileReadx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/KMLMeshWritex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/KMLMeshWritex/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/KMLMeshWritex)
-# }}}
-# KML_SOURCES {{{
-set(KML_SOURCES $ENV{ISSM_DIR}/src/c/modules/KMLMeshWritex/KMLMeshWritex.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/KMLOverlayx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/KMLOverlayx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/KMLOverlayx)
-# }}}
-# KML_SOURCES {{{
-set(KML_SOURCES $ENV{ISSM_DIR}/src/c/modules/KMLOverlayx/KMLOverlayx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/Kml2Expx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Kml2Expx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Kml2Expx)
-# }}}
-# KML_SOURCES {{{
-set(KML_SOURCES $ENV{ISSM_DIR}/src/c/modules/Kml2Expx/Kml2Expx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/Krigingx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Krigingx)
-# }}}
-# KRIGING_SOURCES {{{
-set(KRIGING_SOURCES $ENV{ISSM_DIR}/src/c/modules/Krigingx/Krigingx.cpp PARENT_SCOPE)
-# }}}
-# PKRIGING_SOURCES {{{
-set(PKRIGING_SOURCES $ENV{ISSM_DIR}/src/c/modules/Krigingx/pKrigingx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/Krigingx/Krigingx.cpp	(revision 16137)
@@ -110,5 +110,5 @@
 		/*launch the thread manager with Krigingxt as a core: */
 		LaunchThread(NearestNeighbort,(void*)&gate,num);
-		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 		xDelete<int>(gate.numdone);
 	}
@@ -132,5 +132,5 @@
 		/*launch the thread manager with Krigingxt as a core: */
 		LaunchThread(idwt,(void*)&gate,num);
-		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 		xDelete<int>(gate.numdone);
 	}
@@ -154,5 +154,5 @@
 		/*launch the thread manager with Krigingxt as a core: */
 		LaunchThread(v4t,(void*)&gate,num);
-		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 		xDelete<int>(gate.numdone);
 	}
@@ -177,5 +177,5 @@
 		/*launch the thread manager with Krigingxt as a core: */
 		LaunchThread(Krigingxt,(void*)&gate,num);
-		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
+		_printf_("\r      interpolation progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 		xDelete<int>(gate.numdone);
 	}
@@ -230,5 +230,5 @@
 			int alldone=numdone[0];
 			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
-			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%");
+			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%   ");
 		}
 
@@ -277,5 +277,5 @@
 			int alldone=numdone[0];
 			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
-			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%");
+			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%   ");
 		}
 
@@ -324,5 +324,5 @@
 			int alldone=numdone[0];
 			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
-			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%");
+			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%   ");
 		}
 
@@ -369,5 +369,5 @@
 			int alldone=numdone[0];
 			for(int i=1;i<num_threads;i++) alldone+=numdone[i];
-			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%");
+			_printf_("\r      interpolation progress: "<<setw(6)<<setprecision(2)<<double(alldone)/double(n_interp)*100.<<"%   ");
 		}
 
Index: /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp	(revision 16137)
@@ -37,5 +37,5 @@
 
 	/*Get some Options*/
-	MPI_Barrier(MPI_COMM_WORLD); start=MPI_Wtime();
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); start=ISSM_MPI_Wtime();
 	options->Get(&radius,"searchradius",0.);
 	options->Get(&mindata,"mindata",1);
@@ -43,7 +43,7 @@
 
 	/*Process observation dataset*/
-	MPI_Barrier(MPI_COMM_WORLD); start_init=MPI_Wtime();
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); start_init=ISSM_MPI_Wtime();
 	observations=new Observations(obs_list,obs_x,obs_y,obs_length,options);
-	MPI_Barrier(MPI_COMM_WORLD); finish_init=MPI_Wtime();
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); finish_init=ISSM_MPI_Wtime();
 
 	/*Allocate output*/
@@ -54,5 +54,5 @@
 	options->Get(&output,"output",(char*)"prediction");
 
-	MPI_Barrier(MPI_COMM_WORLD); start_core=MPI_Wtime( );
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); start_core=ISSM_MPI_Wtime( );
 	if(strcmp(output,"quadtree")==0){
 		observations->QuadtreeColoring(predictions,x_interp,y_interp,n_interp);
@@ -68,17 +68,15 @@
 		/*partition loop across threads: */
 		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
-			_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%\n");
+			_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%  \n");
 			observations->InterpolationKriging(&predictions[idx],&error[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata,variogram);
 		}
-		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%\n");
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%  \n");
 
-#ifdef _HAVE_MPI_
 		double *sumpredictions =xNew<double>(n_interp);
 		double *sumerror       =xNew<double>(n_interp);
-		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
-		MPI_Allreduce(error,sumerror,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
+		ISSM_MPI_Allreduce(predictions,sumpredictions,n_interp,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
+		ISSM_MPI_Allreduce(error,sumerror,n_interp,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
 		xDelete<double>(error); error=sumerror;
 		xDelete<double>(predictions); predictions=sumpredictions;
-#endif
 	}
 	else if(strcmp(output,"v4")==0){
@@ -86,14 +84,12 @@
 		/*partition loop across threads: */
 		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
-			_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%\n");
+			_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%  \n");
 			observations->InterpolationV4(&predictions[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata);
 		}
-		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%\n");
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%  \n");
 
-#ifdef _HAVE_MPI_
 		double *sumpredictions =xNew<double>(n_interp);
-		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
+		ISSM_MPI_Allreduce(predictions,sumpredictions,n_interp,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
 		xDelete<double>(predictions); predictions=sumpredictions;
-#endif
 	}
 	else if(strcmp(output,"nearestneighbor")==0){
@@ -101,14 +97,12 @@
 		/*partition loop across threads: */
 		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
-			_printf0_("      interpolation progress: "<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%\n");
+			_printf0_("      interpolation progress: "<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%  \n");
 			observations->InterpolationNearestNeighbor(&predictions[idx],x_interp[idx],y_interp[idx],radius);
 		}
-		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%\n");
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%  \n");
 
-#ifdef _HAVE_MPI_
 		double *sumpredictions =xNew<double>(n_interp);
-		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
+		ISSM_MPI_Allreduce(predictions,sumpredictions,n_interp,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
 		xDelete<double>(predictions); predictions=sumpredictions;
-#endif
 	}
 	else if(strcmp(output,"idw")==0){
@@ -118,19 +112,17 @@
 		/*partition loop across threads: */
 		for(int idx=my_rank;idx<n_interp;idx+=num_procs){
-			_printf0_("      interpolation progress: "<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%\n");
+			_printf0_("      interpolation progress: "<<setw(6)<<setprecision(4)<<double(idx)/double(n_interp)*100.<<"%  \n");
 			observations->InterpolationIDW(&predictions[idx],x_interp[idx],y_interp[idx],radius,mindata,maxdata,power);
 		}
-		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%\n");
+		_printf0_("      interpolation progress: "<<fixed<<setw(6)<<setprecision(4)<<100.<<"%  \n");
 
-#ifdef _HAVE_MPI_
 		double *sumpredictions =xNew<double>(n_interp);
-		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
+		ISSM_MPI_Allreduce(predictions,sumpredictions,n_interp,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
 		xDelete<double>(predictions); predictions=sumpredictions;
-#endif
 	}
 	else{
 		_error_("output '" << output << "' not supported yet");
 	}
-	MPI_Barrier(MPI_COMM_WORLD); finish_core=MPI_Wtime( );
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); finish_core=ISSM_MPI_Wtime( );
 
 	/*clean-up and Assign output pointer*/
@@ -141,5 +133,5 @@
 	*perror       = error;
 
-	MPI_Barrier(MPI_COMM_WORLD); finish=MPI_Wtime( );
+	ISSM_MPI_Barrier(ISSM_MPI_COMM_WORLD); finish=ISSM_MPI_Wtime( );
 	_printf0_("\n   " << setw(34) << left << "Observation fitering elapsed time: " << finish_init-start_init << " seconds  \n\n");
 	_printf0_("   " << setw(34) << left << "Kriging prediction elapsed time: " << finish_core-start_core << " seconds  \n\n");
Index: sm/trunk/src/c/modules/Mergesolutionfromftogx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Mergesolutionfromftogx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Mergesolutionfromftogx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/MeshPartitionx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/MeshPartitionx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/MeshPartitionx)
-# }}}
Index: /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h
===================================================================
--- /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 16137)
@@ -10,5 +10,5 @@
 /* local prototypes: */
 template <class doubletype> 
-int MeshPartitionx(int** pepart, int** pnpart, int numberofelements,int numberofnodes,doubletype* elements,
+int MeshPartitionx(int** pepart, int** pnpart, int numberofelements,int numberofnodes,int* elements,
 		int numberofelements2d,int numberofnodes2d,doubletype* elements2d,int numlayers,int elements_width, int dim,int num_procs){
 
@@ -37,5 +37,5 @@
 		for (i=0;i<numberofelements;i++){
 			for (j=0;j<elements_width;j++){
-				*(index+elements_width*i+j)=reCast<int>(*(elements+elements_width*i+j))-1; //-1 for C indexing in Metis
+				*(index+elements_width*i+j)=(*(elements+elements_width*i+j))-1; //-1 for C indexing in Metis
 			}
 		}
@@ -118,4 +118,4 @@
 	xDelete<int>(index2d);
 	return noerr;
-}	
+}
 #endif /* _MESHPARTITIONX_H */
Index: sm/trunk/src/c/modules/MeshProfileIntersectionx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/MeshProfileIntersectionx)
-# }}}
Index: sm/trunk/src/c/modules/ModelProcessorx/Autodiff/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 16137)
@@ -113,9 +113,14 @@
 		/*initialize a placeholder to store solver pointers: {{{*/
 		GenericParam<Adolc_edf> *theAdolcEDF_p=new GenericParam<Adolc_edf>(AdolcParamEnum);
+		#ifdef _HAVE_GSL_
 		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(EDF_for_solverx);
+		#endif
+		#ifdef _HAVE_MUMPS_
+		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(mumpsSolveEDF);
+		#endif
 		// to save some space:
 		// we know we won't use adolc inside of  the solver:
 		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p->nestedAdolc=false;
-		// the solution vector is just allocated and doesn't have a meaningfull prior value
+		// the solution vector is just allocated and doesn't have a meaningful prior value
 		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p->dp_y_priorRequired=false;
 		// the solver wrapper makes sure the matrix and the right hand side don't change
Index: sm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# BALANCED_SOURCES {{{
-set(BALANCED_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp
-                           $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp
-                           $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp
-                        $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp	(revision 16137)
@@ -14,10 +14,7 @@
 	Constraints* constraints=*pconstraints;
 
-	/*Create constraints if they do not exist yet*/
-	if(!constraints) constraints = new Constraints();
-
 	/*Do not add constraints in DG*/
 	if(stabilization!=3){
-		IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancethicknessAnalysisEnum);
+		IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancethicknessAnalysisEnum,P1Enum);
 	}
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 16137)
@@ -12,27 +12,23 @@
 	int element;
 	int stabilization;
-	int numberofedges;
 
 	/*Fetch parameters: */
 	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
-	iomodel->Constant(&numberofedges,MeshNumberofedgesEnum);
 
 	/*Recover pointer: */
 	Loads* loads=*ploads;
 
-	/*Create loads if they do not exist yet*/
-	if(!loads) loads = new Loads();
-
 	/*Loads only in DG*/
 	if (stabilization==3){
 
-		/*Get edges and elements*/
-		iomodel->FetchData(3,MeshEdgesEnum,MeshElementsEnum,ThicknessEnum);
+		/*Get faces and elements*/
+		CreateFaces(iomodel);
+		iomodel->FetchData(1,ThicknessEnum);
 
 		/*First load data:*/
-		for (int i=0;i<numberofedges;i++){
+		for(int i=0;i<iomodel->numberoffaces;i++){
 
 			/*Get left and right elements*/
-			element=reCast<int,IssmDouble>(iomodel->Data(MeshEdgesEnum)[4*i+2])-1; //edges are [node1 node2 elem1 elem2]
+			element=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
 
 			/*Now, if this element is not in the partition, pass: */
@@ -40,9 +36,9 @@
 
 			/* Add load */
-			loads->AddObject(new Numericalflux(iomodel->loadcounter+i+1,i,iomodel,BalancethicknessAnalysisEnum));
+			loads->AddObject(new Numericalflux(iomodel->loadcounter+i+1,i,i,iomodel,BalancethicknessAnalysisEnum));
 		}
 
 		/*Free data: */
-		iomodel->DeleteData(3,MeshEdgesEnum,MeshElementsEnum,ThicknessEnum);
+		iomodel->DeleteData(1,ThicknessEnum);
 	}
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 16137)
@@ -11,77 +11,19 @@
 void	CreateNodesBalancethickness(Nodes** pnodes, IoModel* iomodel){
 
-	/*Intermediary*/
-	int  i,j;
-	int  node_id;
-	int  vertex_id;
-	int  io_index;
-	bool continuous_galerkin=true;
-	int    dim;
-	int    numberofelements;
-	int    numberofvertices;
-	int    stabilization;
-
 	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	int  stabilization;
 	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
 
-	/*Recover pointer: */
-	Nodes* nodes=*pnodes;
-
-	/*Create nodes if they do not exist yet*/
-	if(!nodes) nodes = new Nodes();
-
-	/*Continuous Galerkin partition of nodes: */
-	if(stabilization==3) continuous_galerkin=false;
-	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-
 	/*Check in 3d*/
-	if(stabilization==3 && dim==3) _error_("DG 3d not implemented yet");
+	if(stabilization==3 && iomodel->dim==3) _error_("DG 3d not implemented yet");
 
 	/*First fetch data: */
-	iomodel->FetchData(7,MeshElementsEnum,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	if(continuous_galerkin){
-
-		/*Build Nodes dataset (Continuous Galerkin)*/
-		for (i=0;i<numberofvertices;i++){
-			if(iomodel->my_vertices[i]){
-
-				/*Add node to nodes dataset: */
-				nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,BalancethicknessAnalysisEnum));
-
-			}
-		}
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	if(stabilization!=3){
+		CreateNodes(pnodes,iomodel,BalancethicknessAnalysisEnum,P1Enum);
 	}
 	else{
-
-		/*Build Nodes dataset -> 3 for each element (Discontinuous Galerkin)*/
-		for (i=0;i<numberofelements;i++){
-			for (j=0;j<3;j++){
-
-				if(iomodel->my_nodes[3*i+j]){ 
-
-					//Get index of the vertex on which the current node is located
-					vertex_id=reCast<int,IssmDouble>(*(iomodel->Data(MeshElementsEnum)+3*i+j)); //(Matlab indexing)
-					io_index=vertex_id-1;                      //(C indexing)
-					_assert_(vertex_id>0 && vertex_id<=numberofvertices);
-
-					//Compute Node id
-					node_id=iomodel->nodecounter+3*i+j+1;
-
-					/*Add node to nodes dataset: */
-					nodes->AddObject(new Node(node_id,node_id-1,vertex_id,io_index,iomodel,BalancethicknessAnalysisEnum));
-
-				}
-			}
-		}
+		CreateNodes(pnodes,iomodel,BalancethicknessAnalysisEnum,P1DGEnum);
 	}
-
-	/*Clean fetched data: */
-	iomodel->DeleteData(7,MeshElementsEnum,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	/*Assign output pointer: */
-	*pnodes=nodes;
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/UpdateElementsBalancethickness.cpp	(revision 16137)
@@ -11,18 +11,21 @@
 void	UpdateElementsBalancethickness(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
 
-	int    dim;
-	int    numberofelements;
+	int    stabilization,finiteelement;
 
 	/*Fetch data needed: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->FetchData(1,MeshElementsEnum);
+	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
+
+	/*Finite element type*/
+	finiteelement = P1Enum;
+	if(stabilization==3){
+		finiteelement = P1DGEnum;
+	}
 
 	/*Update elements: */
 	int counter=0;
-	for(int i=0;i<numberofelements;i++){
+	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); //we need i to index into elements.
+			element->Update(i,iomodel,analysis_counter,analysis_type,finiteelement);
 			counter++;
 		}
@@ -32,6 +35,5 @@
 	iomodel->FetchDataToInput(elements,SurfaceEnum);
 	iomodel->FetchDataToInput(elements,BedEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
 	iomodel->FetchDataToInput(elements,VxEnum);
 	iomodel->FetchDataToInput(elements,VyEnum);
@@ -40,9 +42,7 @@
 	iomodel->FetchDataToInput(elements,BalancethicknessThickeningRateEnum);
 
-	if (dim==3){
+	if(iomodel->dim==3){
 		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
 		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
 	}
-	/*Free data: */
-	iomodel->DeleteData(1,MeshElementsEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/CreateConstraintsBalancevelocity.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/CreateConstraintsBalancevelocity.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/CreateConstraintsBalancevelocity.cpp	(revision 16137)
@@ -0,0 +1,17 @@
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+#include "../../IoModelToConstraintsx/IoModelToConstraintsx.h"
+
+void	CreateConstraintsBalancevelocity(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Recover pointer: */
+	Constraints* constraints=*pconstraints;
+
+	/*No constraints for now*/
+	//IoModelToConstraintsx(constraints,iomodel,BalancethicknessSpcthicknessEnum,BalancevelocityAnalysisEnum,P1Enum);
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/CreateLoadsBalancevelocity.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/CreateLoadsBalancevelocity.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/CreateLoadsBalancevelocity.cpp	(revision 16137)
@@ -0,0 +1,13 @@
+/*! \file CreateLoadsBalancevelocity.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsBalancevelocity(Loads** ploads, IoModel* iomodel){
+
+	/*No loads*/
+
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/CreateNodesBalancevelocity.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/CreateNodesBalancevelocity.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/CreateNodesBalancevelocity.cpp	(revision 16137)
@@ -0,0 +1,20 @@
+/*
+ * CreateNodesBalancevelocity.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesBalancevelocity(Nodes** pnodes, IoModel* iomodel){
+
+	/*Check in 3d*/
+	if(iomodel->dim==3) _error_("DG 3d not implemented yet");
+
+	/*First fetch data: */
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,BalancevelocityAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/UpdateElementsBalancevelocity.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/UpdateElementsBalancevelocity.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancevelocity/UpdateElementsBalancevelocity.cpp	(revision 16137)
@@ -0,0 +1,37 @@
+/*
+ * UpdateElementsBalancevelocity:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsBalancevelocity(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,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,BalancethicknessThickeningRateEnum);
+
+	if(iomodel->dim==3){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	}
+}
Index: sm/trunk/src/c/modules/ModelProcessorx/BedSlope/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# SLOPE_SOURCES {{{
-set(SLOPE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp
-                        $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp
-                        $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp
-                     $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 16137)
@@ -10,11 +10,5 @@
 void	CreateConstraintsBedSlope(Constraints** pconstraints, IoModel* iomodel){
 
-	/*Recover pointer: */
-	Constraints* constraints=*pconstraints;
+	/*No constraints*/
 
-	/*Create constraints if they do not exist yet*/
-	if(!constraints) constraints = new Constraints();
-
-	/*Assign output pointer: */
-	*pconstraints=constraints;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 16137)
@@ -9,11 +9,5 @@
 void	CreateLoadsBedSlope(Loads** ploads, IoModel* iomodel){
 
-	/*Recover pointer: */
-	Loads* loads=*ploads;
+	/*No loads*/
 
-	/*Create loads if they do not exist yet*/
-	if(!loads) loads = new Loads();
-
-	/*Assign output pointer: */
-	*ploads=loads;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 16137)
@@ -11,37 +11,6 @@
 void	CreateNodesBedSlope(Nodes** pnodes, IoModel* iomodel){
 
-	/*Intermediary*/
-	int i;
-	bool continuous_galerkin=true;
-
-	/*Fetch parameters: */
-	int    numberofvertices;
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-
-	/*Recover pointer: */
-	Nodes* nodes=*pnodes;
-
-	/*Create nodes if they do not exist yet*/
-	if(!nodes) nodes = new Nodes();
-
-	/*Continuous Galerkin partition of nodes: */
-	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-
-	/*First fetch data: */
-	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	for (i=0;i<numberofvertices;i++){
-		if(iomodel->my_vertices[i]){
-
-			/*Add node to nodes dataset: */
-			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,BedSlopeAnalysisEnum));
-
-		}
-	}
-
-	/*Clean fetched data: */
-	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	/*Assign output pointer: */
-	*pnodes=nodes;
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,BedSlopeAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 16137)
@@ -11,18 +11,10 @@
 void	UpdateElementsBedSlope(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
 
-	int    dim;
-	int    numberofelements;
-
-	/*Fetch data needed: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->FetchData(1,MeshElementsEnum);
-
 	/*Update elements: */
 	int counter=0;
-	for(int i=0;i<numberofelements;i++){
+	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); //we need i to index into elements.
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
 			counter++;
 		}
@@ -31,12 +23,8 @@
 	iomodel->FetchDataToInput(elements,SurfaceEnum);
 	iomodel->FetchDataToInput(elements,BedEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
-
-	if (dim==3){
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->dim==3){
 		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
 		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
 	}
-
-	/*Free data: */
-	iomodel->DeleteData(1,MeshElementsEnum);
 }
Index: sm/trunk/src/c/modules/ModelProcessorx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,33 +1,0 @@
-# Subdirectories {{{
-add_subdirectory(Autodiff)
-add_subdirectory(Balancethickness)
-add_subdirectory(BedSlope)
-add_subdirectory(Control)
-add_subdirectory(Dakota)
-add_subdirectory(DiagnosticHoriz)
-add_subdirectory(DiagnosticHutter)
-add_subdirectory(DiagnosticVert)
-add_subdirectory(Enthalpy)
-add_subdirectory(Hydrology)
-add_subdirectory(Melting)
-add_subdirectory(Prognostic)
-add_subdirectory(SurfaceSlope)
-add_subdirectory(Thermal)
-add_subdirectory(Transient)
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/CreateDataSets.cpp
-$ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
-$ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp
-               $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/CreateParameters.cpp
-$ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp
-              $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp
-$ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp
-                $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/ModelProcessorx.cpp
-              $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/NodesPartitioning.cpp
-                   $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/SortDataSets.cpp
-                 $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/UpdateCounters.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/ModelProcessorx/Control/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,2 +1,0 @@
-# Subdirectories {{{
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 16137)
@@ -16,10 +16,8 @@
 	Element  *element = NULL;
 	Material *material = NULL;
-	int    numberofelements;
 	int    num_control_type;
 	bool   control_analysis;
 
 	/*Fetch parameters: */
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
 	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
 	if(control_analysis) iomodel->Constant(&num_control_type,InversionNumControlParametersEnum);
@@ -29,5 +27,4 @@
 
 	/*Fetch data needed: */
-	iomodel->FetchData(1,MeshElementsEnum);
 	iomodel->FetchDataToInput(elements,InversionVxObsEnum);
 	iomodel->FetchDataToInput(elements,InversionVyObsEnum); 
@@ -50,5 +47,5 @@
 	/*Update elements and materials: */
 	counter=0;
-	for (i=0;i<numberofelements;i++){
+	for (i=0;i<iomodel->numberofelements;i++){
 		if(iomodel->my_elements[i]){
 			element=(Element*)elements->GetObjectByOffset(counter);
@@ -62,4 +59,4 @@
 
 	/*Free data: */
-	iomodel->DeleteData(1+4+6,MeshElementsEnum,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum,BalancethicknessThickeningRateEnum,VxEnum,VyEnum,FrictionCoefficientEnum,MaterialsRheologyBEnum,MaterialsRheologyZEnum);
+	iomodel->DeleteData(4+7,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum,BalancethicknessThickeningRateEnum,VxEnum,VyEnum,ThicknessEnum,FrictionCoefficientEnum,MaterialsRheologyBEnum,MaterialsRheologyZEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 16137)
@@ -11,12 +11,17 @@
 #include "../../classes/classes.h"
 #include "../../shared/shared.h"
+#include "../MeshPartitionx/MeshPartitionx.h"
 #include "./ModelProcessorx.h"
 
 void CreateDataSets(Elements** pelements,Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,const int analysis_type,const int nummodels,int analysis_counter){
 
-	bool        continuous = true;
 	Elements   *elements   = NULL;
 	Materials  *materials  = NULL;
 	Parameters *parameters = NULL;
+
+	/*Process Finite Element Mesh*/
+
+	/*Partition Elements and Nodes*/
+	ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
 
 	/*Create elements, vertices and materials, independent of analysis_type: */
@@ -24,30 +29,35 @@
 
 	/*Recover elements and materials, for future update: */
-	elements=*pelements;
-	materials=*pmaterials;
+	elements  = *pelements;
+	materials = *pmaterials;
+
+	/*Creates Nodes and constraints datasets if empty*/
+	if(!*pnodes)       *pnodes       = new Nodes();
+	if(!*pconstraints) *pconstraints = new Constraints();
+	if(!*ploads)       *ploads       = new Loads();
 
 	/*Now, branch onto analysis dependent model generation: */
 	switch(analysis_type){
 
-		#ifdef _HAVE_DIAGNOSTIC_
-		case DiagnosticHorizAnalysisEnum:
-			CreateNodesDiagnosticHoriz(pnodes, iomodel);
-			CreateConstraintsDiagnosticHoriz(pconstraints,iomodel);
-			CreateLoadsDiagnosticHoriz(ploads,iomodel);
-			UpdateElementsDiagnosticHoriz(elements,iomodel,analysis_counter,analysis_type);
+		#ifdef _HAVE_STRESSBALANCE_
+		case StressbalanceAnalysisEnum:
+			CreateNodesStressbalance(pnodes,iomodel);
+			CreateConstraintsStressbalance(pconstraints,iomodel);
+			CreateLoadsStressbalance(ploads,iomodel);
+			UpdateElementsStressbalance(elements,iomodel,analysis_counter,analysis_type);
 			break;
 
-		case DiagnosticVertAnalysisEnum:
-			CreateNodesDiagnosticVert(pnodes, iomodel);
-			CreateConstraintsDiagnosticVert(pconstraints,iomodel);
-			CreateLoadsDiagnosticVert(ploads,iomodel);
-			UpdateElementsDiagnosticVert(elements,iomodel,analysis_counter,analysis_type);
+		case StressbalanceVerticalAnalysisEnum:
+			CreateNodesStressbalanceVertical(pnodes, iomodel);
+			CreateConstraintsStressbalanceVertical(pconstraints,iomodel);
+			CreateLoadsStressbalanceVertical(ploads,iomodel);
+			UpdateElementsStressbalanceVertical(elements,iomodel,analysis_counter,analysis_type);
 			break;
 
-		case DiagnosticHutterAnalysisEnum:
-			CreateNodesDiagnosticHutter(pnodes, iomodel);
-			CreateConstraintsDiagnosticHutter(pconstraints,iomodel);
-			CreateLoadsDiagnosticHutter(ploads,iomodel);
-			UpdateElementsDiagnosticHutter(elements,iomodel,analysis_counter,analysis_type);
+		case StressbalanceSIAAnalysisEnum:
+			CreateNodesStressbalanceSIA(pnodes, iomodel);
+			CreateConstraintsStressbalanceSIA(pconstraints,iomodel);
+			CreateLoadsStressbalanceSIA(ploads,iomodel);
+			UpdateElementsStressbalanceSIA(elements,iomodel,analysis_counter,analysis_type);
 			break;
 		#endif
@@ -104,4 +114,10 @@
 			UpdateElementsBalancethickness(elements,iomodel,analysis_counter,analysis_type);
 			break;
+		case BalancevelocityAnalysisEnum:
+			CreateNodesBalancevelocity(pnodes, iomodel);
+			CreateConstraintsBalancevelocity(pconstraints,iomodel);
+			CreateLoadsBalancevelocity(ploads,iomodel);
+			UpdateElementsBalancevelocity(elements,iomodel,analysis_counter,analysis_type);
+			break;
 		#endif
 
@@ -131,10 +147,22 @@
 		#endif
 
-		#ifdef _HAVE_PROGNOSTIC_
-		case PrognosticAnalysisEnum:
-			CreateNodesPrognostic(pnodes, iomodel);
-			CreateConstraintsPrognostic(pconstraints,iomodel);
-			CreateLoadsPrognostic(ploads,iomodel);
-			UpdateElementsPrognostic(elements,iomodel,analysis_counter,analysis_type);
+		#ifdef _HAVE_MASSTRANSPORT_
+		case MasstransportAnalysisEnum:
+			CreateNodesMasstransport(pnodes, iomodel);
+			CreateConstraintsMasstransport(pconstraints,iomodel);
+			CreateLoadsMasstransport(ploads,iomodel);
+			UpdateElementsMasstransport(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		case FreeSurfaceTopAnalysisEnum:
+			CreateNodesFreeSurfaceTop(pnodes, iomodel);
+			CreateConstraintsFreeSurfaceTop(pconstraints,iomodel);
+			CreateLoadsFreeSurfaceTop(ploads,iomodel);
+			UpdateElementsFreeSurfaceTop(elements,iomodel,analysis_counter,analysis_type);
+			break;
+		case FreeSurfaceBaseAnalysisEnum:
+			CreateNodesFreeSurfaceBase(pnodes, iomodel);
+			CreateConstraintsFreeSurfaceBase(pconstraints,iomodel);
+			CreateLoadsFreeSurfaceBase(ploads,iomodel);
+			UpdateElementsFreeSurfaceBase(elements,iomodel,analysis_counter,analysis_type);
 			break;
 		#endif
@@ -163,5 +191,6 @@
 	SortDataSets(pelements,pnodes,pvertices, ploads, pmaterials, pconstraints, pparameters);
 
-	/*Update counters, because we have created more nodes, loads and constraints, and ids for objects created in next call to CreateDataSets
+	/* Update counters, because we have created more nodes, loads and
+	 * constraints, and ids for objects created in next call to CreateDataSets
 	 * will need to start at the end of the updated counters: */
 	UpdateCounters(iomodel,pnodes,ploads,pconstraints);
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateEdges.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateEdges.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateEdges.cpp	(revision 16137)
@@ -0,0 +1,131 @@
+/*!\file:  CreateEdges.cpp
+ * \brief: create edges from 2d mesh
+ */ 
+
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+
+void CreateEdges(IoModel* iomodel){
+
+	/*If edges are already present, exit*/
+	if(iomodel->edges) return;
+
+	/*Check Iomodel properties*/
+	if(iomodel->numberofvertices<3) _error_("not enough elements in mesh");
+	_assert_(iomodel->elements);
+
+	/*Intermediaries*/
+	bool exist;
+	int  i,j,v1,v2,v3;
+	int  maxnbe,nbe,elementnbe,elementnbv;
+	int *elementedges         = NULL;
+	int *elementedges_markers = NULL;
+
+	/*Mesh dependent variables*/
+	if(iomodel->dim==2){
+		elementnbv = 3;
+		elementnbe = 3;
+		elementedges         = xNew<int>(elementnbe*2);
+		elementedges_markers = xNew<int>(elementnbe);
+		elementedges[2*0+0] = 1; elementedges[2*0+1] = 2; elementedges_markers[0] = 1;
+		elementedges[2*1+0] = 2; elementedges[2*1+1] = 0; elementedges_markers[1] = 1;
+		elementedges[2*2+0] = 0; elementedges[2*2+1] = 1; elementedges_markers[2] = 1;
+	}
+	else if(iomodel->dim==3){
+		elementnbv = 6;
+		elementnbe = 9;
+		elementedges         = xNew<int>(elementnbe*2);
+		elementedges_markers = xNew<int>(elementnbe);
+		elementedges[2*0+0] = 0; elementedges[2*0+1] = 3; elementedges_markers[0] = 2;
+		elementedges[2*1+0] = 1; elementedges[2*1+1] = 4; elementedges_markers[1] = 2;
+		elementedges[2*2+0] = 2; elementedges[2*2+1] = 5; elementedges_markers[2] = 2;
+		elementedges[2*3+0] = 1; elementedges[2*3+1] = 2; elementedges_markers[3] = 1;
+		elementedges[2*4+0] = 2; elementedges[2*4+1] = 0; elementedges_markers[4] = 1;
+		elementedges[2*5+0] = 0; elementedges[2*5+1] = 1; elementedges_markers[5] = 1;
+		elementedges[2*6+0] = 4; elementedges[2*6+1] = 5; elementedges_markers[6] = 3;
+		elementedges[2*7+0] = 5; elementedges[2*7+1] = 3; elementedges_markers[7] = 3;
+		elementedges[2*8+0] = 3; elementedges[2*8+1] = 4; elementedges_markers[8] = 3;
+	}
+	else{
+		_error_("mesh dimension not supported yet");
+	}
+
+	/*Maximum number of edges*/
+	maxnbe = elementnbe*iomodel->numberofelements;
+
+	/*Initialize intermediaries*/
+	int *edgestemp                 = xNew<int>(maxnbe*3);                             /*format: [vertex1 vertex2 marker]       */
+	int *element_edge_connectivity = xNew<int>(iomodel->numberofelements*elementnbe); /*format: [edge1 edge2 ... edgen] */
+
+	/*Initialize chain*/
+	int* head_minv = xNew<int>(iomodel->numberofvertices);
+	int* next_edge = xNew<int>(maxnbe);
+	for(i=0;i<iomodel->numberofvertices;i++) head_minv[i]=-1;
+
+	/*Initialize number of edges*/
+	nbe = 0;
+
+	for(i=0;i<iomodel->numberofelements;i++){
+		for(j=0;j<elementnbe;j++){
+
+			/*Get the two indices of the edge number j of the ith element*/
+			v1 = iomodel->elements[i*elementnbv+elementedges[2*j+0]]-1; _assert_(v1>=0 & v1<iomodel->numberofvertices);
+			v2 = iomodel->elements[i*elementnbv+elementedges[2*j+1]]-1; _assert_(v2>=0 & v2<iomodel->numberofvertices);
+
+			/*v1 and v2 must be sorted*/
+			if(v2<v1){
+				v3=v2; v2=v1; v1=v3;
+			}
+
+			/*This edge a priori has not been processed yet*/
+			exist = false;
+
+			/*Go through all processed edges connected to v1 and check whether we have seen this edge yet*/
+			for(int e=head_minv[v1]; e!=-1; e=next_edge[e]){
+				if(edgestemp[e*3+1]==v2+1){
+					exist = true;
+					element_edge_connectivity[i*elementnbe+j]=e;
+					break;
+				}
+			}
+
+			/*If this edge is new, add it to the lists*/
+			if(!exist){
+				_assert_(nbe<maxnbe);
+
+				/*Update edges*/
+				edgestemp[nbe*3+0] = v1+1;
+				edgestemp[nbe*3+1] = v2+1;
+				edgestemp[nbe*3+2] = elementedges_markers[j];
+
+				/*Update Connectivity*/
+				element_edge_connectivity[i*elementnbe+j]=nbe;
+
+				/*Update chain*/
+				next_edge[nbe] = head_minv[v1];
+				head_minv[v1]  = nbe;
+
+				/*Increase number of edges*/
+				nbe++;
+			}
+		}
+	}
+
+	/*Clean up*/
+	xDelete<int>(head_minv);
+	xDelete<int>(next_edge);
+	xDelete<int>(elementedges_markers);
+
+	/*Create final edges*/
+	int* edges = xNew<int>(nbe*3); /*format: [vertex1 vertex2 marker]*/
+	for(int i=0;i<3*nbe;i++) edges[i] = edgestemp[i];
+
+	/*Clean up*/
+	xDelete<int>(edgestemp);
+	xDelete<int>(elementedges);
+
+	/*Assign output pointers*/
+	iomodel->edges                     = edges;
+	iomodel->elementtoedgeconnectivity = element_edge_connectivity;
+	iomodel->numberofedges             = nbe;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 16137)
@@ -1,4 +1,4 @@
 /*
- * CreateElementsNodesAndMaterialsDiagnosticHoriz.c:
+ * CreateElementsNodesAndMaterialsStressbalanceHoriz.c:
  */
 
@@ -6,5 +6,4 @@
 #include "../../classes/classes.h"
 #include "../../shared/shared.h"
-#include "../MeshPartitionx/MeshPartitionx.h"
 #include "./ModelProcessorx.h"
 
@@ -13,7 +12,5 @@
 	/*Intermediary*/
 	int i;
-	int dim,materials_type;
-	int numberofelements;
-	int numberofvertices;
+	int materials_type;
 	bool control_analysis;
 	bool dakota_analysis;
@@ -25,7 +22,4 @@
 
 	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 	iomodel->Constant(&control_analysis,InversionIscontrolEnum);
 	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
@@ -40,19 +34,15 @@
 	materials = new Materials();
 
-	/*First, partition elements and vertices. Nodes will partitioned on a per analysis_type basis. If partitining already done, ignore: */
-	ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
-
-	iomodel->FetchData(2,MeshElementsEnum,MeshElementconnectivityEnum);
 	#ifdef _HAVE_3D_
-	if(dim==3)iomodel->FetchData(2,MeshUpperelementsEnum,MeshLowerelementsEnum);
+	if(iomodel->dim==3)iomodel->FetchData(2,MeshUpperelementsEnum,MeshLowerelementsEnum);
 	#endif
 	if(control_analysis)iomodel->FetchData(3,InversionControlParametersEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
 
 	/*Create elements*/
-	for (i=0;i<numberofelements;i++){
+	for(i=0;i<iomodel->numberofelements;i++){
 		if(iomodel->my_elements[i]){
 
 			/*Create and add tria element to elements dataset: */
-			if(dim==2) elements->AddObject(new Tria(i+1,i,i,iomodel,nummodels));
+			if(iomodel->dim==2) elements->AddObject(new Tria(i+1,i,i,iomodel,nummodels));
 	        #ifdef _HAVE_3D_
 			else       elements->AddObject(new Penta(i+1,i,i,iomodel,nummodels));
@@ -65,7 +55,7 @@
 		case MaticeEnum:
 			iomodel->FetchData(2,MaterialsRheologyBEnum,MaterialsRheologyNEnum);
-			for (i=0;i<numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matice(i+1,i,iomodel));
+			for (i=0;i<iomodel->numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matice(i+1,i,iomodel));
 			if(dakota_analysis){
-				if(dim==2) materials->InputDuplicate(MaterialsRheologyBbarEnum,QmuMaterialsRheologyBEnum); 
+				if(iomodel->dim==2) materials->InputDuplicate(MaterialsRheologyBbarEnum,QmuMaterialsRheologyBEnum); 
            #ifdef _HAVE_3D_
 				else       materials->InputDuplicate(MaterialsRheologyBEnum,QmuMaterialsRheologyBEnum); 
@@ -75,5 +65,5 @@
 		case MatdamageiceEnum:
 			iomodel->FetchData(3,MaterialsRheologyBEnum,MaterialsRheologyNEnum,MaterialsRheologyZEnum);
-			for (i=0;i<numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matdamageice(i+1,i,iomodel));
+			for (i=0;i<iomodel->numberofelements;i++) if(iomodel->my_elements[i]) materials->AddObject(new Matdamageice(i+1,i,iomodel));
 			break;
 		default:
@@ -82,18 +72,18 @@
 
 	/*Free data: */
-	iomodel->DeleteData(10,MeshElementsEnum,MeshElementconnectivityEnum,MeshUpperelementsEnum,MeshLowerelementsEnum,
+	iomodel->DeleteData(8,MeshUpperelementsEnum,MeshLowerelementsEnum,
 				MaterialsRheologyBEnum,MaterialsRheologyNEnum,MaterialsRheologyZEnum,InversionControlParametersEnum,InversionMinParametersEnum,
 				InversionMaxParametersEnum);
 
 	/*Add new constant material property to materials, at the end: */
-	materials->AddObject(new Matpar(numberofelements+1,iomodel));//put it at the end of the materials
+	materials->AddObject(new Matpar(iomodel->numberofelements+1,iomodel));//put it at the end of the materials
 
 	/*Create vertices: */
 
 	/*Fetch data:*/
-	iomodel->FetchData(6,MeshElementsEnum,MeshXEnum,MeshYEnum,MeshZEnum,BedEnum,ThicknessEnum);
+	iomodel->FetchData(6,MeshXEnum,MeshYEnum,MeshZEnum,BedEnum,ThicknessEnum,MaskIceLevelsetEnum);
 	CreateNumberNodeToElementConnectivity(iomodel);
 
-	for (i=0;i<numberofvertices;i++){
+	for(i=0;i<iomodel->numberofvertices;i++){
 
 		/*vertices and nodes (same number, as we are running continuous galerkin formulation): */
@@ -106,5 +96,5 @@
 
 	/*Free data: */
-	iomodel->DeleteData(6,MeshElementsEnum,MeshXEnum,MeshYEnum,MeshZEnum,BedEnum,ThicknessEnum);
+	iomodel->DeleteData(6,MeshXEnum,MeshYEnum,MeshZEnum,BedEnum,ThicknessEnum,MaskIceLevelsetEnum);
 
 	/*Assign output pointer: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateFaces.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateFaces.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateFaces.cpp	(revision 16137)
@@ -0,0 +1,111 @@
+/*!\file:  CreateFaces.cpp
+ * \brief: create faces from 2d mesh
+ */ 
+
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+
+void CreateFaces(IoModel* iomodel){
+
+	/*If faces are already present, exit*/
+	if(iomodel->faces) return;
+
+	/*Check Iomodel properties*/
+	if(iomodel->dim!=2)             _error_("only 2d model are supported");
+	if(iomodel->numberofvertices<3) _error_("not enough elements in mesh");
+	_assert_(iomodel->elements);
+
+	/*Intermediaries*/
+	bool exist;
+	int  i,j,v1,v2,v3;
+	int  maxnbf,nbf;
+
+	/*Maximum number of faces*/
+	maxnbf = 3*iomodel->numberofelements;
+
+	/*Initialize intermediaries*/
+	int*  facestemp = xNew<int>(maxnbf*4);         /*format: [vertex1 vertex2 element1 element2]                */
+	bool* exchange  = xNewZeroInit<bool>(maxnbf);  /*Faces are ordered, we need to keep track of vertex swapping*/
+	for(i=0;i<maxnbf;i++) facestemp[i*4+3]=-1;     /*Initialize last column of faces as -1 (boundary edge)      */
+
+	/*Initialize chain*/
+	int* head_minv = xNew<int>(iomodel->numberofvertices);
+	int* next_edge = xNew<int>(maxnbf);
+	for(i=0;i<iomodel->numberofvertices;i++) head_minv[i]=-1;
+
+	/*Initialize number of faces*/
+	nbf = 0;
+
+	for(i=0;i<iomodel->numberofelements;i++){
+		for(j=0;j<3;j++){
+
+			/*Get the two indices of the edge number j of the ith triangle*/
+			v1 = iomodel->elements[i*3+j];
+			if(j==2)
+			 v2 = iomodel->elements[i*3+0];
+			else
+			 v2 = iomodel->elements[i*3+j+1];
+
+			/*v1 and v2 must be sorted*/
+			if(v2<v1){
+				v3=v2; v2=v1; v1=v3;
+			}
+
+			/*This edge a priori has not been processed yet*/
+			exist = false;
+
+			/*Go through all processed faces connected to v1 and check whether we have seen this edge yet*/
+			_assert_(v1>=0 & v1<iomodel->numberofvertices);
+			for(int e=head_minv[v1]; e!=-1; e=next_edge[e]){
+				if(facestemp[e*4+1]==v2){
+					exist = true;
+					facestemp[e*4+3]=i+1;
+					break;
+				}
+			}
+
+			/*If this edge is new, add it to the lists*/
+			if(!exist){
+				_assert_(nbf<maxnbf);
+
+				/*Update faces*/
+				facestemp[nbf*4+0] = v1;
+				facestemp[nbf*4+1] = v2;
+				facestemp[nbf*4+2] = i+1;
+				if(v1!=iomodel->elements[i*3+j]) exchange[nbf]=true;
+
+				/*Update chain*/
+				next_edge[nbf] = head_minv[v1];
+				head_minv[v1]  = nbf;
+
+				/*Increase number of faces*/
+				nbf++;
+			}
+		}
+	}
+
+	/*Clean up*/
+	xDelete<int>(head_minv);
+	xDelete<int>(next_edge);
+
+	/*Create final faces*/
+	int* faces = xNew<int>(nbf*4); /*vertex1 vertex2 element1 element2*/
+	for(int i=0;i<nbf;i++){
+		if(exchange[i]){
+			faces[i*4+0]=facestemp[i*4+1];
+			faces[i*4+1]=facestemp[i*4+0];
+		}
+		else{
+			faces[i*4+0]=facestemp[i*4+0];
+			faces[i*4+1]=facestemp[i*4+1];
+		}
+		faces[i*4+2]=facestemp[i*4+2];
+		faces[i*4+3]=facestemp[i*4+3];
+	}
+	xDelete<int>(facestemp);
+	xDelete<bool>(exchange);
+
+	/*Assign output pointers*/
+	iomodel->faces         = faces;
+	iomodel->numberoffaces = nbf;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateNodes.cpp	(revision 16137)
@@ -0,0 +1,233 @@
+/*
+ * CreateNodes.c:
+ */
+
+#include "../../toolkits/toolkits.h"
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "../MeshPartitionx/MeshPartitionx.h"
+#include "./ModelProcessorx.h"
+
+void CreateNodes(Nodes** pnodes, IoModel* iomodel,int analysis,int finite_element,int approximation){
+
+	/*Intermediaries*/
+	int   i,j,counter,lid=0;
+	bool *my_edges = NULL;
+	bool *my_nodes = NULL;
+	Node *node     = NULL;
+
+	/*Recover pointer: */
+	Nodes* nodes=*pnodes;
+
+	/*First create nodes*/
+	if(!nodes) nodes = new Nodes();
+
+	switch(finite_element){
+		case P1Enum:
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			break;
+
+		case P1DGEnum:
+			NodesPartitioning(&my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,false);
+			for(i=0;i<iomodel->numberofelements;i++){
+				for(j=0;j<3;j++){
+					if(my_nodes[3*i+j]){ 
+						nodes->AddObject(new Node(iomodel->nodecounter+3*i+j+1,iomodel->nodecounter+3*i+j,lid++,iomodel->elements[+3*i+j]-1,iomodel,analysis,approximation));
+
+					}
+				}
+			}
+			break;
+
+		case P1bubbleEnum:
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,approximation));
+				}
+			}
+			break;
+
+		case P1bubblecondensedEnum:
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			for(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,analysis,approximation);
+					node->Deactivate();
+					nodes->AddObject(node);
+				}
+			}
+			break;
+
+		case P1xP2Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+
+			counter = iomodel->numberofvertices;
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(iomodel->edges[i*3+2]==2){
+					if(my_edges[i]){
+						node = new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,counter+1,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+					}
+					counter++;
+				}
+			}
+			break;
+		case P2xP1Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+
+			counter = iomodel->numberofvertices;
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(iomodel->edges[i*3+2]!=2){
+					if(my_edges[i]){
+						node = new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,counter+1,lid++,0,iomodel,analysis,approximation);
+						nodes->AddObject(node);
+					}
+					counter++;
+				}
+			}
+			break;
+
+		case P2Enum:
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,analysis,approximation));
+				}
+			}
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(my_edges[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,approximation));
+				}
+			}
+			break;
+
+		/*Stokes elements*/
+		case P1P1Enum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P1 velocity*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			/*P1 pressure*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,i,iomodel,analysis,FSpressureEnum));
+				}
+			}
+			break;
+		case P1P1GLSEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P1 velocity*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			/*P1 pressure*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,i,iomodel,analysis,FSpressureEnum));
+				}
+			}
+			break;
+		case MINIcondensedEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P1+ velocity (bubble statically condensed)*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			for(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,analysis,FSvelocityEnum);
+					node->Deactivate();
+					nodes->AddObject(node);
+				}
+			}
+			/*P1 pressure*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,iomodel->numberofvertices+iomodel->numberofelements+i,lid++,i,iomodel,analysis,FSpressureEnum));
+				}
+			}
+			break;
+		case MINIEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P1+ velocity*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			for(i=0;i<iomodel->numberofelements;i++){
+				if(iomodel->my_elements[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			/*P1 pressure*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofelements+i+1,iomodel->numberofvertices+iomodel->numberofelements+i,lid++,i,iomodel,analysis,FSpressureEnum));
+				}
+			}
+			break;
+		case TaylorHoodEnum:
+			_assert_(approximation==FSApproximationEnum);
+			/*P2 velocity*/
+			EdgesPartitioning(&my_edges,iomodel);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,lid++,i,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+			for(i=0;i<iomodel->numberofedges;i++){
+				if(my_edges[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+iomodel->numberofvertices+i+1,iomodel->numberofvertices+i,lid++,0,iomodel,analysis,FSvelocityEnum));
+				}
+			}
+
+			/*P1 pressure*/
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					nodes->AddObject(new Node(iomodel->nodecounter+iomodel->numberofvertices+iomodel->numberofedges+i+1,iomodel->numberofvertices+iomodel->numberofedges+i,lid++,i,iomodel,analysis,FSpressureEnum));
+				}
+			}
+			break;
+
+		default:
+			_error_("Finite element "<<EnumToStringx(finite_element)<<" not supported yet");
+	}
+
+	/*Clean up*/
+	xDelete<bool>(my_edges);
+	xDelete<bool>(my_nodes);
+
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateNumberNodeToElementConnectivity.cpp	(revision 16137)
@@ -20,8 +20,4 @@
 	int vertexid;
 	int elementswidth;
-	int    dim;
-	int    numberofelements;
-	int    numberofvertices;
-	IssmDouble* elements=NULL;
 
 	/*output*/
@@ -31,20 +27,14 @@
 	if(iomodel->numbernodetoelementconnectivity) return;
 
-	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-	elements=iomodel->Data(MeshElementsEnum);
-
 	/*Some checks if debugging*/
-	_assert_(numberofvertices);
-	_assert_(numberofelements);
-	_assert_(elements);
+	_assert_(iomodel->numberofvertices);
+	_assert_(iomodel->numberofelements);
+	_assert_(iomodel->elements);
 
 	/*Allocate ouput*/
-	connectivity=xNewZeroInit<int>(numberofvertices);
+	connectivity=xNewZeroInit<int>(iomodel->numberofvertices);
 
 	/*Get element width (3 or 6)*/
-	if (dim==2){
+	if(iomodel->dim==2){
 		elementswidth=3;
 	}
@@ -54,8 +44,8 @@
 
 	/*Create connectivity table*/
-	for (i=0;i<numberofelements;i++){
+	for (i=0;i<iomodel->numberofelements;i++){
 		for (j=0;j<elementswidth;j++){
-			vertexid=reCast<int>(elements[elementswidth*i+j]);
-			_assert_(vertexid>0 && vertexid-1<numberofvertices);
+			vertexid=iomodel->elements[elementswidth*i+j];
+			_assert_(vertexid>0 && vertexid-1<iomodel->numberofvertices);
 			connectivity[vertexid-1]+=1;
 		}
@@ -64,5 +54,3 @@
 	/*Assign to iomodel*/
 	iomodel->numbernodetoelementconnectivity=connectivity;
-
-	/*Do not free connectivity!!!*/
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 16137)
@@ -45,14 +45,17 @@
 	/*Copy some constants from iomodel */
 	parameters->AddObject(iomodel->CopyConstantObject(MeshDimensionEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIshutterEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsmacayealpattynEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsl1l2Enum));
-	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsstokesEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsSIAEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsSSAEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsL1L2Enum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsHOEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationIsFSEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(FlowequationFeFSEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsOutputFrequencyEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticRestolEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticReltolEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticAbstolEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticIsnewtonEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRestolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceReltolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceAbstolEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceIsnewtonEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceMaxiterEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalancePenaltyFactorEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SteadystateReltolEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SteadystateMaxiterEnum));
@@ -63,9 +66,9 @@
 	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingTimeStepEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(TimesteppingCflCoefficientEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(PrognosticHydrostaticAdjustmentEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(PrognosticStabilizationEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticPenaltyFactorEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(PrognosticMinThicknessEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(PrognosticPenaltyFactorEnum));
+	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));
 	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyFactorEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsLowmemEnum));
@@ -79,8 +82,8 @@
 	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyThresholdEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(ThermalPenaltyLockEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticRiftPenaltyThresholdEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticStokesreconditioningEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticShelfDampeningEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(DiagnosticViscosityOvershootEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceRiftPenaltyThresholdEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceFSreconditioningEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceShelfDampeningEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(StressbalanceViscosityOvershootEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsWaitonlockEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(MeshNumberofelementsEnum));
@@ -90,6 +93,6 @@
 	parameters->AddObject(iomodel->CopyConstantObject(SettingsResultsAsPatchesEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(GroundinglineMigrationEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(TransientIsdiagnosticEnum));
-	parameters->AddObject(iomodel->CopyConstantObject(TransientIsprognosticEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsstressbalanceEnum));
+	parameters->AddObject(iomodel->CopyConstantObject(TransientIsmasstransportEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(TransientIsthermalEnum));
 	parameters->AddObject(iomodel->CopyConstantObject(TransientIsgroundinglineEnum));
@@ -145,8 +148,8 @@
 
 	/*Requested outputs*/
-	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,DiagnosticRequestedOutputsEnum);
-	parameters->AddObject(new IntParam(DiagnosticNumRequestedOutputsEnum,numoutputs));
-	if(numoutputs)parameters->AddObject(new IntVecParam(DiagnosticRequestedOutputsEnum,requestedoutputs,numoutputs));
-	iomodel->DeleteData(requestedoutputs,DiagnosticRequestedOutputsEnum);
+	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,StressbalanceRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(StressbalanceNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new IntVecParam(StressbalanceRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(requestedoutputs,StressbalanceRequestedOutputsEnum);
 
 	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,TransientRequestedOutputsEnum);
@@ -160,8 +163,8 @@
 	iomodel->DeleteData(requestedoutputs,SteadystateRequestedOutputsEnum);
 
-	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,PrognosticRequestedOutputsEnum);
-	parameters->AddObject(new IntParam(PrognosticNumRequestedOutputsEnum,numoutputs));
-	if(numoutputs)parameters->AddObject(new IntVecParam(PrognosticRequestedOutputsEnum,requestedoutputs,numoutputs));
-	iomodel->DeleteData(requestedoutputs,PrognosticRequestedOutputsEnum);
+	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,MasstransportRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(MasstransportNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new IntVecParam(MasstransportRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(requestedoutputs,MasstransportRequestedOutputsEnum);
 
 	/*Deal with mass flux segments: {{{*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateSingleNodeToElementConnectivity.cpp	(revision 16137)
@@ -2,10 +2,4 @@
  * \brief: create connectivity table
  */ 
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
 
 #include "../../shared/shared.h"
@@ -17,11 +11,6 @@
 
 	/*Intermediary*/
-	int i,j;
 	int vertexid;
 	int elementswidth;
-	int    dim;
-	int    numberofelements;
-	int    numberofvertices;
-	IssmDouble* elements=NULL;
 
 	/*output*/
@@ -31,21 +20,15 @@
 	if(iomodel->singlenodetoelementconnectivity) return;
 
-	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-	elements=iomodel->Data(MeshElementsEnum);
-
 	/*Some checks if debugging*/
-	_assert_(numberofvertices);
-	_assert_(numberofelements);
+	_assert_(iomodel->numberofvertices);
+	_assert_(iomodel->numberofelements);
 	_assert_(iomodel->my_elements);
-	_assert_(elements);
+	_assert_(iomodel->elements);
 
 	/*Allocate ouput*/
-	connectivity=xNewZeroInit<int>(numberofvertices);
+	connectivity=xNewZeroInit<int>(iomodel->numberofvertices);
 
 	/*Get element width (3 or 6)*/
-	if (dim==2){
+	if(iomodel->dim==2){
 		elementswidth=3;
 	}
@@ -55,10 +38,10 @@
 
 	/*Create connectivity table*/
-	for (i=0;i<numberofelements;i++){
+	for(int i=0;i<iomodel->numberofelements;i++){
 		/*!! in parallel we do not want the vertex to be connected to an element that is not in its partition!!*/
 		if(iomodel->my_elements[i]){
-			for (j=0;j<elementswidth;j++){
-				vertexid=reCast<int>(elements[elementswidth*i+j]);
-				_assert_(vertexid>0 && vertexid-1<numberofvertices);
+			for(int j=0;j<elementswidth;j++){
+				vertexid=iomodel->elements[elementswidth*i+j];
+				_assert_(vertexid>0 && vertexid-1<iomodel->numberofvertices);
 				connectivity[vertexid-1]=i+1;
 			}
@@ -68,5 +51,3 @@
 	/*Assign to iomodel*/
 	iomodel->singlenodetoelementconnectivity=connectivity;
-
-	/*Do not free connectivity!!!*/
 }
Index: sm/trunk/src/c/modules/ModelProcessorx/Dakota/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# DAKOTA_SOURCES {{{
-set(DAKOTA_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 16137)
@@ -36,5 +36,4 @@
 	char*    name=NULL;
 	int      numberofresponses;
-	int      numberofvertices;
 	int      nrows;
 	int      ncols;
@@ -52,5 +51,4 @@
 		iomodel->Constant(&name,MiscellaneousNameEnum);
 		iomodel->Constant(&numberofresponses,QmuNumberofresponsesEnum);
-		iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 
 		/*name of qmu input, error and output files:{{{*/
@@ -92,8 +90,8 @@
 			ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
 
-			dpart=xNew<double>(numberofvertices);
-			for(i=0;i<numberofvertices;i++)dpart[i]=iomodel->my_vertices[i];
+			dpart=xNew<double>(iomodel->numberofvertices);
+			for(i=0;i<iomodel->numberofvertices;i++)dpart[i]=iomodel->my_vertices[i];
 		}
-		parameters->AddObject(new DoubleVecParam(QmuPartitionEnum,dpart,numberofvertices));
+		parameters->AddObject(new DoubleVecParam(QmuPartitionEnum,dpart,iomodel->numberofvertices));
 		/*}}}*/
 		/*Deal with data needed because of qmu variables: {{{*/
@@ -109,5 +107,5 @@
 
 				/*Add to parameters: */
-				if(nrows==numberofvertices){
+				if(nrows==iomodel->numberofvertices){
 					parameters->AddObject(new DoubleMatParam(StringToEnumx(tag),dakota_parameter,nrows,ncols));
 				}
Index: /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 16137)
@@ -6,99 +6,119 @@
 #include "../../classes/classes.h"
 
-void DistributeNumDofs(DofIndexing* index,int analysis_type,IssmDouble* vertices_type){
+void DistributeNumDofs(DofIndexing* index,int analysis_type,int node_type){
 
 	/*For now, we distribute by analysis_type, later, we will distribute using the analysis_type,
-	 * but also the vertices_type: */
+	 * but also the node_type: */
 
-	int numdofs=2; //default numdofs
-	int* doftype=NULL;
+	int  numdofs = -1;   //default numdofs
+	int *doftype = NULL;
 
 	/*ok, according to analysis type: */
-	if (analysis_type==DiagnosticHorizAnalysisEnum){
-		if (vertices_type[0]==MacAyealApproximationEnum){
+	switch(analysis_type){
+		case StressbalanceAnalysisEnum:
+			switch(node_type){
+				case SSAApproximationEnum:
+					numdofs=2;
+					break;
+				case L1L2ApproximationEnum:
+					numdofs=2;
+					break;
+				case HOApproximationEnum:
+					numdofs=2;
+					break;
+				case SIAApproximationEnum:
+					numdofs=2;
+					break;
+				case FSvelocityEnum:
+					numdofs=3;
+					break;
+				case FSpressureEnum:
+					numdofs=1;
+					break;
+				case NoneApproximationEnum:
+					numdofs=4;
+					break;
+				case SSAHOApproximationEnum:
+					numdofs=4;
+					doftype=xNew<int>(numdofs);
+					doftype[0]=SSAApproximationEnum;
+					doftype[1]=SSAApproximationEnum;
+					doftype[2]=HOApproximationEnum;
+					doftype[3]=HOApproximationEnum;
+					break;
+				case HOFSApproximationEnum:
+					numdofs=5;
+					doftype=xNew<int>(numdofs);
+					doftype[0]=HOApproximationEnum;
+					doftype[1]=HOApproximationEnum;
+					doftype[2]=FSvelocityEnum;
+					doftype[3]=FSvelocityEnum;
+					doftype[4]=FSvelocityEnum;
+					break;
+				case SSAFSApproximationEnum:
+					numdofs=5;
+					doftype=xNew<int>(numdofs);
+					doftype[0]=SSAApproximationEnum;
+					doftype[1]=SSAApproximationEnum;
+					doftype[2]=FSvelocityEnum;
+					doftype[3]=FSvelocityEnum;
+					doftype[4]=FSvelocityEnum;
+					break;
+				default:
+					_error_("Approximationtype " << node_type << " (" << EnumToStringx(node_type) << ") not implemented yet for StressbalanceHoriz");
+
+			}
+			break;
+		case StressbalanceVerticalAnalysisEnum:
+			numdofs=1;
+			break;
+		case StressbalanceSIAAnalysisEnum:
 			numdofs=2;
-		}
-		else if (vertices_type[0]==L1L2ApproximationEnum){
-			numdofs=2;
-		}
-		else if (vertices_type[0]==PattynApproximationEnum){
-			numdofs=2;
-		}
-		else if (vertices_type[0]==HutterApproximationEnum){
-			numdofs=2;
-		}
-		else if (vertices_type[0]==StokesApproximationEnum){
-			numdofs=4;
-		}
-		else if (vertices_type[0]==NoneApproximationEnum){
-			numdofs=4;
-		}
-		else if (vertices_type[0]==MacAyealPattynApproximationEnum){
-			numdofs=4;
-			doftype=xNew<int>(numdofs);
-			doftype[0]=MacAyealApproximationEnum;
-			doftype[1]=MacAyealApproximationEnum;
-			doftype[2]=PattynApproximationEnum;
-			doftype[3]=PattynApproximationEnum;
-		}
-		else if (vertices_type[0]==PattynStokesApproximationEnum){
-			numdofs=6;
-			doftype=xNew<int>(numdofs);
-			doftype[0]=PattynApproximationEnum;
-			doftype[1]=PattynApproximationEnum;
-			doftype[2]=StokesApproximationEnum;
-			doftype[3]=StokesApproximationEnum;
-			doftype[4]=StokesApproximationEnum;
-			doftype[5]=StokesApproximationEnum;
-		}
-		else if (vertices_type[0]==MacAyealStokesApproximationEnum){
-			numdofs=6;
-			doftype=xNew<int>(numdofs);
-			doftype[0]=MacAyealApproximationEnum;
-			doftype[1]=MacAyealApproximationEnum;
-			doftype[2]=StokesApproximationEnum;
-			doftype[3]=StokesApproximationEnum;
-			doftype[4]=StokesApproximationEnum;
-			doftype[5]=StokesApproximationEnum;
-		}
-		else _error_("Approximationtype " << reCast<int>(*vertices_type) << " (" << EnumToStringx(reCast<int>(*vertices_type)) << ") not implemented yet for DiagnosticHoriz");
+			break;
+		case BedSlopeAnalysisEnum:
+			numdofs=1;
+			break;
+		case SurfaceSlopeAnalysisEnum:
+			numdofs=1;
+			break;
+		case ThermalAnalysisEnum:
+			numdofs=1;
+			break;
+		case EnthalpyAnalysisEnum:
+			numdofs=1;
+			break;
+		case HydrologyDCInefficientAnalysisEnum:
+			numdofs=1;
+			break;
+		case HydrologyDCEfficientAnalysisEnum:
+			numdofs=1;
+			break;
+		case HydrologyShreveAnalysisEnum:
+			numdofs=1;
+			break;
+		case MeltingAnalysisEnum:
+			numdofs=1;
+			break;
+		case MasstransportAnalysisEnum:
+			numdofs=1;
+			break;
+		case FreeSurfaceTopAnalysisEnum:
+			numdofs=1;
+			break;
+		case FreeSurfaceBaseAnalysisEnum:
+			numdofs=1;
+			break;
+		case GiaAnalysisEnum:
+			numdofs=1;
+			break;
+		case BalancethicknessAnalysisEnum:
+			numdofs=1;
+			break;
+		case BalancevelocityAnalysisEnum:
+			numdofs=1;
+			break;
+		default:
+			_error_("analysis type: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not implemented yet");
 	}
-	else if (analysis_type==DiagnosticVertAnalysisEnum){
-		numdofs=1;
-	}
-	else if (analysis_type==DiagnosticHutterAnalysisEnum){
-		numdofs=2;
-	}
-	else if (analysis_type==BedSlopeAnalysisEnum || analysis_type==SurfaceSlopeAnalysisEnum){
-		numdofs=1;
-	}
-	else if (analysis_type==ThermalAnalysisEnum){
-		numdofs=1;
-	}
-	else if (analysis_type==EnthalpyAnalysisEnum){
-		numdofs=1;
-	}
-	else if (analysis_type==HydrologyDCInefficientAnalysisEnum){
-		numdofs=1;
-	}
-	else if (analysis_type==HydrologyDCEfficientAnalysisEnum){
-		numdofs=1;
-	}
-	else if (analysis_type==HydrologyShreveAnalysisEnum){
-		numdofs=1;
-	}
-	else if (analysis_type==MeltingAnalysisEnum){
-		numdofs=1;
-	}
-	else if (analysis_type==PrognosticAnalysisEnum){
-		numdofs=1;
-	}
-	else if (analysis_type==GiaAnalysisEnum){
-		numdofs=1;
-	}
-	else if (analysis_type==BalancethicknessAnalysisEnum){
-		numdofs=1;
-	}
-	else _error_("analysis type: " << analysis_type << " (" << EnumToStringx(analysis_type) << ") not implemented yet");
 
 	/*Now initialize the index*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/EdgesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/EdgesPartitioning.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/EdgesPartitioning.cpp	(revision 16137)
@@ -0,0 +1,42 @@
+/*!\file:  EdgesPartitioning.cpp
+ * \brief: partition elements and nodes and vertices
+ */ 
+
+#include <string.h>
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "./ModelProcessorx.h"
+
+void EdgesPartitioning(bool** pmy_edges,IoModel* iomodel){
+
+	/*Intermediaries*/
+	int elementnbe;
+
+	/*Get edges and elements*/
+	CreateEdges(iomodel);
+	_assert_(iomodel->elementtoedgeconnectivity);
+
+	/*Mesh dependent variables*/
+	if(iomodel->dim==2){
+		elementnbe = 3;
+	}
+	else if(iomodel->dim==3){
+		elementnbe = 9;
+	}
+	else{
+		_error_("mesh dimension not supported yet");
+	}
+	/*output: */
+	bool* my_edges=xNewZeroInit<bool>(iomodel->numberofedges);
+
+	for(int i=0;i<iomodel->numberofelements;i++){
+		if(iomodel->my_elements[i]){
+			for(int j=0;j<elementnbe;j++){
+				my_edges[iomodel->elementtoedgeconnectivity[i*elementnbe+j]] = true;
+			}
+		}
+	}
+
+	/*Free data and assign output pointers */
+	*pmy_edges=my_edges;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 16137)
@@ -21,35 +21,28 @@
 	int my_rank;
 	int num_procs;
-	int    numberofelements;
-	int    numberofvertices;
-	int    numberofelements2d;
-	int    numberofvertices2d;
-	int    numlayers;
-	int    numrifts;
-	int    numvertex_pairing;
+	int numberofelements2d;
+	int numberofvertices2d;
+	int numlayers;
+	int numrifts;
+	int numvertex_pairing;
 
 	/*output: */
-	bool* my_elements=NULL;
-	int* my_vertices=NULL;
+	bool *my_elements = NULL;
+	int  *my_vertices = NULL;
 
 	/*intermediary: */
-	int* epart=NULL; //element partitioning.
-	int* npart=NULL; //node partitioning.
-	int  elements_width; //number of columns in elements (2d->3, 3d->6)
-	int  el1,el2;
-	int    dim;
-	IssmDouble* elements=NULL;
-	IssmDouble* elements2d=NULL;
-	IssmDouble* riftinfo=NULL;
-	IssmDouble* vertex_pairing=NULL;
+	int        *epart          = NULL; //element partitioning.
+	int        *npart          = NULL; //node partitioning.
+	int         elements_width;        //number of columns in elements (2d->3, 3d->6)
+	int         el1,el2;
+	int        *elements2d     = NULL;
+	int        *vertex_pairing = NULL;
+	IssmDouble *riftinfo       = NULL;
 
 	/*Get my_rank:*/
-	my_rank=IssmComm::GetRank();
-	num_procs=IssmComm::GetSize();
+	my_rank   = IssmComm::GetRank();
+	num_procs = IssmComm::GetSize();
 
 	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 	iomodel->Constant(&numberofelements2d,MeshNumberofelements2dEnum);
 	iomodel->Constant(&numberofvertices2d,MeshNumberofvertices2dEnum);
@@ -61,22 +54,17 @@
 
 	/*Number of vertices per elements, needed to correctly retrieve data: */
-	if(dim==2) elements_width=3; //tria elements
-	else elements_width=6; //penta elements
-
 	/*Determine parallel partitioning of elements: we use Metis for now. First load the data, then partition*/
-	if(dim==2){
-		/*load elements: */
-		iomodel->FetchData(&elements,NULL,NULL,MeshElementsEnum);
+	if(iomodel->dim==2){
+		elements_width=3; //tria elements
 	}
 	else{
-		/*load elements2d: */
+		elements_width=6; //penta elements
 		iomodel->FetchData(&elements2d,NULL,NULL,MeshElements2dEnum);
 	}
 
-	MeshPartitionx(&epart, &npart,numberofelements,numberofvertices,elements, numberofelements2d,numberofvertices2d,elements2d,numlayers,elements_width, dim,num_procs);
+	MeshPartitionx(&epart,&npart,iomodel->numberofelements,iomodel->numberofvertices,iomodel->elements,numberofelements2d,numberofvertices2d,elements2d,numlayers,elements_width,iomodel->dim,num_procs);
 
-	/*Free elements and elements2d: */
-	iomodel->DeleteData(elements,MeshElementsEnum);
-	iomodel->DeleteData(elements2d,MeshElements2dEnum);
+	/*Free elements2d: */
+	xDelete<int>(elements2d);
 
 	/*Deal with rifts, they have to be included into one partition only, not several: */
@@ -92,10 +80,9 @@
 
 	/*Used later on: */
-	my_vertices=xNewZeroInit<int>(numberofvertices);
-	my_elements=xNewZeroInit<bool>(numberofelements);
+	my_vertices=xNewZeroInit<int>(iomodel->numberofvertices);
+	my_elements=xNewZeroInit<bool>(iomodel->numberofelements);
 
 	/*Start figuring out, out of the partition, which elements belong to this cpu: */
-	iomodel->FetchData(&elements,NULL,NULL,MeshElementsEnum);
-	for (i=0;i<numberofelements;i++){
+	for (i=0;i<iomodel->numberofelements;i++){
 
 		/*!All elements have been partitioned above, only deal with elements for this cpu: */
@@ -108,35 +95,33 @@
 			 into the vertices coordinates. If we start plugging 1 into my_vertices for each index[n][i] (i=0:2), then my_vertices 
 			 will hold which vertices belong to this partition*/
-			my_vertices[reCast<int>(*(elements+elements_width*i+0))-1]=1;
-			my_vertices[reCast<int>(*(elements+elements_width*i+1))-1]=1;
-			my_vertices[reCast<int>(*(elements+elements_width*i+2))-1]=1;
+			my_vertices[iomodel->elements[elements_width*i+0]-1]=1;
+			my_vertices[iomodel->elements[elements_width*i+1]-1]=1;
+			my_vertices[iomodel->elements[elements_width*i+2]-1]=1;
 
 			if(elements_width==6){
-				my_vertices[reCast<int>(*(elements+elements_width*i+3))-1]=1;
-				my_vertices[reCast<int>(*(elements+elements_width*i+4))-1]=1;
-				my_vertices[reCast<int>(*(elements+elements_width*i+5))-1]=1;
+				my_vertices[iomodel->elements[elements_width*i+3]-1]=1;
+				my_vertices[iomodel->elements[elements_width*i+4]-1]=1;
+				my_vertices[iomodel->elements[elements_width*i+5]-1]=1;
 			}
 		}
-	}//for (i=0;i<numberofelements;i++)
-	/*Free data : */
-	iomodel->DeleteData(elements,MeshElementsEnum);
+	}
 
 	/*We might have vertex_pairing in which case, some vertices have to be cloned:
 	 * penpair has 2 nodes that are poointing toward 2 vertices.
 	 * The 2 vertices must be in the same cpu as the penpair*/
-	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,DiagnosticVertexPairingEnum);
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,StressbalanceVertexPairingEnum);
 	for(i=0;i<numvertex_pairing;i++){
-		if(my_vertices[reCast<int>(vertex_pairing[2*i+0])-1] && !my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]){
-			my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]=2; //to know that these elements are not on the partition
+		if(my_vertices[vertex_pairing[2*i+0]-1] && !my_vertices[vertex_pairing[2*i+1]-1]){
+			my_vertices[vertex_pairing[2*i+1]-1]=2; //to know that these elements are not on the partition
 		}
 	}
-	iomodel->DeleteData(vertex_pairing,DiagnosticVertexPairingEnum);
-	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,PrognosticVertexPairingEnum);
+	xDelete<int>(vertex_pairing);
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
 	for(i=0;i<numvertex_pairing;i++){
-		if(my_vertices[reCast<int>(vertex_pairing[2*i+0])-1] && !my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]){
-			my_vertices[reCast<int>(vertex_pairing[2*i+1])-1]=2; //to know that these elements are not on the partition
+		if(my_vertices[vertex_pairing[2*i+0]-1] && !my_vertices[vertex_pairing[2*i+1]-1]){
+			my_vertices[vertex_pairing[2*i+1]-1]=2; //to know that these elements are not on the partition
 		}
 	}
-	iomodel->DeleteData(vertex_pairing,PrognosticVertexPairingEnum);
+	xDelete<int>(vertex_pairing);
 
 	/*Free ressources:*/
Index: sm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# THERMAL_SOURCES {{{
-set(THERMAL_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp
-                          $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp
-                          $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp
-                       $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 16137)
@@ -11,10 +11,8 @@
 
 	/*Intermediary*/
-	int    i,j;
-	int    count;
-	int    dim;
-	int    M,N;
-	int    numberofvertices;
-	bool   spcpresent=false;
+	int        i,j;
+	int        count;
+	int        M,N;
+	bool       spcpresent = false;
 	IssmDouble heatcapacity;
 	IssmDouble referencetemperature;
@@ -26,6 +24,4 @@
 
 	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 	iomodel->Constant(&heatcapacity,MaterialsHeatcapacityEnum);
 	iomodel->Constant(&referencetemperature,ConstantsReferencetemperatureEnum);
@@ -34,12 +30,6 @@
 	Constraints* constraints=*pconstraints;
 
-	/*Create constraints if they do not exist yet*/
-	if(!constraints) constraints = new Constraints();
-
 	/*return if 2d mesh*/
-	if (dim==2){
-		*pconstraints=constraints;
-		return;
-	}
+	if(iomodel->dim==2) return;
 
 	/*Fetch data: */
@@ -48,9 +38,9 @@
 	//FIX ME: SHOULD USE IOMODELCREATECONSTRAINTS 
 	/*Transient or static?:*/
-	if(M==numberofvertices){
+	if(M==iomodel->numberofvertices){
 		/*static: just create Constraints objects*/
 		count=0;
 
-		for (i=0;i<numberofvertices;i++){
+		for(int i=0;i<iomodel->numberofvertices;i++){
 			/*keep only this partition's nodes:*/
 			if((iomodel->my_vertices[i])){
@@ -65,5 +55,5 @@
 		}
 	}
-	else if (M==(numberofvertices+1)){
+	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: */
@@ -72,10 +62,10 @@
 		/*figure out times: */
 		times=xNew<IssmDouble>(N);
-		for(j=0;j<N;j++){
+		for(int j=0;j<N;j++){
 			times[j]=spcvector[(M-1)*N+j];
 		}
 
 		/*Create constraints from x,y,z: */
-		for (i=0;i<numberofvertices;i++){
+		for(int i=0;i<iomodel->numberofvertices;i++){
 
 			/*keep only this partition's nodes:*/
@@ -85,5 +75,5 @@
 				values=xNew<IssmDouble>(N);
 				spcpresent=false;
-				for(j=0;j<N;j++){
+				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
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 16137)
@@ -9,11 +9,4 @@
 void	CreateLoadsEnthalpy(Loads** ploads, IoModel* iomodel){
 
-	/*Recover pointer: */
-	Loads* loads=*ploads;
-
-	/*Create loads if they do not exist yet*/
-	if(!loads) loads = new Loads();
-
-	/*Assign output pointer: */
-	*ploads=loads;
+	/*No loads */
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 16137)
@@ -11,37 +11,6 @@
 void	CreateNodesEnthalpy(Nodes** pnodes, IoModel* iomodel){
 
-	/*Intermediary*/
-	int i;
-	bool continuous_galerkin=true;
-	int    numberofvertices;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-
-	/*Recover pointer: */
-	Nodes* nodes=*pnodes;
-
-	/*Create nodes if they do not exist yet*/
-	if(!nodes) nodes = new Nodes();
-
-	/*Continuous Galerkin partition of nodes: */
-	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-
-	/*Create nodes and vertices: */
-	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	for (i=0;i<numberofvertices;i++){
-		if(iomodel->my_vertices[i]){
-
-			/*Add node to nodes dataset: */
-			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,EnthalpyAnalysisEnum));
-
-		}
-	}
-
-	/*Clean fetched data: */
-	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	/*Assign output pointer: */
-	*pnodes=nodes;
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,EnthalpyAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 16137)
@@ -11,23 +11,16 @@
 void	UpdateElementsEnthalpy(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
 
-	int    dim;
-	int    numberofelements;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-
 	/*Now, is the model 3d? otherwise, do nothing: */
-	if(dim==2)return;
+	if(iomodel->dim==2)return;
 
 	/*Fetch data needed: */
-	iomodel->FetchData(4,MeshElementsEnum,TemperatureEnum,WaterfractionEnum,PressureEnum);
+	iomodel->FetchData(3,TemperatureEnum,WaterfractionEnum,PressureEnum);
 
 	/*Update elements: */
 	int counter=0;
-	for(int i=0;i<numberofelements;i++){
+	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); //we need i to index into elements.
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
 			counter++;
 		}
@@ -40,8 +33,8 @@
 	iomodel->FetchDataToInput(elements,FrictionPEnum);
 	iomodel->FetchDataToInput(elements,FrictionQEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
 	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
 	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
@@ -51,4 +44,6 @@
 	iomodel->FetchDataToInput(elements,WaterfractionEnum);
 	iomodel->FetchDataToInput(elements,BasalforcingsGeothermalfluxEnum);
+	iomodel->FetchDataToInput(elements,WatercolumnEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,VxEnum);
 	iomodel->FetchDataToInput(elements,VyEnum);
@@ -56,4 +51,4 @@
 
 	/*Free data: */
-	iomodel->DeleteData(4,MeshElementsEnum,TemperatureEnum,WaterfractionEnum,PressureEnum);
+	iomodel->DeleteData(3,TemperatureEnum,WaterfractionEnum,PressureEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/FacesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/FacesPartitioning.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/FacesPartitioning.cpp	(revision 16137)
@@ -0,0 +1,42 @@
+/*!\file:  FacesPartitioning.cpp
+ * \brief: partition elements and nodes and vertices
+ */ 
+
+#include <string.h>
+#include "../../classes/classes.h"
+#include "../../shared/shared.h"
+#include "./ModelProcessorx.h"
+
+void FacesPartitioning(bool** pmy_faces,IoModel* iomodel){
+
+	/*Intermediaries*/
+	int  el1,el2;
+	bool my_face;
+
+	/*Check Iomodel properties*/
+	if(iomodel->dim!=2) _error_("only 2d model are supported");
+
+	/*Get faces and elements*/
+	CreateFaces(iomodel);
+
+	/*output: */
+	bool* my_faces=xNew<bool>(iomodel->numberoffaces);
+
+	for(int i=0;i<iomodel->numberoffaces;i++){
+
+		/*Get left and right elements*/
+		el1=iomodel->faces[4*i+2]-1; //faces are [node1 node2 elem1 elem2]
+		el2=iomodel->faces[4*i+3]-1; //faces are [node1 node2 elem1 elem2]
+
+		/*Check whether we should include this face (el2 is -2 for boundary faces)*/
+		my_face = iomodel->my_elements[el1];
+		if(!my_face && el2>=0){
+			my_face = iomodel->my_elements[el2];
+		}
+
+		my_faces[i] = my_face;
+	}
+
+	/*Free data and assign output pointers */
+	*pmy_faces=my_faces;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/CreateConstraintsFreeSurfaceBase.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/CreateConstraintsFreeSurfaceBase.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/CreateConstraintsFreeSurfaceBase.cpp	(revision 16137)
@@ -0,0 +1,10 @@
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+#include "../../IoModelToConstraintsx/IoModelToConstraintsx.h"
+
+void	CreateConstraintsFreeSurfaceBase(Constraints** pconstraints, IoModel* iomodel){
+
+	/*No constraints*/
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/CreateLoadsFreeSurfaceBase.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/CreateLoadsFreeSurfaceBase.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/CreateLoadsFreeSurfaceBase.cpp	(revision 16137)
@@ -0,0 +1,54 @@
+/*! \file CreateLoadsFreeSurfaceBase.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsFreeSurfaceBase(Loads** ploads, IoModel* iomodel){
+
+	/*Intermediaries*/
+	int element;
+	int penpair_ids[2];
+	int count=0;
+	int numvertex_pairing;
+
+	/*Recover pointer: */
+	Loads* loads=*ploads;
+
+	/*Create Penpair for vertex_pairing: */
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonbed=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	iomodel->FetchData(&nodeonbed,NULL,NULL,MeshVertexonbedEnum);
+	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(!(reCast<bool>(nodeonbed[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonbed[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(nodeonbed,MeshVertexonbedEnum);
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/CreateNodesFreeSurfaceBase.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/CreateNodesFreeSurfaceBase.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/CreateNodesFreeSurfaceBase.cpp	(revision 16137)
@@ -0,0 +1,17 @@
+/*
+ * CreateNodesFreeSurfaceBase.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesFreeSurfaceBase(Nodes** pnodes, IoModel* iomodel){
+
+	/*Create Nodes either DG or CG depending on stabilization*/
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,FreeSurfaceBaseAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/UpdateElementsFreeSurfaceBase.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/UpdateElementsFreeSurfaceBase.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceBase/UpdateElementsFreeSurfaceBase.cpp	(revision 16137)
@@ -0,0 +1,42 @@
+/*
+ * UpdateElementsFreeSurfaceBase:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsFreeSurfaceBase(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    finiteelement;
+	bool   dakota_analysis;
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if (iomodel->dim==2)return;
+
+	/*Finite element type*/
+	finiteelement = P1Enum;
+
+	/*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++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateCorrectionEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,VzEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/CreateConstraintsFreeSurfaceTop.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/CreateConstraintsFreeSurfaceTop.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/CreateConstraintsFreeSurfaceTop.cpp	(revision 16137)
@@ -0,0 +1,10 @@
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+#include "../../IoModelToConstraintsx/IoModelToConstraintsx.h"
+
+void	CreateConstraintsFreeSurfaceTop(Constraints** pconstraints, IoModel* iomodel){
+
+	/*No constraints*/
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/CreateLoadsFreeSurfaceTop.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/CreateLoadsFreeSurfaceTop.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/CreateLoadsFreeSurfaceTop.cpp	(revision 16137)
@@ -0,0 +1,54 @@
+/*! \file CreateLoadsFreeSurfaceTop.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsFreeSurfaceTop(Loads** ploads, IoModel* iomodel){
+
+	/*Intermediaries*/
+	int element;
+	int penpair_ids[2];
+	int count=0;
+	int numvertex_pairing;
+
+	/*Recover pointer: */
+	Loads* loads=*ploads;
+
+	/*Create Penpair for vertex_pairing: */
+	IssmDouble *vertex_pairing=NULL;
+	IssmDouble *nodeonsurface=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	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(!(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);
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/CreateNodesFreeSurfaceTop.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/CreateNodesFreeSurfaceTop.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/CreateNodesFreeSurfaceTop.cpp	(revision 16137)
@@ -0,0 +1,17 @@
+/*
+ * CreateNodesFreeSurfaceTop.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesFreeSurfaceTop(Nodes** pnodes, IoModel* iomodel){
+
+	/*Create Nodes either DG or CG depending on stabilization*/
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,FreeSurfaceTopAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/UpdateElementsFreeSurfaceTop.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/UpdateElementsFreeSurfaceTop.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/FreeSurfaceTop/UpdateElementsFreeSurfaceTop.cpp	(revision 16137)
@@ -0,0 +1,41 @@
+/*
+ * UpdateElementsFreeSurfaceTop:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsFreeSurfaceTop(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    finiteelement;
+	bool   dakota_analysis;
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if (iomodel->dim==2)return;
+
+	finiteelement = P1Enum;
+
+	/*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++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateCorrectionEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,VzEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+}
Index: sm/trunk/src/c/modules/ModelProcessorx/Gia/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Gia/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# SLOPE_SOURCES {{{
-set(SLOPE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Gia/CreateConstraintsGia.cpp
-                        $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Gia/CreateLoadsGia.cpp
-                        $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Gia/CreateNodesGia.cpp
-                     $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Gia/UpdateElementsGia.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateConstraintsGia.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateConstraintsGia.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateConstraintsGia.cpp	(revision 16137)
@@ -10,11 +10,5 @@
 void	CreateConstraintsGia(Constraints** pconstraints, IoModel* iomodel){
 
-	/*Recover pointer: */
-	Constraints* constraints=*pconstraints;
+	/*No constraints*/
 
-	/*Create constraints if they do not exist yet*/
-	if(!constraints) constraints = new Constraints();
-
-	/*Assign output pointer: */
-	*pconstraints=constraints;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateLoadsGia.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateLoadsGia.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateLoadsGia.cpp	(revision 16137)
@@ -9,11 +9,5 @@
 void	CreateLoadsGia(Loads** ploads, IoModel* iomodel){
 
-	/*Recover pointer: */
-	Loads* loads=*ploads;
+	/*No loads*/
 
-	/*Create loads if they do not exist yet*/
-	if(!loads) loads = new Loads();
-
-	/*Assign output pointer: */
-	*ploads=loads;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateNodesGia.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateNodesGia.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Gia/CreateNodesGia.cpp	(revision 16137)
@@ -10,39 +10,4 @@
 
 void	CreateNodesGia(Nodes** pnodes, IoModel* iomodel){
-
-	/*Intermediary*/
-	int i;
-	bool continuous_galerkin=true;
-
-	/*Fetch parameters: */
-	int    numberofvertices;
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-
-	/*Recover pointer: */
-	Nodes* nodes=*pnodes;
-
-	/*Create nodes if they do not exist yet*/
-	if(!nodes) nodes = new Nodes();
-
-	/*Continuous Galerkin partition of nodes: */
-	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-
-	/*First fetch data: */
-	iomodel->FetchData(1,MaskVertexonwaterEnum);
-
-	/*First fetch data: */
-	for (i=0;i<numberofvertices;i++){
-		if(iomodel->my_vertices[i]){
-
-			/*Add node to nodes dataset: */
-			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,GiaAnalysisEnum));
-
-		}
-	}
-
-	/*Clean fetched data: */
-	iomodel->DeleteData(1,MaskVertexonwaterEnum);
-
-	/*Assign output pointer: */
-	*pnodes=nodes;
+	CreateNodes(pnodes,iomodel,GiaAnalysisEnum,P1Enum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Gia/UpdateElementsGia.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Gia/UpdateElementsGia.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Gia/UpdateElementsGia.cpp	(revision 16137)
@@ -11,20 +11,10 @@
 void	UpdateElementsGia(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
 
-	int    dim;
-	int    numberofelements;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-
-	/*Fetch data needed: */
-	iomodel->FetchData(1,MeshElementsEnum);
-
 	/*Update elements: */
 	int counter=0;
-	for(int i=0;i<numberofelements;i++){
+	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); //we need i to index into elements.
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
 			counter++;
 		}
@@ -35,6 +25,3 @@
 	iomodel->FetchDataToInput(elements,GiaLithosphereThicknessEnum);
 
-	/*Free data: */
-	iomodel->DeleteData(1,MeshElementsEnum);
-
 }
Index: sm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# HYDROLOGY_SOURCES {{{
-set(HYDROLOGY_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateConstraintsHydrologyDCEfficient.cpp
-                         $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateLoadsHydrologyDCEfficient.cpp
-                         $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateNodesHydrologyDCEfficient.cpp
-                         $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyDCEfficient/UpdateElementsHydrologyDCEfficient.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateConstraintsHydrologyDCEfficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateConstraintsHydrologyDCEfficient.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateConstraintsHydrologyDCEfficient.cpp	(revision 16137)
@@ -12,26 +12,17 @@
 
 	/*Recover pointer: */
-	bool         isefficientlayer;
-	int          hydrology_model;
 	Constraints* constraints=*pconstraints;
 
-	/*Create constraints if they do not exist yet*/
-	if(!constraints) constraints = new Constraints();
-
 	/*Do we really want DC?*/
+	int  hydrology_model;
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
-	if(hydrology_model!=HydrologydcEnum){
-		*pconstraints=constraints;
-		return;
-	}
+	if(hydrology_model!=HydrologydcEnum) return;
 
 	/*Do we want an efficient layer*/
+	bool isefficientlayer;
 	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
-	if(!isefficientlayer){
-		*pconstraints=constraints;
-		return;
-	}
+	if(!isefficientlayer) return;
 
-	IoModelToConstraintsx(constraints,iomodel,HydrologydcSpceplHeadEnum,HydrologyDCEfficientAnalysisEnum);
+	IoModelToConstraintsx(constraints,iomodel,HydrologydcSpceplHeadEnum,HydrologyDCEfficientAnalysisEnum,P1Enum);
 
 	/*Assign output pointer: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateLoadsHydrologyDCEfficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateLoadsHydrologyDCEfficient.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateLoadsHydrologyDCEfficient.cpp	(revision 16137)
@@ -9,32 +9,16 @@
 void	CreateLoadsHydrologyDCEfficient(Loads** ploads, IoModel* iomodel){
 
-	/*Intermediary*/
-	bool     isefficientlayer;
-	int      hydrology_model;
-	int      numberofvertices;
-	Pengrid *pengrid = NULL;
-
 	/*Recover pointer: */
 	Loads* loads=*ploads;
 
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-
-	/*Create loads if they do not exist yet*/
-	if(!loads) loads = new Loads();
-
 	/*Do we really want DC?*/
+	int  hydrology_model;
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
-	if(hydrology_model!=HydrologydcEnum){
-		*ploads=loads;
-		return;
-	}
+	if(hydrology_model!=HydrologydcEnum) return;
 
 	/*Do we want an efficient layer*/
+	bool isefficientlayer;
 	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
-	if(!isefficientlayer){
-		*ploads=loads;
-		return;
-	}
+	if(!isefficientlayer) return;
 
 	/*Nothing for now*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateNodesHydrologyDCEfficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateNodesHydrologyDCEfficient.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/CreateNodesHydrologyDCEfficient.cpp	(revision 16137)
@@ -11,50 +11,16 @@
 void	CreateNodesHydrologyDCEfficient(Nodes** pnodes, IoModel* iomodel){
 
-	/*Intermediary*/
-	int  i;
-	bool isefficientlayer;
-	bool continuous_galerkin=true;
+	/*Now, do we really want DC?*/
 	int  hydrology_model;
-	int  numberofvertices;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-
-	/*Recover pointer: */
-	Nodes* nodes=*pnodes;
-
-	/*Create nodes if they do not exist yet*/
-	if(!nodes) nodes = new Nodes();
-
-	/*Now, do we really want DC?*/
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
-	if(hydrology_model!=HydrologydcEnum){
-		*pnodes=nodes;
-		return;
-	}
+	if(hydrology_model!=HydrologydcEnum) return;
 
 	/*Do we want an efficient layer*/
+	bool isefficientlayer;
 	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
-	if(!isefficientlayer){
-		*pnodes=nodes;
-		return;
-	}
+	if(!isefficientlayer) return;
 
-	/*Continuous Galerkin partition of nodes: */
-	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-
-	/*Create nodes and vertices: */
-	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-	for (i=0;i<numberofvertices;i++){
-
-		if(iomodel->my_vertices[i]){
-			/*Add node to nodes dataset: */
-			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,HydrologyDCEfficientAnalysisEnum));
-
-		}
-	}
-	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	/*Assign output pointer: */
-	*pnodes=nodes;
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,HydrologyDCEfficientAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/UpdateElementsHydrologyDCEfficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/UpdateElementsHydrologyDCEfficient.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCEfficient/UpdateElementsHydrologyDCEfficient.cpp	(revision 16137)
@@ -13,8 +13,4 @@
 	bool   isefficientlayer;
 	int    hydrology_model;
-	int    numberofelements;
-
-	/*Fetch data needed: */
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
 
 	/*Now, do we really want DC?*/
@@ -26,13 +22,10 @@
 	if(!isefficientlayer) return;
 
-	/*Fetch data needed: */
-	iomodel->FetchData(1,MeshElementsEnum);
-
 	/*Update elements: */
 	int counter=0;
-	for(int i=0;i<numberofelements;i++){
+	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); //we need i to index into elements.
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
 			counter++;
 		}
@@ -42,12 +35,8 @@
 	iomodel->FetchDataToInput(elements,SurfaceEnum);
 	iomodel->FetchDataToInput(elements,BedEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
 	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,EplHeadEnum);
-
-	/*Free data: */
-	iomodel->DeleteData(1,MeshElementsEnum);
 }
Index: sm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# HYDROLOGY_SOURCES {{{
-set(HYDROLOGY_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateConstraintsHydrologyDCInefficient.cpp
-                         $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateLoadsHydrologyDCInefficient.cpp
-                         $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateNodesHydrologyDCInefficient.cpp
-                         $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyDCInefficient/UpdateElementsHydrologyDCInefficient.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateConstraintsHydrologyDCInefficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateConstraintsHydrologyDCInefficient.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateConstraintsHydrologyDCInefficient.cpp	(revision 16137)
@@ -12,19 +12,12 @@
 
 	/*Recover pointer: */
-	int          hydrology_model;
 	Constraints* constraints=*pconstraints;
 
 	/*retrieve some parameters: */
+	int hydrology_model;
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
 
-	/*Create constraints if they do not exist yet*/
-	if(!constraints) constraints = new Constraints();
-
-	if(hydrology_model!=HydrologydcEnum){
-		*pconstraints=constraints;
-		return;
-	}
-
-	IoModelToConstraintsx(constraints,iomodel,HydrologydcSpcsedimentHeadEnum,HydrologyDCInefficientAnalysisEnum);
+	IoModelToConstraintsx(constraints,iomodel,HydrologydcSpcsedimentHeadEnum,HydrologyDCInefficientAnalysisEnum,P1Enum);
 
 	/*Assign output pointer: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateLoadsHydrologyDCInefficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateLoadsHydrologyDCInefficient.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateLoadsHydrologyDCInefficient.cpp	(revision 16137)
@@ -9,37 +9,31 @@
 void	CreateLoadsHydrologyDCInefficient(Loads** ploads, IoModel* iomodel){
 
-	/*Intermediary*/
-	int      hydrology_model;
-	int      numberofvertices;
-	Pengrid *pengrid = NULL;
-
 	/*Recover pointer: */
 	Loads* loads=*ploads;
 
 	/*Fetch parameters: */
+	int hydrology_model;
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	if(hydrology_model!=HydrologydcEnum) return;
 
-	/*Create loads if they do not exist yet*/
-	if(!loads) loads = new Loads();
-
-	if(hydrology_model!=HydrologydcEnum){
-		*ploads=loads;
-		return;
-	}
+	iomodel->FetchData(1,MeshVertexonbedEnum);
 
 	//create penalties for nodes: no node can have a temperature over the melting point
-	iomodel->FetchData(1,MeshElementsEnum);
 	CreateSingleNodeToElementConnectivity(iomodel);
-
-	for(int i=0;i<numberofvertices;i++){
-		/*keep only this partition's nodes:*/
-		if((iomodel->my_vertices[i]==1)){
-			loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,HydrologyDCInefficientAnalysisEnum));
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		if (iomodel->dim==3){
+			/*keep only this partition's nodes:*/
+			if((iomodel->my_vertices[i]==1)){
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,HydrologyDCInefficientAnalysisEnum));
+			}
+		}
+		else if(reCast<int>(iomodel->Data(MeshVertexonbedEnum)[i])){
+			if((iomodel->my_vertices[i]==1)){
+				loads->AddObject(new Pengrid(iomodel->loadcounter+i+1,i,iomodel,HydrologyDCInefficientAnalysisEnum));
+			}	
 		}
 	}
-	iomodel->DeleteData(1,MeshElementsEnum);
-
 	/*Assign output pointer: */
 	*ploads=loads;
+	iomodel->DeleteData(1,MeshVertexonbedEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateNodesHydrologyDCInefficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateNodesHydrologyDCInefficient.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/CreateNodesHydrologyDCInefficient.cpp	(revision 16137)
@@ -11,42 +11,13 @@
 void	CreateNodesHydrologyDCInefficient(Nodes** pnodes, IoModel* iomodel){
 
-	/*Intermediary*/
-	int  i;
-	bool continuous_galerkin=true;
+	/*Fetch parameters: */
 	int  hydrology_model;
-	int  numberofvertices;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
 
-	/*Recover pointer: */
-	Nodes* nodes=*pnodes;
+	/*Now, do we really want DC?*/
+	if(hydrology_model!=HydrologydcEnum) return;
 
-	/*Create nodes if they do not exist yet*/
-	if(!nodes) nodes = new Nodes();
-
-	/*Now, do we really want DC?*/
-	if(hydrology_model!=HydrologydcEnum){
-		*pnodes=nodes;
-		return;
-	}
-
-	/*Continuous Galerkin partition of nodes: */
-	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-
-	/*Create nodes and vertices: */
-	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-	for (i=0;i<numberofvertices;i++){
-
-		if(iomodel->my_vertices[i]){
-			/*Add node to nodes dataset: */
-			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,HydrologyDCInefficientAnalysisEnum));
-
-		}
-	}
-	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	/*Assign output pointer: */
-	*pnodes=nodes;
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,HydrologyDCInefficientAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/UpdateElementsHydrologyDCInefficient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/UpdateElementsHydrologyDCInefficient.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyDCInefficient/UpdateElementsHydrologyDCInefficient.cpp	(revision 16137)
@@ -13,9 +13,7 @@
 	bool   isefficientlayer;
 	int    hydrology_model;
-	int    numberofelements;
 
 	/*Fetch data needed: */
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
 
 	/*Now, do we really want DC?*/
@@ -24,12 +22,11 @@
 	/*Fetch data needed: */
 	iomodel->Constant(&isefficientlayer,HydrologydcIsefficientlayerEnum);
-	iomodel->FetchData(1,MeshElementsEnum);
 
 	/*Update elements: */
 	int counter=0;
-	for(int i=0;i<numberofelements;i++){
+	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); //we need i to index into elements.
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
 			counter++;
 		}
@@ -39,13 +36,9 @@
 	iomodel->FetchDataToInput(elements,SurfaceEnum);
 	iomodel->FetchDataToInput(elements,BedEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
 	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,SedimentHeadEnum);
 	if(isefficientlayer)iomodel->FetchDataToInput(elements,HydrologydcMaskEplactiveEnum);
-
-	/*Free data: */
-	iomodel->DeleteData(1,MeshElementsEnum);
 }
Index: sm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# HYDROLOGY_SOURCES {{{
-set(HYDROLOGY_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyShreve/CreateConstraintsHydrologyShreve.cpp
-                            $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyShreve/CreateLoadsHydrologyShreve.cpp
-                            $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyShreve/CreateNodesHydrologyShreve.cpp
-                         $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/HydrologyShreve/UpdateElementsHydrologyShreve.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateConstraintsHydrologyShreve.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateConstraintsHydrologyShreve.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateConstraintsHydrologyShreve.cpp	(revision 16137)
@@ -12,20 +12,13 @@
 
 	/*Recover pointer: */
-	int          hydrology_model;
-	bool         isefficientlayer;
 	Constraints* constraints=*pconstraints;
 
 	/*retrieve some parameters: */
+	int          hydrology_model;
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
 
-	/*Create constraints if they do not exist yet*/
-	if(!constraints) constraints = new Constraints();
+	if(hydrology_model!=HydrologyshreveEnum) return;
 
-	if(hydrology_model!=HydrologyshreveEnum){
-		*pconstraints=constraints;
-		return;
-	}
-
-	IoModelToConstraintsx(constraints,iomodel,HydrologyshreveSpcwatercolumnEnum,HydrologyShreveAnalysisEnum);
+	IoModelToConstraintsx(constraints,iomodel,HydrologyshreveSpcwatercolumnEnum,HydrologyShreveAnalysisEnum,P1Enum);
 
 	/*Assign output pointer: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateLoadsHydrologyShreve.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateLoadsHydrologyShreve.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateLoadsHydrologyShreve.cpp	(revision 16137)
@@ -9,15 +9,5 @@
 void	CreateLoadsHydrologyShreve(Loads** ploads, IoModel* iomodel){
 
-	/*Intermediary*/
-	int      numberofvertices;
-	Pengrid *pengrid = NULL;
+	/*No loads*/
 
-	/*Recover pointer: */
-	Loads* loads=*ploads;
-
-	/*Create loads if they do not exist yet*/
-	if(!loads) loads = new Loads();
-
-	/*Assign output pointer: */
-	*ploads=loads;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateNodesHydrologyShreve.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateNodesHydrologyShreve.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/CreateNodesHydrologyShreve.cpp	(revision 16137)
@@ -11,41 +11,13 @@
 void	CreateNodesHydrologyShreve(Nodes** pnodes, IoModel* iomodel){
 
-	/*Intermediary*/
-	int  i;
+	/*Fetch parameters: */
 	int  hydrology_model;
-	bool continuous_galerkin=true;
-	int  numberofvertices;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
 
-	/*Recover pointer: */
-	Nodes* nodes=*pnodes;
+	/*Now, do we really want Shreve?*/
+	if(hydrology_model!=HydrologyshreveEnum) return;
 
-	/*Create nodes if they do not exist yet*/
-	if(!nodes) nodes = new Nodes();
-
-	/*Now, do we really want Shreve?*/
-	if(hydrology_model!=HydrologyshreveEnum){
-		*pnodes=nodes;
-		return;
-	}
-
-	/*Continuous Galerkin partition of nodes: */
-	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-
-	/*Create nodes and vertices: */
-	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-	for (i=0;i<numberofvertices;i++){
-
-		if(iomodel->my_vertices[i]){
-			/*Add node to nodes dataset: */
-			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,HydrologyShreveAnalysisEnum));
-		}
-	}
-	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	/*Assign output pointer: */
-	*pnodes=nodes;
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,HydrologyShreveAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/UpdateElementsHydrologyShreve.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/UpdateElementsHydrologyShreve.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/HydrologyShreve/UpdateElementsHydrologyShreve.cpp	(revision 16137)
@@ -12,22 +12,17 @@
 
 	int    hydrology_model;
-	int    numberofelements;
 
 	/*Fetch data needed: */
 	iomodel->Constant(&hydrology_model,HydrologyModelEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
 
 	/*Now, do we really want Shreve?*/
 	if(hydrology_model!=HydrologyshreveEnum) return;
 
-	/*Fetch data needed: */
-	iomodel->FetchData(1,MeshElementsEnum);
-
 	/*Update elements: */
 	int counter=0;
-	for(int i=0;i<numberofelements;i++){
+	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); //we need i to index into elements.
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
 			counter++;
 		}
@@ -37,14 +32,11 @@
 	iomodel->FetchDataToInput(elements,SurfaceEnum);
 	iomodel->FetchDataToInput(elements,BedEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
 	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,WatercolumnEnum);
 
 	elements->InputDuplicate(WatercolumnEnum,WaterColumnOldEnum);
-
-	/*Free data: */
-	iomodel->DeleteData(1,MeshElementsEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/CreateConstraintsMasstransport.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/CreateConstraintsMasstransport.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/CreateConstraintsMasstransport.cpp	(revision 16137)
@@ -0,0 +1,23 @@
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+#include "../../IoModelToConstraintsx/IoModelToConstraintsx.h"
+
+void	CreateConstraintsMasstransport(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Fetch parameters: */
+	int stabilization;
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Recover pointer: */
+	Constraints* constraints=*pconstraints;
+
+	/*Do not add constraints in DG, they are weakly imposed*/
+	if(stabilization!=3){
+		IoModelToConstraintsx(constraints,iomodel,MasstransportSpcthicknessEnum,MasstransportAnalysisEnum,P1Enum);
+	}
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/CreateLoadsMasstransport.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/CreateLoadsMasstransport.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/CreateLoadsMasstransport.cpp	(revision 16137)
@@ -0,0 +1,83 @@
+/*! \file CreateLoadsMasstransport.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsMasstransport(Loads** ploads, IoModel* iomodel){
+
+	/*Intermediaries*/
+	int element;
+	int penpair_ids[2];
+	int count=0;
+	int stabilization;
+	int numvertex_pairing;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Recover pointer: */
+	Loads* loads=*ploads;
+
+	/*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 *nodeonbed=NULL;
+	iomodel->FetchData(&vertex_pairing,&numvertex_pairing,NULL,MasstransportVertexPairingEnum);
+	iomodel->FetchData(&nodeonbed,NULL,NULL,MeshVertexonbedEnum);
+
+	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(!(reCast<bool>(nodeonbed[reCast<int>(vertex_pairing[2*i+0])-1])) || !(reCast<bool>(nodeonbed[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(nodeonbed,MeshVertexonbedEnum);
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/CreateNodesMasstransport.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/CreateNodesMasstransport.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/CreateNodesMasstransport.cpp	(revision 16137)
@@ -0,0 +1,29 @@
+/*
+ * CreateNodesMasstransport.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesMasstransport(Nodes** pnodes, IoModel* iomodel){
+
+	/*Fetch parameters: */
+	int  stabilization;
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+
+	/*Check in 3d*/
+	if(stabilization==3 && iomodel->dim==3) _error_("DG 3d not implemented yet");
+
+	/*Create Nodes either DG or CG depending on stabilization*/
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	if(stabilization!=3){
+		CreateNodes(pnodes,iomodel,MasstransportAnalysisEnum,P1Enum);
+	}
+	else{
+		CreateNodes(pnodes,iomodel,MasstransportAnalysisEnum,P1DGEnum);
+	}
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/UpdateElementsMasstransport.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/UpdateElementsMasstransport.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Masstransport/UpdateElementsMasstransport.cpp	(revision 16137)
@@ -0,0 +1,99 @@
+/*
+ * UpdateElementsMasstransport:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsMasstransport(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    stabilization,finiteelement;
+	bool   dakota_analysis;
+	bool   issmbgradients;
+	bool   ispdd;
+	bool   isdelta18o;
+
+	/*Fetch data needed: */
+	iomodel->Constant(&stabilization,MasstransportStabilizationEnum);
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
+	iomodel->Constant(&ispdd,SurfaceforcingsIspddEnum);
+	iomodel->Constant(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+	iomodel->Constant(&issmbgradients,SurfaceforcingsIssmbgradientsEnum);
+
+	/*Finite element type*/
+	finiteelement = P1Enum;
+	if(stabilization==3){
+		finiteelement = P1DGEnum;
+	}
+
+	/*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++;
+		}
+	}
+
+	iomodel->FetchDataToInput(elements,ThicknessEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,BathymetryEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateCorrectionEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+
+	if(stabilization==3){
+		iomodel->FetchDataToInput(elements,MasstransportSpcthicknessEnum); //for DG, we need the spc in the element
+	}
+
+	if(dakota_analysis){
+		elements->InputDuplicate(BedEnum,QmuBedEnum);
+		elements->InputDuplicate(ThicknessEnum,QmuThicknessEnum);
+		elements->InputDuplicate(SurfaceEnum,QmuSurfaceEnum);
+		elements->InputDuplicate(BasalforcingsMeltingRateEnum,QmuMeltingEnum);
+		elements->InputDuplicate(VxEnum,QmuVxEnum);
+		elements->InputDuplicate(VyEnum,QmuVyEnum);
+	}
+
+	if(iomodel->dim==3){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+		iomodel->FetchDataToInput(elements,PressureEnum);
+		iomodel->FetchDataToInput(elements,TemperatureEnum);
+		iomodel->FetchDataToInput(elements,VzEnum);
+		if(dakota_analysis){
+			elements->InputDuplicate(PressureEnum,QmuPressureEnum);
+			elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
+			elements->InputDuplicate(VzEnum,QmuVzEnum);
+		}
+	}
+	if(issmbgradients){
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsHrefEnum);
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsSmbrefEnum);
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsBPosEnum);
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsBNegEnum);
+	}
+	if(ispdd){
+		iomodel->FetchDataToInput(elements,ThermalSpctemperatureEnum);
+		if(isdelta18o){
+			iomodel->FetchDataToInput(elements,SurfaceforcingsTemperaturesLgmEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsTemperaturesPresentdayEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationsPresentdayEnum);
+		}
+		else{
+			iomodel->FetchDataToInput(elements,SurfaceforcingsPrecipitationEnum);
+			iomodel->FetchDataToInput(elements,SurfaceforcingsMonthlytemperaturesEnum);
+		}
+	}
+	if(~ispdd & ~issmbgradients){
+		iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	}
+}
Index: sm/trunk/src/c/modules/ModelProcessorx/Melting/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# THERMAL_SOURCES {{{
-set(THERMAL_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp
-                          $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp
-                          $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp
-                       $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 16137)
@@ -10,11 +10,5 @@
 void	CreateConstraintsMelting(Constraints** pconstraints, IoModel* iomodel){
 
-	/*Recover pointer: */
-	Constraints* constraints=*pconstraints;
+	/*No constraints*/
 
-	/*Create constraints if they do not exist yet*/
-	if(!constraints) constraints = new Constraints();
-
-	/*Assign output pointer: */
-	*pconstraints=constraints;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 16137)
@@ -9,24 +9,15 @@
 void	CreateLoadsMelting(Loads** ploads, IoModel* iomodel){
 
-	/*Intermediary*/
-	int dim;
-	int numberofvertices;
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-
 	/*if 2d: Error*/
-	if (dim==2) _error_("2d meshes not supported yet");
+	if(iomodel->dim==2) _error_("2d meshes not supported yet");
 
 	/*Recover pointer: */
 	Loads* loads=*ploads;
 
-	/*Create loads if they do not exist yet*/
-	if(!loads) loads = new Loads();
-
 	//create penalties for nodes: no node can have a temperature over the melting point
-	iomodel->FetchData(2,MeshVertexonbedEnum,MeshElementsEnum);
+	iomodel->FetchData(1,MeshVertexonbedEnum);
 	CreateSingleNodeToElementConnectivity(iomodel);
 
-	for(int i=0;i<numberofvertices;i++){
+	for(int i=0;i<iomodel->numberofvertices;i++){
 		if((iomodel->my_vertices[i]==1)){
 			if (reCast<int>(iomodel->Data(MeshVertexonbedEnum)[i])){
@@ -35,5 +26,5 @@
 		}
 	}
-	iomodel->DeleteData(2,MeshVertexonbedEnum,MeshElementsEnum);
+	iomodel->DeleteData(1,MeshVertexonbedEnum);
 
 	/*Assign output pointer: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 16137)
@@ -11,35 +11,6 @@
 void	CreateNodesMelting(Nodes** pnodes, IoModel* iomodel){
 
-	/*Intermediary*/
-	int i;
-	bool continuous_galerkin=true;
-	int    numberofvertices;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-
-	/*Recover pointer: */
-	Nodes* nodes=*pnodes;
-
-	/*Create nodes if they do not exist yet*/
-	if(!nodes) nodes = new Nodes();
-
-	/*Continuous Galerkin partition of nodes: */
-	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-
-	/*First fetch data: */
-	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-	for (i=0;i<numberofvertices;i++){
-
-		if(iomodel->my_vertices[i]){
-
-			/*Add node to nodes dataset: */
-			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,MeltingAnalysisEnum));
-
-		}
-	}
-	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	/*Assign output pointer: */
-	*pnodes=nodes;
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,MeltingAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 16137)
@@ -11,23 +11,13 @@
 void	UpdateElementsMelting(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
 
-	int    dim;
-	int    numberofelements;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-
 	/*Now, is the model 3d? otherwise, do nothing: */
-	if (dim==2)return;
-
-	/*Fetch data needed: */
-	iomodel->FetchData(1,MeshElementsEnum);
+	if(iomodel->dim==2)return;
 
 	/*Update elements: */
 	int counter=0;
-	for(int i=0;i<numberofelements;i++){
+	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); //we need i to index into elements.
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
 			counter++;
 		}
@@ -41,8 +31,7 @@
 	iomodel->FetchDataToInput(elements,FrictionPEnum);
 	iomodel->FetchDataToInput(elements,FrictionQEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
 	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
 	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
@@ -50,6 +39,3 @@
 	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,PressureEnum);
-
-	/*Free data: */
-	iomodel->DeleteData(1,MeshElementsEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 16137)
@@ -15,6 +15,6 @@
 void ModelProcessorx(Elements** pelements, Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads, Parameters** pparameters, FILE* IOMODEL,char* rootpath,const int solution_type,const int nummodels,const int* analysis_type_list){
 
-	int   i,analysis_type,dim,verbose;
-	bool  isthermal,isprognostic,isdiagnostic,isgroundingline,isenthalpy;
+	int   i,analysis_type,verbose;
+	bool  isthermal,ismasstransport,isstressbalance,isgroundingline,isenthalpy;
 
 	/*output: */
@@ -31,10 +31,9 @@
 
 	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
 	iomodel->Constant(&verbose,VerboseEnum);
 	iomodel->Constant(&isthermal,TransientIsthermalEnum);
 	iomodel->Constant(&isenthalpy,ThermalIsenthalpyEnum);
-	iomodel->Constant(&isprognostic,TransientIsprognosticEnum);
-	iomodel->Constant(&isdiagnostic,TransientIsdiagnosticEnum);
+	iomodel->Constant(&ismasstransport,TransientIsmasstransportEnum);
+	iomodel->Constant(&isstressbalance,TransientIsstressbalanceEnum);
 	iomodel->Constant(&isgroundingline,TransientIsgroundinglineEnum);
 
@@ -48,7 +47,7 @@
 
 		/*Hack for trasient runs (FIXME: to be improved)*/
-		if(solution_type==TransientSolutionEnum && analysis_type==ThermalAnalysisEnum && dim==2) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==MeltingAnalysisEnum && dim==2) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==EnthalpyAnalysisEnum && dim==2) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==ThermalAnalysisEnum  && iomodel->dim==2) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==MeltingAnalysisEnum  && iomodel->dim==2) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==EnthalpyAnalysisEnum && iomodel->dim==2) continue;
 		if(solution_type==TransientSolutionEnum && analysis_type==ThermalAnalysisEnum && isthermal==false) continue;
 		if(solution_type==TransientSolutionEnum && analysis_type==MeltingAnalysisEnum && isthermal==false) continue;
@@ -57,8 +56,8 @@
 		if(solution_type==TransientSolutionEnum && analysis_type==MeltingAnalysisEnum && isenthalpy==true) continue;
 		if(solution_type==TransientSolutionEnum && analysis_type==EnthalpyAnalysisEnum && isenthalpy==false) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==PrognosticAnalysisEnum && isprognostic==false && isgroundingline==false) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==DiagnosticHorizAnalysisEnum && isdiagnostic==false) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==DiagnosticVertAnalysisEnum && isdiagnostic==false) continue;
-		if(solution_type==TransientSolutionEnum && analysis_type==DiagnosticHutterAnalysisEnum && isdiagnostic==false) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==MasstransportAnalysisEnum && ismasstransport==false && isgroundingline==false) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==StressbalanceAnalysisEnum && isstressbalance==false) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==StressbalanceVerticalAnalysisEnum && isstressbalance==false) continue;
+		if(solution_type==TransientSolutionEnum && analysis_type==StressbalanceSIAAnalysisEnum && isstressbalance==false) continue;
 		if(solution_type==SteadystateSolutionEnum && analysis_type==ThermalAnalysisEnum && isenthalpy==true) continue;
 		if(solution_type==SteadystateSolutionEnum && analysis_type==MeltingAnalysisEnum && isenthalpy==true) continue;
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 16137)
@@ -13,118 +13,139 @@
 
 /*Creation of fem datasets: general drivers*/
-void  CreateDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,const int nummodels,int analysis_counter);
-void  CreateElementsVerticesAndMaterials(Elements** pelements,Vertices** pvertices,Materials** pmaterials, IoModel* iomodel,const int nummodels);
-void  CreateParameters(Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,int analysis_counter);
-void  CreateParametersAutodiff(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
-void  CreateParametersControl(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
-void  CreateParametersDakota(Parameters** pparameters,IoModel* iomodel,char* rootpath,int solution_type,int analysis_type);
-void  CreateParametersHydrologyShreve(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
-void  CreateParametersHydrologyDCInefficient(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
-void  CreateParametersHydrologyDCEfficient(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
-void  UpdateElementsAndMaterialsControl(Elements* elements,Materials* materials, IoModel* iomodel);
+void CreateDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,const int nummodels,int analysis_counter);
+void CreateElementsVerticesAndMaterials(Elements** pelements,Vertices** pvertices,Materials** pmaterials, IoModel* iomodel,const int nummodels);
+void CreateParameters(Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,int analysis_counter);
+void CreateParametersAutodiff(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
+void CreateParametersControl(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
+void CreateParametersDakota(Parameters** pparameters,IoModel* iomodel,char* rootpath,int solution_type,int analysis_type);
+void CreateParametersHydrologyShreve(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
+void CreateParametersHydrologyDCInefficient(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
+void CreateParametersHydrologyDCEfficient(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type);
+void UpdateElementsAndMaterialsControl(Elements* elements,Materials* materials, IoModel* iomodel);
+void CreateNodes(Nodes** pnodes, IoModel* iomodel,int analysis,int finite_element,int approximation=NoneApproximationEnum);
 
 /*Creation of fem datasets: specialised drivers: */
 
-/*diagnostic horizontal*/
-void	CreateNodesDiagnosticHoriz(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsDiagnosticHoriz(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsDiagnosticHoriz(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsDiagnosticHoriz(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+/*stressbalance horizontal*/
+void CreateNodesStressbalance(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsStressbalance(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsStressbalance(Loads** ploads, IoModel* iomodel);
+void UpdateElementsStressbalance(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
-/*diagnostic vertical*/
-void	CreateNodesDiagnosticVert(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsDiagnosticVert(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsDiagnosticVert(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsDiagnosticVert(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+/*stressbalance vertical*/
+void CreateNodesStressbalanceVertical(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsStressbalanceVertical(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsStressbalanceVertical(Loads** ploads, IoModel* iomodel);
+void UpdateElementsStressbalanceVertical(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
-/*diagnostic hutter*/
-void	CreateNodesDiagnosticHutter(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsDiagnosticHutter(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsDiagnosticHutter(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsDiagnosticHutter(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+/*stressbalance SIA*/
+void CreateNodesStressbalanceSIA(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsStressbalanceSIA(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsStressbalanceSIA(Loads** ploads, IoModel* iomodel);
+void UpdateElementsStressbalanceSIA(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
 #ifdef _HAVE_GIA_
 /*gia*/
-void	CreateNodesGia(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsGia(Constraints** pconstraints,IoModel* iomodel);
-void    CreateLoadsGia(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsGia(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesGia(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsGia(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsGia(Loads** ploads, IoModel* iomodel);
+void UpdateElementsGia(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 #endif
 
 /*bed slope*/
-void	CreateNodesBedSlope(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsBedSlope(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsBedSlope(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsBedSlope(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesBedSlope(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsBedSlope(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsBedSlope(Loads** ploads, IoModel* iomodel);
+void UpdateElementsBedSlope(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
 /*surface slope*/
-void	CreateNodesSurfaceSlope(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsSurfaceSlope(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsSurfaceSlope(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsSurfaceSlope(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesSurfaceSlope(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsSurfaceSlope(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsSurfaceSlope(Loads** ploads, IoModel* iomodel);
+void UpdateElementsSurfaceSlope(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
 /*thermal:*/
-void	CreateNodesThermal(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsThermal(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsThermal(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsThermal(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesThermal(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsThermal(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsThermal(Loads** ploads, IoModel* iomodel);
+void UpdateElementsThermal(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
 /*enthalpy:*/
-void	CreateNodesEnthalpy(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsEnthalpy(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsEnthalpy(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsEnthalpy(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesEnthalpy(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsEnthalpy(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsEnthalpy(Loads** ploads, IoModel* iomodel);
+void UpdateElementsEnthalpy(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
 /*hydrology Shreve:*/
-void	CreateNodesHydrologyShreve(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsHydrologyShreve(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsHydrologyShreve(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsHydrologyShreve(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesHydrologyShreve(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsHydrologyShreve(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsHydrologyShreve(Loads** ploads, IoModel* iomodel);
+void UpdateElementsHydrologyShreve(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
 /*hydrology DC:*/
-void	CreateNodesHydrologyDCInefficient(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsHydrologyDCInefficient(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsHydrologyDCInefficient(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsHydrologyDCInefficient(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
-void	CreateNodesHydrologyDCEfficient(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsHydrologyDCEfficient(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsHydrologyDCEfficient(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsHydrologyDCEfficient(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesHydrologyDCInefficient(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsHydrologyDCInefficient(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsHydrologyDCInefficient(Loads** ploads, IoModel* iomodel);
+void UpdateElementsHydrologyDCInefficient(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesHydrologyDCEfficient(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsHydrologyDCEfficient(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsHydrologyDCEfficient(Loads** ploads, IoModel* iomodel);
+void UpdateElementsHydrologyDCEfficient(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
 /*melting:*/
-void	CreateNodesMelting(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsMelting(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsMelting(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsMelting(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesMelting(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsMelting(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsMelting(Loads** ploads, IoModel* iomodel);
+void UpdateElementsMelting(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
-/*prognostic:*/
-void	CreateNodesPrognostic(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsPrognostic(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsPrognostic(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsPrognostic(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+/*masstransport:*/
+void CreateNodesMasstransport(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsMasstransport(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsMasstransport(Loads** ploads, IoModel* iomodel);
+void UpdateElementsMasstransport(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesFreeSurfaceTop(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsFreeSurfaceTop(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsFreeSurfaceTop(Loads** ploads, IoModel* iomodel);
+void UpdateElementsFreeSurfaceTop(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesFreeSurfaceBase(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsFreeSurfaceBase(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsFreeSurfaceBase(Loads** ploads, IoModel* iomodel);
+void UpdateElementsFreeSurfaceBase(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
 /*balancedthickness:*/
-void	CreateNodesBalancethickness(Nodes** pnodes,IoModel* iomodel);
-void	CreateConstraintsBalancethickness(Constraints** pconstraints,IoModel* iomodel);
-void  CreateLoadsBalancethickness(Loads** ploads, IoModel* iomodel);
-void	UpdateElementsBalancethickness(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+void CreateNodesBalancethickness(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsBalancethickness(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsBalancethickness(Loads** ploads, IoModel* iomodel);
+void UpdateElementsBalancethickness(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
+
+/*balancedvelocity:*/
+void CreateNodesBalancevelocity(Nodes** pnodes,IoModel* iomodel);
+void CreateConstraintsBalancevelocity(Constraints** pconstraints,IoModel* iomodel);
+void CreateLoadsBalancevelocity(Loads** ploads, IoModel* iomodel);
+void UpdateElementsBalancevelocity(Elements* elements,IoModel* iomodel,int analysis_counter,int analysis_type);
 
 /*transient: */
-void	UpdateElementsTransient(Elements* elements,Parameters* parameters,IoModel* iomodel,int analysis_counter,int analysis_type);
+void UpdateElementsTransient(Elements* elements,Parameters* parameters,IoModel* iomodel,int analysis_counter,int analysis_type);
 
 /*partitioning: */
-void  ElementsAndVerticesPartitioning(bool** pmy_elements, int** pmy_vertices, IoModel* iomodel);
-void  NodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices,  IoModel* iomodel, bool continuous);
+void ElementsAndVerticesPartitioning(bool** pmy_elements, int** pmy_vertices, IoModel* iomodel);
+void NodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices,  IoModel* iomodel, bool continuous);
+void FacesPartitioning(bool** pmy_faces,IoModel* iomodel);
+void EdgesPartitioning(bool** pmy_edges,IoModel* iomodel);
+
+/*Mesh properties*/
+void CreateFaces(IoModel* iomodel);
+void CreateEdges(IoModel* iomodel);
 
 /*Connectivity*/
-void  CreateSingleNodeToElementConnectivity(IoModel* iomodel);
-void  CreateNumberNodeToElementConnectivity(IoModel* iomodel);
+void CreateSingleNodeToElementConnectivity(IoModel* iomodel);
+void CreateNumberNodeToElementConnectivity(IoModel* iomodel);
 
 /*Diverse: */
-void  SortDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Loads** ploads, Materials** pmaterials, Constraints** pconstraints, Parameters** pparameters);
-void  UpdateCounters(IoModel* iomodel,Nodes** pnodes,Loads** ploads, Constraints** pconstraints);
+void SortDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Loads** ploads, Materials** pmaterials, Constraints** pconstraints, Parameters** pparameters);
+void UpdateCounters(IoModel* iomodel,Nodes** pnodes,Loads** ploads, Constraints** pconstraints);
 
 /*Distribution of dofs: */
-void DistributeNumDofs(DofIndexing* index,int analysis_type,IssmDouble* vertices_type);
+void DistributeNumDofs(DofIndexing* index,int analysis_type,int node_type);
 
 #endif
Index: /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 16137)
@@ -20,8 +20,4 @@
 void  NodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel, bool continuous){
 
-	/*First thing, this is a new partition for a new analysis_type, therefore, to avoid a leak, erase the nodes partition that might come through pmy_nodes: */
-	xDelete<bool>(*pmy_nodes);
-
-	/*Now, depending on whether we are running galerkin discontinous or continuous elements, carry out a different partition of the nodes: */
 	if(continuous==true)
 		ContinuousGalerkinNodesPartitioning(pmy_nodes,my_elements, my_vertices, iomodel);
@@ -32,15 +28,7 @@
 void  ContinuousGalerkinNodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel){
 
-	/*as many nodes as there are vertices */
-	int    numberofvertices;
-
 	/*output: */
-	bool* my_nodes=NULL;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-
-	my_nodes=xNew<bool>(numberofvertices);
-	for(int i=0;i<numberofvertices;i++) my_nodes[i]=(bool)my_vertices[i];
+	bool* my_nodes=xNew<bool>(iomodel->numberofvertices);
+	for(int i=0;i<iomodel->numberofvertices;i++) my_nodes[i]=(bool)my_vertices[i];
 
 	/*Assign output pointers:*/
@@ -50,45 +38,34 @@
 void  DiscontinuousGalerkinNodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel){
 
-	int    numberofelements;
+	/* Each element has it own nodes (as many as vertices) + additional nodes
+	 * from neighboring elements for each face. This yields to a very different
+	 * partition for the nodes and the vertices. The vertices are similar to
+	 * continuous galerkin, but the nodes partitioning involves faces, which
+	 * messes up sorting of ids. */
 
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-
-	/*each element has it own nodes (as many as vertices) + additional nodes from neighbouring elements for each edge. This yields to a very different partition for 
-	 * the nodes and the vertices. The vertices are similar to continuous galerkin, but the nodes partitioning involves edges, which mess up sorting of 
-	 * ids. */
-
-	int i,j;
-	int    dim;
-
-	/*output: */
-	bool*   my_nodes=NULL;
-
-	int  i1,i2;
+	/*Intermediaries*/
+	int  i,i1,i2;
 	int  cols;
 	int  e1,e2;
 	int  pos;
-	int  numberofedges;
-	int *edges         = NULL;
-	int *elements      = NULL;
 
-	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
+	/*Get faces and elements*/
+	CreateEdges(iomodel);
 
 	/*Build discontinuous node partitioning
 	 *  - there are three nodes per element (discontinous)
 	 *  - for each element present of each partition, its three nodes will be in this partition
-	 *  - the edges require the dofs of the 2 nodes of each elements sharing the edge.
-	 *    if the 2 elements sharing the edge are on 2 different cpus, we must duplicate
-	 *    the two nodes that are not on the cpus so that the edge can access the dofs of
+	 *  - the faces require the dofs of the 2 nodes of each elements sharing the face.
+	 *    if the 2 elements sharing the face are on 2 different cpus, we must duplicate
+	 *    the two nodes that are not on the cpus so that the face can access the dofs of
 	 *    all its 4 nodes
 	 */
 
 	/*Allocate*/
-	my_nodes=xNewZeroInit<bool>(3*numberofelements);
+	bool* my_nodes=xNewZeroInit<bool>(3*iomodel->numberofelements);
 
 	/*First: add all the nodes of all the elements belonging to this cpu*/
-	if (dim==2){
-		for (i=0;i<numberofelements;i++){
+	if(iomodel->dim==2){
+		for (i=0;i<iomodel->numberofelements;i++){
 			if (my_elements[i]){
 				my_nodes[3*i+0]=true;
@@ -104,18 +81,16 @@
 	/*Second: add all missing nodes*/
 
-	/*Get edges and elements*/
-	iomodel->FetchData(&edges,&numberofedges,&cols,MeshEdgesEnum);
-	iomodel->FetchData(&elements,NULL,NULL,MeshElementsEnum);
-	if (cols!=4) _error_("field edges should have 4 columns");
+	/*Get faces and elements*/
+	CreateFaces(iomodel);
 
 	/*!All elements have been partitioned above, only create elements for this CPU: */
-	for (i=0;i<numberofedges;i++){
+	for(int i=0;i<iomodel->numberoffaces;i++){
 
 		/*Get left and right elements*/
-		e1=edges[4*i+2]-1; //edges are [node1 node2 elem1 elem2]
-		e2=edges[4*i+3]-1; //edges are [node1 node2 elem1 elem2]
+		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 edge of the element is shared by another element (internal edge)
+		 * 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)
@@ -124,16 +99,16 @@
 
 			/*1: Get vertices ids*/
-			i1=edges[4*i+0];
-			i2=edges[4*i+1];
+			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(j=0;j<3;j++){
-				if (elements[3*e2+j]==i1) pos=j;
+			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){
+			if(pos==0){
 				my_nodes[e2*3+0]=true;
 				my_nodes[e2*3+2]=true;
@@ -143,19 +118,15 @@
 				my_nodes[e2*3+0]=true;
 			}
-			else if (pos==2){
+			else if(pos==2){
 				my_nodes[e2*3+2]=true;
 				my_nodes[e2*3+1]=true;
 			}
 			else{
-				_error_("Problem in edges creation");
+				_error_("Problem in faces creation");
 			}
 		}
 	}
 
-	/*Free data: */
-	xDelete<int>(elements);
-	xDelete<int>(edges);
-
-	/*Assign output pointers:*/
+	/*Free data and assign output pointers */
 	*pmy_nodes=my_nodes;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 16137)
@@ -15,31 +15,31 @@
 void SortDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Loads** ploads, Materials** pmaterials, Constraints** pconstraints, Parameters** pparameters){
 
-	Elements* elements=NULL;
-	Nodes* nodes=NULL;
-	Vertices* vertices=NULL;
-	Loads* loads=NULL;
-	Materials* materials=NULL;
-	Constraints* constraints=NULL;
-	Parameters* parameters=NULL;
+	Elements    *elements    = NULL;
+	Nodes       *nodes       = NULL;
+	Vertices    *vertices    = NULL;
+	Loads       *loads       = NULL;
+	Materials   *materials   = NULL;
+	Constraints *constraints = NULL;
+	Parameters  *parameters  = NULL;
 
 	/*Recover pointers: */
-	elements=*pelements;
-	nodes=*pnodes;
-	vertices=*pvertices;
-	loads=*ploads;
-	materials=*pmaterials;
-	constraints=*pconstraints;
-	parameters=*pparameters;
+	elements    = *pelements;
+	nodes       = *pnodes;
+	vertices    = *pvertices;
+	loads       = *ploads;
+	materials   = *pmaterials;
+	constraints = *pconstraints;
+	parameters  = *pparameters;
 
-	/*All our datasets are already ordered by ids. Set presort flag so that later on, when sorting is requested on these 
-	 * datasets, it will not be redone: */
-
-	if(elements)elements->Presort();
-	if(nodes)nodes->Presort();
-	if(vertices)vertices->Presort();
-	if(loads)loads->Presort();
-	if(materials)materials->Presort();
-	if(constraints)constraints->Presort();
-	if(parameters)parameters->Presort();
+	/*All our datasets are already ordered by ids. Set presort flag so that
+	 * later on, when sorting is requested on these datasets, it will not be
+	 * redone: */
+	if(elements)    elements->Presort();
+	if(nodes)       nodes->Presort();
+	if(vertices)    vertices->Presort();
+	if(loads)       loads->Presort();
+	if(materials)   materials->Presort();
+	if(constraints) constraints->Presort();
+	if(parameters)  parameters->Presort();
 
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/CreateConstraintsStressbalance.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/CreateConstraintsStressbalance.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/CreateConstraintsStressbalance.cpp	(revision 16137)
@@ -0,0 +1,426 @@
+/*
+ * CreateConstraintsStressbalance.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../IoModelToConstraintsx/IoModelToConstraintsx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsStressbalance(Constraints** pconstraints, 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 *nodeonbed      = 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;
+
+	/*Output*/
+	Constraints *constraints      = NULL;
+	SpcStatic   *spcstatic        = 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);
+
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Now, is the flag macayaealHO on? otherwise, do nothing: */
+	if(!isSSA & !isHO & !isFS & !isL1L2){
+		*pconstraints=constraints;
+		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;
+				default: _error_("finite element "<<finiteelement<<" not supported");
+			}
+		}
+
+		IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvxEnum,StressbalanceAnalysisEnum,finiteelement,1);
+		IoModelToConstraintsx(constraints,iomodel,StressbalanceSpcvyEnum,StressbalanceAnalysisEnum,finiteelement,2);
+
+		if(isFS){
+
+			/*Constraint at the bedrock interface (v.n = vz = 0) (Coordinates will be updated according to the bed slope)*/
+			iomodel->FetchData(&spcvz,&Mz,&Nz,StressbalanceSpcvzEnum);
+			iomodel->FetchData(&vertices_type,NULL,NULL,FlowequationVertexEquationEnum);
+			iomodel->FetchData(&nodeonFS,NULL,NULL,FlowequationBorderFSEnum);
+			iomodel->FetchData(&nodeonbed,NULL,NULL,MeshVertexonbedEnum);
+			iomodel->FetchData(&groundedice_ls,NULL,NULL,MaskGroundediceLevelsetEnum);
+			for(i=0;i<iomodel->numberofvertices;i++){
+				if(iomodel->my_vertices[i]){
+					if(nodeonbed[i]>0. && groundedice_ls[i]>0. && nodeonFS[i]>0.){
+						if(vertices_type[i] == FSApproximationEnum){
+							for(j=0;j<Nz;j++) spcvz[i*Nz+j] = 0.;
+						}
+						else{
+							_error_("not supported");
+						}
+					}
+				}
+			}
+			IoModelToConstraintsx(constraints,iomodel,spcvz,Mz,Nz,StressbalanceAnalysisEnum,finiteelement,3);
+			iomodel->DeleteData(spcvz,StressbalanceSpcvzEnum);
+			iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+			iomodel->DeleteData(nodeonFS,FlowequationBorderFSEnum);
+			iomodel->DeleteData(nodeonbed,MeshVertexonbedEnum);
+			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 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,1,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,1,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum));
+								count++;
+							}
+						}
+					}
+					break;
+				default:
+					_error_("not implemented yet");
+			}
+			iomodel->DeleteData(vertices_type,FlowequationVertexEquationEnum);
+			iomodel->DeleteData(surface,SurfaceEnum);
+			iomodel->DeleteData(z,MeshZEnum);
+		}
+
+		*pconstraints=constraints;
+		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->dim==3)iomodel->FetchData(&nodeonHO,NULL,NULL,FlowequationBorderHOEnum);
+	if(iomodel->dim==3)iomodel->FetchData(&nodeonFS,NULL,NULL,FlowequationBorderFSEnum);
+	if(iomodel->dim==3)iomodel->FetchData(&nodeonbed,NULL,NULL,MeshVertexonbedEnum);
+	if(iomodel->dim==3)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,1,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,2,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,3,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,4,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,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,1,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,2,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,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++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,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,1,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,2,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,1,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,2,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,3,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,4,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,5,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,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++;
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,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,1,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,2,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,1,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,2,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,3,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,4,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,5,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,1,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,1,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,1,StressbalanceAnalysisEnum));
+					count++;
+				}
+
+				if (My==iomodel->numberofvertices && !xIsNan<IssmDouble>(spcvy[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,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,2,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,2,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,3,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,3,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,1,g*rho_ice*(surface[i]-z[i])/FSreconditioning,StressbalanceAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+					count++;
+				}
+			}
+
+			/*Constraint at the bedrock interface (v.n = vz = 0) (Coordinates will be updated according to the bed slope)*/
+			if (iomodel->dim==3) if(nodeonbed[i]>0. && groundedice_ls[i]>=0. && nodeonFS[i]>0.){
+				 switch(reCast<int,IssmDouble>(vertices_type[i])){
+					case SSAFSApproximationEnum:
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0.,StressbalanceAnalysisEnum));
+						count++;
+						break;
+					case HOFSApproximationEnum:
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,5,0.,StressbalanceAnalysisEnum));
+						count++;
+						break;
+					case FSApproximationEnum:
+						constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,3,0.,StressbalanceAnalysisEnum));
+						count++;
+						break;
+					default: _error_("Vertex approximation " << EnumToStringx(reCast<int,IssmDouble>(vertices_type[i])) << " not supported");
+				}
+			}
+		}
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(spcvx,StressbalanceSpcvxEnum);
+	iomodel->DeleteData(spcvy,StressbalanceSpcvyEnum);
+	iomodel->DeleteData(spcvz,StressbalanceSpcvzEnum);
+	iomodel->DeleteData(nodeonSSA,FlowequationBorderSSAEnum);
+	if(iomodel->dim==3)iomodel->DeleteData(nodeonHO,FlowequationBorderHOEnum);
+	if(iomodel->dim==3)iomodel->DeleteData(nodeonFS,FlowequationBorderFSEnum);
+	if(iomodel->dim==3)iomodel->DeleteData(nodeonbed,MeshVertexonbedEnum);
+	if(iomodel->dim==3)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);
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/CreateLoadsStressbalance.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/CreateLoadsStressbalance.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/CreateLoadsStressbalance.cpp	(revision 16137)
@@ -0,0 +1,90 @@
+/*! \file CreateLoadsStressbalance.c:
+ */
+#include <string.h>
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsStressbalance(Loads** ploads, IoModel* iomodel){
+
+	/*DataSets*/
+	Pengrid   *pengrid   = NULL;
+
+	/*Intermediary*/
+	int         segment_width;
+	int         element;
+	int         i;
+	int         count;
+	int         penpair_ids[2];
+	bool        isSSA,isL1L2,isHO,isFS;
+	int         numpenalties,numberofpressureloads,numrifts,numriftsegments;
+	IssmDouble *pressureload   = NULL;
+	IssmDouble *elements_type  = NULL;
+	IssmDouble *nodeoniceshelf = NULL;
+	IssmDouble *riftinfo       = NULL;
+	IssmDouble *nodeonbed      = NULL;
+	IssmDouble *nodeonFS   = NULL;
+	IssmDouble *nodeonicesheet = NULL;
+	IssmDouble *vertices_type  = 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);
+
+	/*Recover pointer: */
+	Loads* loads=*ploads;
+
+	/*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: */
+	#ifdef _HAVE_RIFTS_
+	if(numrifts){
+		iomodel->FetchData(&riftinfo,&numriftsegments,NULL,RiftsRiftstructEnum);
+		iomodel->FetchData(5,RiftsRiftstructEnum,ThicknessEnum,BedEnum,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,BedEnum,SurfaceEnum,MaskGroundediceLevelsetEnum);
+		xDelete<IssmDouble>(riftinfo);
+	}
+	#endif
+
+	/*Assign output pointer: */
+	*ploads=loads;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/CreateNodesStressbalance.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/CreateNodesStressbalance.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/CreateNodesStressbalance.cpp	(revision 16137)
@@ -0,0 +1,110 @@
+/*
+ * CreateNodesStressbalance.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesStressbalance(Nodes** pnodes, 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(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+		CreateNodes(pnodes,iomodel,StressbalanceAnalysisEnum,finiteelement,approximation);
+		iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+	}
+	else{
+		/*Coupling: we are going to create P1 Elements only*/
+
+		/*Recover nodes*/
+		Nodes* nodes = *pnodes;
+		Node*  node  = NULL;
+		int    lid=0;
+		if(!nodes) nodes = new Nodes();
+
+		iomodel->FetchData(6,MeshVertexonbedEnum,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,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+					FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+
+		/*Assign output pointer: */
+		*pnodes=nodes;
+	}
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/UpdateElementsStressbalance.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/UpdateElementsStressbalance.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Stressbalance/UpdateElementsStressbalance.cpp	(revision 16137)
@@ -0,0 +1,144 @@
+/*
+ * UpdateElementsStressbalance:
+ */
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsStressbalance(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	int    materials_type,finiteelement;
+	int    approximation;
+	int*   finiteelement_list=NULL;
+	bool   isSSA,isL1L2,isHO,isFS,iscoupling;
+	bool   control_analysis;
+	bool   dakota_analysis;
+
+	/*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);
+
+	/*Now, is the flag macayaealHO on? otherwise, do nothing: */
+	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;
+
+	/*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,GeometryHydrostaticRatioEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,FrictionCoefficientEnum);
+	iomodel->FetchDataToInput(elements,FrictionPEnum);
+	iomodel->FetchDataToInput(elements,FrictionQEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
+	iomodel->FetchDataToInput(elements,MaterialsRheologyNEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+	iomodel->FetchDataToInput(elements,LoadingforceXEnum);
+	iomodel->FetchDataToInput(elements,LoadingforceYEnum);
+	if(materials_type==MatdamageiceEnum){
+		iomodel->FetchDataToInput(elements,MaterialsRheologyZEnum);
+	}
+	if(iomodel->dim==3){
+		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+		iomodel->FetchDataToInput(elements,VzEnum);
+		iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+		iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+		iomodel->FetchDataToInput(elements,FlowequationBorderFSEnum);
+		iomodel->FetchDataToInput(elements,LoadingforceZEnum);
+	}
+
+	if(control_analysis){
+		iomodel->FetchDataToInput(elements,InversionVxObsEnum);
+		iomodel->FetchDataToInput(elements,InversionVyObsEnum);
+	}
+
+	/*Post-process: */
+	elements->InputDuplicate(VxEnum,VxPicardEnum);
+	elements->InputDuplicate(VxEnum,InversionVxObsEnum);
+	if(dakota_analysis)elements->InputDuplicate(VxEnum,QmuVxEnum);
+
+	#ifdef _HAVE_ANDROID_
+	elements->InputDuplicate(FrictionCoefficientEnum,AndroidFrictionCoefficientEnum);
+	#endif
+
+	elements->InputDuplicate(VyEnum,VyPicardEnum);
+	elements->InputDuplicate(VyEnum,InversionVyObsEnum);
+	if(dakota_analysis)elements->InputDuplicate(VyEnum,QmuVyEnum);
+
+	if(iomodel->dim==3){
+		elements->InputDuplicate(VzEnum,VzPicardEnum);
+		elements->InputDuplicate(VzEnum,InversionVzObsEnum);
+		if(dakota_analysis)elements->InputDuplicate(VzEnum,QmuVzEnum);
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(1,FlowequationElementEquationEnum);
+	xDelete<int>(finiteelement_list);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/CreateConstraintsStressbalanceSIA.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/CreateConstraintsStressbalanceSIA.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/CreateConstraintsStressbalanceSIA.cpp	(revision 16137)
@@ -0,0 +1,68 @@
+/*
+ * CreateConstraintsStressbalanceSIA.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsStressbalanceSIA(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Intermediary*/
+	int        count;
+	IssmDouble yts;
+	bool       isSIA;
+
+	/*Output*/
+	Constraints* constraints = NULL;
+	SpcStatic*    spcstatic  = NULL;
+
+	/*Recover pointer: */
+	constraints=*pconstraints;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+
+	/*Now, is the flag isSIA on? otherwise, do nothing: */
+	if (!isSIA) return;
+
+	/*Fetch data: */
+	iomodel->FetchData(3,StressbalanceSpcvxEnum,StressbalanceSpcvyEnum,FlowequationVertexEquationEnum);
+
+	/*Initialize conunter*/
+	count=0;
+
+	/*vx and vy are spc'd if we are not on nodeonSIA: */
+	for(int i=0;i<iomodel->numberofvertices;i++){
+		/*keep only this partition's nodes:*/
+		if((iomodel->my_vertices[i])){
+			if (!reCast<int,IssmDouble>(iomodel->Data(FlowequationVertexEquationEnum)[i])==SIAApproximationEnum){
+
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceSIAAnalysisEnum));
+				count++;
+
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,0,StressbalanceSIAAnalysisEnum));
+				count++;
+			}
+			else{
+				if (!xIsNan<IssmDouble>(iomodel->Data(StressbalanceSpcvxEnum)[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,iomodel->Data(StressbalanceSpcvxEnum)[i]/yts,StressbalanceSIAAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+					count++;
+				}
+
+				if (!xIsNan<IssmDouble>(iomodel->Data(StressbalanceSpcvyEnum)[i])){
+					constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,2,iomodel->Data(StressbalanceSpcvyEnum)[i]/yts,StressbalanceSIAAnalysisEnum)); //add count'th spc, on node i+1, setting dof 2 to vy
+					count++;
+				}
+			}
+		}
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(3,StressbalanceSpcvxEnum,StressbalanceSpcvyEnum,FlowequationVertexEquationEnum);
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/CreateLoadsStressbalanceSIA.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/CreateLoadsStressbalanceSIA.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/CreateLoadsStressbalanceSIA.cpp	(revision 16137)
@@ -0,0 +1,12 @@
+/*! \file CreateLoadsStressbalanceSIA.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsStressbalanceSIA(Loads** ploads, IoModel* iomodel){
+
+	/*No loads*/
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/CreateNodesStressbalanceSIA.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/CreateNodesStressbalanceSIA.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/CreateNodesStressbalanceSIA.cpp	(revision 16137)
@@ -0,0 +1,52 @@
+/*
+ * CreateNodesStressbalanceSIA.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesStressbalanceSIA(Nodes** pnodes, 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*/
+	Nodes* nodes=*pnodes;
+	int    lid=0;
+	if(!nodes) nodes = new Nodes();
+
+	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+				FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+
+	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,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBorderSSAEnum,FlowequationBorderFSEnum,
+				FlowequationVertexEquationEnum,StressbalanceReferentialEnum);
+
+	/*Assign output pointer: */
+	*pnodes=nodes;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/UpdateElementsStressbalanceSIA.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/UpdateElementsStressbalanceSIA.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceSIA/UpdateElementsStressbalanceSIA.cpp	(revision 16137)
@@ -0,0 +1,37 @@
+/*
+ * UpdateElementsStressbalanceSIA:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsStressbalanceSIA(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	/*Fetch data needed: */
+	bool   isSIA;
+	iomodel->Constant(&isSIA,FlowequationIsSIAEnum);
+
+	/*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,GeometryHydrostaticRatioEnum);
+
+	/*Free data: */
+	iomodel->DeleteData(1,FlowequationElementEquationEnum);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/CreateConstraintsStressbalanceVertical.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/CreateConstraintsStressbalanceVertical.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/CreateConstraintsStressbalanceVertical.cpp	(revision 16137)
@@ -0,0 +1,55 @@
+/*
+ * CreateConstraintsStressbalanceHoriz.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateConstraintsStressbalanceVertical(Constraints** pconstraints, IoModel* iomodel){
+
+	/*Intermediary*/
+	int count;
+	IssmDouble yts;
+
+	/*Fetch parameters: */
+	iomodel->Constant(&yts,ConstantsYtsEnum);
+
+	/*Recover pointer: */
+	Constraints* constraints=*pconstraints;
+
+	/*return if 2d mesh*/
+	if(iomodel->dim==2) return;
+
+	/*Fetch data: */
+	iomodel->FetchData(2,StressbalanceSpcvzEnum,FlowequationBorderFSEnum);
+
+	/*Initialize counter*/
+	count=0;
+
+	/*Create spcs from x,y,z, as well as the spc values on those spcs: */
+	for(int i=0;i<iomodel->numberofvertices;i++){
+
+		/*keep only this partition's nodes:*/
+		if(iomodel->my_vertices[i]){
+
+			if (reCast<int,IssmDouble>(iomodel->Data(FlowequationBorderFSEnum)[i])){
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,0,StressbalanceVerticalAnalysisEnum)); //spc to zero as vertical velocity is done in Horiz for FS
+				count++;
+			}
+			else if (!xIsNan<IssmDouble>(iomodel->Data(StressbalanceSpcvzEnum)[i])){
+				constraints->AddObject(new SpcStatic(iomodel->constraintcounter+count+1,iomodel->nodecounter+i+1,1,
+								iomodel->Data(StressbalanceSpcvzEnum)[i]/yts,StressbalanceVerticalAnalysisEnum)); //add count'th spc, on node i+1, setting dof 1 to vx.
+				count++;
+
+			}
+		} 
+	}
+
+	/*Free data: */
+	iomodel->DeleteData(2,StressbalanceSpcvzEnum,FlowequationBorderFSEnum);
+
+	/*Assign output pointer: */
+	*pconstraints=constraints;
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/CreateLoadsStressbalanceVertical.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/CreateLoadsStressbalanceVertical.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/CreateLoadsStressbalanceVertical.cpp	(revision 16137)
@@ -0,0 +1,13 @@
+/*! \file CreateLoadsStressbalanceVertical.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../ModelProcessorx.h"
+
+void	CreateLoadsStressbalanceVertical(Loads** ploads, IoModel* iomodel){
+
+	/*No loads*/
+
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/CreateNodesStressbalanceVertical.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/CreateNodesStressbalanceVertical.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/CreateNodesStressbalanceVertical.cpp	(revision 16137)
@@ -0,0 +1,19 @@
+/*
+ * CreateNodesStressbalanceVertical.c:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	CreateNodesStressbalanceVertical(Nodes** pnodes, IoModel* iomodel){
+
+	/*Now, is the flag macayaealHO on? otherwise, do nothing: */
+	if(iomodel->dim==2) return;
+
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,StressbalanceVerticalAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+}
Index: /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/UpdateElementsStressbalanceVertical.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/UpdateElementsStressbalanceVertical.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/ModelProcessorx/StressbalanceVertical/UpdateElementsStressbalanceVertical.cpp	(revision 16137)
@@ -0,0 +1,37 @@
+/*
+ * UpdateElementsStressbalanceVertical:
+ */
+
+#include "../../../toolkits/toolkits.h"
+#include "../../../classes/classes.h"
+#include "../../../shared/shared.h"
+#include "../../MeshPartitionx/MeshPartitionx.h"
+#include "../ModelProcessorx.h"
+
+void	UpdateElementsStressbalanceVertical(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
+
+	/*Now, is the model 3d? otherwise, do nothing: */
+	if (iomodel->dim==2)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,GeometryHydrostaticRatioEnum);
+	iomodel->FetchDataToInput(elements,SurfaceEnum);
+	iomodel->FetchDataToInput(elements,BedEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
+	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
+	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
+	iomodel->FetchDataToInput(elements,SurfaceforcingsMassBalanceEnum);
+	iomodel->FetchDataToInput(elements,VxEnum);
+	iomodel->FetchDataToInput(elements,VyEnum);
+}
Index: sm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# SLOPE_SOURCES {{{
-set(SLOPE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp
-                        $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp
-                        $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp
-                     $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 16137)
@@ -10,11 +10,4 @@
 void	CreateConstraintsSurfaceSlope(Constraints** pconstraints, IoModel* iomodel){
 
-	/*Recover pointer: */
-	Constraints* constraints=*pconstraints;
-
-	/*Create constraints if they do not exist yet*/
-	if(!constraints) constraints = new Constraints();
-
-	/*Assign output pointer: */
-	*pconstraints=constraints;
+	/*No constraints*/
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 16137)
@@ -9,11 +9,5 @@
 void	CreateLoadsSurfaceSlope(Loads** ploads, IoModel* iomodel){
 
-	/*Recover pointer: */
-	Loads* loads=*ploads;
+	/*No loads*/
 
-	/*Create loads if they do not exist yet*/
-	if(!loads) loads = new Loads();
-
-	/*Assign output pointer: */
-	*ploads=loads;
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 16137)
@@ -11,36 +11,6 @@
 void	CreateNodesSurfaceSlope(Nodes** pnodes, IoModel* iomodel){
 
-	/*Intermediary*/
-	bool continuous_galerkin=true;
-	int    numberofvertices;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-
-	/*Recover pointer: */
-	Nodes* nodes=*pnodes;
-
-	/*Create nodes if they do not exist yet*/
-	if(!nodes) nodes = new Nodes();
-
-	/*Continuous Galerkin partition of nodes: */
-	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-
-	/*First fetch data: */
-	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	for(int i=0;i<numberofvertices;i++){
-		if(iomodel->my_vertices[i]){
-
-			/*Add node to nodes dataset: */
-			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,SurfaceSlopeAnalysisEnum));
-
-		}
-	}
-
-	/*Clean fetched data: */
-	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	/*Assign output pointer: */
-	*pnodes=nodes;
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,SurfaceSlopeAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 16137)
@@ -11,18 +11,10 @@
 void	UpdateElementsSurfaceSlope(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
 
-	int    dim;
-	int    numberofelements;
-
-	/*Fetch data needed: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->FetchData(1,MeshElementsEnum);
-
 	/*Update elements: */
 	int counter=0;
-	for(int i=0;i<numberofelements;i++){
+	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); //we need i to index into elements.
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
 			counter++;
 		}
@@ -31,12 +23,8 @@
 	iomodel->FetchDataToInput(elements,SurfaceEnum);
 	iomodel->FetchDataToInput(elements,BedEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
-
-	if (dim==3){
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	if(iomodel->dim==3){
 		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
 		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
 	}
-
-	/*Free data: */
-	iomodel->DeleteData(1,MeshElementsEnum);
 }
Index: sm/trunk/src/c/modules/ModelProcessorx/Thermal/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# THERMAL_SOURCES {{{
-set(THERMAL_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp
-                          $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp
-                          $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp
-                       $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 16137)
@@ -11,17 +11,10 @@
 void	CreateConstraintsThermal(Constraints** pconstraints, IoModel* iomodel){
 
-	/*Fetch parameters: */
-	int    dim;
-	iomodel->Constant(&dim,MeshDimensionEnum);
-
 	/*Recover pointer: */
 	Constraints* constraints=*pconstraints;
 
-	/*Create constraints if they do not exist yet*/
-	if(!constraints) constraints = new Constraints();
-
 	/*Only 3d mesh supported*/
-	if (dim==3){
-		IoModelToConstraintsx(constraints,iomodel,ThermalSpctemperatureEnum,ThermalAnalysisEnum);
+	if(iomodel->dim==3){
+		IoModelToConstraintsx(constraints,iomodel,ThermalSpctemperatureEnum,ThermalAnalysisEnum,P1Enum);
 	}
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 16137)
@@ -9,27 +9,14 @@
 void	CreateLoadsThermal(Loads** ploads, IoModel* iomodel){
 
-	/*Intermediary*/
-	int      dim;
-	int      numberofvertices;
-	Pengrid *pengrid          = NULL;
-
 	/*Recover pointer: */
 	Loads* loads=*ploads;
 
-	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
+	if(iomodel->dim==2) _error_("2d meshes not supported yet");
 
-	/*Create loads if they do not exist yet*/
-	if(!loads) loads = new Loads();
-
-	/*return if 2d mesh*/
-	if (dim==2) _error_("2d meshes not supported yet");
-
-	//create penalties for nodes: no node can have a temperature over the melting point
-	iomodel->FetchData(2,ThermalSpctemperatureEnum,MeshElementsEnum);
+	/*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<numberofvertices;i++){
+	for(int i=0;i<iomodel->numberofvertices;i++){
 
 		/*keep only this partition's nodes:*/
@@ -40,5 +27,5 @@
 		}
 	}
-	iomodel->DeleteData(2,ThermalSpctemperatureEnum,MeshElementsEnum);
+	iomodel->DeleteData(1,ThermalSpctemperatureEnum);
 
 	/*Assign output pointer: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 16137)
@@ -11,35 +11,6 @@
 void	CreateNodesThermal(Nodes** pnodes, IoModel* iomodel){
 
-	/*Intermediary*/
-	bool continuous_galerkin=true;
-
-	/*Fetch parameters: */
-	int    numberofvertices;
-	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-
-	/*Recover pointer: */
-	Nodes* nodes=*pnodes;
-
-	/*Create nodes if they do not exist yet*/
-	if(!nodes) nodes = new Nodes();
-
-	/*Continuous Galerkin partition of nodes: */
-	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-
-	/*Create nodes and vertices: */
-	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	for(int i=0;i<numberofvertices;i++){
-		if(iomodel->my_vertices[i]){
-			/*Add node to nodes dataset: */
-			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,ThermalAnalysisEnum));
-
-		}
-	}
-
-	/*Clean fetched data: */
-	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-
-	/*Assign output pointer: */
-	*pnodes=nodes;
+	iomodel->FetchData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
+	CreateNodes(pnodes,iomodel,ThermalAnalysisEnum,P1Enum);
+	iomodel->DeleteData(3,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationVertexEquationEnum);
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 16137)
@@ -11,25 +11,13 @@
 void	UpdateElementsThermal(Elements* elements, IoModel* iomodel,int analysis_counter,int analysis_type){
 
-	int    dim;
-	int    numberofelements;
-	bool   dakota_analysis;
-
-	/*Fetch parameters: */
-	iomodel->Constant(&dim,MeshDimensionEnum);
-	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
-	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
-
 	/*Now, is the model 3d? otherwise, do nothing: */
-	if (dim==2)return;
-
-	/*Fetch data needed: */
-	iomodel->FetchData(1,MeshElementsEnum);
+	if(iomodel->dim==2)return;
 
 	/*Update elements: */
 	int counter=0;
-	for(int i=0;i<numberofelements;i++){
+	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); //we need i to index into elements.
+			element->Update(i,iomodel,analysis_counter,analysis_type,P1Enum);
 			counter++;
 		}
@@ -42,8 +30,8 @@
 	iomodel->FetchDataToInput(elements,FrictionPEnum);
 	iomodel->FetchDataToInput(elements,FrictionQEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonfloatingiceEnum);
+	iomodel->FetchDataToInput(elements,MaskIceLevelsetEnum);
+	iomodel->FetchDataToInput(elements,MaskGroundediceLevelsetEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
 	iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
-	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
 	iomodel->FetchDataToInput(elements,FlowequationElementEquationEnum);
 	iomodel->FetchDataToInput(elements,MaterialsRheologyBEnum);
@@ -56,4 +44,6 @@
 	iomodel->FetchDataToInput(elements,VzEnum);
 
+	bool dakota_analysis;
+	iomodel->Constant(&dakota_analysis,QmuIsdakotaEnum);
 	if(dakota_analysis){
 		elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
@@ -61,6 +51,3 @@
 		elements->InputDuplicate(BasalforcingsMeltingRateEnum,QmuMeltingEnum);
 	}
-
-	/*Free data: */
-	iomodel->DeleteData(1,MeshElementsEnum);
 }
Index: sm/trunk/src/c/modules/ModelProcessorx/Transient/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Transient/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# TRANSIENT_SOURCES {{{
-set(TRANSIENT_SOURCES $ENV{ISSM_DIR}/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp	(revision 16137)
@@ -10,40 +10,3 @@
 
 void	UpdateElementsTransient(Elements* elements, Parameters* parameters,IoModel* iomodel,int analysis_counter,int analysis_type){
-
-	bool        isgl;
-	int         migration_style;
-	int         i,numberofvertices;
-	IssmDouble  rho_ice,rho_water;
-	IssmDouble *phi   = NULL;
-
-	/*Fetch data needed*/
-	iomodel->Constant(&isgl,TransientIsgroundinglineEnum);
-	iomodel->Constant(&migration_style,GroundinglineMigrationEnum);
-
-	if(isgl==1 && (migration_style==SubelementMigrationEnum || migration_style==SubelementMigration2Enum)){
-
-		/*get parameters and constants: */
-		iomodel->Constant(&rho_ice,MaterialsRhoIceEnum);
-		iomodel->Constant(&rho_water,MaterialsRhoWaterEnum);
-		iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-		iomodel->FetchData(3,MeshElementsEnum,ThicknessEnum,BathymetryEnum);
-
-		/*Create phi vector */
-		phi=xNew<IssmDouble>(numberofvertices);
-		for (i=0;i<numberofvertices;i++){
-			if(iomodel->my_vertices[i]){
-				phi[i] = iomodel->Data(ThicknessEnum)[i] + rho_water/rho_ice * iomodel->Data(BathymetryEnum)[i];
-			}
-		}
-
-		/*Update elements: */
-		for(i=0;i<elements->Size();i++){
-			Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
-			element->InputCreate(phi,element->Sid(),iomodel,numberofvertices,1,1,GLlevelsetEnum,1);
-		}
-
-		/*Free ressources:*/
-		iomodel->DeleteData(3,MeshElementsEnum,ThicknessEnum,BathymetryEnum);
-		xDelete<IssmDouble>(phi);
-	}
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 16137)
@@ -24,5 +24,5 @@
 	constraints=*pconstraints;
 
-	if(nodes) iomodel->nodecounter=nodes->NumberOfNodes();
+	if(nodes) iomodel->nodecounter=nodes->MaximumId();
 	else iomodel->nodecounter=0;
 
Index: sm/trunk/src/c/modules/NodalValuex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/NodalValuex/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/NodalValuex)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/NodalValuex/NodalValuex.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 16137)
@@ -37,16 +37,10 @@
 
 	/*Broadcast whether we found the element: */
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
+	ISSM_MPI_Allreduce ( &found,&sumfound,1,ISSM_MPI_INT,ISSM_MPI_SUM,IssmComm::GetComm());
 	if(!sumfound)_error_("could not find element with vertex with id" << index << " to compute nodal value " << EnumToStringx(natureofdataenum));
-	#endif
 
 	/*Broadcast and plug into response: */
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( &cpu_found,&cpu_found,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
-	MPI_Bcast(&value,1,MPI_DOUBLE,cpu_found,IssmComm::GetComm()); 
-	#else
-	value=cpu_found;
-	#endif
+	ISSM_MPI_Allreduce ( &cpu_found,&cpu_found,1,ISSM_MPI_INT,ISSM_MPI_MAX,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&value,1,ISSM_MPI_DOUBLE,cpu_found,IssmComm::GetComm()); 
 
 	*pnodalvalue=value;
Index: sm/trunk/src/c/modules/NodeConnectivityx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/NodeConnectivityx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/NodeConnectivityx)
-# }}}
Index: sm/trunk/src/c/modules/NodesDofx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/NodesDofx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/NodesDofx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/NodesDofx/NodesDofx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/NodesDofx/NodesDofx.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodesDofx/NodesDofx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/NodesDofx/NodesDofx.cpp	(revision 16137)
@@ -10,21 +10,22 @@
 void NodesDofx(Nodes* nodes, Parameters* parameters,int configuration_type){
 
-	int noerr=1;
-	int found=0;
+	/*Do we have any nodes for this analysis type? :*/
+	if(!nodes->NumberOfNodes(configuration_type)) return;
 
-	/*Do we have any nodes for this analysis type? :*/
-	if(nodes->NumberOfNodes(configuration_type)){ 
+	/*Do we really need to update dof indexings*/
+	if(!nodes->RequiresDofReindexing(configuration_type)) return;
 
-		/*Ensure that only for each cpu, the partition border nodes only will be taken into account once 
-		 * across the cluster. To do so, we flag all the clone nodes: */
-		nodes->FlagClones(configuration_type);
+	if(VerboseModule()) _printf0_("   Renumbering degrees of freedom\n");
 
-		/*Go through all nodes, and build degree of freedom lists. Each node gets a fixed number of dofs. When 
-		 *a  node has already been distributed dofs on one cpu, all other cpus with the same node cannot distribute it 
-		 *anymore. Use clone field to be sure of that: */
-		nodes->DistributeDofs(configuration_type,GsetEnum);
-		nodes->DistributeDofs(configuration_type,FsetEnum);
-		nodes->DistributeDofs(configuration_type,SsetEnum);
-	}
+	/*Ensure that only for each cpu, the partition border nodes only will be taken into account once 
+	 * across the cluster. To do so, we flag all the clone nodes: */
+	nodes->FlagClones(configuration_type);
+
+	/*Go through all nodes, and build degree of freedom lists. Each node gets a fixed number of dofs. When 
+	 *a  node has already been distributed dofs on one cpu, all other cpus with the same node cannot distribute it 
+	 *anymore. Use clone field to be sure of that: */
+	nodes->DistributeDofs(configuration_type,GsetEnum);
+	nodes->DistributeDofs(configuration_type,FsetEnum);
+	nodes->DistributeDofs(configuration_type,SsetEnum);
 
 }
Index: sm/trunk/src/c/modules/Orthx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Orthx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Orthx)
-# }}}
Index: sm/trunk/src/c/modules/OutputResultsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/OutputResultsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/OutputResultsx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/OutputResultsx/OutputResultsx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 16137)
@@ -61,5 +61,5 @@
 		if(io_gather){
 			/*Just open the file for output on cpu 0. We are gathering the data on cpu 0 from all other cpus: */
-			if(my_rank==0) fid=pfopen(outputfilename ,"wb");
+			if(my_rank==0) fid=pfopen0(outputfilename ,"wb");
 		}
 		else{
Index: sm/trunk/src/c/modules/OutputRiftsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/OutputRiftsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/OutputRiftsx)
-# }}}
Index: /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.cpp	(revision 16137)
@@ -1,4 +1,4 @@
 /*!\file OutputRiftsx
- * \brief: output results from diagnostic solution, for rifts. Notably: fraction of 
+ * \brief: output results from stressbalance solution, for rifts. Notably: fraction of 
  * melange, and penetration.
  */
Index: sm/trunk/src/c/modules/ParseToolkitsOptionsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ParseToolkitsOptionsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ParseToolkitsOptionsx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ParseToolkitsOptionsx/ParseToolkitsOptionsx.cpp	(revision 16137)
@@ -95,12 +95,10 @@
 
 	/*Ok, broadcast to other cpus: */
- 	#ifdef _HAVE_MPI_
-	MPI_Bcast(&numanalyses,1,MPI_INT,0,IssmComm::GetComm());
+	ISSM_MPI_Bcast(&numanalyses,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 	if(my_rank!=0){
 		analyses=xNew<IssmDouble>(numanalyses);
 		strings=xNew<char*>(numanalyses);
 	}
-	MPI_Bcast(analyses,numanalyses,MPI_DOUBLE,0,IssmComm::GetComm());
-	#endif
+	ISSM_MPI_Bcast(analyses,numanalyses,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
 	for(i=0;i<numanalyses;i++){
 		char* string=strings[i];
@@ -109,10 +107,8 @@
 		}
 		if(my_rank==0)stringlength=(strlen(string)+1)*sizeof(char);
-		#ifdef _HAVE_MPI_
-		MPI_Bcast(&stringlength,1,MPI_INT,0,IssmComm::GetComm());
+		ISSM_MPI_Bcast(&stringlength,1,ISSM_MPI_INT,0,IssmComm::GetComm());
 		if(my_rank!=0)string=xNew<char>(stringlength);
-		MPI_Bcast(string,stringlength,MPI_CHAR,0,IssmComm::GetComm());
+		ISSM_MPI_Bcast(string,stringlength,ISSM_MPI_CHAR,0,IssmComm::GetComm());
 		if(my_rank!=0)strings[i]=string;
-		#endif
 	}
 
Index: sm/trunk/src/c/modules/PointCloudFindNeighborsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/PointCloudFindNeighborsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/PointCloudFindNeighborsx)
-# }}}
Index: /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 16137)
@@ -49,5 +49,5 @@
 		/*display current iteration*/
 		if (my_thread==0 && fmod((double)i,(double)100)==0)
-		 _printf_("\r      loop progress: "<<setw(6)<<setprecision(2)<<double(i-i0)/double(i1-i0)*100<<"%");
+		 _printf_("\r      loop progress: "<<setw(6)<<setprecision(2)<<double(i-i0)/double(i1-i0)*100<<"%   ");
 
 		distance=mindistance+100; //make sure initialization respects min distance criterion.
@@ -70,5 +70,5 @@
 	}
 	if (my_thread==0)
-	 _printf_("\r      loop progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%\n");
+	 _printf_("\r      loop progress: "<<fixed<<setw(6)<<setprecision(2)<<100.<<"%  \n");
 
 	/*Free ressources:*/
Index: sm/trunk/src/c/modules/PositiveDegreeDayx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/PositiveDegreeDayx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/PositiveDegreeDayx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.cpp
===================================================================
--- /issm/trunk/src/c/modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.cpp	(revision 16137)
@@ -0,0 +1,31 @@
+/*!\file PostprocessingEnthalpyx.cpp
+ * \brief: execute processing of variables after computation: water drainage, subglacial melting rates, update of thermal BCs
+ */
+
+#include "./PostprocessingEnthalpyx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+
+void PostprocessingEnthalpyx(FemModel* femmodel){
+    /*Intermediary*/
+	int i;
+	Element* element=NULL;
+
+	/*drain excess water fraction: */
+	for (i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->DrainWaterfraction();
+	}
+
+	/*Compute basal melting rates: */
+	for (i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->ComputeBasalMeltingrate();
+	}
+
+	/*Update basal dirichlet BCs for enthalpy: */
+	for (i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->UpdateThermalBasalConstraints();
+	}
+}
Index: /issm/trunk/src/c/modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.h
===================================================================
--- /issm/trunk/src/c/modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.h	(revision 16137)
+++ /issm/trunk/src/c/modules/PostprocessingEnthalpyx/PostprocessingEnthalpyx.h	(revision 16137)
@@ -0,0 +1,13 @@
+/*!\file PostprocessingEnthalpy.h
+ * \brief: header file for PostprocessingEnthalpy
+ */
+
+#ifndef _POSTPROCESSINGENTHALPYX_H
+#define _POSTPROCESSINGENTHALPYX_H
+
+#include "../../classes/classes.h"
+#include "../../toolkits/toolkits.h"
+
+void PostprocessingEnthalpyx(FemModel* femmodel);
+
+#endif  /* _POSTPROCESSINGENTHALPYX_H */
Index: sm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/PropagateFlagsFromConnectivityx)
-# }}}
Index: sm/trunk/src/c/modules/Reduceloadx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Reduceloadx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Reduceloadx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/Reduceloadx/Reduceloadx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/Reducevectorgtofx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtofx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Reducevectorgtofx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/Reducevectorgtosx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtosx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Reducevectorgtosx)
-# }}}
Index: sm/trunk/src/c/modules/ResetConstraintsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ResetConstraintsx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp PARENT_SCOPE)
-# }}}
-# THERMAL_SOURCES {{{
-set(THERMAL_SOURCES $ENV{ISSM_DIR}/src/c/modules/ResetConstraintsx/ThermalConstraintsReset.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 16137)
@@ -14,8 +14,6 @@
 #include "../ConstraintsStatex/ConstraintsStatex.h"
 
-void ResetConstraintsx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters){
+void ResetConstraintsx(FemModel* femmodel){
 
-	/*output: */
-	int analysis_type;
 
 	/*Display message*/
@@ -23,18 +21,18 @@
 
 	/*recover parameters: */
-	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	int analysis_type;
+	femmodel->parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 
 	/*Do we have penalties linked to rifts? In this case, run our special rifts penalty 
 	 * management routine, otherwise, skip : */
 	#ifdef _HAVE_RIFTS_
-	if (RiftIsPresent(loads,analysis_type)){
+	if(RiftIsPresent(femmodel->loads,analysis_type)){
 		_error_("rift constraints reset not supported yet!");
 	}
 	#endif
 	#ifdef _HAVE_THERMAL_
-	if(ThermalIsPresent(loads,analysis_type)){
-		ThermalConstraintsReset(loads,analysis_type);
+	if(ThermalIsPresent(femmodel->loads,analysis_type)){
+		ThermalConstraintsReset(femmodel->loads,analysis_type);
 	}
 	#endif
-
 }
Index: /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 16137)
@@ -9,6 +9,6 @@
 
 /* local prototypes: */
-void  ThermalConstraintsReset(Loads* loads, int configuration_type);
-void ResetConstraintsx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters); 
+void ThermalConstraintsReset(Loads* loads, int configuration_type);
+void ResetConstraintsx(FemModel* femmodel);
 
 #endif  /* _RESETCONSTRAINTSX_H */
Index: sm/trunk/src/c/modules/ResetCoordinateSystemx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ResetCoordinateSystemx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ResetCoordinateSystemx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp	(revision 16137)
@@ -1,4 +1,4 @@
 /*!\file ResetCoordinateSystemx
- * \brief: reset coordinate system for full-Stokes: tangential to the bedrock
+ * \brief: reset coordinate system for full-FS: tangential to the bedrock
  */
 
Index: sm/trunk/src/c/modules/RheologyBbarAbsGradientx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/RheologyBbarAbsGradientx)
-# }}}
Index: /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 16137)
@@ -25,9 +25,7 @@
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
Index: sm/trunk/src/c/modules/Scotchx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Scotchx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Scotchx)
-# }}}
Index: sm/trunk/src/c/modules/SetControlInputsFromVectorx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/SetControlInputsFromVectorx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/SetControlInputsFromVectorx)
-# }}}
Index: sm/trunk/src/c/modules/Shp2Expx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Shp2Expx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Shp2Expx)
-# }}}
-# KML_SOURCES {{{
-set(KML_SOURCES $ENV{ISSM_DIR}/src/c/modules/Shp2Expx/Shp2Expx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/Shp2Kmlx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Shp2Kmlx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Shp2Kmlx)
-# }}}
-# KML_SOURCES {{{
-set(KML_SOURCES $ENV{ISSM_DIR}/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/SmbGradientsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/SmbGradientsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/SmbGradientsx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/SmbGradientsx/SmbGradientsx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/Solverx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/Solverx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/Solverx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/Solverx/Solverx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/SpcNodesx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/SpcNodesx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/SpcNodesx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/SpcNodesx/SpcNodesx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/SurfaceAbsVelMisfitx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/SurfaceAbsVelMisfitx)
-# }}}
Index: /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 16137)
@@ -25,9 +25,7 @@
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
Index: sm/trunk/src/c/modules/SurfaceAreax/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAreax/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/SurfaceAreax)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/SurfaceAreax/SurfaceAreax.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 16137)
@@ -9,29 +9,26 @@
 #include "../InputUpdateFromConstantx/InputUpdateFromConstantx.h"
 
-void SurfaceAreax( IssmDouble* pS, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
+void SurfaceAreax(IssmDouble* pS,FemModel* femmodel){
 
 	/*Intermediary*/
 	Element* element=NULL;
-	int i;
 
 	/*output: */
-	IssmDouble S=0;
+	IssmDouble S = 0.;
 	IssmDouble S_sum;
 
 	/*Compute gradients: */
-	for (i=0;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(int i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		S+=element->SurfaceArea();
 	}
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
- 	MPI_Reduce (&S,&S_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&S_sum,1,MPI_DOUBLE,0,IssmComm::GetComm()); 
+ 	ISSM_MPI_Reduce (&S,&S_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
+	ISSM_MPI_Bcast(&S_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm()); 
 	S=S_sum;
-	#endif
 
 	/*add surface area to element inputs:*/
-	InputUpdateFromConstantx(elements,nodes,vertices,loads,materials,parameters,S,SurfaceAreaEnum);
+	InputUpdateFromConstantx(femmodel,S,SurfaceAreaEnum);
 
 	/*Assign output pointers: */
Index: /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 16136)
+++ /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 16137)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void SurfaceAreax( IssmDouble* pS, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters);
+void SurfaceAreax(IssmDouble* pS,FemModel* femmodel);
 
 #endif  /* _SURFACEAREAX_H */
Index: sm/trunk/src/c/modules/SurfaceAverageVelMisfitx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/SurfaceAverageVelMisfitx)
-# }}}
Index: /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 16137)
@@ -9,29 +9,26 @@
 #include "../SurfaceAreax/SurfaceAreax.h"
 
-void SurfaceAverageVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,int weight_index){
+void SurfaceAverageVelMisfitx(IssmDouble* pJ,FemModel* femmodel,int weight_index){
 
 	/*Intermediary*/
-	int i;
 	Element* element=NULL;
 
 	/*output: */
-	IssmDouble J=0;
+	IssmDouble J = 0.;
 	IssmDouble J_sum;
 
 	/*Compute surface area and add to elements inputs */
-	SurfaceAreax(NULL,elements,nodes,vertices, loads,materials,parameters);
+	SurfaceAreax(NULL,femmodel);
 
 	/*Compute Misfit: */
-	for (i=0;i<elements->Size();i++){
-		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+	for(int i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
 		J+=element->SurfaceAverageVelMisfit(weight_index);
 	}
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
Index: /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 16136)
+++ /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.h	(revision 16137)
@@ -9,5 +9,5 @@
 
 /* local prototypes: */
-void SurfaceAverageVelMisfitx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int weight_index);
+void SurfaceAverageVelMisfitx(IssmDouble* pJ,FemModel* femmodel,int weight_index);
 
 #endif
Index: sm/trunk/src/c/modules/SurfaceLogVelMisfitx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/SurfaceLogVelMisfitx)
-# }}}
Index: /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 16137)
@@ -25,9 +25,7 @@
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
Index: sm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/SurfaceLogVxVyMisfitx)
-# }}}
Index: /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 16137)
@@ -25,9 +25,7 @@
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
Index: sm/trunk/src/c/modules/SurfaceRelVelMisfitx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/SurfaceRelVelMisfitx)
-# }}}
Index: /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 16137)
@@ -25,9 +25,7 @@
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
Index: /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 16137)
+++ /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.cpp	(revision 16137)
@@ -0,0 +1,121 @@
+/*!\file SystemMatricesx
+ * \brief retrieve vector from inputs in elements
+ */
+
+#include "./SystemMatricesx.h"
+#include "../../shared/shared.h"
+#include "../../toolkits/toolkits.h"
+#include "../AllocateSystemMatricesx/AllocateSystemMatricesx.h"
+
+void SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** pdf, IssmDouble* pkmax,FemModel* femmodel){
+
+	/*intermediary: */
+	int      i,M,N;
+	int      configuration_type;
+	Element *element = NULL;
+	Load    *load    = NULL;
+
+	/*output: */
+	Matrix<IssmDouble> *Kff  = NULL;
+	Matrix<IssmDouble> *Kfs  = NULL;
+	Vector<IssmDouble> *pf   = NULL;
+	Vector<IssmDouble> *df   = NULL;
+	IssmDouble          kmax = 0;
+
+	/*Display message*/
+	if(VerboseModule()) _printf0_("   Generating matrices");
+
+	/*retrive parameters: */
+	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	/*First, we might need to do a dry run to get kmax if penalties are employed*/
+	if(femmodel->loads->IsPenalty(configuration_type)){
+
+		/*Allocate Kff_temp*/
+		Matrix<IssmDouble> *Kff_temp = NULL;
+		AllocateSystemMatricesx(&Kff_temp,NULL,NULL,NULL,femmodel);
+
+		/*Get complete stiffness matrix without penalties*/
+		for (i=0;i<femmodel->elements->Size();i++){
+			element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+			element->CreateKMatrix(Kff_temp,NULL);
+		}
+
+		for (i=0;i<femmodel->loads->Size();i++){
+			load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+			if(load->InAnalysis(configuration_type)) load->CreateKMatrix(Kff_temp,NULL);
+		}
+		Kff_temp->Assemble();
+
+		/*Now, figure out maximum value of stiffness matrix, so that we can penalize it correctly: */
+		kmax=Kff_temp->Norm(NORM_INF);
+		delete Kff_temp;
+	}
+
+	/*Allocate stiffness matrices and load vector*/
+	AllocateSystemMatricesx(&Kff,&Kfs,&df,&pf,femmodel);
+
+	/*Display size*/
+	if(VerboseModule()){
+		Kff->GetSize(&M,&N);
+		_printf0_(" (Kff stiffness matrix size: "<<M<<" x "<<N<<")\n");
+	}
+
+	/*Fill stiffness matrix from elements and loads */
+	for (i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->CreateKMatrix(Kff,Kfs);
+	}
+
+	for (i=0;i<femmodel->loads->Size();i++){
+		load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+		if(load->InAnalysis(configuration_type)) load->CreateKMatrix(Kff,Kfs);
+	}
+
+	/*Fill right hand side vector, from elements and loads */
+	for (i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->CreatePVector(pf);
+	}
+	for (i=0;i<femmodel->loads->Size();i++){
+		load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+		if(load->InAnalysis(configuration_type)) load->CreatePVector(pf);
+	}
+
+	/*Now deal with penalties (only in loads)*/
+	if(femmodel->loads->IsPenalty(configuration_type)){
+		for (i=0;i<femmodel->loads->Size();i++){
+			load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+			if(load->InAnalysis(configuration_type)) load->PenaltyCreateKMatrix(Kff,Kfs,kmax);
+		}
+		for (i=0;i<femmodel->loads->Size();i++){
+			load=dynamic_cast<Load*>(femmodel->loads->GetObjectByOffset(i));
+			if(load->InAnalysis(configuration_type)) load->PenaltyCreatePVector(pf,kmax);
+		}
+	}
+
+	/*Create dof vector for stiffness matrix preconditioning*/
+	for (i=0;i<femmodel->elements->Size();i++){
+		element=dynamic_cast<Element*>(femmodel->elements->GetObjectByOffset(i));
+		element->CreateDVector(df);
+	}
+
+	/*Assemble matrices and vector*/
+	Kff->Assemble();
+	Kfs->Assemble();
+	pf->Assemble();
+	df->Assemble();
+	//Kff->AllocationInfo();
+	//Kfs->AllocationInfo();
+
+	/*Assign output pointers: */
+	if(pKff) *pKff=Kff;
+	else      delete Kff;
+	if(pKfs) *pKfs=Kfs;
+	else      delete Kfs;
+	if(ppf)  *ppf=pf;
+	else      delete pf;
+	if(pdf)  *pdf=df;
+	else      delete df;
+	if(pkmax) *pkmax=kmax;
+}
Index: /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.h
===================================================================
--- /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.h	(revision 16137)
+++ /issm/trunk/src/c/modules/SystemMatricesx/SystemMatricesx.h	(revision 16137)
@@ -0,0 +1,12 @@
+/*!\file:  SystemMatricesx.h
+*/ 
+
+#ifndef _SYSTEMMATRICESX_H
+#define _SYSTEMMATRICESX_H
+
+#include "../../classes/classes.h"
+
+/* local prototypes: */
+void SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** pdf, IssmDouble* pkmax,FemModel* femmodel);
+
+#endif  /* _SYSTEMMATRICESX_H */
Index: sm/trunk/src/c/modules/ThicknessAbsMisfitx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsMisfitx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ThicknessAbsMisfitx)
-# }}}
Index: /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 16137)
@@ -25,9 +25,7 @@
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
Index: sm/trunk/src/c/modules/ThicknessAcrossGradientx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAcrossGradientx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ThicknessAcrossGradientx)
-# }}}
Index: /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 16137)
@@ -25,9 +25,7 @@
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
Index: sm/trunk/src/c/modules/ThicknessAlongGradientx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAlongGradientx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/ThicknessAlongGradientx)
-# }}}
Index: /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 16136)
+++ /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 16137)
@@ -25,9 +25,7 @@
 
 	/*Sum all J from all cpus of the cluster:*/
-	#ifdef _HAVE_MPI_
-	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
-	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	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;
-	#endif
 
 	/*Assign output pointers: */
Index: sm/trunk/src/c/modules/TriMeshProcessRiftsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/TriMeshProcessRiftsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/TriMeshProcessRiftsx)
-# }}}
Index: sm/trunk/src/c/modules/TriMeshx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/TriMeshx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/TriMeshx)
-# }}}
Index: sm/trunk/src/c/modules/TriaSearchx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/TriaSearchx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/TriaSearchx)
-# }}}
Index: sm/trunk/src/c/modules/UpdateDynamicConstraintsx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/UpdateDynamicConstraintsx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/VecMergex/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/VecMergex/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/VecMergex)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/VecMergex/VecMergex.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/VertexCoordinatesx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/VertexCoordinatesx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/VerticesDofx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/VerticesDofx/VerticesDofx.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/modules/VerticesDofx/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/modules/VerticesDofx/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/modules/VerticesDofx)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/modules/VerticesDofx/VerticesDofx.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/modules/modules.h
===================================================================
--- /issm/trunk/src/c/modules/modules.h	(revision 16136)
+++ /issm/trunk/src/c/modules/modules.h	(revision 16137)
@@ -7,4 +7,5 @@
 
 /*Modules: */
+#include "./AllocateSystemMatricesx/AllocateSystemMatricesx.h"
 #include "./AverageFilterx/AverageFilterx.h"
 #include "./AverageOntoPartitionx/AverageOntoPartitionx.h"
@@ -22,4 +23,5 @@
 #include "./ControlInputScaleGradientx/ControlInputScaleGradientx.h"
 #include "./CreateNodalConstraintsx/CreateNodalConstraintsx.h"
+#include "./CreateJacobianMatrixx/CreateJacobianMatrixx.h"
 #include "./Delta18oParameterizationx/Delta18oParameterizationx.h"
 #include "./DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
@@ -75,4 +77,5 @@
 #include "./PointCloudFindNeighborsx/PointCloudFindNeighborsx.h"
 #include "./PositiveDegreeDayx/PositiveDegreeDayx.h"
+#include "./PostprocessingEnthalpyx/PostprocessingEnthalpyx.h"
 #include "./PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h"
 #include "./Reduceloadx/Reduceloadx.h"
@@ -87,4 +90,5 @@
 #include "./SmbGradientsx/SmbGradientsx.h"
 #include "./Solverx/Solverx.h"
+#include "./SystemMatricesx/SystemMatricesx.h"
 #include "./SpcNodesx/SpcNodesx.h"
 #include "./SurfaceAreax/SurfaceAreax.h"
Index: sm/trunk/src/c/shared/Bamg/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/Bamg/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared/Bamg)
-# }}}
-# BAMG_SOURCES {{{
-set(BAMG_SOURCES $ENV{ISSM_DIR}/src/c/shared/Bamg/BigPrimeNumber.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/shared/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,17 +1,0 @@
-# Subdirectories {{{
-add_subdirectory(Alloc)
-add_subdirectory(Bamg)
-add_subdirectory(Elements)
-add_subdirectory(Exceptions)
-add_subdirectory(Exp)
-add_subdirectory(Matrix)
-add_subdirectory(MemOps)
-add_subdirectory(Numerics)
-add_subdirectory(Sorting)
-add_subdirectory(String)
-add_subdirectory(Threads)
-add_subdirectory(TriMesh)
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared)
-# }}}
Index: /issm/trunk/src/c/shared/Elements/Arrhenius.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/Arrhenius.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/Elements/Arrhenius.cpp	(revision 16137)
@@ -26,5 +26,5 @@
 
 	/*Some physical constants (Payne2000)*/
-	IssmDouble beta=8.66*pow(10.,-4.);
+	IssmDouble beta=8.66*1.e-4;
 	IssmDouble R=8.314;
 
@@ -33,14 +33,14 @@
 
 	/*convert temperature to absolute temperature*/
-	_assert_(depth);
+	_assert_(depth>0);
 	Tstar=temperature-beta*depth;
-	_assert_(Tstar);
+	_assert_(Tstar>0);
 
 	/*Get A*/
 	if(Tstar<263.15){
-		A=3.61*pow(10.,-13.) * exp(  -6.*pow(10.,4.)/(R*Tstar));
+		A=3.61e-13*exp(  -6.e+4/(R*Tstar));
 	}
 	else{
-		A=1.73*pow(10.,  3.) * exp(-13.9*pow(10.,4.)/(R*Tstar));
+		A=1.73e+3 *exp(-13.9e+4/(R*Tstar));
 	}
 
Index: sm/trunk/src/c/shared/Elements/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/Elements/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,23 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared/Elements)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/shared/Elements/Arrhenius.cpp
-$ENV{ISSM_DIR}/src/c/shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp
-          $ENV{ISSM_DIR}/src/c/shared/Elements/GetGlobalDofList.cpp
-           $ENV{ISSM_DIR}/src/c/shared/Elements/GetLocalDofList.cpp
-           $ENV{ISSM_DIR}/src/c/shared/Elements/GetNumberOfDofs.cpp
-    $ENV{ISSM_DIR}/src/c/shared/Elements/GetVerticesCoordinates.cpp
-                  $ENV{ISSM_DIR}/src/c/shared/Elements/Paterson.cpp
-     $ENV{ISSM_DIR}/src/c/shared/Elements/PddSurfaceMassBalance.cpp
-               $ENV{ISSM_DIR}/src/c/shared/Elements/PrintArrays.cpp PARENT_SCOPE)
-# }}}
-# DIAGNOSTIC_SOURCES {{{
-set(DIAGNOSTIC_SOURCES $ENV{ISSM_DIR}/src/c/shared/Elements/CoordinateSystemTransform.cpp
-                $ENV{ISSM_DIR}/src/c/shared/Elements/TransformInvStiffnessMatrixCoord.cpp
-                        $ENV{ISSM_DIR}/src/c/shared/Elements/TransformLoadVectorCoord.cpp
-                          $ENV{ISSM_DIR}/src/c/shared/Elements/TransformSolutionCoord.cpp
-                   $ENV{ISSM_DIR}/src/c/shared/Elements/TransformStiffnessMatrixCoord.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp	(revision 16137)
+++ /issm/trunk/src/c/shared/Elements/DrainageFunctionWaterfraction.cpp	(revision 16137)
@@ -0,0 +1,43 @@
+/*!\file DrainageFunctionWaterfraction.cpp
+ * \brief: drain excess water fraction
+ */
+
+#include <math.h>
+#include "../Numerics/types.h"
+#include "../Exceptions/exceptions.h"
+
+/*FUNCTION IssmDouble DrainageFunctionWaterfraction()*/
+IssmDouble DrainageFunctionWaterfraction(IssmDouble waterfraction, IssmDouble dt=0.){
+    /* DrainageFunctionWaterfraction returns how much of the waterfraction is drained per year */
+    _assert_(waterfraction>=0.);
+    _assert_(dt>=0.);
+
+    IssmDouble w0=0.01, w1=0.02, w2=0.03;
+    IssmDouble Dret, D0=0, D1=0.005, D2=0.05;
+
+    /*get drainage function value*/
+    if((w0==w1)||(w1==w2)||(w0==w2))
+        _error_("Error: equal ordinates in DrainageFunctionWaterfraction -> division by zero. Abort");
+    if(waterfraction<=w0)
+        Dret=D0;
+    if((waterfraction>w0) && (waterfraction<=w1))
+        Dret=(D1-D0)/(w1-w0)*(waterfraction-w0)+D0;
+    if((waterfraction>w1) && (waterfraction<=w2))
+        Dret=(D2-D1)/(w2-w1)*(waterfraction-w1)+D1;
+    else 
+        Dret=D2;
+    
+    /*check if dt*Dret>waterfraction. If so, drain whole waterfraction*/
+    if(dt==0.){
+      if(Dret>waterfraction)
+        return waterfraction;
+      else
+        return Dret;
+    }
+    else{
+      if(dt*Dret>waterfraction)
+        return waterfraction;
+      else
+        return dt*Dret;
+    }
+}
Index: /issm/trunk/src/c/shared/Elements/LliboutryDuval.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/LliboutryDuval.cpp	(revision 16137)
+++ /issm/trunk/src/c/shared/Elements/LliboutryDuval.cpp	(revision 16137)
@@ -0,0 +1,110 @@
+/* \file LliboutryDuval.cpp
+ * \brief figure out B of ice for a certain temperature and water fraction or enthalpy
+ */
+
+#include <math.h>
+#include "../Numerics/types.h"
+#include "../Exceptions/exceptions.h"
+
+
+/* get ice stiffness B from enthalpy, pressure and flow law exponent*/
+IssmDouble LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure,IssmDouble n){
+  /*Use parameterization for the rheology: Aschwanden 2012
+   *
+   *  A(H,p) = A0 exp(-Q/RT(H,p)), if H < H_s(p)
+   *         = A0 exp(-Q/RTpmp) (1+181.25w(H,p)), if H_s(p) \le H < H_l(p)
+   *  
+   *  T(H,p) = Tref + H/c_i, if H < H_s(p)
+   *         = Tpmp , if H_s(p) \le H \le H_l(p)
+   *
+   *  w(H,p) = 0, if H < H_s(p)
+   *         = (H - H_s(p))/L
+   *
+   *  H_s(p) = c_i (Tpmp - Tref)
+   *
+   *  Tpmp   = T - beta p;
+   *
+   *  A0 constant of proportionality
+   *     = 3.61 * 10^-13   if T*<263.15K
+   *     = 1.73 * 10^3     if T*>263.15K
+   *  Q  Activation energy for creep
+   *     = 6.0  * 10^4     if T*<263.15K
+   *     = 13.9 * 10^4     if T*>263.15K
+   *  R  Universal gas constant
+   *     = 8.314
+   *  
+   *  Convert A to B :  B = A^(-1/n) */
+  
+  /*Some physical constants (Aschwanden 2012)*/
+  /*TODO: get those constants from model*/
+  IssmDouble beta=7.9*pow(10.,-8.);
+  IssmDouble R=8.314;
+  IssmDouble heatcapacity=2009; // J/kg/K
+  IssmDouble Tref=253.15;
+  IssmDouble latentheat=3.34*pow(10,5.); // from Aschwanden 2012
+
+  /*Intermediaries*/
+  IssmDouble A,B,Tstar,Tpmp,H_sp,waterfraction;
+	
+  _assert_(pressure>0);
+  _assert_(enthalpy>0);
+  Tpmp=273.15-beta*pressure; 
+  H_sp=heatcapacity*(Tpmp - Tref);
+  if (enthalpy < H_sp){
+    Tstar = Tref + enthalpy/heatcapacity - beta*pressure;	
+    waterfraction = 0;
+  }
+  else{
+    Tstar=Tpmp;
+    waterfraction=(enthalpy - H_sp)/latentheat;
+  }
+
+  /*Get A*/
+  if(Tstar<263.15){
+    A=3.61*pow(10.,-13.) * exp(  -6.*pow(10.,4.)/(R*Tstar));
+  }
+  else{
+    A=1.73*pow(10.,  3.) * exp(-13.9*pow(10.,4.)/(R*Tstar));
+  }
+  A*=(1 + 181.25*waterfraction);
+
+  /*Convert to B*/
+  _assert_(n>0);
+  B=pow(A,-1./n);
+
+  return B;
+}
+
+/*Get stiffness from temperature, waterfraction and depth*/
+IssmDouble LliboutryDuval(IssmDouble temperature, IssmDouble waterfraction, IssmDouble depth,IssmDouble n){
+	/*Use parameterization for the rheology: Greve and Blatter 2009
+	 * get enthalpy from temperature and water fraction,
+	 * and use LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure,IssmDouble n) */
+  
+  IssmDouble rho_ice=910; // kg/m^3
+  IssmDouble g=9.81; //kg*m/s^2
+  IssmDouble heatcapacity=2009; // J/kg/K
+  IssmDouble Tref=253.15;
+  IssmDouble beta=7.9*pow(10.,-8.);
+  IssmDouble latentheat=3.34*pow(10,5.); // from Aschwanden 2012
+  IssmDouble Tstar, enthalpy, pressure, B;
+  _assert_(temperature>0);
+  _assert_(waterfraction>0);
+  _assert_(depth>0);
+
+  /*get pressure*/
+  pressure= rho_ice*g*depth;
+  Tstar=temperature-beta*pressure; // TODO: check whether plus or minus
+  /*get enthalpy*/
+  if (Tstar < 273.15){
+    enthalpy=heatcapacity*(Tstar - Tref);
+  }
+  else{
+    enthalpy=heatcapacity*(273.15 - Tref) + waterfraction*latentheat;
+  }
+	
+  B=LliboutryDuval(enthalpy, pressure, n);
+
+  return B;
+}
+
Index: /issm/trunk/src/c/shared/Elements/elements.h
===================================================================
--- /issm/trunk/src/c/shared/Elements/elements.h	(revision 16136)
+++ /issm/trunk/src/c/shared/Elements/elements.h	(revision 16137)
@@ -10,4 +10,6 @@
 IssmDouble Paterson(IssmDouble temperature);
 IssmDouble Arrhenius(IssmDouble temperature,IssmDouble depth,IssmDouble n);
+IssmDouble LliboutryDuval(IssmDouble enthalpy, IssmDouble pressure,IssmDouble n);
+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,
@@ -17,5 +19,6 @@
 				     IssmDouble* PrecipitationsPresentday,
 				     IssmDouble* TemperaturesLgm, IssmDouble* TemperaturesPresentday, 
-					     IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout);
+					  IssmDouble* monthlytemperaturesout, IssmDouble* monthlyprecout);
+IssmDouble DrainageFunctionWaterfraction(IssmDouble waterfraction, IssmDouble dt=0.);
 
 /*Print arrays*/
Index: sm/trunk/src/c/shared/Enum/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/Enum/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/EnumDefinitions)
-# }}}
Index: /issm/trunk/src/c/shared/Enum/EnumDefinitions.h
===================================================================
--- /issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 16136)
+++ /issm/trunk/src/c/shared/Enum/EnumDefinitions.h	(revision 16137)
@@ -41,34 +41,38 @@
 	ConstantsYtsEnum,
 	DependentObjectEnum,
-	DiagnosticAbstolEnum,
-	DiagnosticIcefrontEnum,
-	DiagnosticIsnewtonEnum,
-	DiagnosticMaxiterEnum,
-	DiagnosticNumRequestedOutputsEnum,
-	DiagnosticPenaltyFactorEnum,
-	DiagnosticReferentialEnum,
-	DiagnosticReltolEnum,
-	DiagnosticRequestedOutputsEnum,
-	DiagnosticRestolEnum,
-	DiagnosticRiftPenaltyLockEnum,
-	DiagnosticRiftPenaltyThresholdEnum,
-	DiagnosticShelfDampeningEnum,
-	DiagnosticSpcvxEnum,
-	DiagnosticSpcvyEnum,
-	DiagnosticSpcvzEnum,
-	DiagnosticStokesreconditioningEnum,
-	DiagnosticVertexPairingEnum,
-	DiagnosticViscosityOvershootEnum,
+	StressbalanceAbstolEnum,
+	StressbalanceIcefrontEnum,
+	StressbalanceIsnewtonEnum,
+	StressbalanceMaxiterEnum,
+	StressbalanceNumRequestedOutputsEnum,
+	StressbalancePenaltyFactorEnum,
+	StressbalanceReferentialEnum,
+	StressbalanceReltolEnum,
+	StressbalanceRequestedOutputsEnum,
+	StressbalanceRestolEnum,
+	StressbalanceRiftPenaltyLockEnum,
+	StressbalanceRiftPenaltyThresholdEnum,
+	StressbalanceShelfDampeningEnum,
+	StressbalanceSpcvxEnum,
+	StressbalanceSpcvyEnum,
+	StressbalanceSpcvzEnum,
+	StressbalanceFSreconditioningEnum,
+	StressbalanceVertexPairingEnum,
+	StressbalanceViscosityOvershootEnum,
 	LoadingforceXEnum,
 	LoadingforceYEnum,
 	LoadingforceZEnum,
-	FlowequationBordermacayealEnum,
-	FlowequationBorderpattynEnum,
-	FlowequationBorderstokesEnum,
+	FlowequationBorderSSAEnum,
+	FlowequationBorderHOEnum,
+	FlowequationBorderFSEnum,
 	FlowequationElementEquationEnum,
-	FlowequationIshutterEnum,
-	FlowequationIsl1l2Enum,
-	FlowequationIsmacayealpattynEnum,
-	FlowequationIsstokesEnum,
+	FlowequationIsSIAEnum,
+	FlowequationIsSSAEnum,
+	FlowequationIsL1L2Enum,
+	FlowequationIsHOEnum,
+	FlowequationIsFSEnum,
+	FlowequationFeSSAEnum,
+	FlowequationFeHOEnum,
+	FlowequationFeFSEnum,
 	FlowequationVertexEquationEnum,
 	FrictionCoefficientEnum,
@@ -138,10 +142,5 @@
 	InversionVyObsEnum,
 	InversionVzObsEnum,
-	MaskElementonfloatingiceEnum,
-	MaskElementongroundediceEnum,
-	MaskElementonwaterEnum,
-	MaskVertexonfloatingiceEnum,
-	MaskVertexongroundediceEnum,
-	MaskVertexonwaterEnum,
+	MaskIceLevelsetEnum,
 	MaterialsBetaEnum,
 	MaterialsHeatcapacityEnum,
@@ -167,6 +166,4 @@
 	MeshAverageVertexConnectivityEnum,
 	MeshDimensionEnum,
-	MeshEdgesEnum,
-	MeshElementconnectivityEnum,
 	MeshElementonbedEnum,
 	MeshElementonsurfaceEnum,
@@ -174,5 +171,4 @@
 	MeshElementsEnum,
 	MeshLowerelementsEnum,
-	MeshNumberofedgesEnum,
 	MeshNumberofelements2dEnum,
 	MeshNumberofelementsEnum,
@@ -187,12 +183,13 @@
 	MeshZEnum,
 	MiscellaneousNameEnum, //FIXME: only used by qmu, should not be marshalled (already in queueing script)
-	PrognosticHydrostaticAdjustmentEnum,
-	PrognosticMinThicknessEnum,
-	PrognosticPenaltyFactorEnum,
-	PrognosticSpcthicknessEnum,
-	PrognosticStabilizationEnum,
-	PrognosticVertexPairingEnum,
-	PrognosticNumRequestedOutputsEnum,
-	PrognosticRequestedOutputsEnum,
+	MasstransportHydrostaticAdjustmentEnum,
+	MasstransportIsfreesurfaceEnum,
+	MasstransportMinThicknessEnum,
+	MasstransportPenaltyFactorEnum,
+	MasstransportSpcthicknessEnum,
+	MasstransportStabilizationEnum,
+	MasstransportVertexPairingEnum,
+	MasstransportNumRequestedOutputsEnum,
+	MasstransportRequestedOutputsEnum,
 	QmuIsdakotaEnum,
 	MassFluxSegmentsEnum,
@@ -239,4 +236,6 @@
 	SurfaceforcingsBPosEnum,
 	SurfaceforcingsBNegEnum,
+	ThermalIsenthalpyEnum,
+    	ThermalIsdynamicbasalspcEnum,
 	ThermalMaxiterEnum,
 	ThermalPenaltyFactorEnum,
@@ -245,5 +244,4 @@
 	ThermalSpctemperatureEnum,
 	ThermalStabilizationEnum,
-	ThermalIsenthalpyEnum,
 	GiaMantleViscosityEnum,
 	GiaLithosphereThicknessEnum,
@@ -254,7 +252,7 @@
 	TimesteppingTimeAdaptEnum,
 	TimesteppingTimeStepEnum,
-	TransientIsdiagnosticEnum,
+	TransientIsstressbalanceEnum,
 	TransientIsgroundinglineEnum,
-	TransientIsprognosticEnum,
+	TransientIsmasstransportEnum,
 	TransientIsthermalEnum,
 	TransientIsgiaEnum,
@@ -276,12 +274,14 @@
 	BalancethicknessSoftAnalysisEnum,
 	BalancethicknessSoftSolutionEnum,
+	BalancevelocityAnalysisEnum,
+	BalancevelocitySolutionEnum,
 	BedSlopeAnalysisEnum,
 	BedSlopeSolutionEnum,
 	BedSlopeXAnalysisEnum,
 	BedSlopeYAnalysisEnum,
-	DiagnosticHorizAnalysisEnum,
-	DiagnosticHutterAnalysisEnum,
-	DiagnosticSolutionEnum,
-	DiagnosticVertAnalysisEnum,
+	StressbalanceAnalysisEnum,
+	StressbalanceSIAAnalysisEnum,
+	StressbalanceSolutionEnum,
+	StressbalanceVerticalAnalysisEnum,
 	EnthalpyAnalysisEnum,
 	EnthalpySolutionEnum,
@@ -293,6 +293,8 @@
 	HydrologySolutionEnum,
 	MeltingAnalysisEnum,
-	PrognosticAnalysisEnum,
-	PrognosticSolutionEnum,
+	MasstransportAnalysisEnum,
+	MasstransportSolutionEnum,
+	FreeSurfaceBaseAnalysisEnum,
+	FreeSurfaceTopAnalysisEnum,
 	SteadystateSolutionEnum,
 	SurfaceSlopeAnalysisEnum,
@@ -300,4 +302,6 @@
 	SurfaceSlopeXAnalysisEnum,
 	SurfaceSlopeYAnalysisEnum,
+	SmoothedSurfaceSlopeXAnalysisEnum,
+	SmoothedSurfaceSlopeYAnalysisEnum,
 	ThermalAnalysisEnum,
 	ThermalSolutionEnum,
@@ -309,12 +313,14 @@
 	ApproximationEnum,
 	NoneApproximationEnum,
-	HutterApproximationEnum,
-	MacAyealApproximationEnum,
-	MacAyealPattynApproximationEnum,
-	MacAyealStokesApproximationEnum,
+	SIAApproximationEnum,
+	SSAApproximationEnum,
+	SSAHOApproximationEnum,
+	SSAFSApproximationEnum,
 	L1L2ApproximationEnum,
-	PattynApproximationEnum,
-	PattynStokesApproximationEnum,
-	StokesApproximationEnum,
+	HOApproximationEnum,
+	HOFSApproximationEnum,
+	FSApproximationEnum,
+	FSvelocityEnum,
+	FSpressureEnum,
 	/*}}}*/
 	/*Datasets {{{*/
@@ -355,6 +361,6 @@
 	TransientParamEnum,
 	IceFrontTypeEnum,
-	MacAyeal2dIceFrontEnum,
-	MacAyeal3dIceFrontEnum,
+	SSA2dIceFrontEnum,
+	SSA3dIceFrontEnum,
 	MaticeEnum,
 	MatdamageiceEnum,
@@ -365,9 +371,9 @@
 	ParamEnum,
 	L1L2IceFrontEnum,
-	PattynIceFrontEnum,
+	HOIceFrontEnum,
 	PengridEnum,
 	PenpairEnum,
 	PentaEnum,
-	PentaP1InputEnum,
+	PentaInputEnum,
 	ProfilerEnum,
 	MatrixParamEnum,
@@ -381,5 +387,5 @@
 	SpcStaticEnum,
 	SpcTransientEnum,
-	StokesIceFrontEnum,
+	FSIceFrontEnum,
 	StringArrayParamEnum,
 	StringParamEnum,
@@ -459,8 +465,8 @@
 	VyPicardEnum,
 	VzEnum,
-	VzMacAyealEnum,
-	VzPattynEnum,
+	VzSSAEnum,
+	VzHOEnum,
 	VzPicardEnum,
-	VzStokesEnum,
+	VzFSEnum,
 	VxMeshEnum,
 	VyMeshEnum,
@@ -498,6 +504,14 @@
 	P1Enum,
 	P1DGEnum,
+	P1bubbleEnum,
+	P1bubblecondensedEnum,
+	P2Enum,
+	P2xP1Enum,
+	P1xP2Enum,
+	P1P1Enum,
+	P1P1GLSEnum,
 	MINIEnum,
-	P2Enum,
+	MINIcondensedEnum,
+	TaylorHoodEnum,
 	/*}}}*/
 	/*Results{{{*/
@@ -545,8 +559,8 @@
 	SubelementMigrationEnum,
 	SubelementMigration2Enum,
-	GLlevelsetEnum,
+	MaskGroundediceLevelsetEnum,
 	/*}}}*/
 	/*Solver{{{*/
-	StokesSolverEnum,
+	FSSolverEnum,
 	/*}}}*/
 	/*Parameters{{{*/
@@ -587,5 +601,5 @@
 	/*Coordinate Systems{{{*/
 	XYEnum,
-	XYZPEnum,
+	XYZEnum,
 	/*}}}*/
 	/*Toolkits{{{*/
@@ -607,6 +621,7 @@
 	PatersonEnum,
 	ArrheniusEnum,
-	/*}}}*/
-	MaximumNumberOfEnums
+	LliboutryDuvalEnum,
+	/*}}}*/
+	MaximumNumberOfDefinitionsEnum
 };
 
Index: /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp
===================================================================
--- /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/Enum/EnumToStringx.cpp	(revision 16137)
@@ -49,34 +49,38 @@
 		case ConstantsYtsEnum : return "ConstantsYts";
 		case DependentObjectEnum : return "DependentObject";
-		case DiagnosticAbstolEnum : return "DiagnosticAbstol";
-		case DiagnosticIcefrontEnum : return "DiagnosticIcefront";
-		case DiagnosticIsnewtonEnum : return "DiagnosticIsnewton";
-		case DiagnosticMaxiterEnum : return "DiagnosticMaxiter";
-		case DiagnosticNumRequestedOutputsEnum : return "DiagnosticNumRequestedOutputs";
-		case DiagnosticPenaltyFactorEnum : return "DiagnosticPenaltyFactor";
-		case DiagnosticReferentialEnum : return "DiagnosticReferential";
-		case DiagnosticReltolEnum : return "DiagnosticReltol";
-		case DiagnosticRequestedOutputsEnum : return "DiagnosticRequestedOutputs";
-		case DiagnosticRestolEnum : return "DiagnosticRestol";
-		case DiagnosticRiftPenaltyLockEnum : return "DiagnosticRiftPenaltyLock";
-		case DiagnosticRiftPenaltyThresholdEnum : return "DiagnosticRiftPenaltyThreshold";
-		case DiagnosticShelfDampeningEnum : return "DiagnosticShelfDampening";
-		case DiagnosticSpcvxEnum : return "DiagnosticSpcvx";
-		case DiagnosticSpcvyEnum : return "DiagnosticSpcvy";
-		case DiagnosticSpcvzEnum : return "DiagnosticSpcvz";
-		case DiagnosticStokesreconditioningEnum : return "DiagnosticStokesreconditioning";
-		case DiagnosticVertexPairingEnum : return "DiagnosticVertexPairing";
-		case DiagnosticViscosityOvershootEnum : return "DiagnosticViscosityOvershoot";
+		case StressbalanceAbstolEnum : return "StressbalanceAbstol";
+		case StressbalanceIcefrontEnum : return "StressbalanceIcefront";
+		case StressbalanceIsnewtonEnum : return "StressbalanceIsnewton";
+		case StressbalanceMaxiterEnum : return "StressbalanceMaxiter";
+		case StressbalanceNumRequestedOutputsEnum : return "StressbalanceNumRequestedOutputs";
+		case StressbalancePenaltyFactorEnum : return "StressbalancePenaltyFactor";
+		case StressbalanceReferentialEnum : return "StressbalanceReferential";
+		case StressbalanceReltolEnum : return "StressbalanceReltol";
+		case StressbalanceRequestedOutputsEnum : return "StressbalanceRequestedOutputs";
+		case StressbalanceRestolEnum : return "StressbalanceRestol";
+		case StressbalanceRiftPenaltyLockEnum : return "StressbalanceRiftPenaltyLock";
+		case StressbalanceRiftPenaltyThresholdEnum : return "StressbalanceRiftPenaltyThreshold";
+		case StressbalanceShelfDampeningEnum : return "StressbalanceShelfDampening";
+		case StressbalanceSpcvxEnum : return "StressbalanceSpcvx";
+		case StressbalanceSpcvyEnum : return "StressbalanceSpcvy";
+		case StressbalanceSpcvzEnum : return "StressbalanceSpcvz";
+		case StressbalanceFSreconditioningEnum : return "StressbalanceFSreconditioning";
+		case StressbalanceVertexPairingEnum : return "StressbalanceVertexPairing";
+		case StressbalanceViscosityOvershootEnum : return "StressbalanceViscosityOvershoot";
 		case LoadingforceXEnum : return "LoadingforceX";
 		case LoadingforceYEnum : return "LoadingforceY";
 		case LoadingforceZEnum : return "LoadingforceZ";
-		case FlowequationBordermacayealEnum : return "FlowequationBordermacayeal";
-		case FlowequationBorderpattynEnum : return "FlowequationBorderpattyn";
-		case FlowequationBorderstokesEnum : return "FlowequationBorderstokes";
+		case FlowequationBorderSSAEnum : return "FlowequationBorderSSA";
+		case FlowequationBorderHOEnum : return "FlowequationBorderHO";
+		case FlowequationBorderFSEnum : return "FlowequationBorderFS";
 		case FlowequationElementEquationEnum : return "FlowequationElementEquation";
-		case FlowequationIshutterEnum : return "FlowequationIshutter";
-		case FlowequationIsl1l2Enum : return "FlowequationIsl1l2";
-		case FlowequationIsmacayealpattynEnum : return "FlowequationIsmacayealpattyn";
-		case FlowequationIsstokesEnum : return "FlowequationIsstokes";
+		case FlowequationIsSIAEnum : return "FlowequationIsSIA";
+		case FlowequationIsSSAEnum : return "FlowequationIsSSA";
+		case FlowequationIsL1L2Enum : return "FlowequationIsL1L2";
+		case FlowequationIsHOEnum : return "FlowequationIsHO";
+		case FlowequationIsFSEnum : return "FlowequationIsFS";
+		case FlowequationFeSSAEnum : return "FlowequationFeSSA";
+		case FlowequationFeHOEnum : return "FlowequationFeHO";
+		case FlowequationFeFSEnum : return "FlowequationFeFS";
 		case FlowequationVertexEquationEnum : return "FlowequationVertexEquation";
 		case FrictionCoefficientEnum : return "FrictionCoefficient";
@@ -146,10 +150,5 @@
 		case InversionVyObsEnum : return "InversionVyObs";
 		case InversionVzObsEnum : return "InversionVzObs";
-		case MaskElementonfloatingiceEnum : return "MaskElementonfloatingice";
-		case MaskElementongroundediceEnum : return "MaskElementongroundedice";
-		case MaskElementonwaterEnum : return "MaskElementonwater";
-		case MaskVertexonfloatingiceEnum : return "MaskVertexonfloatingice";
-		case MaskVertexongroundediceEnum : return "MaskVertexongroundedice";
-		case MaskVertexonwaterEnum : return "MaskVertexonwater";
+		case MaskIceLevelsetEnum : return "MaskIceLevelset";
 		case MaterialsBetaEnum : return "MaterialsBeta";
 		case MaterialsHeatcapacityEnum : return "MaterialsHeatcapacity";
@@ -175,6 +174,4 @@
 		case MeshAverageVertexConnectivityEnum : return "MeshAverageVertexConnectivity";
 		case MeshDimensionEnum : return "MeshDimension";
-		case MeshEdgesEnum : return "MeshEdges";
-		case MeshElementconnectivityEnum : return "MeshElementconnectivity";
 		case MeshElementonbedEnum : return "MeshElementonbed";
 		case MeshElementonsurfaceEnum : return "MeshElementonsurface";
@@ -182,5 +179,4 @@
 		case MeshElementsEnum : return "MeshElements";
 		case MeshLowerelementsEnum : return "MeshLowerelements";
-		case MeshNumberofedgesEnum : return "MeshNumberofedges";
 		case MeshNumberofelements2dEnum : return "MeshNumberofelements2d";
 		case MeshNumberofelementsEnum : return "MeshNumberofelements";
@@ -195,12 +191,13 @@
 		case MeshZEnum : return "MeshZ";
 		case MiscellaneousNameEnum : return "MiscellaneousName";
-		case PrognosticHydrostaticAdjustmentEnum : return "PrognosticHydrostaticAdjustment";
-		case PrognosticMinThicknessEnum : return "PrognosticMinThickness";
-		case PrognosticPenaltyFactorEnum : return "PrognosticPenaltyFactor";
-		case PrognosticSpcthicknessEnum : return "PrognosticSpcthickness";
-		case PrognosticStabilizationEnum : return "PrognosticStabilization";
-		case PrognosticVertexPairingEnum : return "PrognosticVertexPairing";
-		case PrognosticNumRequestedOutputsEnum : return "PrognosticNumRequestedOutputs";
-		case PrognosticRequestedOutputsEnum : return "PrognosticRequestedOutputs";
+		case MasstransportHydrostaticAdjustmentEnum : return "MasstransportHydrostaticAdjustment";
+		case MasstransportIsfreesurfaceEnum : return "MasstransportIsfreesurface";
+		case MasstransportMinThicknessEnum : return "MasstransportMinThickness";
+		case MasstransportPenaltyFactorEnum : return "MasstransportPenaltyFactor";
+		case MasstransportSpcthicknessEnum : return "MasstransportSpcthickness";
+		case MasstransportStabilizationEnum : return "MasstransportStabilization";
+		case MasstransportVertexPairingEnum : return "MasstransportVertexPairing";
+		case MasstransportNumRequestedOutputsEnum : return "MasstransportNumRequestedOutputs";
+		case MasstransportRequestedOutputsEnum : return "MasstransportRequestedOutputs";
 		case QmuIsdakotaEnum : return "QmuIsdakota";
 		case MassFluxSegmentsEnum : return "MassFluxSegments";
@@ -247,4 +244,6 @@
 		case SurfaceforcingsBPosEnum : return "SurfaceforcingsBPos";
 		case SurfaceforcingsBNegEnum : return "SurfaceforcingsBNeg";
+		case ThermalIsenthalpyEnum : return "ThermalIsenthalpy";
+		case ThermalIsdynamicbasalspcEnum : return "ThermalIsdynamicbasalspc";
 		case ThermalMaxiterEnum : return "ThermalMaxiter";
 		case ThermalPenaltyFactorEnum : return "ThermalPenaltyFactor";
@@ -253,5 +252,4 @@
 		case ThermalSpctemperatureEnum : return "ThermalSpctemperature";
 		case ThermalStabilizationEnum : return "ThermalStabilization";
-		case ThermalIsenthalpyEnum : return "ThermalIsenthalpy";
 		case GiaMantleViscosityEnum : return "GiaMantleViscosity";
 		case GiaLithosphereThicknessEnum : return "GiaLithosphereThickness";
@@ -262,7 +260,7 @@
 		case TimesteppingTimeAdaptEnum : return "TimesteppingTimeAdapt";
 		case TimesteppingTimeStepEnum : return "TimesteppingTimeStep";
-		case TransientIsdiagnosticEnum : return "TransientIsdiagnostic";
+		case TransientIsstressbalanceEnum : return "TransientIsstressbalance";
 		case TransientIsgroundinglineEnum : return "TransientIsgroundingline";
-		case TransientIsprognosticEnum : return "TransientIsprognostic";
+		case TransientIsmasstransportEnum : return "TransientIsmasstransport";
 		case TransientIsthermalEnum : return "TransientIsthermal";
 		case TransientIsgiaEnum : return "TransientIsgia";
@@ -282,12 +280,14 @@
 		case BalancethicknessSoftAnalysisEnum : return "BalancethicknessSoftAnalysis";
 		case BalancethicknessSoftSolutionEnum : return "BalancethicknessSoftSolution";
+		case BalancevelocityAnalysisEnum : return "BalancevelocityAnalysis";
+		case BalancevelocitySolutionEnum : return "BalancevelocitySolution";
 		case BedSlopeAnalysisEnum : return "BedSlopeAnalysis";
 		case BedSlopeSolutionEnum : return "BedSlopeSolution";
 		case BedSlopeXAnalysisEnum : return "BedSlopeXAnalysis";
 		case BedSlopeYAnalysisEnum : return "BedSlopeYAnalysis";
-		case DiagnosticHorizAnalysisEnum : return "DiagnosticHorizAnalysis";
-		case DiagnosticHutterAnalysisEnum : return "DiagnosticHutterAnalysis";
-		case DiagnosticSolutionEnum : return "DiagnosticSolution";
-		case DiagnosticVertAnalysisEnum : return "DiagnosticVertAnalysis";
+		case StressbalanceAnalysisEnum : return "StressbalanceAnalysis";
+		case StressbalanceSIAAnalysisEnum : return "StressbalanceSIAAnalysis";
+		case StressbalanceSolutionEnum : return "StressbalanceSolution";
+		case StressbalanceVerticalAnalysisEnum : return "StressbalanceVerticalAnalysis";
 		case EnthalpyAnalysisEnum : return "EnthalpyAnalysis";
 		case EnthalpySolutionEnum : return "EnthalpySolution";
@@ -299,6 +299,8 @@
 		case HydrologySolutionEnum : return "HydrologySolution";
 		case MeltingAnalysisEnum : return "MeltingAnalysis";
-		case PrognosticAnalysisEnum : return "PrognosticAnalysis";
-		case PrognosticSolutionEnum : return "PrognosticSolution";
+		case MasstransportAnalysisEnum : return "MasstransportAnalysis";
+		case MasstransportSolutionEnum : return "MasstransportSolution";
+		case FreeSurfaceBaseAnalysisEnum : return "FreeSurfaceBaseAnalysis";
+		case FreeSurfaceTopAnalysisEnum : return "FreeSurfaceTopAnalysis";
 		case SteadystateSolutionEnum : return "SteadystateSolution";
 		case SurfaceSlopeAnalysisEnum : return "SurfaceSlopeAnalysis";
@@ -306,4 +308,6 @@
 		case SurfaceSlopeXAnalysisEnum : return "SurfaceSlopeXAnalysis";
 		case SurfaceSlopeYAnalysisEnum : return "SurfaceSlopeYAnalysis";
+		case SmoothedSurfaceSlopeXAnalysisEnum : return "SmoothedSurfaceSlopeXAnalysis";
+		case SmoothedSurfaceSlopeYAnalysisEnum : return "SmoothedSurfaceSlopeYAnalysis";
 		case ThermalAnalysisEnum : return "ThermalAnalysis";
 		case ThermalSolutionEnum : return "ThermalSolution";
@@ -313,12 +317,14 @@
 		case ApproximationEnum : return "Approximation";
 		case NoneApproximationEnum : return "NoneApproximation";
-		case HutterApproximationEnum : return "HutterApproximation";
-		case MacAyealApproximationEnum : return "MacAyealApproximation";
-		case MacAyealPattynApproximationEnum : return "MacAyealPattynApproximation";
-		case MacAyealStokesApproximationEnum : return "MacAyealStokesApproximation";
+		case SIAApproximationEnum : return "SIAApproximation";
+		case SSAApproximationEnum : return "SSAApproximation";
+		case SSAHOApproximationEnum : return "SSAHOApproximation";
+		case SSAFSApproximationEnum : return "SSAFSApproximation";
 		case L1L2ApproximationEnum : return "L1L2Approximation";
-		case PattynApproximationEnum : return "PattynApproximation";
-		case PattynStokesApproximationEnum : return "PattynStokesApproximation";
-		case StokesApproximationEnum : return "StokesApproximation";
+		case HOApproximationEnum : return "HOApproximation";
+		case HOFSApproximationEnum : return "HOFSApproximation";
+		case FSApproximationEnum : return "FSApproximation";
+		case FSvelocityEnum : return "FSvelocity";
+		case FSpressureEnum : return "FSpressure";
 		case ConstraintsEnum : return "Constraints";
 		case LoadsEnum : return "Loads";
@@ -355,6 +361,6 @@
 		case TransientParamEnum : return "TransientParam";
 		case IceFrontTypeEnum : return "IceFrontType";
-		case MacAyeal2dIceFrontEnum : return "MacAyeal2dIceFront";
-		case MacAyeal3dIceFrontEnum : return "MacAyeal3dIceFront";
+		case SSA2dIceFrontEnum : return "SSA2dIceFront";
+		case SSA3dIceFrontEnum : return "SSA3dIceFront";
 		case MaticeEnum : return "Matice";
 		case MatdamageiceEnum : return "Matdamageice";
@@ -365,9 +371,9 @@
 		case ParamEnum : return "Param";
 		case L1L2IceFrontEnum : return "L1L2IceFront";
-		case PattynIceFrontEnum : return "PattynIceFront";
+		case HOIceFrontEnum : return "HOIceFront";
 		case PengridEnum : return "Pengrid";
 		case PenpairEnum : return "Penpair";
 		case PentaEnum : return "Penta";
-		case PentaP1InputEnum : return "PentaP1Input";
+		case PentaInputEnum : return "PentaInput";
 		case ProfilerEnum : return "Profiler";
 		case MatrixParamEnum : return "MatrixParam";
@@ -381,5 +387,5 @@
 		case SpcStaticEnum : return "SpcStatic";
 		case SpcTransientEnum : return "SpcTransient";
-		case StokesIceFrontEnum : return "StokesIceFront";
+		case FSIceFrontEnum : return "FSIceFront";
 		case StringArrayParamEnum : return "StringArrayParam";
 		case StringParamEnum : return "StringParam";
@@ -453,8 +459,8 @@
 		case VyPicardEnum : return "VyPicard";
 		case VzEnum : return "Vz";
-		case VzMacAyealEnum : return "VzMacAyeal";
-		case VzPattynEnum : return "VzPattyn";
+		case VzSSAEnum : return "VzSSA";
+		case VzHOEnum : return "VzHO";
 		case VzPicardEnum : return "VzPicard";
-		case VzStokesEnum : return "VzStokes";
+		case VzFSEnum : return "VzFS";
 		case VxMeshEnum : return "VxMesh";
 		case VyMeshEnum : return "VyMesh";
@@ -490,6 +496,14 @@
 		case P1Enum : return "P1";
 		case P1DGEnum : return "P1DG";
+		case P1bubbleEnum : return "P1bubble";
+		case P1bubblecondensedEnum : return "P1bubblecondensed";
+		case P2Enum : return "P2";
+		case P2xP1Enum : return "P2xP1";
+		case P1xP2Enum : return "P1xP2";
+		case P1P1Enum : return "P1P1";
+		case P1P1GLSEnum : return "P1P1GLS";
 		case MINIEnum : return "MINI";
-		case P2Enum : return "P2";
+		case MINIcondensedEnum : return "MINIcondensed";
+		case TaylorHoodEnum : return "TaylorHood";
 		case SaveResultsEnum : return "SaveResults";
 		case BoolElementResultEnum : return "BoolElementResult";
@@ -529,6 +543,6 @@
 		case SubelementMigrationEnum : return "SubelementMigration";
 		case SubelementMigration2Enum : return "SubelementMigration2";
-		case GLlevelsetEnum : return "GLlevelset";
-		case StokesSolverEnum : return "StokesSolver";
+		case MaskGroundediceLevelsetEnum : return "MaskGroundediceLevelset";
+		case FSSolverEnum : return "FSSolver";
 		case AdjointEnum : return "Adjoint";
 		case ColinearEnum : return "Colinear";
@@ -563,5 +577,5 @@
 		case NearestInterpEnum : return "NearestInterp";
 		case XYEnum : return "XY";
-		case XYZPEnum : return "XYZP";
+		case XYZEnum : return "XYZ";
 		case DenseEnum : return "Dense";
 		case MpiDenseEnum : return "MpiDense";
@@ -577,4 +591,6 @@
 		case PatersonEnum : return "Paterson";
 		case ArrheniusEnum : return "Arrhenius";
+		case LliboutryDuvalEnum : return "LliboutryDuval";
+		case MaximumNumberOfDefinitionsEnum : return "MaximumNumberOfDefinitions";
 		default : return "unknown";
 
Index: /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp
===================================================================
--- /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/Enum/StringToEnumx.cpp	(revision 16137)
@@ -49,34 +49,38 @@
 	      else if (strcmp(name,"ConstantsYts")==0) return ConstantsYtsEnum;
 	      else if (strcmp(name,"DependentObject")==0) return DependentObjectEnum;
-	      else if (strcmp(name,"DiagnosticAbstol")==0) return DiagnosticAbstolEnum;
-	      else if (strcmp(name,"DiagnosticIcefront")==0) return DiagnosticIcefrontEnum;
-	      else if (strcmp(name,"DiagnosticIsnewton")==0) return DiagnosticIsnewtonEnum;
-	      else if (strcmp(name,"DiagnosticMaxiter")==0) return DiagnosticMaxiterEnum;
-	      else if (strcmp(name,"DiagnosticNumRequestedOutputs")==0) return DiagnosticNumRequestedOutputsEnum;
-	      else if (strcmp(name,"DiagnosticPenaltyFactor")==0) return DiagnosticPenaltyFactorEnum;
-	      else if (strcmp(name,"DiagnosticReferential")==0) return DiagnosticReferentialEnum;
-	      else if (strcmp(name,"DiagnosticReltol")==0) return DiagnosticReltolEnum;
-	      else if (strcmp(name,"DiagnosticRequestedOutputs")==0) return DiagnosticRequestedOutputsEnum;
-	      else if (strcmp(name,"DiagnosticRestol")==0) return DiagnosticRestolEnum;
-	      else if (strcmp(name,"DiagnosticRiftPenaltyLock")==0) return DiagnosticRiftPenaltyLockEnum;
-	      else if (strcmp(name,"DiagnosticRiftPenaltyThreshold")==0) return DiagnosticRiftPenaltyThresholdEnum;
-	      else if (strcmp(name,"DiagnosticShelfDampening")==0) return DiagnosticShelfDampeningEnum;
-	      else if (strcmp(name,"DiagnosticSpcvx")==0) return DiagnosticSpcvxEnum;
-	      else if (strcmp(name,"DiagnosticSpcvy")==0) return DiagnosticSpcvyEnum;
-	      else if (strcmp(name,"DiagnosticSpcvz")==0) return DiagnosticSpcvzEnum;
-	      else if (strcmp(name,"DiagnosticStokesreconditioning")==0) return DiagnosticStokesreconditioningEnum;
-	      else if (strcmp(name,"DiagnosticVertexPairing")==0) return DiagnosticVertexPairingEnum;
-	      else if (strcmp(name,"DiagnosticViscosityOvershoot")==0) return DiagnosticViscosityOvershootEnum;
+	      else if (strcmp(name,"StressbalanceAbstol")==0) return StressbalanceAbstolEnum;
+	      else if (strcmp(name,"StressbalanceIcefront")==0) return StressbalanceIcefrontEnum;
+	      else if (strcmp(name,"StressbalanceIsnewton")==0) return StressbalanceIsnewtonEnum;
+	      else if (strcmp(name,"StressbalanceMaxiter")==0) return StressbalanceMaxiterEnum;
+	      else if (strcmp(name,"StressbalanceNumRequestedOutputs")==0) return StressbalanceNumRequestedOutputsEnum;
+	      else if (strcmp(name,"StressbalancePenaltyFactor")==0) return StressbalancePenaltyFactorEnum;
+	      else if (strcmp(name,"StressbalanceReferential")==0) return StressbalanceReferentialEnum;
+	      else if (strcmp(name,"StressbalanceReltol")==0) return StressbalanceReltolEnum;
+	      else if (strcmp(name,"StressbalanceRequestedOutputs")==0) return StressbalanceRequestedOutputsEnum;
+	      else if (strcmp(name,"StressbalanceRestol")==0) return StressbalanceRestolEnum;
+	      else if (strcmp(name,"StressbalanceRiftPenaltyLock")==0) return StressbalanceRiftPenaltyLockEnum;
+	      else if (strcmp(name,"StressbalanceRiftPenaltyThreshold")==0) return StressbalanceRiftPenaltyThresholdEnum;
+	      else if (strcmp(name,"StressbalanceShelfDampening")==0) return StressbalanceShelfDampeningEnum;
+	      else if (strcmp(name,"StressbalanceSpcvx")==0) return StressbalanceSpcvxEnum;
+	      else if (strcmp(name,"StressbalanceSpcvy")==0) return StressbalanceSpcvyEnum;
+	      else if (strcmp(name,"StressbalanceSpcvz")==0) return StressbalanceSpcvzEnum;
+	      else if (strcmp(name,"StressbalanceFSreconditioning")==0) return StressbalanceFSreconditioningEnum;
+	      else if (strcmp(name,"StressbalanceVertexPairing")==0) return StressbalanceVertexPairingEnum;
+	      else if (strcmp(name,"StressbalanceViscosityOvershoot")==0) return StressbalanceViscosityOvershootEnum;
 	      else if (strcmp(name,"LoadingforceX")==0) return LoadingforceXEnum;
 	      else if (strcmp(name,"LoadingforceY")==0) return LoadingforceYEnum;
 	      else if (strcmp(name,"LoadingforceZ")==0) return LoadingforceZEnum;
-	      else if (strcmp(name,"FlowequationBordermacayeal")==0) return FlowequationBordermacayealEnum;
-	      else if (strcmp(name,"FlowequationBorderpattyn")==0) return FlowequationBorderpattynEnum;
-	      else if (strcmp(name,"FlowequationBorderstokes")==0) return FlowequationBorderstokesEnum;
+	      else if (strcmp(name,"FlowequationBorderSSA")==0) return FlowequationBorderSSAEnum;
+	      else if (strcmp(name,"FlowequationBorderHO")==0) return FlowequationBorderHOEnum;
+	      else if (strcmp(name,"FlowequationBorderFS")==0) return FlowequationBorderFSEnum;
 	      else if (strcmp(name,"FlowequationElementEquation")==0) return FlowequationElementEquationEnum;
-	      else if (strcmp(name,"FlowequationIshutter")==0) return FlowequationIshutterEnum;
-	      else if (strcmp(name,"FlowequationIsl1l2")==0) return FlowequationIsl1l2Enum;
-	      else if (strcmp(name,"FlowequationIsmacayealpattyn")==0) return FlowequationIsmacayealpattynEnum;
-	      else if (strcmp(name,"FlowequationIsstokes")==0) return FlowequationIsstokesEnum;
+	      else if (strcmp(name,"FlowequationIsSIA")==0) return FlowequationIsSIAEnum;
+	      else if (strcmp(name,"FlowequationIsSSA")==0) return FlowequationIsSSAEnum;
+	      else if (strcmp(name,"FlowequationIsL1L2")==0) return FlowequationIsL1L2Enum;
+	      else if (strcmp(name,"FlowequationIsHO")==0) return FlowequationIsHOEnum;
+	      else if (strcmp(name,"FlowequationIsFS")==0) return FlowequationIsFSEnum;
+	      else if (strcmp(name,"FlowequationFeSSA")==0) return FlowequationFeSSAEnum;
+	      else if (strcmp(name,"FlowequationFeHO")==0) return FlowequationFeHOEnum;
+	      else if (strcmp(name,"FlowequationFeFS")==0) return FlowequationFeFSEnum;
 	      else if (strcmp(name,"FlowequationVertexEquation")==0) return FlowequationVertexEquationEnum;
 	      else if (strcmp(name,"FrictionCoefficient")==0) return FrictionCoefficientEnum;
@@ -133,12 +137,12 @@
 	      else if (strcmp(name,"InversionIscontrol")==0) return InversionIscontrolEnum;
 	      else if (strcmp(name,"InversionTao")==0) return InversionTaoEnum;
-	      else if (strcmp(name,"InversionIncompleteAdjoint")==0) return InversionIncompleteAdjointEnum;
+         else stage=2;
+   }
+   if(stage==2){
+	      if (strcmp(name,"InversionIncompleteAdjoint")==0) return InversionIncompleteAdjointEnum;
 	      else if (strcmp(name,"InversionMaxParameters")==0) return InversionMaxParametersEnum;
 	      else if (strcmp(name,"InversionMaxiterPerStep")==0) return InversionMaxiterPerStepEnum;
 	      else if (strcmp(name,"InversionMinParameters")==0) return InversionMinParametersEnum;
-         else stage=2;
-   }
-   if(stage==2){
-	      if (strcmp(name,"InversionNsteps")==0) return InversionNstepsEnum;
+	      else if (strcmp(name,"InversionNsteps")==0) return InversionNstepsEnum;
 	      else if (strcmp(name,"InversionNumControlParameters")==0) return InversionNumControlParametersEnum;
 	      else if (strcmp(name,"InversionNumCostFunctions")==0) return InversionNumCostFunctionsEnum;
@@ -149,10 +153,5 @@
 	      else if (strcmp(name,"InversionVyObs")==0) return InversionVyObsEnum;
 	      else if (strcmp(name,"InversionVzObs")==0) return InversionVzObsEnum;
-	      else if (strcmp(name,"MaskElementonfloatingice")==0) return MaskElementonfloatingiceEnum;
-	      else if (strcmp(name,"MaskElementongroundedice")==0) return MaskElementongroundediceEnum;
-	      else if (strcmp(name,"MaskElementonwater")==0) return MaskElementonwaterEnum;
-	      else if (strcmp(name,"MaskVertexonfloatingice")==0) return MaskVertexonfloatingiceEnum;
-	      else if (strcmp(name,"MaskVertexongroundedice")==0) return MaskVertexongroundediceEnum;
-	      else if (strcmp(name,"MaskVertexonwater")==0) return MaskVertexonwaterEnum;
+	      else if (strcmp(name,"MaskIceLevelset")==0) return MaskIceLevelsetEnum;
 	      else if (strcmp(name,"MaterialsBeta")==0) return MaterialsBetaEnum;
 	      else if (strcmp(name,"MaterialsHeatcapacity")==0) return MaterialsHeatcapacityEnum;
@@ -178,6 +177,4 @@
 	      else if (strcmp(name,"MeshAverageVertexConnectivity")==0) return MeshAverageVertexConnectivityEnum;
 	      else if (strcmp(name,"MeshDimension")==0) return MeshDimensionEnum;
-	      else if (strcmp(name,"MeshEdges")==0) return MeshEdgesEnum;
-	      else if (strcmp(name,"MeshElementconnectivity")==0) return MeshElementconnectivityEnum;
 	      else if (strcmp(name,"MeshElementonbed")==0) return MeshElementonbedEnum;
 	      else if (strcmp(name,"MeshElementonsurface")==0) return MeshElementonsurfaceEnum;
@@ -185,5 +182,4 @@
 	      else if (strcmp(name,"MeshElements")==0) return MeshElementsEnum;
 	      else if (strcmp(name,"MeshLowerelements")==0) return MeshLowerelementsEnum;
-	      else if (strcmp(name,"MeshNumberofedges")==0) return MeshNumberofedgesEnum;
 	      else if (strcmp(name,"MeshNumberofelements2d")==0) return MeshNumberofelements2dEnum;
 	      else if (strcmp(name,"MeshNumberofelements")==0) return MeshNumberofelementsEnum;
@@ -198,12 +194,13 @@
 	      else if (strcmp(name,"MeshZ")==0) return MeshZEnum;
 	      else if (strcmp(name,"MiscellaneousName")==0) return MiscellaneousNameEnum;
-	      else if (strcmp(name,"PrognosticHydrostaticAdjustment")==0) return PrognosticHydrostaticAdjustmentEnum;
-	      else if (strcmp(name,"PrognosticMinThickness")==0) return PrognosticMinThicknessEnum;
-	      else if (strcmp(name,"PrognosticPenaltyFactor")==0) return PrognosticPenaltyFactorEnum;
-	      else if (strcmp(name,"PrognosticSpcthickness")==0) return PrognosticSpcthicknessEnum;
-	      else if (strcmp(name,"PrognosticStabilization")==0) return PrognosticStabilizationEnum;
-	      else if (strcmp(name,"PrognosticVertexPairing")==0) return PrognosticVertexPairingEnum;
-	      else if (strcmp(name,"PrognosticNumRequestedOutputs")==0) return PrognosticNumRequestedOutputsEnum;
-	      else if (strcmp(name,"PrognosticRequestedOutputs")==0) return PrognosticRequestedOutputsEnum;
+	      else if (strcmp(name,"MasstransportHydrostaticAdjustment")==0) return MasstransportHydrostaticAdjustmentEnum;
+	      else if (strcmp(name,"MasstransportIsfreesurface")==0) return MasstransportIsfreesurfaceEnum;
+	      else if (strcmp(name,"MasstransportMinThickness")==0) return MasstransportMinThicknessEnum;
+	      else if (strcmp(name,"MasstransportPenaltyFactor")==0) return MasstransportPenaltyFactorEnum;
+	      else if (strcmp(name,"MasstransportSpcthickness")==0) return MasstransportSpcthicknessEnum;
+	      else if (strcmp(name,"MasstransportStabilization")==0) return MasstransportStabilizationEnum;
+	      else if (strcmp(name,"MasstransportVertexPairing")==0) return MasstransportVertexPairingEnum;
+	      else if (strcmp(name,"MasstransportNumRequestedOutputs")==0) return MasstransportNumRequestedOutputsEnum;
+	      else if (strcmp(name,"MasstransportRequestedOutputs")==0) return MasstransportRequestedOutputsEnum;
 	      else if (strcmp(name,"QmuIsdakota")==0) return QmuIsdakotaEnum;
 	      else if (strcmp(name,"MassFluxSegments")==0) return MassFluxSegmentsEnum;
@@ -250,4 +247,6 @@
 	      else if (strcmp(name,"SurfaceforcingsBPos")==0) return SurfaceforcingsBPosEnum;
 	      else if (strcmp(name,"SurfaceforcingsBNeg")==0) return SurfaceforcingsBNegEnum;
+	      else if (strcmp(name,"ThermalIsenthalpy")==0) return ThermalIsenthalpyEnum;
+	      else if (strcmp(name,"ThermalIsdynamicbasalspc")==0) return ThermalIsdynamicbasalspcEnum;
 	      else if (strcmp(name,"ThermalMaxiter")==0) return ThermalMaxiterEnum;
 	      else if (strcmp(name,"ThermalPenaltyFactor")==0) return ThermalPenaltyFactorEnum;
@@ -256,19 +255,18 @@
 	      else if (strcmp(name,"ThermalSpctemperature")==0) return ThermalSpctemperatureEnum;
 	      else if (strcmp(name,"ThermalStabilization")==0) return ThermalStabilizationEnum;
-	      else if (strcmp(name,"ThermalIsenthalpy")==0) return ThermalIsenthalpyEnum;
 	      else if (strcmp(name,"GiaMantleViscosity")==0) return GiaMantleViscosityEnum;
 	      else if (strcmp(name,"GiaLithosphereThickness")==0) return GiaLithosphereThicknessEnum;
 	      else if (strcmp(name,"Thickness")==0) return ThicknessEnum;
+	      else if (strcmp(name,"TimesteppingStartTime")==0) return TimesteppingStartTimeEnum;
+	      else if (strcmp(name,"TimesteppingFinalTime")==0) return TimesteppingFinalTimeEnum;
          else stage=3;
    }
    if(stage==3){
-	      if (strcmp(name,"TimesteppingStartTime")==0) return TimesteppingStartTimeEnum;
-	      else if (strcmp(name,"TimesteppingFinalTime")==0) return TimesteppingFinalTimeEnum;
-	      else if (strcmp(name,"TimesteppingCflCoefficient")==0) return TimesteppingCflCoefficientEnum;
+	      if (strcmp(name,"TimesteppingCflCoefficient")==0) return TimesteppingCflCoefficientEnum;
 	      else if (strcmp(name,"TimesteppingTimeAdapt")==0) return TimesteppingTimeAdaptEnum;
 	      else if (strcmp(name,"TimesteppingTimeStep")==0) return TimesteppingTimeStepEnum;
-	      else if (strcmp(name,"TransientIsdiagnostic")==0) return TransientIsdiagnosticEnum;
+	      else if (strcmp(name,"TransientIsstressbalance")==0) return TransientIsstressbalanceEnum;
 	      else if (strcmp(name,"TransientIsgroundingline")==0) return TransientIsgroundinglineEnum;
-	      else if (strcmp(name,"TransientIsprognostic")==0) return TransientIsprognosticEnum;
+	      else if (strcmp(name,"TransientIsmasstransport")==0) return TransientIsmasstransportEnum;
 	      else if (strcmp(name,"TransientIsthermal")==0) return TransientIsthermalEnum;
 	      else if (strcmp(name,"TransientIsgia")==0) return TransientIsgiaEnum;
@@ -288,12 +286,14 @@
 	      else if (strcmp(name,"BalancethicknessSoftAnalysis")==0) return BalancethicknessSoftAnalysisEnum;
 	      else if (strcmp(name,"BalancethicknessSoftSolution")==0) return BalancethicknessSoftSolutionEnum;
+	      else if (strcmp(name,"BalancevelocityAnalysis")==0) return BalancevelocityAnalysisEnum;
+	      else if (strcmp(name,"BalancevelocitySolution")==0) return BalancevelocitySolutionEnum;
 	      else if (strcmp(name,"BedSlopeAnalysis")==0) return BedSlopeAnalysisEnum;
 	      else if (strcmp(name,"BedSlopeSolution")==0) return BedSlopeSolutionEnum;
 	      else if (strcmp(name,"BedSlopeXAnalysis")==0) return BedSlopeXAnalysisEnum;
 	      else if (strcmp(name,"BedSlopeYAnalysis")==0) return BedSlopeYAnalysisEnum;
-	      else if (strcmp(name,"DiagnosticHorizAnalysis")==0) return DiagnosticHorizAnalysisEnum;
-	      else if (strcmp(name,"DiagnosticHutterAnalysis")==0) return DiagnosticHutterAnalysisEnum;
-	      else if (strcmp(name,"DiagnosticSolution")==0) return DiagnosticSolutionEnum;
-	      else if (strcmp(name,"DiagnosticVertAnalysis")==0) return DiagnosticVertAnalysisEnum;
+	      else if (strcmp(name,"StressbalanceAnalysis")==0) return StressbalanceAnalysisEnum;
+	      else if (strcmp(name,"StressbalanceSIAAnalysis")==0) return StressbalanceSIAAnalysisEnum;
+	      else if (strcmp(name,"StressbalanceSolution")==0) return StressbalanceSolutionEnum;
+	      else if (strcmp(name,"StressbalanceVerticalAnalysis")==0) return StressbalanceVerticalAnalysisEnum;
 	      else if (strcmp(name,"EnthalpyAnalysis")==0) return EnthalpyAnalysisEnum;
 	      else if (strcmp(name,"EnthalpySolution")==0) return EnthalpySolutionEnum;
@@ -305,6 +305,8 @@
 	      else if (strcmp(name,"HydrologySolution")==0) return HydrologySolutionEnum;
 	      else if (strcmp(name,"MeltingAnalysis")==0) return MeltingAnalysisEnum;
-	      else if (strcmp(name,"PrognosticAnalysis")==0) return PrognosticAnalysisEnum;
-	      else if (strcmp(name,"PrognosticSolution")==0) return PrognosticSolutionEnum;
+	      else if (strcmp(name,"MasstransportAnalysis")==0) return MasstransportAnalysisEnum;
+	      else if (strcmp(name,"MasstransportSolution")==0) return MasstransportSolutionEnum;
+	      else if (strcmp(name,"FreeSurfaceBaseAnalysis")==0) return FreeSurfaceBaseAnalysisEnum;
+	      else if (strcmp(name,"FreeSurfaceTopAnalysis")==0) return FreeSurfaceTopAnalysisEnum;
 	      else if (strcmp(name,"SteadystateSolution")==0) return SteadystateSolutionEnum;
 	      else if (strcmp(name,"SurfaceSlopeAnalysis")==0) return SurfaceSlopeAnalysisEnum;
@@ -312,4 +314,6 @@
 	      else if (strcmp(name,"SurfaceSlopeXAnalysis")==0) return SurfaceSlopeXAnalysisEnum;
 	      else if (strcmp(name,"SurfaceSlopeYAnalysis")==0) return SurfaceSlopeYAnalysisEnum;
+	      else if (strcmp(name,"SmoothedSurfaceSlopeXAnalysis")==0) return SmoothedSurfaceSlopeXAnalysisEnum;
+	      else if (strcmp(name,"SmoothedSurfaceSlopeYAnalysis")==0) return SmoothedSurfaceSlopeYAnalysisEnum;
 	      else if (strcmp(name,"ThermalAnalysis")==0) return ThermalAnalysisEnum;
 	      else if (strcmp(name,"ThermalSolution")==0) return ThermalSolutionEnum;
@@ -319,12 +323,14 @@
 	      else if (strcmp(name,"Approximation")==0) return ApproximationEnum;
 	      else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
-	      else if (strcmp(name,"HutterApproximation")==0) return HutterApproximationEnum;
-	      else if (strcmp(name,"MacAyealApproximation")==0) return MacAyealApproximationEnum;
-	      else if (strcmp(name,"MacAyealPattynApproximation")==0) return MacAyealPattynApproximationEnum;
-	      else if (strcmp(name,"MacAyealStokesApproximation")==0) return MacAyealStokesApproximationEnum;
+	      else if (strcmp(name,"SIAApproximation")==0) return SIAApproximationEnum;
+	      else if (strcmp(name,"SSAApproximation")==0) return SSAApproximationEnum;
+	      else if (strcmp(name,"SSAHOApproximation")==0) return SSAHOApproximationEnum;
+	      else if (strcmp(name,"SSAFSApproximation")==0) return SSAFSApproximationEnum;
 	      else if (strcmp(name,"L1L2Approximation")==0) return L1L2ApproximationEnum;
-	      else if (strcmp(name,"PattynApproximation")==0) return PattynApproximationEnum;
-	      else if (strcmp(name,"PattynStokesApproximation")==0) return PattynStokesApproximationEnum;
-	      else if (strcmp(name,"StokesApproximation")==0) return StokesApproximationEnum;
+	      else if (strcmp(name,"HOApproximation")==0) return HOApproximationEnum;
+	      else if (strcmp(name,"HOFSApproximation")==0) return HOFSApproximationEnum;
+	      else if (strcmp(name,"FSApproximation")==0) return FSApproximationEnum;
+	      else if (strcmp(name,"FSvelocity")==0) return FSvelocityEnum;
+	      else if (strcmp(name,"FSpressure")==0) return FSpressureEnum;
 	      else if (strcmp(name,"Constraints")==0) return ConstraintsEnum;
 	      else if (strcmp(name,"Loads")==0) return LoadsEnum;
@@ -361,6 +367,6 @@
 	      else if (strcmp(name,"TransientParam")==0) return TransientParamEnum;
 	      else if (strcmp(name,"IceFrontType")==0) return IceFrontTypeEnum;
-	      else if (strcmp(name,"MacAyeal2dIceFront")==0) return MacAyeal2dIceFrontEnum;
-	      else if (strcmp(name,"MacAyeal3dIceFront")==0) return MacAyeal3dIceFrontEnum;
+	      else if (strcmp(name,"SSA2dIceFront")==0) return SSA2dIceFrontEnum;
+	      else if (strcmp(name,"SSA3dIceFront")==0) return SSA3dIceFrontEnum;
 	      else if (strcmp(name,"Matice")==0) return MaticeEnum;
 	      else if (strcmp(name,"Matdamageice")==0) return MatdamageiceEnum;
@@ -371,11 +377,14 @@
 	      else if (strcmp(name,"Param")==0) return ParamEnum;
 	      else if (strcmp(name,"L1L2IceFront")==0) return L1L2IceFrontEnum;
-	      else if (strcmp(name,"PattynIceFront")==0) return PattynIceFrontEnum;
+	      else if (strcmp(name,"HOIceFront")==0) return HOIceFrontEnum;
 	      else if (strcmp(name,"Pengrid")==0) return PengridEnum;
 	      else if (strcmp(name,"Penpair")==0) return PenpairEnum;
 	      else if (strcmp(name,"Penta")==0) return PentaEnum;
-	      else if (strcmp(name,"PentaP1Input")==0) return PentaP1InputEnum;
+	      else if (strcmp(name,"PentaInput")==0) return PentaInputEnum;
 	      else if (strcmp(name,"Profiler")==0) return ProfilerEnum;
-	      else if (strcmp(name,"MatrixParam")==0) return MatrixParamEnum;
+         else stage=4;
+   }
+   if(stage==4){
+	      if (strcmp(name,"MatrixParam")==0) return MatrixParamEnum;
 	      else if (strcmp(name,"NodeSId")==0) return NodeSIdEnum;
 	      else if (strcmp(name,"VectorParam")==0) return VectorParamEnum;
@@ -383,12 +392,9 @@
 	      else if (strcmp(name,"RiftfrontType")==0) return RiftfrontTypeEnum;
 	      else if (strcmp(name,"Segment")==0) return SegmentEnum;
-         else stage=4;
-   }
-   if(stage==4){
-	      if (strcmp(name,"SegmentRiftfront")==0) return SegmentRiftfrontEnum;
+	      else if (strcmp(name,"SegmentRiftfront")==0) return SegmentRiftfrontEnum;
 	      else if (strcmp(name,"SpcDynamic")==0) return SpcDynamicEnum;
 	      else if (strcmp(name,"SpcStatic")==0) return SpcStaticEnum;
 	      else if (strcmp(name,"SpcTransient")==0) return SpcTransientEnum;
-	      else if (strcmp(name,"StokesIceFront")==0) return StokesIceFrontEnum;
+	      else if (strcmp(name,"FSIceFront")==0) return FSIceFrontEnum;
 	      else if (strcmp(name,"StringArrayParam")==0) return StringArrayParamEnum;
 	      else if (strcmp(name,"StringParam")==0) return StringParamEnum;
@@ -462,8 +468,8 @@
 	      else if (strcmp(name,"VyPicard")==0) return VyPicardEnum;
 	      else if (strcmp(name,"Vz")==0) return VzEnum;
-	      else if (strcmp(name,"VzMacAyeal")==0) return VzMacAyealEnum;
-	      else if (strcmp(name,"VzPattyn")==0) return VzPattynEnum;
+	      else if (strcmp(name,"VzSSA")==0) return VzSSAEnum;
+	      else if (strcmp(name,"VzHO")==0) return VzHOEnum;
 	      else if (strcmp(name,"VzPicard")==0) return VzPicardEnum;
-	      else if (strcmp(name,"VzStokes")==0) return VzStokesEnum;
+	      else if (strcmp(name,"VzFS")==0) return VzFSEnum;
 	      else if (strcmp(name,"VxMesh")==0) return VxMeshEnum;
 	      else if (strcmp(name,"VyMesh")==0) return VyMeshEnum;
@@ -499,6 +505,17 @@
 	      else if (strcmp(name,"P1")==0) return P1Enum;
 	      else if (strcmp(name,"P1DG")==0) return P1DGEnum;
+	      else if (strcmp(name,"P1bubble")==0) return P1bubbleEnum;
+         else stage=5;
+   }
+   if(stage==5){
+	      if (strcmp(name,"P1bubblecondensed")==0) return P1bubblecondensedEnum;
+	      else if (strcmp(name,"P2")==0) return P2Enum;
+	      else if (strcmp(name,"P2xP1")==0) return P2xP1Enum;
+	      else if (strcmp(name,"P1xP2")==0) return P1xP2Enum;
+	      else if (strcmp(name,"P1P1")==0) return P1P1Enum;
+	      else if (strcmp(name,"P1P1GLS")==0) return P1P1GLSEnum;
 	      else if (strcmp(name,"MINI")==0) return MINIEnum;
-	      else if (strcmp(name,"P2")==0) return P2Enum;
+	      else if (strcmp(name,"MINIcondensed")==0) return MINIcondensedEnum;
+	      else if (strcmp(name,"TaylorHood")==0) return TaylorHoodEnum;
 	      else if (strcmp(name,"SaveResults")==0) return SaveResultsEnum;
 	      else if (strcmp(name,"BoolElementResult")==0) return BoolElementResultEnum;
@@ -506,8 +523,5 @@
 	      else if (strcmp(name,"DoubleElementResult")==0) return DoubleElementResultEnum;
 	      else if (strcmp(name,"DoubleExternalResult")==0) return DoubleExternalResultEnum;
-         else stage=5;
-   }
-   if(stage==5){
-	      if (strcmp(name,"DoubleMatExternalResult")==0) return DoubleMatExternalResultEnum;
+	      else if (strcmp(name,"DoubleMatExternalResult")==0) return DoubleMatExternalResultEnum;
 	      else if (strcmp(name,"IntExternalResult")==0) return IntExternalResultEnum;
 	      else if (strcmp(name,"J")==0) return JEnum;
@@ -541,6 +555,6 @@
 	      else if (strcmp(name,"SubelementMigration")==0) return SubelementMigrationEnum;
 	      else if (strcmp(name,"SubelementMigration2")==0) return SubelementMigration2Enum;
-	      else if (strcmp(name,"GLlevelset")==0) return GLlevelsetEnum;
-	      else if (strcmp(name,"StokesSolver")==0) return StokesSolverEnum;
+	      else if (strcmp(name,"MaskGroundediceLevelset")==0) return MaskGroundediceLevelsetEnum;
+	      else if (strcmp(name,"FSSolver")==0) return FSSolverEnum;
 	      else if (strcmp(name,"Adjoint")==0) return AdjointEnum;
 	      else if (strcmp(name,"Colinear")==0) return ColinearEnum;
@@ -575,5 +589,5 @@
 	      else if (strcmp(name,"NearestInterp")==0) return NearestInterpEnum;
 	      else if (strcmp(name,"XY")==0) return XYEnum;
-	      else if (strcmp(name,"XYZP")==0) return XYZPEnum;
+	      else if (strcmp(name,"XYZ")==0) return XYZEnum;
 	      else if (strcmp(name,"Dense")==0) return DenseEnum;
 	      else if (strcmp(name,"MpiDense")==0) return MpiDenseEnum;
@@ -589,4 +603,6 @@
 	      else if (strcmp(name,"Paterson")==0) return PatersonEnum;
 	      else if (strcmp(name,"Arrhenius")==0) return ArrheniusEnum;
+	      else if (strcmp(name,"LliboutryDuval")==0) return LliboutryDuvalEnum;
+	      else if (strcmp(name,"MaximumNumberOfDefinitions")==0) return MaximumNumberOfDefinitionsEnum;
          else stage=6;
    }
Index: /issm/trunk/src/c/shared/Enum/Synchronize.sh
===================================================================
--- /issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 16136)
+++ /issm/trunk/src/c/shared/Enum/Synchronize.sh	(revision 16137)
@@ -3,5 +3,5 @@
 
 #Get all lines of EnumDefinitions2.h which hold Enum | remove all commas > put everything in file temp
-cat EnumDefinitions.h | grep -e "[0-9]Enum," -e "[a-zA-Z]Enum," | grep -v include | sed -e "s/,/ /g" | awk '{print $1}' > temp
+cat EnumDefinitions.h | grep -e "[0-9]Enum," -e "[a-zA-Z]Enum," -e "MaximumNumberOfDefinitionsEnum" | grep -v include | sed -e "s/,/ /g" | awk '{print $1}' > temp
 
 #Removed existing files
@@ -101,8 +101,5 @@
 END
 #}}}
-
-# go through the lines of temp
-ENUM=0;
-#Add header to pythonenum file{{{
+#Build EnumDefinitions.py{{{
 cat <<END > $ISSM_DIR/src/m/enum/EnumDefinitions.py
 from StringToEnum import StringToEnum
@@ -110,12 +107,17 @@
 """
 
-   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
+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
 
 """
 
 END
+#core
+cat temp |  awk '{print "def " $1"(): return StringToEnum(\"" substr($1,1,length($1)-4) "\")[0]"}' >> $ISSM_DIR/src/m/enum/EnumDefinitions.py
 #}}}
+
+# go through the lines of temp
+ENUM=0;
 
 for NAMEENUM in $(cat temp); do
@@ -157,62 +159,6 @@
 END
 #}}}
-	#Add case to pythonenum file{{{
-	cat <<END >> $ISSM_DIR/src/m/enum/EnumDefinitions.py
-def $(echo $NAMEENUM)():
-	"""
-	$(echo $NAMEENUM | awk {'print toupper($1)'}) - Enum of $(echo $NAME)
-
-	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=$NAMEENUM()
-	"""
-
-	return StringToEnum('$NAME')[0]
-
-END
-#}}}
 
 done
-#MaximumNumberOfEnums (matlab){{{
-cat <<END > $ISSM_DIR/src/m/enum/MaximumNumberOfEnums.m
-function macro=MaximumNumberOfEnums()
-%$(echo "MaximumNumberOfEnums" | awk {'print toupper($1)'}) - Enum of MaximumNumberOfEnums
-%
-%   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=MaximumNumberOfEnums()
-
-macro=$(cat EnumDefinitions.h | grep -e "[0-9]Enum" -e "[a-zA-Z]Enum" | grep -v include \
-		| awk '{ printf "%s %s\n", NR-1, $0 }' \
-		| grep "MaximumNumberOfEnums" | awk '{print $1}');
-END
-#}}}
-#MaximumNumberOfEnums (python){{{
-cat <<END >> $ISSM_DIR/src/m/enum/EnumDefinitions.py
-def MaximumNumberOfEnums():
-	"""
-	$(echo "MaximumNumberOfEnums" | awk {'print toupper($1)'}) - Enum of MaximumNumberOfEnums
-
-	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=MaximumNumberOfEnums()
-	"""
-
-	return $(cat EnumDefinitions.h | grep -e "[0-9]Enum" -e "[a-zA-Z]Enum" | grep -v include \
-		| awk '{ printf "%s %s\n", NR-1, $0 }' \
-		| grep "MaximumNumberOfEnums" | awk '{print $1}')
-
-END
-#}}}
-
 #clean up{{{
 rm temp
Index: sm/trunk/src/c/shared/Exceptions/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,9 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared/Exceptions)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/shared/Exceptions/Exceptions.cpp
-                   $ENV{ISSM_DIR}/src/c/shared/Exceptions/exprintf.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp	(revision 16137)
@@ -11,5 +11,5 @@
 #include "./exceptions.h"
 #include "../io/Print/Print.h"
-#include "../io/Comm/Comm.h"
+#include "../io/Comm/IssmComm.h"
 
 ErrorException::ErrorException(const string &what_arg){/*{{{*/
Index: sm/trunk/src/c/shared/Exp/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/Exp/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared/Exp)
-# }}}
Index: /issm/trunk/src/c/shared/LatLong/Ll2xyx.cpp
===================================================================
--- /issm/trunk/src/c/shared/LatLong/Ll2xyx.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/LatLong/Ll2xyx.cpp	(revision 16137)
@@ -58,5 +58,5 @@
 	cde = 57.29577951;
 	/*  Radius of the earth in meters  */
-	re  = 6378.273*pow(10.,3.);
+	re  = 6378.273*1.e3;
 	/*  Eccentricity of the Hughes ellipsoid squared  */
 	ex2 = 0.006693883;
@@ -77,5 +77,5 @@
 			sl  = slat*PI/180.;
 			tc  = tan(PI/4.-sl/2.)/pow(((1.-ex*sin(sl))/(1.+ex*sin(sl))),(ex/2.));
-			mc  = cos(sl)/sqrt(1.0-ex2*(pow(sin(sl),2.)));
+			mc  = cos(sl)/sqrt(1.0-ex2*(pow(sin(sl),2)));
 			rho = re*mc*T/tc;
 		}
Index: /issm/trunk/src/c/shared/LatLong/Xy2llx.cpp
===================================================================
--- /issm/trunk/src/c/shared/LatLong/Xy2llx.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/LatLong/Xy2llx.cpp	(revision 16137)
@@ -59,5 +59,5 @@
 	cde  = 57.29577951;
 	/*  Radius of the earth in meters  */
-	re   = 6378.273*pow(10.,3.);
+	re   = 6378.273e+3;
 	/*  Eccentricity of the Hughes ellipsoid squared  */
 	ex2  = 0.006693883;
@@ -68,6 +68,6 @@
 	for(i=0; i<ncoord; i++){
 		sl = slat*PI/180.;
-		cm = cos(sl)/sqrt(1.0-ex2*(pow(sin(sl),2.)));
-		rho= sqrt(pow(x[i],2.) + pow(y[i],2.));
+		cm = cos(sl)/sqrt(1.0-ex2*(pow(sin(sl),2)));
+		rho= sqrt(pow(x[i],2) + pow(y[i],2));
 		T  = tan((PI/4.0) - (sl/2.0))/pow(((1.0-ex*sin(sl))/(1.0+ex*sin(sl))),(ex/2.0));
 
Index: sm/trunk/src/c/shared/Matrix/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/Matrix/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared/Matrix)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/shared/Matrix/MatrixUtils.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp
===================================================================
--- /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/Matrix/MatrixUtils.cpp	(revision 16137)
@@ -21,7 +21,7 @@
 	int         idima,idimb,idimc,idimd;
 	IssmDouble *dtemp;
+	_assert_(a && b && c && d);
 
 	/*  set up dimensions for triple product  */
-
 	if (!itrna){
 		idima=nrowa;
@@ -83,4 +83,6 @@
 	int i,j,k,ipta,iptb,iptc;
 	int nrowc,ncolc,iinca,jinca,iincb,jincb,ntrma,ntrmb,nterm;
+
+	_assert_(a && b && c);
 
 	/*  set up dimensions and increments for matrix a  */
@@ -326,5 +328,5 @@
 	/*Compute determinant*/
 	Matrix2x2Determinant(&det,A);
-	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller that machine epsilon");
+	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller than machine epsilon");
 
 	/*Compute invert*/
@@ -351,5 +353,5 @@
 	/*Compute determinant*/
 	Matrix3x3Determinant(&det,A);
-	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller that machine epsilon");
+	if (fabs(det) < DBL_EPSILON) _error_("Determinant smaller than machine epsilon");
 
 	/*Compute invert*/
Index: sm/trunk/src/c/shared/MemOps/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/MemOps/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared/MemOps)
-# }}}
Index: /issm/trunk/src/c/shared/MemOps/MemOps.cpp
===================================================================
--- /issm/trunk/src/c/shared/MemOps/MemOps.cpp	(revision 16137)
+++ /issm/trunk/src/c/shared/MemOps/MemOps.cpp	(revision 16137)
@@ -0,0 +1,24 @@
+/*
+ * MemOps.cpp
+ *
+ *  Created on: Sep 10, 2013
+ *      Author: utke
+ */
+
+
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "MemOps.h"
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+template <> adouble*  xNew(unsigned int size) {
+	ensureContiguousLocations(size);
+	adouble* aT_p=new adouble[size];
+	assert(aT_p);
+	return aT_p;
+}
+#endif
Index: /issm/trunk/src/c/shared/MemOps/MemOps.h
===================================================================
--- /issm/trunk/src/c/shared/MemOps/MemOps.h	(revision 16136)
+++ /issm/trunk/src/c/shared/MemOps/MemOps.h	(revision 16137)
@@ -29,6 +29,5 @@
 template <class T> T** xNew(unsigned int dim1, unsigned int dim2) { /*{{{*/
 #ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
-  T* buf=new T[dim1*dim2];
-  assert(buf );
+  T* buf=xNew<T>(dim1*dim2);
   T** aT_pp =new T*[dim1];
   assert(aT_pp );
@@ -143,3 +142,8 @@
 /*}}}*/
 
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+#include "../Numerics/types.h"
+template <> adouble*  xNew(unsigned int size);
 #endif
+
+#endif
Index: sm/trunk/src/c/shared/Numerics/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/Numerics/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,15 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared/Numerics)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/shared/Numerics/cross.cpp
-                 $ENV{ISSM_DIR}/src/c/shared/Numerics/cubic.cpp
-               $ENV{ISSM_DIR}/src/c/shared/Numerics/extrema.cpp
-           $ENV{ISSM_DIR}/src/c/shared/Numerics/GaussPoints.cpp
-                 $ENV{ISSM_DIR}/src/c/shared/Numerics/isnan.cpp
-   $ENV{ISSM_DIR}/src/c/shared/Numerics/OptionsFromAnalysis.cpp
-             $ENV{ISSM_DIR}/src/c/shared/Numerics/Verbosity.cpp
-$ENV{ISSM_DIR}/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/Numerics/GaussPoints.cpp	(revision 16137)
@@ -1452,7 +1452,5 @@
 					  *(5.+3.*egaus[j]-zgaus[k]-3.*egaus[j]*zgaus[k]);
 					zeta      =sqrt(2./3.)*(1.+zgaus[k]);
-					(*pwgt)[ipt]=xwgt[i]*ewgt[j]*zwgt[k]
-					  *(SQRT2/16.
-								  *(1.-egaus[j])*pow(1.-zgaus[k],2.));
+					(*pwgt)[ipt]=xwgt[i]*ewgt[j]*zwgt[k]*(SQRT2/16.*(1.-egaus[j])*pow(1.-zgaus[k],2));
 
 					(*pl1 )[ipt]=(1.-xi-eta/SQRT3-zeta/sqrt(6.))/2.;
Index: /issm/trunk/src/c/shared/Numerics/types.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/types.h	(revision 16136)
+++ /issm/trunk/src/c/shared/Numerics/types.h	(revision 16137)
@@ -17,8 +17,6 @@
 #if ISSM_USE_64BIT_INDICES == 1
 typedef long long IssmInt;
-//#define MPIU_INT MPI_LONG_LONG_INT already define in petsc
 #else
 typedef int IssmInt;
-//#define MPIU_INT MPI_INT already defined in petsc
 #endif  
 
Index: sm/trunk/src/c/shared/Sorting/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/Sorting/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared/Sorting)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/shared/Sorting/binary_search.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/shared/String/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/String/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,8 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared/String)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/shared/String/DescriptorIndex.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/shared/Threads/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/Threads/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared/Threads)
-# }}}
Index: sm/trunk/src/c/shared/TriMesh/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/shared/TriMesh)
-# }}}
Index: sm/trunk/src/c/shared/io/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/io/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,9 +1,0 @@
-# Subdirectories {{{
-add_subdirectory(Disk)
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/io)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/io/PrintfFunction.cpp PARENT_SCOPE)
-# }}}
Index: sm/trunk/src/c/shared/io/Comm/Comm.h
===================================================================
--- /issm/trunk/src/c/shared/io/Comm/Comm.h	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-/*\file Comm.h
- *\brief: communicator information
- */
-
-#ifndef _IO_COMM_H_
-#define _IO_COMM_H_
-
-#include "./CommDef.h"
-#include "./IssmComm.h"
-
-#endif
Index: sm/trunk/src/c/shared/io/Comm/CommDef.h
===================================================================
--- /issm/trunk/src/c/shared/io/Comm/CommDef.h	(revision 16136)
+++ 	(revision )
@@ -1,16 +1,0 @@
-/*\file CommDef.h
- *\brief: defined communicator typedefs
- */
-
-#ifndef _IO_COMMDEF_H_
-#define _IO_COMMDEF_H_
-
-/*Define communicator: */
-#ifdef _HAVE_MPI_
-	#include <mpi.h>
-	typedef MPI_Comm COMM;
-#else
-	typedef int COMM;
-#endif
-
-#endif
Index: /issm/trunk/src/c/shared/io/Comm/IssmComm.cpp
===================================================================
--- /issm/trunk/src/c/shared/io/Comm/IssmComm.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/io/Comm/IssmComm.cpp	(revision 16137)
@@ -13,5 +13,5 @@
 #include "../../Exceptions/exceptions.h"
 
-void IssmComm::SetComm(COMM incomm){ /*{{{*/
+void IssmComm::SetComm(ISSM_MPI_Comm incomm){ /*{{{*/
 
 	/*A comm is provided, we are running in parallel (this is not a module)*/
@@ -28,5 +28,5 @@
 
 }/*}}}*/
-COMM IssmComm::GetComm(){  /*{{{*/
+ISSM_MPI_Comm IssmComm::GetComm(){  /*{{{*/
 	if(!parallel) _error_("Cannot return comm in serial mode");
 	return comm;
@@ -39,7 +39,5 @@
 	if(!parallel) return my_rank;
 
-	#ifdef _HAVE_MPI_
-	MPI_Comm_rank(comm,&my_rank);
-	#endif
+	ISSM_MPI_Comm_rank(comm,&my_rank);
 
 	return my_rank;
@@ -53,7 +51,5 @@
 	if(!parallel) return size;
 
-	#ifdef _HAVE_MPI_
-	MPI_Comm_size(comm,&size);
-	#endif
+	ISSM_MPI_Comm_size(comm,&size);
 
 	return size;
Index: /issm/trunk/src/c/shared/io/Comm/IssmComm.h
===================================================================
--- /issm/trunk/src/c/shared/io/Comm/IssmComm.h	(revision 16136)
+++ /issm/trunk/src/c/shared/io/Comm/IssmComm.h	(revision 16137)
@@ -14,5 +14,5 @@
 #endif
 
-#include "./CommDef.h"
+#include "../../../toolkits/mpi/issmmpi.h"
 
 /*}}}*/
@@ -21,11 +21,11 @@
 
 	private:
-		static COMM comm;
+		static ISSM_MPI_Comm comm;
 		static bool parallel;
 
 	public:
-		static void SetComm(COMM incomm);
+		static void SetComm(ISSM_MPI_Comm incomm);
 		static void SetComm(void);
-		static COMM GetComm(void);
+		static ISSM_MPI_Comm GetComm(void);
 		static int GetRank(void);
 		static int GetSize(void);
Index: sm/trunk/src/c/shared/io/Disk/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/shared/io/Disk/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,10 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/io/Disk)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/io/Disk/pfclose.cpp
-                  $ENV{ISSM_DIR}/src/c/io/Disk/pfopen.cpp
-           $ENV{ISSM_DIR}/src/c/io/Disk/WriteLockFile.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/shared/io/Disk/WriteLockFile.cpp
===================================================================
--- /issm/trunk/src/c/shared/io/Disk/WriteLockFile.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/io/Disk/WriteLockFile.cpp	(revision 16137)
@@ -2,7 +2,9 @@
  * \brief
  */ 
+#include <cstdio>
 #include "../../Exceptions/exceptions.h"
-#include "../Comm/Comm.h"
+#include "../Comm/IssmComm.h"
 #include "../Print/Print.h"
+#include <cstdio>
 
 void WriteLockFile(char* filename){
Index: /issm/trunk/src/c/shared/io/Disk/diskio.h
===================================================================
--- /issm/trunk/src/c/shared/io/Disk/diskio.h	(revision 16136)
+++ /issm/trunk/src/c/shared/io/Disk/diskio.h	(revision 16137)
@@ -9,4 +9,5 @@
 
 FILE* pfopen(char* filename,const char* format);
+FILE* pfopen0(char* filename,const char* format);
 void  pfclose(FILE* fid,char* filename);
 void WriteLockFile(char* filename);
Index: /issm/trunk/src/c/shared/io/Disk/pfopen.cpp
===================================================================
--- /issm/trunk/src/c/shared/io/Disk/pfopen.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/io/Disk/pfopen.cpp	(revision 16137)
@@ -4,5 +4,5 @@
 
 #ifdef HAVE_CONFIG_H
-	#include <config.h>
+#include <config.h>
 #else
 #error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
@@ -10,13 +10,36 @@
 
 #include <stdio.h>
-#include "../../shared.h"
+#include "../Print/Print.h"
+#include "../Comm/IssmComm.h"
+#include "../../Exceptions/exceptions.h"
 
+FILE* pfopen0(char* filename,const char* format){
+
+	FILE* fid=NULL;
+
+	/*recover my_rank:*/
+	int my_rank  = IssmComm::GetRank();
+	if(my_rank) _error_("This function should only be called by cpu 0");
+
+	/*Open handle to data on disk*/
+	fid = fopen(filename,format);
+	if(fid==NULL) _error_("could not open file " << filename << " for binary reading or writing");
+
+	return fid;
+}
 FILE* pfopen(char* filename,const char* format){
 
 	FILE* fid=NULL;
 
-	/*Open handle to data on disk: */
-	fid=fopen(filename,format);
-	if(fid==NULL) _error_("could not open file " << filename << " for binary reading or writing"); 
+	/*recover my_rank:*/
+	int my_rank  = IssmComm::GetRank();
+	int num_proc = IssmComm::GetSize();
+
+	/*Open handle to data on disk (one by one to avoid errors)*/
+	for(int i=0;i<num_proc;i++){
+		if(my_rank==i) fid = fopen(filename,format);
+		ISSM_MPI_Barrier(IssmComm::GetComm());
+	}
+	if(fid==NULL) _error_("could not open file " << filename << " for binary reading or writing");
 
 	return fid;
Index: /issm/trunk/src/c/shared/io/Print/PrintfFunction.cpp
===================================================================
--- /issm/trunk/src/c/shared/io/Print/PrintfFunction.cpp	(revision 16136)
+++ /issm/trunk/src/c/shared/io/Print/PrintfFunction.cpp	(revision 16137)
@@ -16,5 +16,5 @@
 #endif
 #include "./Print.h"
-#include "../Comm/Comm.h"
+#include "../Comm/IssmComm.h"
 #include "../../String/sharedstring.h"
 #include "../../MemOps/MemOps.h"
Index: /issm/trunk/src/c/shared/io/io.h
===================================================================
--- /issm/trunk/src/c/shared/io/io.h	(revision 16136)
+++ /issm/trunk/src/c/shared/io/io.h	(revision 16137)
@@ -14,5 +14,5 @@
 #include "./Disk/diskio.h"
 #include "./Print/Print.h"
-#include "./Comm/Comm.h"
+#include "./Comm/IssmComm.h"
 
 #endif	/* _IO_H_ */
Index: sm/trunk/src/c/solutionsequences/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/solutionsequences/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,16 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/solutionsequences)
-# }}}
-# CORE_SOURCES {{{
-set(CORE_SOURCES $ENV{ISSM_DIR}/src/c/solutionsequences/solutionsequence_linear.cpp
-                 $ENV{ISSM_DIR}/src/c/solutionsequences/solutionsequence_newton.cpp
-              $ENV{ISSM_DIR}/src/c/solutionsequences/solutionsequence_nonlinear.cpp PARENT_SCOPE)
-# }}}
-# THERMAL_SOURCES {{{
-set(THERMAL_SOURCES $ENV{ISSM_DIR}/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp PARENT_SCOPE)
-# }}}
-# DIAGNOSTIC_SOURCES {{{
-set(DIAGNOSTIC_SOURCES $ENV{ISSM_DIR}/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp PARENT_SCOPE)
-# }}}
Index: /issm/trunk/src/c/solutionsequences/convergence.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/convergence.cpp	(revision 16136)
+++ /issm/trunk/src/c/solutionsequences/convergence.cpp	(revision 16137)
@@ -40,7 +40,7 @@
 
 	/*get convergence options*/
-	parameters->FindParam(&eps_res,DiagnosticRestolEnum);
-	parameters->FindParam(&eps_rel,DiagnosticReltolEnum);
-	parameters->FindParam(&eps_abs,DiagnosticAbstolEnum);
+	parameters->FindParam(&eps_res,StressbalanceRestolEnum);
+	parameters->FindParam(&eps_rel,StressbalanceReltolEnum);
+	parameters->FindParam(&eps_abs,StressbalanceAbstolEnum);
 	parameters->FindParam(&yts,ConstantsYtsEnum);
 
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp	(revision 16136)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_adjoint_linear.cpp	(revision 16137)
@@ -26,10 +26,10 @@
 	femmodel->UpdateConstraintsx();
 
-	femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
+	SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel);
 	CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 	Reduceloadx(pf, Kfs, ys,true); delete Kfs; //true means spc = 0
 	Solverx(&uf, Kff, pf, NULL, df, femmodel->parameters); delete Kff; delete pf; delete df;
 	Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters,true); delete ys; //true means spc0
-	InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);
+	InputUpdateFromSolutionx(femmodel,ug);
 	delete ug; delete uf;
 }
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 16136)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_hydro_nonlinear.cpp	(revision 16137)
@@ -10,14 +10,17 @@
 void solutionsequence_hydro_nonlinear(FemModel* femmodel){
 	/*solution : */
-	Vector<IssmDouble>* ug_sed=NULL;
+	Vector<IssmDouble>* ug_sed=NULL; 
+	Vector<IssmDouble>* uf_sed=NULL; 
+	Vector<IssmDouble>* uf_sed_sub_iter=NULL; 
+	Vector<IssmDouble>* ug_sed_main_iter=NULL;
+
 	Vector<IssmDouble>* ug_epl=NULL; 
-	Vector<IssmDouble>* uf=NULL;
-	Vector<IssmDouble>* uf_int_iter=NULL; 
-	Vector<IssmDouble>* ug_sed_main_iter=NULL; 
-	Vector<IssmDouble>* ug_epl_main_iter=NULL; 
+	Vector<IssmDouble>* uf_epl=NULL;
+	Vector<IssmDouble>* uf_epl_sub_iter=NULL; 
+	Vector<IssmDouble>* ug_epl_main_iter=NULL;
+
 	Vector<IssmDouble>* ys=NULL; 
-	Vector<IssmDouble>* dug=NULL; 
-	Vector<IssmDouble>* old_ug=NULL; 
-	
+	Vector<IssmDouble>* dug=NULL;
+
 	Matrix<IssmDouble>* Kff=NULL;
 	Matrix<IssmDouble>* Kfs=NULL;
@@ -37,5 +40,5 @@
 
 	/*Recover parameters: */
-	femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);//FIXME
+	femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
 	femmodel->parameters->FindParam(&isefficientlayer,HydrologydcIsefficientlayerEnum);
 	femmodel->parameters->FindParam(&eps_hyd,HydrologydcRelTolEnum);
@@ -43,28 +46,30 @@
 	hydro_maxiter=150;
 	hydrocount=1;
-
-	/*Iteration on the two layers*/
-	femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
-	GetSolutionFromInputsx(&ug_sed, femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+	hydroconverged=false;
+
+	/*Retrieve inputs as the initial state for the non linear iteration*/
+	//femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
+	GetSolutionFromInputsx(&ug_sed,femmodel);
+
 	if(isefficientlayer) {
 		femmodel->SetCurrentConfiguration(HydrologyDCEfficientAnalysisEnum);
-		GetSolutionFromInputsx(&ug_epl, femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+		GetSolutionFromInputsx(&ug_epl,femmodel);
 	}
 
-	hydroconverged=false;
+	/*Iteration on the two layers*/
 	for(;;){
 		sedcount=1;
 		eplcount=1;
 		//save pointer to old velocity
-		delete ug_sed_main_iter;
-		ug_sed_main_iter=ug_sed;
+		ug_sed_main_iter=ug_sed->Duplicate();
+		ug_sed->Copy(ug_sed_main_iter);
 		if(isefficientlayer){
-			delete ug_epl_main_iter;
-			ug_epl_main_iter=ug_epl;
+			ug_epl_main_iter=ug_epl->Duplicate();
+			ug_epl->Copy(ug_epl_main_iter);
 		}
 
 		femmodel->SetCurrentConfiguration(HydrologyDCInefficientAnalysisEnum);
-		InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,true,ResetPenaltiesEnum);
-		InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,false,ConvergedEnum);
+		InputUpdateFromConstantx(femmodel,true,ResetPenaltiesEnum);
+		InputUpdateFromConstantx(femmodel,false,ConvergedEnum);
 		femmodel->UpdateConstraintsx();
 		femmodel->parameters->SetParam(HydrologySedimentEnum,HydrologyLayerEnum);
@@ -74,16 +79,17 @@
 		for(;;){
 			femmodel->HydrologyTransferx();
-			femmodel->SystemMatricesx(&Kff, &Kfs, &pf,&df, &sediment_kmax);
+			SystemMatricesx(&Kff,&Kfs,&pf,&df,&sediment_kmax,femmodel);
 			CreateNodalConstraintsx(&ys,femmodel->nodes,HydrologyDCInefficientAnalysisEnum);
 			Reduceloadx(pf,Kfs,ys); delete Kfs;
-			delete uf;
-			Solverx(&uf, Kff, pf,uf_int_iter, df, femmodel->parameters);
-			delete uf_int_iter; uf_int_iter=uf->Duplicate();
-			if(sedcount>1)delete ug_sed; /*Not on first time to avoid deleting ug_sed_main_iter*/
+			delete uf_sed;
+			Solverx(&uf_sed,Kff,pf,uf_sed_sub_iter,df,femmodel->parameters);
 			delete Kff; delete pf; delete df;
-
-			Mergesolutionfromftogx(&ug_sed,uf,ys,femmodel->nodes,femmodel->parameters); delete ys;
-			InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ug_sed);
-			ConstraintsStatex(&constraints_converged,&num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+			delete uf_sed_sub_iter;
+			uf_sed_sub_iter=uf_sed->Duplicate();
+			uf_sed->Copy(uf_sed_sub_iter);
+			delete ug_sed;
+			Mergesolutionfromftogx(&ug_sed,uf_sed,ys,femmodel->nodes,femmodel->parameters); delete ys;
+			InputUpdateFromSolutionx(femmodel,ug_sed);
+			ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
 
 			if (!sedconverged){
@@ -98,7 +104,7 @@
 			if(sedconverged){
 				femmodel->parameters->SetParam(sediment_kmax,HydrologySedimentKmaxEnum);
-				InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,sedconverged,ConvergedEnum);
-				InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ug_sed);
-				InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,sediment_kmax,HydrologySedimentKmaxEnum);
+				InputUpdateFromConstantx(femmodel,sedconverged,ConvergedEnum);
+				InputUpdateFromSolutionx(femmodel,ug_sed);
+				InputUpdateFromConstantx(femmodel,sediment_kmax,HydrologySedimentKmaxEnum);
 				break;
 			}
@@ -108,26 +114,28 @@
 		if(isefficientlayer){
 			femmodel->SetCurrentConfiguration(HydrologyDCEfficientAnalysisEnum);
-			InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,true,ResetPenaltiesEnum);
-			InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,false,ConvergedEnum);
+			InputUpdateFromConstantx(femmodel,true,ResetPenaltiesEnum);
+			InputUpdateFromConstantx(femmodel,false,ConvergedEnum);
 			femmodel->HydrologyEPLupdateDomainx();
 			femmodel->parameters->SetParam(HydrologyEfficientEnum,HydrologyLayerEnum);
+
+			/*Iteration on the EPL layer*/
 			eplconverged = false;
-			/*Iteration on the EPL layer*/
 			for(;;){
 				femmodel->HydrologyTransferx();
-				femmodel->SystemMatricesx(&Kff, &Kfs, &pf,&df,NULL);
+				SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
 				CreateNodalConstraintsx(&ys,femmodel->nodes,HydrologyDCEfficientAnalysisEnum);
 				Reduceloadx(pf,Kfs,ys); delete Kfs;
-				delete uf;
-				Solverx(&uf, Kff, pf,uf_int_iter, df, femmodel->parameters);
-				delete uf_int_iter; uf_int_iter=uf->Duplicate();
-				if(eplcount>1) delete ug_epl; 
-				delete Kff;delete pf;
-				delete df;
-				Mergesolutionfromftogx(&ug_epl,uf,ys,femmodel->nodes,femmodel->parameters); delete ys;
-				InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ug_epl);
-				ConstraintsStatex(&constraints_converged,&num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+				delete uf_epl;
+				Solverx(&uf_epl,Kff,pf,uf_epl_sub_iter,df,femmodel->parameters);
+				delete Kff; delete pf; delete df;
+				delete uf_epl_sub_iter; 
+				uf_epl_sub_iter=uf_epl->Duplicate();
+				uf_epl->Copy(uf_epl_sub_iter);
+				delete ug_epl; 
+				Mergesolutionfromftogx(&ug_epl,uf_epl,ys,femmodel->nodes,femmodel->parameters); delete ys;
+				InputUpdateFromSolutionx(femmodel,ug_epl);
+				ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
 				femmodel->HydrologyEPLupdateDomainx();			
-				
+
 				if (!eplconverged){
 					if(VerboseConvergence()) _printf0_("   # EPL unstable constraints = " << num_unstable_constraints << "\n");
@@ -140,7 +148,7 @@
 
 				if(eplconverged){
-					InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,eplconverged,ConvergedEnum);
-					InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,sediment_kmax,MeltingOffsetEnum);
-					InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ug_epl);
+					InputUpdateFromConstantx(femmodel,eplconverged,ConvergedEnum);
+					InputUpdateFromConstantx(femmodel,sediment_kmax,MeltingOffsetEnum);
+					InputUpdateFromSolutionx(femmodel,ug_epl);
 					break;
 				}
@@ -153,5 +161,8 @@
 			ug_sed_main_iter->Copy(dug);	
 			dug->AYPX(ug_sed,-1.0);
-			ndu_sed=dug->Norm(NORM_TWO); nu_sed=ug_sed_main_iter->Norm(NORM_TWO);
+			ndu_sed=dug->Norm(NORM_TWO); 
+			delete dug;
+			nu_sed=ug_sed_main_iter->Norm(NORM_TWO);
+			delete ug_sed_main_iter;
 			if (xIsNan<IssmDouble>(ndu_sed) || xIsNan<IssmDouble>(nu_sed)) _error_("Sed convergence criterion is NaN!");
 			if (!xIsNan<IssmDouble>(eps_hyd)){
@@ -171,6 +182,7 @@
 					dug->AYPX(ug_epl,-1.0);
 					ndu_epl=dug->Norm(NORM_TWO); 
+					delete dug;
 					nu_epl=ug_epl_main_iter->Norm(NORM_TWO);
-
+					delete ug_epl_main_iter;
 					if (xIsNan<IssmDouble>(ndu_epl) || xIsNan<IssmDouble>(nu_epl)) _error_("EPL convergence criterion is NaN!");
 					if (ndu_epl==0.0 && nu_epl==0.0) nu_epl=1.0e-6; /*Hacking the case where the EPL is used but empty*/
@@ -194,14 +206,15 @@
 		if(hydroconverged)break;
 	}
-	InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug_sed);
-	if(isefficientlayer)InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug_epl);
+
+	InputUpdateFromSolutionx(femmodel,ug_sed);
+	if(isefficientlayer)InputUpdateFromSolutionx(femmodel,ug_epl);
 
 	/*Free ressources: */
 	delete ug_epl;
 	delete ug_sed;
-	delete uf;
-	delete uf_int_iter;
-	delete ug_sed_main_iter;
-	delete ug_epl_main_iter;
-	delete dug;
+	delete uf_sed;
+	delete uf_epl;
+	delete uf_sed_sub_iter;
+	delete uf_epl_sub_iter;
+	//delete dug;
 }
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_linear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_linear.cpp	(revision 16136)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_linear.cpp	(revision 16137)
@@ -24,5 +24,5 @@
 	femmodel->UpdateConstraintsx();
 
-	femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
+	SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
 	CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 	Reduceloadx(pf, Kfs, ys); delete Kfs;
@@ -35,5 +35,5 @@
 //#endif
 	Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);delete uf; delete ys;
-	InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug); 
+	InputUpdateFromSolutionx(femmodel,ug); 
 	delete ug;  
 }
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp	(revision 16136)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_newton.cpp	(revision 16137)
@@ -33,7 +33,7 @@
 
 	/*Recover parameters: */
-	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
 	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-	femmodel->parameters->FindParam(&newton,DiagnosticIsnewtonEnum);
+	femmodel->parameters->FindParam(&newton,StressbalanceIsnewtonEnum);
 	femmodel->UpdateConstraintsx();
 
@@ -42,10 +42,10 @@
 
 	/*Start non-linear iteration using input velocity: */
-	GetSolutionFromInputsx(&ug,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	GetSolutionFromInputsx(&ug,femmodel);
 	Reducevectorgtofx(&uf,ug,femmodel->nodes,femmodel->parameters);
 
 	//Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
-	InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,converged,ConvergedEnum);
-	InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ug);
+	InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+	InputUpdateFromSolutionx(femmodel,ug);
 
 	for(;;){
@@ -56,10 +56,10 @@
 		/*Solver forward model*/
 		if(count==1 || newton==2){
-			femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
+			SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
 			CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 			Reduceloadx(pf,Kfs,ys);delete Kfs;
 			Solverx(&uf,Kff,pf,old_uf,df,femmodel->parameters);delete df; delete Kff; delete pf;
 			Mergesolutionfromftogx(&ug,uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
-			InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ug);
+			InputUpdateFromSolutionx(femmodel,ug);
 			delete old_ug;old_ug=ug;
 			delete old_uf;old_uf=uf;
@@ -68,17 +68,17 @@
 
 		/*Prepare next iteration using Newton's method*/
-		femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);delete df;
+		SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);delete df;
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf,Kfs,ys);delete Kfs;
 
 		pJf=pf->Duplicate();
-		Kff->MatMult(uf,pJf);// delete Kff);
-		pJf->Scale(-1.0); pJf->AXPY(pf,+1.0);     //delete pf);
+		Kff->MatMult(uf,pJf);
+		pJf->Scale(-1.0); pJf->AXPY(pf,+1.0);
 
-		femmodel->CreateJacobianMatrixx(&Jff,kmax);
+		CreateJacobianMatrixx(&Jff,femmodel,kmax);
 		Solverx(&duf,Jff,pJf,NULL,NULL,femmodel->parameters); delete Jff; delete pJf;
 		uf->AXPY(duf, 1.0); delete duf;
 		Mergesolutionfromftogx(&ug,uf,ys,femmodel->nodes,femmodel->parameters);delete ys;
-		InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ug);
+		InputUpdateFromSolutionx(femmodel,ug);
 
 		/*Check convergence*/
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp	(revision 16136)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_nonlinear.cpp	(revision 16137)
@@ -33,6 +33,6 @@
 
 	/*Recover parameters: */
-	femmodel->parameters->FindParam(&min_mechanical_constraints,DiagnosticRiftPenaltyThresholdEnum);
-	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
+	femmodel->parameters->FindParam(&min_mechanical_constraints,StressbalanceRiftPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
 	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
 	femmodel->UpdateConstraintsx();
@@ -47,10 +47,10 @@
 
 	/*Start non-linear iteration using input velocity: */
-	GetSolutionFromInputsx(&ug, femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+	GetSolutionFromInputsx(&ug,femmodel);
 	Reducevectorgtofx(&uf, ug, femmodel->nodes,femmodel->parameters);
 
 	//Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
-	InputUpdateFromConstantx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
-	InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);
+	InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+	InputUpdateFromSolutionx(femmodel,ug);
 
 	for(;;){
@@ -60,5 +60,5 @@
 		delete ug;
 
-		femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
+		SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel);
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf, Kfs, ys); delete Kfs;
@@ -67,8 +67,8 @@
 
 		convergence(&converged,Kff,pf,uf,old_uf,femmodel->parameters); delete Kff; delete pf; delete df;
-		InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
-		InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);
+		InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+		InputUpdateFromSolutionx(femmodel,ug);
 
-		ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
 		if(VerboseConvergence()) _printf0_("   number of unstable constraints: " << num_unstable_constraints << "\n");
 
@@ -93,6 +93,6 @@
 			_printf0_("   maximum number of nonlinear iterations (" << max_nonlinear_iterations << ") exceeded\n"); 
 			converged=true;
-			InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
-			InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);		
+			InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
+			InputUpdateFromSolutionx(femmodel,ug);		
 			bool max_iteration_state=true;
 			int tempStep=1;
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp	(revision 16136)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_stokescoupling_nonlinear.cpp	(revision 16137)
@@ -1,4 +1,4 @@
-/*!\file: solutionsequence_stokescoupling_nonlinear.cpp
- * \brief: core of the coupling between stokes and macayealpattyn
+/*!\file: solutionsequence_FScoupling_nonlinear.cpp
+ * \brief: core of the coupling between FS and SSAHO
  */ 
 
@@ -9,5 +9,5 @@
 #include "../modules/modules.h"
 
-void solutionsequence_stokescoupling_nonlinear(FemModel* femmodel,bool conserve_loads){
+void solutionsequence_FScoupling_nonlinear(FemModel* femmodel,bool conserve_loads){
 
 	/*intermediary: */
@@ -35,6 +35,6 @@
 
 	/*Recover parameters: */
-	femmodel->parameters->FindParam(&min_mechanical_constraints,DiagnosticRiftPenaltyThresholdEnum);
-	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
+	femmodel->parameters->FindParam(&min_mechanical_constraints,StressbalanceRiftPenaltyThresholdEnum);
+	femmodel->parameters->FindParam(&max_nonlinear_iterations,StressbalanceMaxiterEnum);
 	femmodel->UpdateConstraintsx();
 
@@ -43,16 +43,16 @@
 
 	/*First get ug_horiz:*/
-	femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
-	GetSolutionFromInputsx(&ug_horiz, femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters);
+	femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
+	GetSolutionFromInputsx(&ug_horiz,femmodel);
 	Reducevectorgtofx(&uf_horiz, ug_horiz, femmodel->nodes,femmodel->parameters);
 
 	for(;;){
 
-		/*First diagnostic horiz:*/
-		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
+		/*First stressbalance horiz:*/
+		femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
 		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
 
 		//Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
-		InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug_horiz);
+		InputUpdateFromSolutionx(femmodel,ug_horiz);
 		delete ug_horiz;
 
@@ -61,19 +61,19 @@
 
 		/*solve: */
-		femmodel->SystemMatricesx(&Kff_horiz, &Kfs_horiz, &pf_horiz, &df_horiz, NULL);
+		SystemMatricesx(&Kff_horiz, &Kfs_horiz, &pf_horiz, &df_horiz, NULL,femmodel);
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf_horiz, Kfs_horiz, ys); delete Kfs_horiz;
 		Solverx(&uf_horiz, Kff_horiz, pf_horiz, old_uf_horiz, df_horiz,femmodel->parameters);
 		Mergesolutionfromftogx(&ug_horiz, uf_horiz,ys,femmodel->nodes,femmodel->parameters); delete ys;
-		InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug_horiz);
+		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;
 
 		/*Second compute vertical velocity: */
-		femmodel->SetCurrentConfiguration(DiagnosticVertAnalysisEnum);
+		femmodel->SetCurrentConfiguration(StressbalanceVerticalAnalysisEnum);
 		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
 
 		/*solve: */
-		femmodel->SystemMatricesx(&Kff_vert, &Kfs_vert, &pf_vert,  &df_vert,NULL);
+		SystemMatricesx(&Kff_vert, &Kfs_vert, &pf_vert, &df_vert,NULL,femmodel);
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf_vert, Kfs_vert, ys); delete Kfs_vert;
@@ -82,5 +82,5 @@
 		delete uf_vert; 
 		delete ys; 
-		InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug_vert);
+		InputUpdateFromSolutionx(femmodel,ug_vert);
 		delete ug_vert;
 
Index: /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 16136)
+++ /issm/trunk/src/c/solutionsequences/solutionsequence_thermal_nonlinear.cpp	(revision 16137)
@@ -41,20 +41,20 @@
 	converged=false;
 
-	InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,true,ResetPenaltiesEnum);
-	InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,false,ConvergedEnum);
+	InputUpdateFromConstantx(femmodel,true,ResetPenaltiesEnum);
+	InputUpdateFromConstantx(femmodel,false,ConvergedEnum);
 	femmodel->UpdateConstraintsx();
 
 	for(;;){
 
-		femmodel->SystemMatricesx(&Kff, &Kfs, &pf,&df, &melting_offset);
+		delete tf_old; tf_old=tf;
+		SystemMatricesx(&Kff, &Kfs, &pf,&df, &melting_offset,femmodel);
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
-		Reduceloadx(pf, Kfs, ys); delete Kfs; delete tf;
+		Reduceloadx(pf, Kfs, ys); delete Kfs;
 		Solverx(&tf, Kff, pf,tf_old, df, femmodel->parameters);
-		delete tf_old; tf_old=tf->Duplicate();
 		delete Kff;delete pf;delete tg; delete df;
 		Mergesolutionfromftogx(&tg, tf,ys,femmodel->nodes,femmodel->parameters); delete ys;
-		InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,tg);
+		InputUpdateFromSolutionx(femmodel,tg);
 
-		ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		ConstraintsStatex(&constraints_converged,&num_unstable_constraints,femmodel);
 
 		if (!converged){
@@ -68,11 +68,11 @@
 		count++;
 
-		InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
+		InputUpdateFromConstantx(femmodel,converged,ConvergedEnum);
 
 		if(converged)break;
 	}
 
-	InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,tg);
-	InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,melting_offset,MeltingOffsetEnum);
+	InputUpdateFromSolutionx(femmodel,tg);
+	InputUpdateFromConstantx(femmodel,melting_offset,MeltingOffsetEnum);
 
 	/*Free ressources: */
Index: /issm/trunk/src/c/solutionsequences/solutionsequences.h
===================================================================
--- /issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 16136)
+++ /issm/trunk/src/c/solutionsequences/solutionsequences.h	(revision 16137)
@@ -16,5 +16,5 @@
 void solutionsequence_nonlinear(FemModel* femmodel,bool conserve_loads);
 void solutionsequence_newton(FemModel* femmodel);
-void solutionsequence_stokescoupling_nonlinear(FemModel* femmodel,bool conserve_loads);
+void solutionsequence_FScoupling_nonlinear(FemModel* femmodel,bool conserve_loads);
 void solutionsequence_linear(FemModel* femmodel);
 void solutionsequence_adjoint_linear(FemModel* femmodel);
Index: sm/trunk/src/c/toolkits/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,12 +1,0 @@
-# Subdirectories {{{
-add_subdirectory(issm)
-add_subdirectory(metis)
-add_subdirectory(mpi)
-add_subdirectory(petsc)
-add_subdirectory(plapack)
-add_subdirectory(scalapack)
-add_subdirectory(triangle)
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits)
-# }}}
Index: /issm/trunk/src/c/toolkits/ToolkitOptions.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/ToolkitOptions.cpp	(revision 16136)
+++ /issm/trunk/src/c/toolkits/ToolkitOptions.cpp	(revision 16137)
@@ -2,10 +2,4 @@
  * \brief  file containing the methods for ToolkitOptions.h
  */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
 
 #include <string.h>
Index: /issm/trunk/src/c/toolkits/ToolkitOptions.h
===================================================================
--- /issm/trunk/src/c/toolkits/ToolkitOptions.h	(revision 16136)
+++ /issm/trunk/src/c/toolkits/ToolkitOptions.h	(revision 16137)
@@ -7,13 +7,4 @@
 #ifndef _TOOLKIT_OPTIONS_H
 #define _TOOLKIT_OPTIONS_H
-
-/*{{{*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-/*}}}*/
 
 class ToolkitOptions {
Index: /issm/trunk/src/c/toolkits/adolc/AdolcEdf.h
===================================================================
--- /issm/trunk/src/c/toolkits/adolc/AdolcEdf.h	(revision 16136)
+++ /issm/trunk/src/c/toolkits/adolc/AdolcEdf.h	(revision 16137)
@@ -16,4 +16,5 @@
 
 #if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+#include "adolc/adolc.h"
 
 struct Adolc_edf {
Index: /issm/trunk/src/c/toolkits/issm/Bucket.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/Bucket.h	(revision 16136)
+++ /issm/trunk/src/c/toolkits/issm/Bucket.h	(revision 16137)
@@ -13,5 +13,5 @@
 /*}}}*/
 
-/*how many MPI_Isend requests does it take to transfer the contents of a bucket to another cpu?*/
+/*how many ISSM_MPI_Isend requests does it take to transfer the contents of a bucket to another cpu?*/
 #define MATRIXBUCKETSIZEOFREQUESTS 7 
 #define VECTORBUCKETSIZEOFREQUESTS 5 
Index: sm/trunk/src/c/toolkits/issm/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/issm/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits/issm)
-# }}}
Index: /issm/trunk/src/c/toolkits/issm/IssmAbsMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmAbsMat.h	(revision 16136)
+++ /issm/trunk/src/c/toolkits/issm/IssmAbsMat.h	(revision 16137)
@@ -12,14 +12,6 @@
 
 /*Headers:*/
-/*{{{*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
 #include "../toolkitsenums.h"
-
-/*}}}*/
+#include "../../shared/Numerics/types.h"
 
 /*We need to template this class, in case we want to create Matrices that hold
@@ -27,6 +19,5 @@
   Such vectors are useful for use without or with the matlab or python
   interface (which do not care for IssmDouble types, but only rely on
-  IssmPDouble types)
-*/
+  IssmPDouble types) */
 
 template <class doubletype> class IssmAbsVec;
Index: /issm/trunk/src/c/toolkits/issm/IssmAbsVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmAbsVec.h	(revision 16136)
+++ /issm/trunk/src/c/toolkits/issm/IssmAbsVec.h	(revision 16137)
@@ -12,14 +12,6 @@
 
 /*Headers:*/
-/*{{{*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
 #include "../toolkitsenums.h"
-
-/*}}}*/
+#include "../../shared/Numerics/types.h"
 
 /*We need to template this class, in case we want to create Vectors that hold
Index: /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 16136)
+++ /issm/trunk/src/c/toolkits/issm/IssmMpiDenseMat.h	(revision 16137)
@@ -153,5 +153,5 @@
 					}
 				}
-				MPI_Barrier(IssmComm::GetComm());
+				ISSM_MPI_Barrier(IssmComm::GetComm());
 			}
 
@@ -187,5 +187,5 @@
 			/*some communicator info: */
 			num_procs=IssmComm::GetSize();
-			MPI_Comm comm=IssmComm::GetComm();
+			ISSM_MPI_Comm comm=IssmComm::GetComm();
 
 			/*First, make a vector of size M, which for each row between 0 and M-1, tells which cpu this row belongs to: */
@@ -215,5 +215,5 @@
 			numvalues_fromcpu   = xNew<int>(num_procs);
 			for(i=0;i<num_procs;i++){
-				MPI_Scatter(numvalues_forcpu,1,MPI_INT,numvalues_fromcpu+i,1,MPI_INT,i,comm);
+				ISSM_MPI_Scatter(numvalues_forcpu,1,ISSM_MPI_INT,numvalues_fromcpu+i,1,ISSM_MPI_INT,i,comm);
 			}
 
@@ -241,6 +241,6 @@
 			/*Scatter values around: {{{*/
 			/*Now, to scatter values across the cluster, we need sendcnts and displs. Our sendbufs have been built by BucketsBuildScatterBuffers, with a stride given 
-			 * by numvalues_forcpu. Get this ready to go before starting the scatter itslef. For reference, here is the MPI_Scatterv prototype: 
-			 * int MPI_Scatterv( void *sendbuf, int *sendcnts, int *displs, MPI_Datatype sendtype, void *recvbuf, int recvcnt, MPI_Datatype recvtype, int root, MPI_Comm comm) :*/
+			 * by numvalues_forcpu. Get this ready to go before starting the scatter itslef. For reference, here is the ISSM_MPI_Scatterv prototype: 
+			 * int ISSM_MPI_Scatterv( void *sendbuf, int *sendcnts, int *displs, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm) :*/
 			sendcnts=xNew<int>(num_procs);
 			displs=xNew<int>(num_procs);
@@ -253,8 +253,8 @@
 
 			for(i=0;i<num_procs;i++){
-				MPI_Scatterv( row_indices_forcpu, sendcnts, displs, MPI_INT, row_indices_fromcpu[i], numvalues_fromcpu[i], MPI_INT, i, comm);
-				MPI_Scatterv( col_indices_forcpu, sendcnts, displs, MPI_INT, col_indices_fromcpu[i], numvalues_fromcpu[i], MPI_INT, i, comm);
-				MPI_Scatterv( values_forcpu, sendcnts, displs, MPI_DOUBLE, values_fromcpu[i], numvalues_fromcpu[i], MPI_DOUBLE, i, comm);
-				MPI_Scatterv( modes_forcpu, sendcnts, displs, MPI_INT, modes_fromcpu[i], numvalues_fromcpu[i], MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( row_indices_forcpu, sendcnts, displs, ISSM_MPI_INT, row_indices_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( col_indices_forcpu, sendcnts, displs, ISSM_MPI_INT, col_indices_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( values_forcpu, sendcnts, displs, ISSM_MPI_DOUBLE, values_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_DOUBLE, i, comm);
+				ISSM_MPI_Scatterv( modes_forcpu, sendcnts, displs, ISSM_MPI_INT, modes_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
 			}
 			/*}}}*/
@@ -330,6 +330,6 @@
 						local_norm=max(local_norm,absolute);
 					}
-					MPI_Reduce(&local_norm, &norm, 1, MPI_DOUBLE, MPI_MAX, 0, IssmComm::GetComm());
-					MPI_Bcast(&norm,1,MPI_DOUBLE,0,IssmComm::GetComm());
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_MAX, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
 					return norm;
 					break; 
@@ -341,6 +341,6 @@
 						}
 					}
-					MPI_Reduce(&local_norm, &norm, 1, MPI_DOUBLE, MPI_SUM, 0, IssmComm::GetComm());
-					MPI_Bcast(&norm,1,MPI_DOUBLE,0,IssmComm::GetComm());
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_SUM, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
 					return sqrt(norm);
 					break; 
@@ -518,5 +518,5 @@
 			/*Let's try and use the MUMPS solver here: */
 			#ifdef _HAVE_MUMPS_
-			MpiDenseMumpsSolve(/*output*/ uf->vector,uf->M,uf->m, /*stiffness matrix:*/ this->matrix,this->M,this->N,this->m, /*right hand side load vector: */ pf->vector,pf->M,pf->m);
+			MpiDenseMumpsSolve(/*output*/ uf->vector,uf->M,uf->m, /*stiffness matrix:*/ this->matrix,this->M,this->N,this->m, /*right hand side load vector: */ pf->vector,pf->M,pf->m,parameters);
 			#else
 			_error_("IssmMpiDenseMat solver requires MUMPS solver");
Index: /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 16136)
+++ /issm/trunk/src/c/toolkits/issm/IssmMpiVec.h	(revision 16137)
@@ -21,7 +21,5 @@
 #include "../../shared/MemOps/MemOps.h"
 #include "../../shared/io/io.h"
-#ifdef _HAVE_MPI_
-#include "../mpi/mpiincludes.h"
-#endif
+#include "../mpi/issmmpi.h"
 #include <math.h>
 
@@ -138,5 +136,5 @@
 					_printf_("\n");
 				}
-				MPI_Barrier(IssmComm::GetComm());
+				ISSM_MPI_Barrier(IssmComm::GetComm());
 			}
 		}
@@ -171,5 +169,5 @@
 			/*some communicator info: */
 			num_procs=IssmComm::GetSize();
-			MPI_Comm comm=IssmComm::GetComm();
+			ISSM_MPI_Comm comm=IssmComm::GetComm();
 
 			/*First, make a vector of size M, which for each row between 0 and M-1, tells which cpu this row belongs to: */
@@ -199,5 +197,5 @@
 			numvalues_fromcpu   = xNew<int>(num_procs);
 			for(i=0;i<num_procs;i++){
-				MPI_Scatter(numvalues_forcpu,1,MPI_INT,numvalues_fromcpu+i,1,MPI_INT,i,comm);
+				ISSM_MPI_Scatter(numvalues_forcpu,1,ISSM_MPI_INT,numvalues_fromcpu+i,1,ISSM_MPI_INT,i,comm);
 			}
 
@@ -222,6 +220,6 @@
 			/*Scatter values around: {{{*/
 			/*Now, to scatter values across the cluster, we need sendcnts and displs. Our sendbufs have been built by BucketsBuildScatterBuffers, with a stride given 
-			 * by numvalues_forcpu. Get this ready to go before starting the scatter itslef. For reference, here is the MPI_Scatterv prototype: 
-			 * int MPI_Scatterv( void *sendbuf, int *sendcnts, int *displs, MPI_Datatype sendtype, void *recvbuf, int recvcnt, MPI_Datatype recvtype, int root, MPI_Comm comm) :*/
+			 * by numvalues_forcpu. Get this ready to go before starting the scatter itslef. For reference, here is the ISSM_MPI_Scatterv prototype: 
+			 * int ISSM_MPI_Scatterv( void *sendbuf, int *sendcnts, int *displs, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm) :*/
 			sendcnts=xNew<int>(num_procs);
 			displs=xNew<int>(num_procs);
@@ -234,7 +232,7 @@
 
 			for(i=0;i<num_procs;i++){
-				MPI_Scatterv( row_indices_forcpu, sendcnts, displs, MPI_INT, row_indices_fromcpu[i], numvalues_fromcpu[i], MPI_INT, i, comm);
-				MPI_Scatterv( values_forcpu, sendcnts, displs, MPI_DOUBLE, values_fromcpu[i], numvalues_fromcpu[i], MPI_DOUBLE, i, comm);
-				MPI_Scatterv( modes_forcpu, sendcnts, displs, MPI_INT, modes_fromcpu[i], numvalues_fromcpu[i], MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( row_indices_forcpu, sendcnts, displs, ISSM_MPI_INT, row_indices_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
+				ISSM_MPI_Scatterv( values_forcpu, sendcnts, displs, ISSM_MPI_DOUBLE, values_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_DOUBLE, i, comm);
+				ISSM_MPI_Scatterv( modes_forcpu, sendcnts, displs, ISSM_MPI_INT, modes_fromcpu[i], numvalues_fromcpu[i], ISSM_MPI_INT, i, comm);
 			}
 			/*}}}*/
@@ -378,8 +376,8 @@
 
 			/*communicator info: */
-			MPI_Comm comm;
+			ISSM_MPI_Comm comm;
 			int num_procs;
 
-			/*MPI_Allgatherv info: */
+			/*ISSM_MPI_Allgatherv info: */
 			int  lower_row,upper_row;
 			int* recvcounts=NULL;
@@ -399,5 +397,5 @@
 
 			/*recvcounts:*/
-			MPI_Allgather(&this->m,1,MPI_INT,recvcounts,1,MPI_INT,comm);
+			ISSM_MPI_Allgather(&this->m,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,comm);
 
 			/*get lower_row: */
@@ -405,8 +403,8 @@
 
 			/*displs: */
-			MPI_Allgather(&lower_row,1,MPI_INT,displs,1,MPI_INT,comm);
+			ISSM_MPI_Allgather(&lower_row,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,comm);
 
 			/*All gather:*/
-			MPI_Allgatherv(this->vector, this->m, MPI_DOUBLE, buffer, recvcounts, displs, MPI_DOUBLE,comm);
+			ISSM_MPI_Allgatherv(this->vector, this->m, ISSM_MPI_DOUBLE, buffer, recvcounts, displs, ISSM_MPI_DOUBLE,comm);
 
 			/*free ressources: */
@@ -445,6 +443,6 @@
 					//local_norm=0; for(i=0;i<this->m;i++)local_norm=max(local_norm,fabs(this->vector[i]));
 					local_norm=0; for(i=0;i<this->m;i++)local_norm=max(local_norm,this->vector[i]);
-					MPI_Reduce(&local_norm, &norm, 1, MPI_DOUBLE, MPI_MAX, 0, IssmComm::GetComm());
-					MPI_Bcast(&norm,1,MPI_DOUBLE,0,IssmComm::GetComm());
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_MAX, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
 					return norm;
 					break;
@@ -452,6 +450,6 @@
 					local_norm=0; 
 					for(i=0;i<this->m;i++)local_norm+=pow(this->vector[i],2);
-					MPI_Reduce(&local_norm, &norm, 1, MPI_DOUBLE, MPI_SUM, 0, IssmComm::GetComm());
-					MPI_Bcast(&norm,1,MPI_DOUBLE,0,IssmComm::GetComm());
+					ISSM_MPI_Reduce(&local_norm, &norm, 1, ISSM_MPI_DOUBLE, ISSM_MPI_SUM, 0, IssmComm::GetComm());
+					ISSM_MPI_Bcast(&norm,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
 					return sqrt(norm);
 					break;
@@ -484,9 +482,7 @@
 			for(i=0;i<this->m;i++)local_dot+=this->vector[i]*input->vector[i];
 
-			#ifdef _HAVE_MPI_
-			/*MPI_SUM all the dots across the cluster: */
-			MPI_Reduce(&local_dot, &dot, 1, MPI_DOUBLE, MPI_SUM, 0, IssmComm::GetComm());
-			MPI_Bcast(&dot,1,MPI_DOUBLE,0,IssmComm::GetComm());
-			#endif
+			/*ISSM_MPI_SUM all the dots across the cluster: */
+			ISSM_MPI_Reduce(&local_dot, &dot, 1, ISSM_MPI_DOUBLE, ISSM_MPI_SUM, 0, IssmComm::GetComm());
+			ISSM_MPI_Bcast(&dot,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
 
 			return dot;
Index: /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp	(revision 16136)
+++ /issm/trunk/src/c/toolkits/issm/IssmToolkitUtils.cpp	(revision 16137)
@@ -12,5 +12,5 @@
 
 #include "../../shared/MemOps/MemOps.h"
-#include "../../shared/io/Comm/Comm.h"
+#include "../../shared/io/Comm/IssmComm.h"
 #include "../../shared/Enum/Enum.h"
 #include "../../shared/Exceptions/exceptions.h"
Index: sm/trunk/src/c/toolkits/metis/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/metis/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,6 +1,0 @@
-# Subdirectories {{{
-add_subdirectory(patches)
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits/metis)
-# }}}
Index: sm/trunk/src/c/toolkits/metis/patches/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/metis/patches/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits/metis/patches)
-# }}}
Index: sm/trunk/src/c/toolkits/mpi/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,6 +1,0 @@
-# Subdirectories {{{
-add_subdirectory(patches)
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits/mpi)
-# }}}
Index: /issm/trunk/src/c/toolkits/mpi/commops/DetermineGlobalSize.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/commops/DetermineGlobalSize.cpp	(revision 16137)
+++ /issm/trunk/src/c/toolkits/mpi/commops/DetermineGlobalSize.cpp	(revision 16137)
@@ -0,0 +1,20 @@
+/* \file DetermineGlobalSize.cpp
+ * \brief: routine to determine global size from local size 
+ */
+
+#include <stdio.h>
+#include <math.h>
+#include "../../../shared/shared.h"
+#include "../../../shared/Numerics/types.h"
+
+int DetermineGlobalSize(int local_size,ISSM_MPI_Comm comm){
+
+	/*output: */
+	int  global_size;
+
+	ISSM_MPI_Reduce(&local_size, &global_size, 1, ISSM_MPI_INT, ISSM_MPI_SUM, 0, comm);
+	ISSM_MPI_Bcast(&global_size,1,ISSM_MPI_INT,0,comm);
+
+	return global_size;
+
+}
Index: /issm/trunk/src/c/toolkits/mpi/commops/DetermineLocalSize.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/commops/DetermineLocalSize.cpp	(revision 16137)
+++ /issm/trunk/src/c/toolkits/mpi/commops/DetermineLocalSize.cpp	(revision 16137)
@@ -0,0 +1,58 @@
+/* \file DetermineLocalSize.cpp
+ * \brief: routine to determine local size of a global petsc matrix or vector. 
+ */
+
+#include <stdio.h>
+#include <math.h>
+#include "../../../shared/shared.h"
+
+int DetermineLocalSize(int global_size,ISSM_MPI_Comm comm){
+
+	/*output: */
+	int  local_size;
+
+	/*intermediary: */
+	int  i;
+	int  row_rest;
+	int* num_local_rows=NULL;
+
+	/*from MPI: */
+	int num_procs;
+	int my_rank;
+
+	/*recover my_rank*/
+	ISSM_MPI_Comm_rank(comm,&my_rank);
+	ISSM_MPI_Comm_size(comm,&num_procs);
+
+	/* TODO replace the following with ->
+
+	local_size=global_size/num_procs; // integer division
+	if (global_size%num_procs>my_rank) local_size++; // distribute the remainder
+	return local_size;
+
+	<- to here  */
+
+	/*We are  not bound by any library, just use what seems most logical*/
+	num_local_rows=xNew<int>(num_procs);    
+
+	for (i=0;i<num_procs;i++){
+		/*Here, we use floor. We under distribute rows. The rows 
+		  left  are then redistributed, therefore resulting in a 
+		  more even distribution.*/
+		num_local_rows[i]=(int)floor((double)global_size/(double)num_procs); 
+	}
+
+	/*There may be some rows left. Distribute evenly.*/ 
+	row_rest=global_size - num_procs*(int)floor((double)global_size/(double)num_procs);
+	for (i=0;i<row_rest;i++){
+		num_local_rows[i]++;
+	}
+	local_size=num_local_rows[my_rank];
+
+	/*free ressources: */
+	xDelete<int>(num_local_rows);
+
+	/*return size: */
+	return local_size;
+
+}
Index: /issm/trunk/src/c/toolkits/mpi/commops/DetermineRowRankFromLocalSize.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/commops/DetermineRowRankFromLocalSize.cpp	(revision 16137)
+++ /issm/trunk/src/c/toolkits/mpi/commops/DetermineRowRankFromLocalSize.cpp	(revision 16137)
@@ -0,0 +1,45 @@
+/* \file DetermineRowRankFromLocalSize.cpp
+ * \brief: routine to determine, from local size of a matrix or vector (in terms of number 
+ * of rows), a vector of global size  which for each row of the matrix or vector, determines
+ * what cpu this row belong to.
+ */
+
+#include <stdio.h>
+#include <math.h>
+#include "../../../shared/shared.h"
+#include "../../../shared/Numerics/types.h"
+
+int* DetermineRowRankFromLocalSize(int global_size,int localsize,ISSM_MPI_Comm comm){
+
+	/*intermediary: */
+	int i,j;
+	int my_rank=0;
+	int num_procs=0;
+	int lower_row,upper_row;
+
+	/*output: */
+	int* RowRank=NULL;
+
+	ISSM_MPI_Comm_rank(comm,&my_rank);
+	ISSM_MPI_Comm_size(comm,&num_procs);
+
+	/*allocate: */
+	RowRank=xNew<int>(global_size);
+
+	/*Gather all local_size values into alllocalsizes, for all cpus*/
+	int* alllocalsizes=xNew<int>(num_procs);
+	ISSM_MPI_Allgather(&localsize,1,ISSM_MPI_INT,alllocalsizes,1,ISSM_MPI_INT,comm);
+
+	/*From all localsizes, get lower row and upper row*/
+	lower_row=0;
+	upper_row=lower_row+alllocalsizes[0];
+	for(j=lower_row;j<upper_row;j++)RowRank[j]=0;
+
+	for(i=1;i<num_procs;i++){
+		lower_row=lower_row+alllocalsizes[i-1];
+		upper_row=upper_row+alllocalsizes[i];
+		for(j=lower_row;j<upper_row;j++)RowRank[j]=i;
+	}
+
+	return RowRank;
+}
Index: /issm/trunk/src/c/toolkits/mpi/commops/GetOwnershipBoundariesFromRange.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/commops/GetOwnershipBoundariesFromRange.cpp	(revision 16137)
+++ /issm/trunk/src/c/toolkits/mpi/commops/GetOwnershipBoundariesFromRange.cpp	(revision 16137)
@@ -0,0 +1,45 @@
+/*! \file:  GetOwnershipBoundariesFromRange.cpp
+ *  \brief from a local range on each cpu, we determine what 
+ *  lower row and upper row from a matrix a cpu owns.
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include "../../../shared/MemOps/MemOps.h"
+#include "../../../shared/io/Comm/IssmComm.h"
+
+void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range,ISSM_MPI_Comm comm){
+
+	/*externals :*/
+	int my_rank;
+	int num_procs;
+
+	/*recover my_rank and num_procs:*/
+	ISSM_MPI_Comm_size(comm,&num_procs);
+	ISSM_MPI_Comm_rank(comm,&my_rank);
+
+	/*output: */
+	int lower_row,upper_row;
+
+	/*Gather all range values into allranges, for all nodes*/
+	int* allranges=xNew<int>(num_procs);
+	ISSM_MPI_Allgather(&range,1,ISSM_MPI_INT,allranges,1,ISSM_MPI_INT,comm);
+
+	/*From all ranges, get lower row and upper row*/
+	lower_row=0;
+	upper_row=lower_row+allranges[0];
+	for(int i=1;i<=my_rank;i++){
+		lower_row=lower_row+allranges[i-1];
+		upper_row=upper_row+allranges[i];
+	}
+
+	/*Assign output*/
+	*plower_row=lower_row;
+	*pupper_row=upper_row;
+	xDelete<int>(allranges);
+}
Index: /issm/trunk/src/c/toolkits/mpi/commops/commops.h
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/commops/commops.h	(revision 16137)
+++ /issm/trunk/src/c/toolkits/mpi/commops/commops.h	(revision 16137)
@@ -0,0 +1,17 @@
+/*! \file mpipatches.h
+ *  \brief: prototype header for all ISSM add-ons to MPI
+ */
+
+#ifndef MPI_PATCHES_H_ 
+#define MPI_PATCHES_H_
+
+#include "../../../shared/Numerics/types.h" 
+#include "../../../shared/io/Comm/IssmComm.h"
+#include "../../mpi/issmmpi.h"
+
+int DetermineLocalSize(int global_size,ISSM_MPI_Comm comm);
+int* DetermineRowRankFromLocalSize(int global_size,int localsize,ISSM_MPI_Comm comm);
+void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range,ISSM_MPI_Comm comm);
+int DetermineGlobalSize(int local_size,ISSM_MPI_Comm comm);
+
+#endif
Index: /issm/trunk/src/c/toolkits/mpi/issmmpi.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/issmmpi.cpp	(revision 16137)
+++ /issm/trunk/src/c/toolkits/mpi/issmmpi.cpp	(revision 16137)
@@ -0,0 +1,495 @@
+/* \file issmmpi.cpp
+ * \brief: implementation of all the mpi wrappers that ISSM requires. The goal is to control 
+ * which MPI layer we are using at compile time: the standard mpi, the autodiff mpi or no mpi at all.
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cassert>
+#include <cstring> // for memcpy
+
+#include "./issmmpi.h"
+#include "../../shared/Numerics/types.h"
+
+#ifndef _HAVE_MPI_
+ISSM_MPI_Status ourIssmMPIStatusIgnore=0;
+size_t sizeHelper(ISSM_MPI_Datatype type) { /*{{{*/
+
+  switch(type) { 
+  case ISSM_MPI_CHAR: 
+    return sizeof(char);
+    break;
+  case ISSM_MPI_DOUBLE: 
+    return sizeof(double);
+    break;
+  case ISSM_MPI_INT: 
+    return sizeof(int);
+    break;
+  default: 
+    assert(0);
+    break;
+  }
+  return 0;
+}/*}}}*/
+#endif
+
+int ISSM_MPI_Allgather(void *sendbuf, int sendcount, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcount, ISSM_MPI_Datatype recvtype, ISSM_MPI_Comm comm) {  /*{{{*/
+  int rc=0;
+  assert(sendcount==recvcount || sendtype==recvtype); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Allgather(sendbuf,
+		    sendcount,
+		    sendtype,
+		    recvbuf,
+		    recvcount,
+		    recvtype,
+		    comm);
+# else
+  rc=MPI_Allgather(sendbuf,
+		   sendcount,
+		   sendtype,
+		   recvbuf,
+		   recvcount,
+		   recvtype,
+		   comm);
+# endif
+#else
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<sendcount;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,sendbuf,sizeHelper(sendtype)*sendcount);
+#endif
+  return rc;
+} /*}}}*/
+int ISSM_MPI_Allgatherv(void *sendbuf, int sendcount, ISSM_MPI_Datatype sendtype, void *recvbuf, int *recvcounts, int *displs, ISSM_MPI_Datatype recvtype, ISSM_MPI_Comm comm) {  /*{{{*/
+  int rc=0;
+  assert(sendtype==recvtype); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Allgatherv(sendbuf,
+		     sendcount,
+		     sendtype,
+		     recvbuf,
+		     recvcounts,
+		     displs,
+		     recvtype,
+		     comm);
+# else
+  rc=MPI_Allgatherv(sendbuf,
+		    sendcount,
+		    sendtype,
+		    recvbuf,
+		    recvcounts,
+		    displs,
+		    recvtype,
+		    comm);
+# endif
+#else
+  assert(sendcount==recvcounts[0]); // we handle only identical representations 
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)(recvbuf)+displs[0];
+    for(int i=0;i<sendcount;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy((char*)recvbuf+(sizeHelper(recvtype)*displs[0]),sendbuf,sizeHelper(sendtype)*sendcount);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Allreduce(void *sendbuf, void *recvbuf, int count, ISSM_MPI_Datatype datatype, ISSM_MPI_Op op, ISSM_MPI_Comm comm){/*{{{*/
+ 
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Allreduce(sendbuf,
+		    recvbuf,
+		    count,
+		    datatype,
+		    op,
+		    comm);
+# else
+  rc=MPI_Allreduce(sendbuf,
+		   recvbuf,
+		   count,
+		   datatype,
+		   op,
+		   comm);
+# endif
+#else
+# ifdef _HAVE_ADOLC_
+  if (datatype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<count;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,sendbuf,sizeHelper(datatype)*count);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Barrier(ISSM_MPI_Comm comm){  /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Barrier(comm);
+# else 
+  rc=MPI_Barrier(comm);
+# endif
+#else
+// do nothing
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Bcast(void *buffer, int count, ISSM_MPI_Datatype datatype, int root, ISSM_MPI_Comm comm){  /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Bcast(buffer, 
+		count,
+		datatype,
+		root,
+		comm);
+# else
+  rc=MPI_Bcast(buffer, 
+	       count,
+	       datatype,
+	       root,
+	       comm);
+# endif
+#else 
+// nothing to be done here 
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Comm_free(ISSM_MPI_Comm *comm){ /*{{{*/
+ 
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  assert(0); // to be implemented
+# else 
+  rc=MPI_Comm_free(comm);
+# endif
+#else
+// do nothing
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Comm_rank(ISSM_MPI_Comm comm, int *rank){  /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+  rc=MPI_Comm_rank(comm,
+		   rank);
+#else
+  *rank=0;
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Comm_size( ISSM_MPI_Comm comm, int *size){ /*{{{*/
+ 
+  int rc=0;
+#ifdef _HAVE_MPI_
+  rc=MPI_Comm_size(comm,
+		   size);
+#else
+  *size=1;
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Finalize(void){  /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Finalize_NT();
+# else
+  rc=MPI_Finalize();
+# endif
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Gather(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm){  /*{{{*/
+
+  int rc=0;
+  assert(sendtype==recvtype && sendcnt==recvcnt); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Gather(sendbuf,
+		 sendcnt,
+		 sendtype,
+		 recvbuf,
+		 recvcnt,
+		 recvtype,
+		 root,
+		 comm);
+# else
+  rc=MPI_Gather(sendbuf,
+		sendcnt,
+		sendtype,
+		recvbuf,
+		recvcnt,
+		recvtype,
+		root,
+		comm);
+# endif
+#else
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<sendcnt;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,sendbuf,sizeHelper(sendtype)*sendcnt);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Gatherv(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int *recvcnts, int *displs, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm){/*{{{*/
+ 
+  int rc=0;
+  assert(sendtype==recvtype); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Gatherv(sendbuf,
+		  sendcnt,
+		  sendtype,
+		  recvbuf,
+		  recvcnts,
+		  displs,
+		  recvtype,
+		  root,
+		  comm);
+# else
+  rc=MPI_Gatherv(sendbuf,
+		 sendcnt,
+		 sendtype,
+		 recvbuf,
+		 recvcnts,
+		 displs,
+		 recvtype,
+		 root,
+		 comm);
+# endif
+#else
+  assert(sendcnt==recvcnts[0]); // we handle only identical representations 
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)(recvbuf)+displs[0];
+    for(int i=0;i<sendcnt;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy((char*)recvbuf+(sizeHelper(recvtype)*displs[0]),sendbuf,sizeHelper(sendtype)*sendcnt);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Init(int *argc, char ***argv){  /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Init_NT(argc,argv);
+# else
+  rc=MPI_Init(argc,argv);
+# endif
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Recv(void *buf, int count, ISSM_MPI_Datatype datatype, int source, int tag, ISSM_MPI_Comm comm, ISSM_MPI_Status *status){ /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Recv(buf, 
+	       count,
+	       datatype,
+	       source,
+	       tag,
+	       AMPI_SEND, // as long as there are no other variants
+	       comm,
+	       status);
+# else
+  rc=MPI_Recv(buf, 
+	      count,
+	      datatype,
+	      source,
+	      tag,
+	      comm,
+	      status);
+# endif
+#else 
+// nothing to be done here 
+// as long as nobody tries to do anything with 'status' 
+// we won't do anything to it here either
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Reduce(void *sendbuf, void *recvbuf, int count, ISSM_MPI_Datatype datatype, ISSM_MPI_Op op, int root, ISSM_MPI_Comm comm){ /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Reduce(sendbuf,
+		 recvbuf,
+		 count,
+		 datatype,
+		 op,
+		 root,
+		 comm);
+# else
+  rc=MPI_Reduce(sendbuf,
+		recvbuf,
+		count,
+		datatype,
+		op,
+		root,
+		comm);
+# endif
+#else
+# ifdef _HAVE_ADOLC_
+  if (datatype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<count;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,sendbuf,sizeHelper(datatype)*count);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Scatter(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm){ /*{{{*/
+
+  int rc=0;
+  assert(sendtype==recvtype && sendcnt==recvcnt); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Scatter(sendbuf,
+		  sendcnt,
+		  sendtype,
+		  recvbuf,
+		  recvcnt,
+		  recvtype,
+		  root,
+		  comm);
+# else
+  rc=MPI_Scatter(sendbuf,
+		 sendcnt,
+		 sendtype,
+		 recvbuf,
+		 recvcnt,
+		 recvtype,
+		 root,
+		 comm);
+# endif
+#else
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)sendbuf;
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<recvcnt;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,sendbuf,sizeHelper(sendtype)*recvcnt);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Scatterv(void *sendbuf, int *sendcnts, int *displs, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm){ /*{{{*/
+
+  int rc=0;
+  assert(sendtype==recvtype); // we handle only identical representations
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Scatterv(sendbuf,
+		   sendcnts,
+		   displs,
+		   sendtype,
+		   recvbuf,
+		   recvcnt,
+		   recvtype,
+		   root,
+		   comm);
+# else
+  rc=MPI_Scatterv(sendbuf,
+		  sendcnts,
+		  displs,
+		  sendtype,
+		  recvbuf,
+		  recvcnt,
+		  recvtype,
+		  root,
+		  comm);
+# endif
+#else
+  assert(sendcnts[0]==recvcnt); // we handle only identical representations 
+# ifdef _HAVE_ADOLC_
+  if (sendtype==ISSM_MPI_DOUBLE) { 
+    IssmDouble* activeSendBuf=(IssmDouble*)(sendbuf)+displs[0];
+    IssmDouble* activeRecvBuf=(IssmDouble*)recvbuf;
+    for(int i=0;i<recvcnt;++i) activeRecvBuf[i]=activeSendBuf[i];
+  }
+  else 
+# endif
+    memcpy(recvbuf,(char*)sendbuf+(sizeHelper(sendtype)*displs[0]),sizeHelper(sendtype)*recvcnt);
+#endif
+  return rc;
+}/*}}}*/
+int ISSM_MPI_Send(void *buf, int count, ISSM_MPI_Datatype datatype, int dest, int tag, ISSM_MPI_Comm comm){ /*{{{*/
+
+  int rc=0;
+#ifdef _HAVE_MPI_
+# ifdef _HAVE_AMPI_
+  rc=AMPI_Send(buf, 
+	       count,
+	       datatype,
+	       dest,
+	       tag,
+	       AMPI_RECV, // as long as there are no other variants
+	       comm);
+# else
+  rc=MPI_Send(buf, 
+	      count,
+	      datatype,
+	      dest,
+	      tag,
+	      comm);
+# endif
+#else 
+// nothing to be done here 
+#endif
+  return rc;
+}/*}}}*/
+double ISSM_MPI_Wtime(void){/*{{{*/
+
+#ifdef _HAVE_MPI_
+	return MPI_Wtime();
+#else 
+	assert(0); // to be implemented
+	return 0.0;
+#endif
+}/*}}}*/
+void ISSM_MPI_ContiguousInAdolc(size_t aSize) { /*{{{*/
+
+#ifdef _HAVE_ADOLC_
+  ensureContiguousLocations(aSize);
+#endif
+}/*}}}*/
Index: /issm/trunk/src/c/toolkits/mpi/issmmpi.h
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/issmmpi.h	(revision 16137)
+++ /issm/trunk/src/c/toolkits/mpi/issmmpi.h	(revision 16137)
@@ -0,0 +1,111 @@
+/* \file issmmpi.h
+ * \brief: header file that defines all the mpi wrappers that ISSM requires. The goal is to control 
+ * which MPI layer we are using at compile time: the standard mpi, the autodiff mpi or no mpi at all.
+ */
+
+#ifndef _ISSM_MPI_H_
+#define _ISSM_MPI_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstddef>
+
+#ifdef _HAVE_MPI_
+	/*Include header files: {{{*/
+	#ifdef _HAVE_AMPI_
+		#include <ampi/ampi.h>
+	#else 
+		#include <mpi.h>
+	#endif
+	/*}}}*/
+	/*MPI defines: *{{{*/
+	// types
+	typedef MPI_Comm             ISSM_MPI_Comm;
+	typedef MPI_Datatype         ISSM_MPI_Datatype;
+	typedef MPI_Op               ISSM_MPI_Op;
+	typedef MPI_Status           ISSM_MPI_Status;
+
+	// data types
+	#define ISSM_MPI_CHAR       MPI_CHAR
+	#ifdef _HAVE_AMPI_
+		#define ISSM_MPI_DOUBLE    AMPI_ADOUBLE // corresponds to IssmDouble
+	#else 
+		#define ISSM_MPI_DOUBLE    MPI_DOUBLE  // corresponds to IssmDouble 
+	#endif
+	#define ISSM_MPI_PDOUBLE    MPI_DOUBLE  // corresponds to IssmPDouble
+	#define ISSM_MPI_INT        MPI_INT
+
+	// operations
+	#define ISSM_MPI_MAX        MPI_MAX
+	#define ISSM_MPI_MIN        MPI_MIN
+	#define ISSM_MPI_PROD       MPI_PROD
+	#define ISSM_MPI_SUM        MPI_SUM
+
+	// others
+	#define ISSM_MPI_COMM_WORLD    MPI_COMM_WORLD
+	#define ISSM_MPI_STATUS_IGNORE MPI_STATUS_IGNORE
+	#define ISSM_MPI_ANY_TAG       MPI_ANY_TAG
+	#define ISSM_MPI_ANY_SOURCE    MPI_ANY_SOURCE
+	
+    /*other include files: */
+	#include "./commops/commops.h"
+	/*}}}*/
+#else  
+	/*Our ISSM MPI defines: {{{*/
+	// types
+	typedef int                  ISSM_MPI_Comm;
+	typedef int                  ISSM_MPI_Datatype;
+	typedef int                  ISSM_MPI_Op;
+	typedef int                  ISSM_MPI_Status;
+
+	// data types
+	#define ISSM_MPI_CHAR       1
+	#define ISSM_MPI_DOUBLE     2
+	#define ISSM_MPI_PDOUBLE    3
+	#define ISSM_MPI_INT        4
+
+	// operations
+	#define ISSM_MPI_MAX        1
+	#define ISSM_MPI_MIN        2
+	#define ISSM_MPI_PROD       3
+	#define ISSM_MPI_SUM        4
+
+	// others
+	#define ISSM_MPI_COMM_WORLD    1
+	extern ISSM_MPI_Status ourIssmMPIStatusIgnore;
+	#define ISSM_MPI_STATUS_IGNORE &ourIssmMPIStatusIgnore
+	#define ISSM_MPI_ANY_TAG       2
+	#define ISSM_MPI_ANY_SOURCE    3
+	/*}}}*/
+# endif 
+/* interfaces  {{{*/
+int ISSM_MPI_Allgather(void *sendbuf, int sendcount, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcount, ISSM_MPI_Datatype recvtype, ISSM_MPI_Comm comm);
+int ISSM_MPI_Allgatherv(void *sendbuf, int sendcount, ISSM_MPI_Datatype sendtype, void *recvbuf, int *recvcounts, int *displs, ISSM_MPI_Datatype recvtype, ISSM_MPI_Comm comm); 
+int ISSM_MPI_Allreduce(void *sendbuf, void *recvbuf, int count, ISSM_MPI_Datatype datatype, ISSM_MPI_Op op, ISSM_MPI_Comm comm); 
+int ISSM_MPI_Barrier(ISSM_MPI_Comm comm);
+int ISSM_MPI_Bcast(void *buffer, int count, ISSM_MPI_Datatype datatype, int root, ISSM_MPI_Comm comm);
+int ISSM_MPI_Comm_free(ISSM_MPI_Comm *comm);
+int ISSM_MPI_Comm_rank(ISSM_MPI_Comm comm, int *rank);
+int ISSM_MPI_Comm_size( ISSM_MPI_Comm comm, int *size);
+int ISSM_MPI_Finalize(void);
+int ISSM_MPI_Gather(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm);
+int ISSM_MPI_Gatherv(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int *recvcnts, int *displs, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm);
+int ISSM_MPI_Init(int *argc, char ***argv);
+int ISSM_MPI_Recv(void *buf, int count, ISSM_MPI_Datatype datatype, int source, int tag, ISSM_MPI_Comm comm, ISSM_MPI_Status *status);
+int ISSM_MPI_Reduce(void *sendbuf, void *recvbuf, int count, ISSM_MPI_Datatype datatype, ISSM_MPI_Op op, int root, ISSM_MPI_Comm comm);
+int ISSM_MPI_Scatter(void *sendbuf, int sendcnt, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm); 
+int ISSM_MPI_Scatterv(void *sendbuf, int *sendcnts, int *displs, ISSM_MPI_Datatype sendtype, void *recvbuf, int recvcnt, ISSM_MPI_Datatype recvtype, int root, ISSM_MPI_Comm comm); 
+int ISSM_MPI_Send(void *buf, int count, ISSM_MPI_Datatype datatype, int dest, int tag, ISSM_MPI_Comm comm);
+double ISSM_MPI_Wtime(void);
+
+// special for Adol-C locations when buffers are allocated with new
+// this could end up in the xNew template specialized for adoubles 
+// so as to not litter the code with it.
+void ISSM_MPI_ContiguousInAdolc(size_t aSize);
+/*}}}*/
+
+#endif  //#ifndef _ISSM_MPI_H_
Index: sm/trunk/src/c/toolkits/mpi/mpiincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/mpiincludes.h	(revision 16136)
+++ 	(revision )
@@ -1,23 +1,0 @@
-/* \file mpiincludes.h
- * \brief all includes for MPI layer
- */
-
-#ifndef _MPI_INCLUDES_H_
-#define _MPI_INCLUDES_H_
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#ifdef _HAVE_MPI_
-
-/*MPI includes: */
-#include <mpi.h>
-
-/*Patches: */
-#include "./patches/mpipatches.h"
-#endif
-
-#endif
Index: /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp	(revision 16136)
+++ /issm/trunk/src/c/toolkits/mumps/MpiDenseMumpsSolve.cpp	(revision 16137)
@@ -13,20 +13,110 @@
 #include "../../shared/MemOps/MemOps.h"
 #include "../../shared/Exceptions/exceptions.h"
-#include "../../shared/io/Comm/Comm.h"
-#include "../mpi/patches/mpipatches.h"
+#include "../../shared/io/Comm/IssmComm.h"
+#include "../../classes/Params/GenericParam.h"
+#include "../../classes/Params/Parameters.h"
+#include "../mpi/issmmpi.h"
+#include "../adolc/adolcincludes.h"
+#include "./mumpsincludes.h"
 
 /*Mumps header files: */
 #include "dmumps_c.h"
-
-#define JOB_INIT -1 
-#define JOB_SOLVE 6
-#define JOB_END  -2
 /*}}}*/
 
-void MpiDenseMumpsSolve( /*output: */ IssmPDouble* uf, int uf_M, int uf_m, /*matrix input: */ IssmPDouble* Kff, int Kff_M, int Kff_N, int Kff_m, /*right hand side vector: */ IssmPDouble* pf, int pf_M, int pf_m){ /*{{{*/
+void MumpsInit(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.par          = 1;  
+	theMumpsStruc.sym          = 0;
+	theMumpsStruc.comm_fortran = MPI_Comm_c2f(IssmComm::GetComm());
+	theMumpsStruc.job          = -1;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsInit
+void MumpsSettings(DMUMPS_STRUC_C &theMumpsStruc) { 
+	/*Control statements:{{{ */
+	theMumpsStruc.icntl[1-1] = 6; //error verbose
+	theMumpsStruc.icntl[2-1] = 1; //std verbose
+	theMumpsStruc.icntl[4-1] = 4; //verbose everything
+	theMumpsStruc.icntl[5-1] = 0;
+	theMumpsStruc.icntl[18-1] = 3;
+
+	theMumpsStruc.icntl[20-1] = 0;
+	theMumpsStruc.icntl[21-1] = 0;
+	theMumpsStruc.icntl[30-1] = 0;
+	/*}}}*/
+}
+
+// must be preceded by a call to MumpsInit
+void MumpsAnalyze(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 1;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsAnalyze
+void MumpsFactorize(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 2;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded by a call to MumpsFactorize
+void MumpsBacksubstitute(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = 3;
+	dmumps_c(&theMumpsStruc);
+}
+
+// must be preceded at least  by a call to MumpsInit
+void MumpsFinalize(DMUMPS_STRUC_C &theMumpsStruc) { 
+	theMumpsStruc.job          = -2;
+	dmumps_c(&theMumpsStruc);
+}
+
+void MumpsSolve(int n,
+		int nnz,
+		int local_nnz,
+		int* irn_loc,
+		int* jcn_loc,
+		IssmPDouble *a_loc,
+		IssmPDouble *rhs,
+		Parameters* parameters=0 /*unused here*/) {
+	/*Initialize mumps: {{{*/
+	DMUMPS_STRUC_C theMumpsStruc;
+	MumpsInit(theMumpsStruc);
+	MumpsSettings(theMumpsStruc);
+	/*}}}*/
+	// now setup the rest of theMumpsStruc 
+	theMumpsStruc.n=n;
+	theMumpsStruc.nz=nnz;
+	theMumpsStruc.nz_loc=local_nnz;
+	theMumpsStruc.irn_loc=irn_loc;
+	theMumpsStruc.jcn_loc=jcn_loc;
+	theMumpsStruc.a_loc=a_loc;
+	theMumpsStruc.rhs=rhs;
+	theMumpsStruc.nrhs=1;
+	theMumpsStruc.lrhs=1;
+	/*Solve system: {{{*/
+	MumpsAnalyze(theMumpsStruc);
+	MumpsFactorize(theMumpsStruc);
+	MumpsBacksubstitute(theMumpsStruc);
+	/*}}}*/
+	MumpsFinalize(theMumpsStruc);
+}
+
+#ifdef _HAVE_ADOLC_
+// prototype for active variant
+void MumpsSolve(int n,
+		int nnz,
+		int local_nnz,
+		int* irn_loc,
+		int* jcn_loc,
+		IssmDouble *a_loc,
+		IssmDouble *rhs,
+		Parameters* parameters);
+#endif 
+
+void MpiDenseMumpsSolve( /*output: */ IssmDouble* uf, int uf_M, int uf_m, /*matrix input: */ IssmDouble* Kff, int Kff_M, int Kff_N, int Kff_m, /*right hand side vector: */ IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters){ /*{{{*/
 
 	/*Variables: {{{*/
 
-	MPI_Comm   comm;
+	ISSM_MPI_Comm   comm;
 	int        my_rank;
 	int        num_procs;
@@ -36,9 +126,9 @@
 	int        *irn_loc = NULL;
 	int        *jcn_loc = NULL;
-	IssmPDouble *a_loc   = NULL;
+	IssmDouble *a_loc   = NULL;
 	int         count;
 	int         lower_row;
 	int         upper_row;
-	IssmPDouble* rhs=NULL;
+	IssmDouble* rhs=NULL;
 	int*        recvcounts=NULL;
 	int*        displs=NULL;
@@ -54,25 +144,5 @@
 	if (uf_m!=Kff_m | uf_m!=pf_m)_error_("solution vector should be locally the same size as stiffness matrix Kff and load vector pf");
 	/*}}}*/
-	/*Initialize mumps: {{{*/
-	DMUMPS_STRUC_C id;
-	id.job          = JOB_INIT;
-	id.par          = 1;  
-	id.sym          = 0;
-	id.comm_fortran = MPI_Comm_c2f(comm);
-	dmumps_c(&id);
-	/*}}}*/
-	/*Control statements:{{{ */
-	id.icntl[1-1] = 6; //error verbose
-	id.icntl[2-1] = 1; //std verbose
-	id.icntl[4-1] = 4; //verbose everything
-	id.icntl[5-1] = 0;
-	id.icntl[18-1] = 3;
-
-	id.icntl[20-1] = 0;
-	id.icntl[21-1] = 0;
-	id.icntl[30-1] = 0;
-	/*}}}*/
 	/*Initialize matrix:{{{ */
-	id.n=Kff_M;
 
 	/*figure out number of non-zero entries: */
@@ -84,8 +154,6 @@
 	}
 
-	MPI_Reduce(&local_nnz,&nnz,1,MPI_INT,MPI_SUM,0,comm);
-	MPI_Bcast(&nnz,1,MPI_INT,0,comm);
-	id.nz=nnz;
-	id.nz_loc=local_nnz;
+	ISSM_MPI_Reduce(&local_nnz,&nnz,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,comm);
+	ISSM_MPI_Bcast(&nnz,1,ISSM_MPI_INT,0,comm);
 
 	/*Allocate: */
@@ -93,5 +161,5 @@
 		irn_loc=xNew<int>(local_nnz);
 		jcn_loc=xNew<int>(local_nnz);
-		a_loc=xNew<IssmPDouble>(local_nnz);
+		a_loc=xNew<IssmDouble>(local_nnz);
 	}
 
@@ -109,10 +177,6 @@
 		}
 	}
-	id.irn_loc=irn_loc;
-	id.jcn_loc=jcn_loc;
-	id.a_loc=a_loc;
-
-	/*Deal with right hand side. We need to MPI_Gather it onto cpu 0: */
-	rhs=xNew<IssmPDouble>(pf_M);
+	/*Deal with right hand side. We need to ISSM_MPI_Gather it onto cpu 0: */
+	rhs=xNew<IssmDouble>(pf_M);
 
 	recvcounts=xNew<int>(num_procs);
@@ -120,41 +184,161 @@
 
 	/*recvcounts:*/
-	MPI_Allgather(&pf_m,1,MPI_INT,recvcounts,1,MPI_INT,comm);
+	ISSM_MPI_Allgather(&pf_m,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,comm);
 
 	/*displs: */
-	MPI_Allgather(&lower_row,1,MPI_INT,displs,1,MPI_INT,comm);
+	ISSM_MPI_Allgather(&lower_row,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,comm);
 
 	/*Gather:*/
-	MPI_Gatherv(pf, pf_m, MPI_DOUBLE, rhs, recvcounts, displs, MPI_DOUBLE,0,comm);
-	id.rhs=rhs;
-	id.nrhs=1;
-	id.lrhs=1;
-
-	/*}}}*/
-	/*Solve system: {{{*/
-	id.job = JOB_SOLVE;
-	dmumps_c (&id);
-	/*}}}*/
+	ISSM_MPI_Gatherv(pf, pf_m, ISSM_MPI_DOUBLE, rhs, recvcounts, displs, ISSM_MPI_DOUBLE,0,comm);
+
+	MumpsSolve(Kff_M,
+		   nnz,
+		   local_nnz,
+		   irn_loc,
+		   jcn_loc,
+		   a_loc,
+		   rhs,
+		   parameters);
+
 	/*Now scatter from cpu 0 to all other cpus: {{{*/
-	MPI_Scatterv( rhs, recvcounts, displs, MPI_DOUBLE, uf, uf_m, MPI_DOUBLE, 0, comm); 
+	ISSM_MPI_Scatterv( rhs, recvcounts, displs, ISSM_MPI_DOUBLE, uf, uf_m, ISSM_MPI_DOUBLE, 0, comm); 
 
 	/*}}}*/
 	/*Cleanup: {{{*/
-	id.job = JOB_END; 
-	dmumps_c (&id);
-
 	xDelete<int>(irn_loc);
 	xDelete<int>(jcn_loc);
-	xDelete<IssmPDouble>(a_loc);
-	xDelete<IssmPDouble>(rhs);
+	xDelete<IssmDouble>(a_loc);
+	xDelete<IssmDouble>(rhs);
 	xDelete<int>(recvcounts);
 	xDelete<int>(displs);
-
 	/*}}}*/
 } /*}}}*/
 
 #ifdef _HAVE_ADOLC_
-void MpiDenseMumpsSolve( /*output: */ IssmDouble* uf, int uf_M, int uf_m, /*matrix input: */ IssmDouble* Kff, int Kff_M, int Kff_N, int Kff_m, /*right hand side vector: */ IssmDouble* pf, int pf_M, int pf_m){ /*{{{*/
-	_error_("not supported yet!");
-} /*}}}*/
+
+int mumpsSolveEDF(int iArrLength, int* iArr, int /* ignored */, IssmPDouble* dp_x, int /* ignored */, IssmPDouble* dp_y) {
+  // unpack parameters
+  int n=iArr[0];
+  int nnz=iArr[1];
+  int local_nnz=iArr[2];
+  int *local_irn=xNew<int>(local_nnz);
+  int *local_jcn=xNew<int>(local_nnz);
+  IssmPDouble *A=xNew<IssmPDouble>(local_nnz);
+  for (int i=0;i<local_nnz;++i) {
+    local_irn[i]=iArr[3+i];
+    local_jcn[i]=iArr[3+local_nnz+i];
+    A[i]=dp_x[i];
+  }
+  IssmPDouble *rhs_sol=xNew<IssmPDouble>(n);
+  for (int i=0;i<n;++i) { 
+    rhs_sol[i]=dp_x[local_nnz+i];
+  }
+  MumpsSolve(n,nnz,local_nnz,local_irn,local_jcn,A,rhs_sol);
+  for (int i=0;i<n;++i) {
+    dp_y[i]=rhs_sol[i];
+  }
+  xDelete(rhs_sol);
+  xDelete(A);
+  xDelete(local_jcn);
+  xDelete(local_irn);
+  return 0;
+}
+
+void MumpsSolve(int n,
+		int nnz,
+		int local_nnz,
+		int* irn_loc,
+		int* jcn_loc,
+		IssmDouble *a_loc,
+		IssmDouble *rhs,
+		Parameters* parameters) {
+  int packedDimsSparseArrLength=1+1+1+local_nnz+local_nnz;
+  int *packedDimsSparseArr=xNew<int>(packedDimsSparseArrLength);
+  packedDimsSparseArr[0]=n;
+  packedDimsSparseArr[1]=nnz;
+  packedDimsSparseArr[2]=local_nnz;
+  for (int i=0;i<local_nnz;++i) {
+    packedDimsSparseArr[3+i]=irn_loc[i];
+    packedDimsSparseArr[3+local_nnz+i]=jcn_loc[i];
+  }
+  IssmDouble *pack_A_rhs=xNew<IssmDouble>(local_nnz+n);
+  for (int i=0;i<local_nnz;++i) { 
+    pack_A_rhs[i]=a_loc[i];
+  }
+  for (int i=0;i<n;++i) { 
+    pack_A_rhs[local_nnz+i]=rhs[i];
+  }
+  IssmPDouble *passivePack_A_rhs=xNew<IssmPDouble>(local_nnz+n);
+  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,
+	       packedDimsSparseArrLength, packedDimsSparseArr,
+	       local_nnz+n, passivePack_A_rhs, pack_A_rhs, 
+	       n, passiveSol,sol);
+  for (int i=0;i<n;++i) { 
+    rhs[i]=sol[i];
+  }
+  xDelete(sol);
+  xDelete(passiveSol);
+  xDelete(passivePack_A_rhs);
+  xDelete(pack_A_rhs);
+  xDelete(packedDimsSparseArr);
+}
+
+int fos_reverse_mumpsSolveEDF(int iArrLength, int* iArr, 
+			      int m, IssmPDouble *dp_U,
+			      int nPlusNz, IssmPDouble *dp_Z,
+			      IssmPDouble *dp_x, IssmPDouble *dp_y) {
+  // unpack parameters
+  int n=iArr[0];
+  int nnz=iArr[1];
+  int local_nnz=iArr[2];
+  int *local_irn=xNew<int>(local_nnz);
+  int *local_jcn=xNew<int>(local_nnz);
+  IssmPDouble *a_loc=xNew<IssmPDouble>(local_nnz);
+  for (int i=0;i<local_nnz;++i) {
+	  local_irn[i]=iArr[3+i];
+	  local_jcn[i]=iArr[3+local_nnz+i];
+	  a_loc[i]=dp_x[i];
+  }
+  IssmPDouble *rhs_sol=xNew<IssmPDouble>(n);
+  for (int i=0;i<n;++i) { 
+    rhs_sol[i]=dp_U[i];
+  }
+  DMUMPS_STRUC_C theMumpsStruc;
+  MumpsInit(theMumpsStruc);
+  MumpsSettings(theMumpsStruc);
+  theMumpsStruc.n=n;
+  theMumpsStruc.nz=nnz;
+  theMumpsStruc.nz_loc=local_nnz;
+  theMumpsStruc.irn_loc=local_irn;
+  theMumpsStruc.jcn_loc=local_jcn;
+  theMumpsStruc.a_loc=a_loc;
+  theMumpsStruc.rhs=rhs_sol;
+  theMumpsStruc.nrhs=1;
+  theMumpsStruc.lrhs=1;
+  theMumpsStruc.icntl[9-1] = 0; //solve for the transpose
+  MumpsAnalyze(theMumpsStruc);
+  MumpsFactorize(theMumpsStruc);
+  MumpsBacksubstitute(theMumpsStruc);
+  MumpsFinalize(theMumpsStruc);
+  // update the adjoint of the rhs:
+  for (int i=0;i<n;++i) {
+    dp_Z[local_nnz+i]+=rhs_sol[i];
+  }
+  // bcast dp_y (the solution of the forward system)
+  ISSM_MPI_Bcast(dp_y,n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+  // bcast the adjoint of the right-hand-side, i.e. this solution
+  ISSM_MPI_Bcast(rhs_sol,n,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
+  // update the adjoint of the matrix with the outer product of right-hand-side adjoint and the original solution
+  for (int i=0;i<local_nnz;++i) {
+    dp_Z[i]-=rhs_sol[iArr[3+i]-1]*dp_y[iArr[3+local_nnz+i]-1];
+  }
+  xDelete(rhs_sol);
+  xDelete(a_loc);
+  xDelete(local_jcn);
+  xDelete(local_irn);
+  return 3;
+}
+
 #endif
Index: /issm/trunk/src/c/toolkits/mumps/mumpsincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/mumps/mumpsincludes.h	(revision 16136)
+++ /issm/trunk/src/c/toolkits/mumps/mumpsincludes.h	(revision 16137)
@@ -6,5 +6,24 @@
 #define _MUMPS_INCLUDES_H_
 
-void MpiDenseMumpsSolve(IssmDouble* uf,int uf_M,int uf_n, IssmDouble* Kff,int Kff_M, int Kff_N, int Kff_m, IssmDouble* pf, int pf_M, int pf_m);
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../../shared/Numerics/types.h"
+/*}}}*/
+
+class Parameters;
+
+void MpiDenseMumpsSolve(IssmDouble* uf,int uf_M,int uf_n, IssmDouble* Kff,int Kff_M, int Kff_N, int Kff_m, IssmDouble* pf, int pf_M, int pf_m, Parameters* parameters);
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+// call back functions:
+ADOLC_ext_fct_iArr mumpsSolveEDF;
+ADOLC_ext_fct_iArr_fos_reverse fos_reverse_mumpsSolveEDF;
+ADOLC_ext_fct_iArr_fov_reverse fov_reverse_mumpsSolveEDF;
+#endif
 
 #endif
Index: sm/trunk/src/c/toolkits/petsc/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,7 +1,0 @@
-# Subdirectories {{{
-add_subdirectory(objects)
-add_subdirectory(patches)
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits/petsc)
-# }}}
Index: sm/trunk/src/c/toolkits/petsc/objects/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits/petsc/objects)
-# }}}
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 16136)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscSolver.cpp	(revision 16137)
@@ -13,5 +13,5 @@
 #include "../../../shared/MemOps/MemOps.h"
 #include "../../../shared/Exceptions/exceptions.h"
-#include "../../../shared/io/Comm/Comm.h"
+#include "../../../shared/io/Comm/IssmComm.h"
 #include "../../../shared/Enum/Enum.h"
 
@@ -52,5 +52,5 @@
 	#endif
 
-	/*Stokes: */
+	/*FS: */
 	IS         isv=NULL;
 	IS         isp=NULL;
@@ -118,9 +118,9 @@
 	}
 
-	/*Stokes: */
-	if (solver_type==StokesSolverEnum){
+	/*FS: */
+	if (solver_type==FSSolverEnum){
 		/*Make indices out of doftypes: */
-		if(!df)_error_("need doftypes for Stokes solver!\n");
-		DofTypesToIndexSet(&isv,&isp,df,StokesSolverEnum);
+		if(!df)_error_("need doftypes for FS solver!\n");
+		DofTypesToIndexSet(&isv,&isp,df,FSSolverEnum);
 
 		/*Set field splits: */
@@ -179,5 +179,5 @@
 	int      velocity_count=0;
 
-	if(typeenum==StokesSolverEnum){
+	if(typeenum==FSSolverEnum){
 
 		/*Ok, recover doftypes vector values and indices: */
Index: sm/trunk/src/c/toolkits/petsc/patches/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits/petsc/patches)
-# }}}
Index: /issm/trunk/src/c/toolkits/petsc/patches/MatMultPatch.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 16136)
+++ /issm/trunk/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 16137)
@@ -14,11 +14,12 @@
 #include <petscksp.h>
 
+#include "../../mpi/issmmpi.h"
 #include "../../../shared/shared.h"
 
 /*Function prototypes: */
-int MatMultCompatible(Mat A,Vec x,COMM comm);
-void VecRelocalize(Vec* outvector,Vec vector,int m,COMM comm);
+int MatMultCompatible(Mat A,Vec x,ISSM_MPI_Comm comm);
+void VecRelocalize(Vec* outvector,Vec vector,int m,ISSM_MPI_Comm comm);
 
-void MatMultPatch(Mat A,Vec X, Vec AX,COMM comm){ //same prototype as MatMult in Petsc
+void MatMultPatch(Mat A,Vec X, Vec AX,ISSM_MPI_Comm comm){ //same prototype as MatMult in Petsc
 
 	int m,n;
@@ -42,5 +43,5 @@
 }
 
-int MatMultCompatible(Mat A,Vec x,COMM comm){
+int MatMultCompatible(Mat A,Vec x,ISSM_MPI_Comm comm){
 
 	/*error management*/
@@ -53,5 +54,5 @@
 
 	/*recover num_procs:*/
-	MPI_Comm_size(comm,&num_procs);
+	ISSM_MPI_Comm_size(comm,&num_procs);
 
 	MatGetLocalSize(A,&local_m,&local_n);;
@@ -61,6 +62,6 @@
 
 	/*synchronize result: */
-	MPI_Reduce (&result,&sumresult,1,MPI_INT,MPI_SUM,0,comm );
-	MPI_Bcast(&sumresult,1,MPI_INT,0,comm);                
+	ISSM_MPI_Reduce (&result,&sumresult,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,comm );
+	ISSM_MPI_Bcast(&sumresult,1,ISSM_MPI_INT,0,comm);                
 	if (sumresult!=num_procs){
 		result=0;
@@ -72,5 +73,5 @@
 }
 
-void VecRelocalize(Vec* poutvector,Vec vector,int m,COMM comm){
+void VecRelocalize(Vec* poutvector,Vec vector,int m,ISSM_MPI_Comm comm){
 
 	/*vector index and vector values*/
Index: /issm/trunk/src/c/toolkits/petsc/patches/MatToSerial.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/MatToSerial.cpp	(revision 16136)
+++ /issm/trunk/src/c/toolkits/petsc/patches/MatToSerial.cpp	(revision 16137)
@@ -12,5 +12,5 @@
 #include "../../../shared/shared.h"
 
-void MatToSerial(double** poutmatrix,Mat matrix,COMM comm){
+void MatToSerial(double** poutmatrix,Mat matrix,ISSM_MPI_Comm comm){
 
 	int i;
@@ -22,5 +22,5 @@
 	int range;
 	int M,N; //size of matrix
-	MPI_Status status;
+	ISSM_MPI_Status status;
 	int* idxm=NULL;
 	int* idxn=NULL; 
@@ -29,6 +29,6 @@
 
 	/*recover my_rank and num_procs:*/
-	MPI_Comm_size(comm,&num_procs);
-	MPI_Comm_rank(comm,&my_rank);
+	ISSM_MPI_Comm_size(comm,&num_procs);
+	ISSM_MPI_Comm_rank(comm,&my_rank);
 
 	/*Output*/
@@ -69,10 +69,10 @@
 			buffer[1]=lower_row;
 			buffer[2]=range;
-			MPI_Send(buffer,3,MPI_INT,0,1,comm);   
-			if (range)MPI_Send(local_matrix,N*range,MPI_DOUBLE,0,1,comm); 
+			ISSM_MPI_Send(buffer,3,ISSM_MPI_INT,0,1,comm);   
+			if (range)ISSM_MPI_Send(local_matrix,N*range,ISSM_MPI_PDOUBLE,0,1,comm); 
 		}
 		if (my_rank==0){
-			MPI_Recv(buffer,3,MPI_INT,i,1,comm,&status); 
-			if (buffer[2])MPI_Recv(outmatrix+(buffer[1]*N),N*buffer[2],MPI_DOUBLE,i,1,comm,&status);
+			ISSM_MPI_Recv(buffer,3,ISSM_MPI_INT,i,1,comm,&status); 
+			if (buffer[2])ISSM_MPI_Recv(outmatrix+(buffer[1]*N),N*buffer[2],ISSM_MPI_PDOUBLE,i,1,comm,&status);
 		}
 	} 
Index: /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 16136)
+++ /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 16137)
@@ -15,10 +15,9 @@
 
 #include "./petscpatches.h"
-
 #include "../../../shared/shared.h"
-#include "../../mpi/patches/mpipatches.h"
+#include "../../mpi/issmmpi.h"
 
 /*NewMat(int M,int N){{{*/
-Mat NewMat(int M,int N,COMM comm){
+Mat NewMat(int M,int N,ISSM_MPI_Comm comm){
 
 	/*output:*/
@@ -47,6 +46,6 @@
 }
 /*}}}*/
-/*NewMat(int M,int N,double sparsity,COMM comm){{{*/
-Mat NewMat(int M,int N,double sparsity,COMM comm){
+/*NewMat(int M,int N,double sparsity,ISSM_MPI_Comm comm){{{*/
+Mat NewMat(int M,int N,double sparsity,ISSM_MPI_Comm comm){
 
 	/*output:*/
@@ -81,5 +80,5 @@
 /*}}}*/
 /*NewMat(int M,int N,int connectivity,int numberofdofspernode){{{*/
-Mat NewMat(int M,int N,int connectivity,int numberofdofspernode,COMM comm){
+Mat NewMat(int M,int N,int connectivity,int numberofdofspernode,ISSM_MPI_Comm comm){
 
 	/*output:*/
Index: /issm/trunk/src/c/toolkits/petsc/patches/NewVec.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/NewVec.cpp	(revision 16136)
+++ /issm/trunk/src/c/toolkits/petsc/patches/NewVec.cpp	(revision 16137)
@@ -15,7 +15,7 @@
 
 #include "./petscpatches.h"
-#include "../../mpi/patches/mpipatches.h"
+#include "../../mpi/issmmpi.h"
 
-Vec NewVec(int size,COMM comm,bool fromlocalsize){
+Vec NewVec(int size,ISSM_MPI_Comm comm,bool fromlocalsize){
 
 	int local_size;
Index: /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 16136)
+++ /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 16137)
@@ -60,6 +60,6 @@
 
 	PetscOptionsGetString(PETSC_NULL,"-issm_option_solver",&option[0],100,&flag);
-	if (strcmp(option,"stokes")==0){
-		solver_type=StokesSolverEnum;
+	if (strcmp(option,"FS")==0){
+		solver_type=FSSolverEnum;
 	}
 
Index: /issm/trunk/src/c/toolkits/petsc/patches/VecToMPISerial.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 16136)
+++ /issm/trunk/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 16137)
@@ -12,5 +12,5 @@
 #include "../../../shared/shared.h"
 
-int VecToMPISerial(double** pgathered_vector, Vec vector,COMM comm){
+int VecToMPISerial(double** pgathered_vector, Vec vector,ISSM_MPI_Comm comm){
 
 	int i;
@@ -19,5 +19,5 @@
 
 	/*Petsc*/
-	MPI_Status status;
+	ISSM_MPI_Status status;
 	PetscInt lower_row,upper_row; 
 	int range;
@@ -35,6 +35,6 @@
 
 	/*recover my_rank and num_procs*/
-	MPI_Comm_size(comm,&num_procs);
-	MPI_Comm_rank(comm,&my_rank);
+	ISSM_MPI_Comm_size(comm,&num_procs);
+	ISSM_MPI_Comm_rank(comm,&my_rank);
 
 	VecGetSize(vector,&vector_size);
@@ -69,10 +69,10 @@
 			buffer[1]=lower_row;
 			buffer[2]=range;
-			MPI_Send(buffer,3,MPI_INT,0,1,comm);  
-			if (range)MPI_Send(local_vector,range,MPI_DOUBLE,0,1,comm); 
+			ISSM_MPI_Send(buffer,3,ISSM_MPI_INT,0,1,comm);  
+			if (range)ISSM_MPI_Send(local_vector,range,ISSM_MPI_PDOUBLE,0,1,comm); 
 		}
 		if (my_rank==0){
-			MPI_Recv(buffer,3,MPI_INT,i,1,comm,&status); 
-			if (buffer[2])MPI_Recv(gathered_vector+buffer[1],buffer[2],MPI_DOUBLE,i,1,comm,&status);
+			ISSM_MPI_Recv(buffer,3,ISSM_MPI_INT,i,1,comm,&status); 
+			if (buffer[2])ISSM_MPI_Recv(gathered_vector+buffer[1],buffer[2],ISSM_MPI_PDOUBLE,i,1,comm,&status);
 		}
 	}
@@ -84,5 +84,5 @@
 
 	/*Now, broadcast gathered_vector from node 0 to other nodes: */
-	MPI_Bcast(gathered_vector,vector_size,MPI_DOUBLE,0,comm);
+	ISSM_MPI_Bcast(gathered_vector,vector_size,ISSM_MPI_PDOUBLE,0,comm);
 
 	/*Assign output pointers: */
Index: /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 16136)
+++ /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 16137)
@@ -13,14 +13,14 @@
 #include "./SolverEnum.h"
 #include "../../toolkitsenums.h"
-#include "../../../shared/io/Comm/Comm.h"
+#include "../../../shared/io/Comm/IssmComm.h"
 
 class Parameters;
 
-Vec NewVec(int size,COMM comm,bool fromlocalsize=false);
-Mat NewMat(int M,int N,COMM comm);
-Mat NewMat(int M,int N,double sparsity,COMM comm);
-Mat NewMat(int M,int N,int connectivity,int numberofdofspernode, COMM comm);
+Vec NewVec(int size,ISSM_MPI_Comm comm,bool fromlocalsize=false);
+Mat NewMat(int M,int N,ISSM_MPI_Comm comm);
+Mat NewMat(int M,int N,double sparsity,ISSM_MPI_Comm comm);
+Mat NewMat(int M,int N,int connectivity,int numberofdofspernode, ISSM_MPI_Comm comm);
 
-int VecToMPISerial(double** pgathered_vector, Vec vector,COMM comm);
+int VecToMPISerial(double** pgathered_vector, Vec vector,ISSM_MPI_Comm comm);
 void MatFree(Mat* pmat);
 void ISFree(IS* pis);
@@ -32,6 +32,6 @@
 void PetscOptionsDetermineSolverType(int* psolver_type);
 void VecMerge(Vec A, Vec B, double* row_partition_vector,int row_partition_size);
-void MatMultPatch(Mat A,Vec X, Vec AX,COMM comm);
-void MatToSerial(double** poutmatrix,Mat matrix,COMM comm);
+void MatMultPatch(Mat A,Vec X, Vec AX,ISSM_MPI_Comm comm);
+void MatToSerial(double** poutmatrix,Mat matrix,ISSM_MPI_Comm comm);
 void VecDuplicatePatch(Vec* output, Vec input);
 Vec  SerialToVec(double* vector,int vector_size);
Index: sm/trunk/src/c/toolkits/plapack/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/plapack/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,6 +1,0 @@
-# Subdirectories {{{
-add_subdirectory(patches)
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits/plapack)
-# }}}
Index: sm/trunk/src/c/toolkits/plapack/patches/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/plapack/patches/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits/plapack/patches)
-# }}}
Index: /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 16136)
+++ /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 16137)
@@ -12,5 +12,5 @@
 #include "../../scalapack/FortranMapping.h"
 
-void PlapackInvertMatrixLocalCleanup(PLA_Obj* pa,PLA_Template* ptempl,double** parrayA,int** pidxnA,MPI_Comm* pcomm_2d);
+void PlapackInvertMatrixLocalCleanup(PLA_Obj* pa,PLA_Template* ptempl,double** parrayA,int** pidxnA,ISSM_MPI_Comm* pcomm_2d);
 
 int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con,COMM comm){ 
@@ -27,6 +27,6 @@
 
 	/*Plapack: */
-	MPI_Datatype   datatype;
-	MPI_Comm       comm_2d;
+	ISSM_MPI_Datatype   datatype;
+	ISSM_MPI_Comm       comm_2d;
 	PLA_Obj a=NULL;
 	PLA_Template   templ;	
@@ -85,5 +85,5 @@
 
 	/* Set the datatype */
-	datatype = MPI_DOUBLE;
+	datatype = ISSM_MPI_DOUBLE;
 
 	/* Copy A into a*/
@@ -123,4 +123,4 @@
 	/*Finalize PLAPACK*/
 	PLA_Finalize();
-	MPI_Comm_free(&comm_2d);
+	ISSM_MPI_Comm_free(&comm_2d);
 }
Index: sm/trunk/src/c/toolkits/scalapack/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/scalapack/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits/scalapack)
-# }}}
Index: /issm/trunk/src/c/toolkits/toolkits.h
===================================================================
--- /issm/trunk/src/c/toolkits/toolkits.h	(revision 16136)
+++ /issm/trunk/src/c/toolkits/toolkits.h	(revision 16137)
@@ -16,7 +16,5 @@
 #endif
 
-#ifdef _HAVE_MPI_
-#include "./mpi/mpiincludes.h"
-#endif
+#include "./mpi/issmmpi.h"
 
 #ifdef _HAVE_METIS_
Index: sm/trunk/src/c/toolkits/triangle/CMakeLists.txt
===================================================================
--- /issm/trunk/src/c/toolkits/triangle/CMakeLists.txt	(revision 16136)
+++ 	(revision )
@@ -1,5 +1,0 @@
-# Subdirectories {{{
-# }}}
-# Include Directory {{{
-include_directories(AFTER $ENV{ISSM_DIR}/src/c/toolkits/triangle)
-# }}}
Index: /issm/trunk/src/dox/issm.dox
===================================================================
--- /issm/trunk/src/dox/issm.dox	(revision 16136)
+++ /issm/trunk/src/dox/issm.dox	(revision 16137)
@@ -47,26 +47,20 @@
 </th>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">469</td><td  bgcolor=#FFFFFF style="text-align:right;">14505</td><td  bgcolor=#FFFFFF style="text-align:right;">16993</td><td  bgcolor=#FFFFFF style="text-align:right;">58467</td><td  bgcolor=#FFFFFF style="text-align:right;">89965</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">478</td><td  bgcolor=#FFFFFF style="text-align:right;">14993</td><td  bgcolor=#FFFFFF style="text-align:right;">17509</td><td  bgcolor=#FFFFFF style="text-align:right;">60128</td><td  bgcolor=#FFFFFF style="text-align:right;">92630</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">959</td><td  bgcolor=#C6E2FF style="text-align:right;">6773</td><td  bgcolor=#C6E2FF style="text-align:right;">13598</td><td  bgcolor=#C6E2FF style="text-align:right;">31759</td><td  bgcolor=#C6E2FF style="text-align:right;">52130</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">1037</td><td  bgcolor=#C6E2FF style="text-align:right;">7053</td><td  bgcolor=#C6E2FF style="text-align:right;">14331</td><td  bgcolor=#C6E2FF style="text-align:right;">33157</td><td  bgcolor=#C6E2FF style="text-align:right;">54541</td>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">365</td><td  bgcolor=#FFFFFF style="text-align:right;">2786</td><td  bgcolor=#FFFFFF style="text-align:right;">2931</td><td  bgcolor=#FFFFFF style="text-align:right;">12036</td><td  bgcolor=#FFFFFF style="text-align:right;">17753</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">381</td><td  bgcolor=#FFFFFF style="text-align:right;">3146</td><td  bgcolor=#FFFFFF style="text-align:right;">3358</td><td  bgcolor=#FFFFFF style="text-align:right;">13275</td><td  bgcolor=#FFFFFF style="text-align:right;">19779</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> Python </th><td  bgcolor=#C6E2FF style="text-align:right;">113</td><td  bgcolor=#C6E2FF style="text-align:right;">3445</td><td  bgcolor=#C6E2FF style="text-align:right;">4852</td><td  bgcolor=#C6E2FF style="text-align:right;">7316</td><td  bgcolor=#C6E2FF style="text-align:right;">15613</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> Python </th><td  bgcolor=#C6E2FF style="text-align:right;">115</td><td  bgcolor=#C6E2FF style="text-align:right;">4054</td><td  bgcolor=#C6E2FF style="text-align:right;">6697</td><td  bgcolor=#C6E2FF style="text-align:right;">7601</td><td  bgcolor=#C6E2FF style="text-align:right;">18352</td>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> Java </th><td  bgcolor=#FFFFFF style="text-align:right;">23</td><td  bgcolor=#FFFFFF style="text-align:right;">460</td><td  bgcolor=#FFFFFF style="text-align:right;">416</td><td  bgcolor=#FFFFFF style="text-align:right;">4061</td><td  bgcolor=#FFFFFF style="text-align:right;">4937</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> m4 </th><td  bgcolor=#FFFFFF style="text-align:right;">2</td><td  bgcolor=#FFFFFF style="text-align:right;">213</td><td  bgcolor=#FFFFFF style="text-align:right;">6</td><td  bgcolor=#FFFFFF style="text-align:right;">1512</td><td  bgcolor=#FFFFFF style="text-align:right;">1731</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> m4 </th><td  bgcolor=#C6E2FF style="text-align:right;">2</td><td  bgcolor=#C6E2FF style="text-align:right;">197</td><td  bgcolor=#C6E2FF style="text-align:right;">6</td><td  bgcolor=#C6E2FF style="text-align:right;">1401</td><td  bgcolor=#C6E2FF style="text-align:right;">1604</td>
-</tr>
-<tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> XML </th><td  bgcolor=#FFFFFF style="text-align:right;">38</td><td  bgcolor=#FFFFFF style="text-align:right;">89</td><td  bgcolor=#FFFFFF style="text-align:right;">10</td><td  bgcolor=#FFFFFF style="text-align:right;">783</td><td  bgcolor=#FFFFFF style="text-align:right;">882</td>
-</tr>
-<tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> CMake </th><td  bgcolor=#C6E2FF style="text-align:right;">163</td><td  bgcolor=#C6E2FF style="text-align:right;">0</td><td  bgcolor=#C6E2FF style="text-align:right;">871</td><td  bgcolor=#C6E2FF style="text-align:right;">631</td><td  bgcolor=#C6E2FF style="text-align:right;">1502</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> CMake </th><td  bgcolor=#C6E2FF style="text-align:right;">158</td><td  bgcolor=#C6E2FF style="text-align:right;">0</td><td  bgcolor=#C6E2FF style="text-align:right;">835</td><td  bgcolor=#C6E2FF style="text-align:right;">598</td><td  bgcolor=#C6E2FF style="text-align:right;">1433</td>
 </tr>
 <tr>
@@ -74,14 +68,14 @@
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#C6E2FF style="text-align:right;">3</td><td  bgcolor=#C6E2FF style="text-align:right;">56</td><td  bgcolor=#C6E2FF style="text-align:right;">73</td><td  bgcolor=#C6E2FF style="text-align:right;">248</td><td  bgcolor=#C6E2FF style="text-align:right;">377</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> Fortran </th><td  bgcolor=#C6E2FF style="text-align:right;">77</td><td  bgcolor=#C6E2FF style="text-align:right;">7</td><td  bgcolor=#C6E2FF style="text-align:right;">4</td><td  bgcolor=#C6E2FF style="text-align:right;">302</td><td  bgcolor=#C6E2FF style="text-align:right;">365</td><td  bgcolor=#C6E2FF style="text-align:right;">678</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>
+<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;">58</td><td  bgcolor=#FFFFFF style="text-align:right;">71</td><td  bgcolor=#FFFFFF style="text-align:right;">252</td><td  bgcolor=#FFFFFF style="text-align:right;">381</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> C </th><td  bgcolor=#C6E2FF style="text-align:right;">2</td><td  bgcolor=#C6E2FF style="text-align:right;">10</td><td  bgcolor=#C6E2FF style="text-align:right;">3</td><td  bgcolor=#C6E2FF style="text-align:right;">81</td><td  bgcolor=#C6E2FF style="text-align:right;">94</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> Perl </th><td  bgcolor=#C6E2FF style="text-align:right;">1</td><td  bgcolor=#C6E2FF style="text-align:right;">6</td><td  bgcolor=#C6E2FF style="text-align:right;">9</td><td  bgcolor=#C6E2FF style="text-align:right;">196</td><td  bgcolor=#C6E2FF style="text-align:right;">211</td>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">2147</td><td  bgcolor=#FFFFFF style="text-align:right;">28423</td><td  bgcolor=#FFFFFF style="text-align:right;">39762</td><td  bgcolor=#FFFFFF style="text-align:right;">117349</td><td  bgcolor=#FFFFFF style="text-align:right;">185534</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">2190</td><td  bgcolor=#FFFFFF style="text-align:right;">29623</td><td  bgcolor=#FFFFFF style="text-align:right;">43118</td><td  bgcolor=#FFFFFF style="text-align:right;">117454</td><td  bgcolor=#FFFFFF style="text-align:right;">190195</td>
 </tr>
 </table>
Index: /issm/trunk/src/m/Makefile.am
===================================================================
--- /issm/trunk/src/m/Makefile.am	(revision 16136)
+++ /issm/trunk/src/m/Makefile.am	(revision 16137)
@@ -3,50 +3,80 @@
 #find . -type d -exec ls -d {} \;
 
+bin_SCRIPTS = 
 if WRAPPERS
-bin_SCRIPTS= ./qmu/*.m \
-				 ./qmu/setupdesign/*.m \
-				 ./qmu/plot/*.m \
-				 ./qmu/examples/*.m \
-				 ./kml/*.m \
-				 ./enum/*.m \
-				 ./classes/*.m \
-				 ./classes/qmu/*.m \
-				 ./classes/qmu/@dakota_method/*.m \
-				 ./classes/clusters/*.m \
-				 ./classes/model/*.m \
-				 ./consistency/*.m \
-				 ./array/*.m \
-				 ./boundaryconditions/*.m \
-				 ./exp/*.m \
-				 ./exp/manipulation/*.m \
-				 ./geometry/*.m \
-				 ./interp/*.m \
-				 ./coordsystems/*.m \
-				 ./mech/*.m \
-				 ./mesh/*.m \
-				 ./mesh/planet/*.m \
-				 ./mesh/rifts/*.m \
-				 ./miscellaneous/*.m \
-				 ./os/*.m \
-				 ./plot/*.m \
-				 ./plot/colormaps/*.m \
-				 ./string/*.m \
-				 ./contrib/massbalance/*.m \
-				 ./contrib/ecco/*.m \
-				 ./contrib/hydrology/*.m \
-				 ./contrib/hack/*.m \
-				 ./contrib/gslib/*.m \
-				 ./contrib/uci/*.m \
-				 ./contrib/oasis/*.m \
-				 ./contrib/bamg/*.m \
-				 ./extrusion/*.m \
-				 ./inversions/*.m \
-				 ./io/*.m \
-				 ./parameterization/*.m \
-				 ./partition/*.m \
-				 ./print/*.m \
-				 ./regional/*.m \
-				 ./solve/*.m \
-				 ./solvers/*.m \
-				 ./materials/*.m
+if MATLAB
+if !DEVELOPMENT
+bin_SCRIPTS += ./qmu/*.m \
+					./qmu/setupdesign/*.m \
+					./qmu/plot/*.m \
+					./qmu/examples/*.m \
+					./kml/*.m \
+					./enum/*.m \
+					./classes/*.m \
+					./classes/qmu/*.m \
+					./classes/qmu/@dakota_method/*.m \
+					./classes/clusters/*.m \
+					./classes/model/*.m \
+					./consistency/*.m \
+					./array/*.m \
+					./boundaryconditions/*.m \
+					./exp/*.m \
+					./exp/operation/*.m \
+					./geometry/*.m \
+					./interp/*.m \
+					./coordsystems/*.m \
+					./mech/*.m \
+					./mesh/*.m \
+					./mesh/planet/*.m \
+					./mesh/rifts/*.m \
+					./miscellaneous/*.m \
+					./os/*.m \
+					./plot/*.m \
+					./plot/colormaps/*.m \
+					./string/*.m \
+					./contrib/massbalance/*.m \
+					./contrib/ecco/*.m \
+					./contrib/hydrology/*.m \
+					./contrib/hack/*.m \
+					./contrib/gslib/*.m \
+					./contrib/uci/*.m \
+					./contrib/oasis/*.m \
+					./contrib/bamg/*.m \
+					./extrusion/*.m \
+					./inversions/*.m \
+					./io/*.m \
+					./parameterization/*.m \
+					./partition/*.m \
+					./print/*.m \
+					./regional/*.m \
+					./solve/*.m \
+					./solvers/*.m \
+					./materials/*.m
 endif
+endif
+if PYTHON
+if !DEVELOPMENT
+bin_SCRIPTS += ./enum/*.py \
+					./classes/*.py \
+					./classes/clusters/*.py \
+					./classes/model/*.py \
+					./consistency/*.py \
+					./boundaryconditions/*.py \
+					./exp/*.py \
+					./geometry/*.py \
+					./coordsystems/*.py \
+					./mech/*.py \
+					./mesh/*.py \
+					./mesh/rifts/*.py \
+					./miscellaneous/*.py \
+					./os/*.py \
+					./plot/*.py \
+					./extrusion/*.py \
+					./io/*.py \
+					./parameterization/*.py \
+					./solve/*.py \
+					./solvers/*.py \
+					./materials/*.py
+endif
+endif
+endif
Index: /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m	(revision 16136)
+++ /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m	(revision 16137)
@@ -1,4 +1,4 @@
 function md=SetIceSheetBC(md)
-%SETICESHEETBC - Create the boundary conditions for diagnostic and thermal models for an IceSheet with no Ice Front
+%SETICESHEETBC - Create the boundary conditions for stressbalance and thermal models for an IceSheet with no Ice Front
 %
 %   Usage:
@@ -9,28 +9,23 @@
 %node on Dirichlet
 pos=find(md.mesh.vertexonboundary);
-md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvy(pos)=0;
-md.diagnostic.spcvz(pos)=0;
-md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
-md.diagnostic.loadingforce=0*ones(md.mesh.numberofvertices,3);
+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.spcvx(pos)=0;
+md.stressbalance.spcvy(pos)=0;
+md.stressbalance.spcvz(pos)=0;
+md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
 
 %Dirichlet Values
 if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
-	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
-	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
-	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+	disp('      boundary conditions for stressbalance model: spc set as observed velocities');
+	md.stressbalance.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.stressbalance.spcvy(pos)=md.inversion.vy_obs(pos);
 else
-	disp('      boundary conditions for diagnostic model: spc set as zero');
+	disp('      boundary conditions for stressbalance model: spc set as zero');
 end
 
-%segment on neumann (Ice Front) -> none
-if (md.mesh.dimension==2)
-	md.diagnostic.icefront=zeros(0,4);
-else
-	md.diagnostic.icefront=zeros(0,6);
-end
+%No ice front: do nothing
 
 %Create zeros basal melting rate and surface mass balance if not specified
@@ -52,5 +47,5 @@
 end
 
-md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 
Index: /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py	(revision 16136)
+++ /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py	(revision 16137)
@@ -5,5 +5,5 @@
 def SetIceSheetBC(md):
 	"""
-	SETICESHEETBC - Create the boundary conditions for diagnostic and thermal models for an IceSheet with no Ice Front
+	SETICESHEETBC - Create the boundary conditions for stressbalance and thermal models for an IceSheet with no Ice Front
 
 	   Usage:
@@ -15,26 +15,22 @@
 	#node on Dirichlet
 	pos=numpy.nonzero(md.mesh.vertexonboundary)
-	md.diagnostic.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvx[pos]=0
-	md.diagnostic.spcvy[pos]=0
-	md.diagnostic.spcvz[pos]=0
-	md.diagnostic.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
-	md.diagnostic.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
+	md.stressbalance.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvx[pos]=0
+	md.stressbalance.spcvy[pos]=0
+	md.stressbalance.spcvz[pos]=0
+	md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
+	md.stressbalance.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
 
 	#Dirichlet Values
 	if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
-		print "      boundary conditions for diagnostic model: spc set as observed velocities"
-		md.diagnostic.spcvx[pos]=md.inversion.vx_obs[pos]
-		md.diagnostic.spcvy[pos]=md.inversion.vy_obs[pos]
+		print "      boundary conditions for stressbalance model: spc set as observed velocities"
+		md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos]
+		md.stressbalance.spcvy[pos]=md.inversion.vy_obs[pos]
 	else:
-		print "      boundary conditions for diagnostic model: spc set as zero"
+		print "      boundary conditions for stressbalance model: spc set as zero"
 
-	#segment on neumann (Ice Front) -> none
-	if md.mesh.dimension==2:
-		md.diagnostic.icefront=numpy.zeros((0,4))
-	else:
-		md.diagnostic.icefront=numpy.zeros((0,6))
+	#No ice front -> do nothing
 
 	#Create zeros basal melting rate and surface mass balance if not specified
@@ -52,5 +48,5 @@
 		print "      no balancethickness.thickening_rate specified: values set as zero"
 
-	md.prognostic.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 
Index: /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m	(revision 16136)
+++ /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.m	(revision 16137)
@@ -1,8 +1,8 @@
 function md=SetIceShelfBC(md,varargin)
-%SETICESHELFBC - Create the boundary conditions for diagnostic and thermal models for a  Ice Shelf with Ice Front
+%SETICESHELFBC - Create the boundary conditions for stressbalance and thermal models for a  Ice Shelf with Ice Front
 %
 %   Neumann BC are used on the ice front (an ANRGUS contour around the ice front
 %   must be given in input)
-%   Dirichlet BC are used elsewhere for diagnostic
+%   Dirichlet BC are used elsewhere for stressbalance
 %
 %   Usage:
@@ -28,40 +28,35 @@
 end
 pos=find(md.mesh.vertexonboundary & ~nodeonicefront);
-md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvy(pos)=0;
-md.diagnostic.spcvz(pos)=0;
-md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
-md.diagnostic.loadingforce=0*ones(md.mesh.numberofvertices,3);
+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);
+
+%Ice front position: 
+md.mask.ice_levelset(find(nodeonicefront))=0;
+
+%First find segments that are not completely on the front
+if(md.mesh.dimension==2),
+	numbernodesfront=2;
+else 
+	numbernodesfront=4;
+end
+segmentsfront=md.mask.ice_levelset(md.mesh.segments(:,1:numbernodesfront))==0;
+segments=find(sum(segmentsfront,2)~=numbernodesfront);
+%Find all nodes for these segments and spc them
+pos=md.mesh.segments(segments,1:numbernodesfront);
+md.stressbalance.spcvx(pos(:))=0;
+md.stressbalance.spcvy(pos(:))=0;
+md.stressbalance.spcvz(pos(:))=0;
 
 %Dirichlet Values
 if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
-	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
-	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
-	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+	disp('      boundary conditions for stressbalance model: spc set as observed velocities');
+	md.stressbalance.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.stressbalance.spcvy(pos)=md.inversion.vy_obs(pos);
 else
-	disp('      boundary conditions for diagnostic model: spc set as zero');
+	disp('      boundary conditions for stressbalance model: spc set as zero');
 end
-
-%segment on Ice Front
-%segment on Neumann (Ice Front)
-pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2)));
-if (md.mesh.dimension==2)
-	pressureload=md.mesh.segments(pos,:);
-elseif md.mesh.dimension==3
-	pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
-	pressureload=[];
-	for i=1:md.mesh.numberoflayers-1,
-		pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
-	end
-end
-
-%Add water or air enum depending on the element
-pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))];
-
-%plug onto model
-md.diagnostic.icefront=pressureload;
 
 %Create zeros basalforcings and surfaceforcings
@@ -83,5 +78,5 @@
 end
 
-md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 
Index: /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py	(revision 16136)
+++ /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py	(revision 16137)
@@ -5,9 +5,9 @@
 def SetIceShelfBC(md,icefrontfile=''):
 	"""
-	SETICESHELFBC - Create the boundary conditions for diagnostic and thermal models for a  Ice Shelf with Ice Front
+	SETICESHELFBC - Create the boundary conditions for stressbalance and thermal models for a  Ice Shelf with Ice Front
 
 	   Neumann BC are used on the ice front (an ARGUS contour around the ice front
 	   must be given in input)
-	   Dirichlet BC are used elsewhere for diagnostic
+	   Dirichlet BC are used elsewhere for stressbalance
 
 	   Usage:
@@ -32,13 +32,32 @@
 #	pos=find(md.mesh.vertexonboundary & ~nodeonicefront);
 	pos=numpy.nonzero(numpy.logical_and(md.mesh.vertexonboundary,numpy.logical_not(nodeonicefront)))[0]
-	md.diagnostic.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvx[pos]=0
-	md.diagnostic.spcvy[pos]=0
-	md.diagnostic.spcvz[pos]=0
-	md.diagnostic.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
-	md.diagnostic.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
+	md.stressbalance.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
+	md.stressbalance.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
 
+	#Icefront position
+	pos=numpy.nonzero(nodeonicefront)[0]
+	md.mask.ice_levelset[pos]=0
+
+	#First find segments that are not completely on the front
+	if md.mesh.dimension==2:
+		numbernodesfront=2
+	else:
+		numbernodesfront=4
+	if any(md.mask.ice_levelset<=0):
+		values=md.mask.ice_levelset[md.mesh.segments[:,0:-1]-1]
+		segmentsfront=1-values
+		numpy.sum(segmentsfront,axis=1)!=numbernodesfront
+		segments=numpy.nonzero(numpy.sum(segmentsfront,axis=1)!=numbernodesfront)[0]
+		#Find all nodes for these segments and spc them
+		pos=md.mesh.segments[segments,0:-1]-1
+	else:
+		pos=numpy.nonzero(md.mesh.vertexonboundary)[0]
+	md.stressbalance.spcvx[pos[:]]=0
+	md.stressbalance.spcvy[pos[:]]=0
+	md.stressbalance.spcvz[pos[:]]=0
+																													   
 	#Dirichlet Values
 	if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
@@ -48,30 +67,9 @@
 		if numpy.ndim(md.inversion.vy_obs)==1:
 			md.inversion.vy_obs=md.inversion.vy_obs.reshape(-1,1)
-		print "      boundary conditions for diagnostic model: spc set as observed velocities"
-		md.diagnostic.spcvx[pos]=md.inversion.vx_obs[pos]
-		md.diagnostic.spcvy[pos]=md.inversion.vy_obs[pos]
+		print "      boundary conditions for stressbalance model: spc set as observed velocities"
+		md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos]
+		md.stressbalance.spcvy[pos]=md.inversion.vy_obs[pos]
 	else:
-		print "      boundary conditions for diagnostic model: spc set as zero"
-
-	#segment on Ice Front
-	#segment on Neumann (Ice Front)
-#	pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2)));
-	pos=numpy.nonzero(numpy.logical_or(nodeonicefront[md.mesh.segments[:,0]-1],nodeonicefront[md.mesh.segments[:,1]-1]))[0]
-	if   md.mesh.dimension==2:
-		pressureload=md.mesh.segments[pos,:]
-	elif md.mesh.dimension==3:
-#		pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
-		pressureload_layer1=numpy.hstack((md.mesh.segments[pos,0:2],md.mesh.segments[pos,1]+md.mesh.numberofvertices2d,md.mesh.segments[pos,0]+md.mesh.numberofvertices2d,md.mesh.segments[pos,2]))
-		pressureload=numpy.zeros((0,5),int)
-		for i in xrange(1,md.mesh.numberoflayers):
-#			pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
-			pressureload=numpy.vstack((pressureload,numpy.hstack((pressureload_layer1[:,0:4]+(i-1)*md.mesh.numberofvertices2d,pressureload_layer1[:,4]+(i-1)*md.mesh.numberofelements2d))))
-
-	#Add water or air enum depending on the element
-#	pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))];
-	pressureload=numpy.hstack((pressureload,1*md.mask.elementonfloatingice[pressureload[:,-1]-1].reshape(-1,1)))
-
-	#plug onto model
-	md.diagnostic.icefront=pressureload
+		print "      boundary conditions for stressbalance model: spc set as zero"
 
 	#Create zeros basalforcings and surfaceforcings
@@ -89,5 +87,5 @@
 		print "      no balancethickness.thickening_rate specified: values set as zero"
 
-	md.prognostic.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 
Index: /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 16136)
+++ /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 16137)
@@ -1,8 +1,8 @@
 function md=SetMarineIceSheetBC(md,varargin)
-%SETICEMARINESHEETBC - Create the boundary conditions for diagnostic and thermal models for a  Marine Ice Sheet with Ice Front
+%SETICEMARINESHEETBC - Create the boundary conditions for stressbalance and thermal models for a  Marine Ice Sheet with Ice Front
 %
 %   Neumann BC are used on the ice front (an ARGUS contour around the ice front
 %   can be given in input, or it will be deduced as onfloatingice & onboundary)
-%   Dirichlet BC are used elsewhere for diagnostic
+%   Dirichlet BC are used elsewhere for stressbalance
 %
 %   Usage:
@@ -23,10 +23,11 @@
 		error(['SetMarineIceSheetBC error message: ice front file ' icefrontfile ' not found']);
 	end
-	nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2);
-	vertexonicefront=double(md.mesh.vertexonboundary & nodeinsideicefront);
+	incontour=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2);
+	vertexonicefront=double(md.mesh.vertexonboundary & incontour);
 else
 	%Guess where the ice front is
+	pos=find(sum(md.mask.groundedice_levelset(md.mesh.elements)<0.,2) >0.);
 	vertexonfloatingice=zeros(md.mesh.numberofvertices,1);
-	vertexonfloatingice(md.mesh.elements(find(md.mask.elementonfloatingice),:))=1;
+	vertexonfloatingice(md.mesh.elements(pos,:))=1.;
 	vertexonicefront=double(md.mesh.vertexonboundary & vertexonfloatingice);
 end
@@ -35,20 +36,34 @@
 	warning('SetMarineIceSheetBC warning: ice front all around the glacier, no dirichlet found. Dirichlet must be added manually')
 end
-md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvy(pos)=0;
-md.diagnostic.spcvz(pos)=0;
-md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
-md.diagnostic.loadingforce=0*ones(md.mesh.numberofvertices,3);
+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);
+
+%Position of ice front
+md.mask.ice_levelset(find(vertexonicefront))=0;
+
+%First find segments that are not completely on the front
+if(md.mesh.dimension==2),
+	numbernodesfront=2;
+else 
+	numbernodesfront=4;
+end
+segmentsfront=md.mask.ice_levelset(md.mesh.segments(:,1:numbernodesfront))==0;
+segments=find(sum(segmentsfront,2)~=numbernodesfront);
+%Find all nodes for these segments and spc them
+pos=md.mesh.segments(segments,1:numbernodesfront);
+md.stressbalance.spcvx(pos(:))=0;
+md.stressbalance.spcvy(pos(:))=0;
+md.stressbalance.spcvz(pos(:))=0;
 
 %Dirichlet Values
 if (length(md.inversion.vx_obs)==md.mesh.numberofvertices & length(md.inversion.vy_obs)==md.mesh.numberofvertices)
-	disp('      boundary conditions for diagnostic model: spc set as observed velocities');
-	md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos);
-	md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos);
+	disp('      boundary conditions for stressbalance model: spc set as observed velocities');
+	md.stressbalance.spcvx(pos)=md.inversion.vx_obs(pos);
+	md.stressbalance.spcvy(pos)=md.inversion.vy_obs(pos);
 else
-	disp('      boundary conditions for diagnostic model: spc set as zero');
+	disp('      boundary conditions for stressbalance model: spc set as zero');
 end
 
@@ -56,22 +71,4 @@
 pos=find(md.mesh.vertexonboundary);
 md.hydrology.spcwatercolumn(pos,1)=1;
-
-%segment on Neumann (Ice Front)
-pos=find(vertexonicefront(md.mesh.segments(:,1)) | vertexonicefront(md.mesh.segments(:,2)));
-if (md.mesh.dimension==2)
-	pressureload=md.mesh.segments(pos,:);
-elseif md.mesh.dimension==3
-	pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
-	pressureload=[];
-	for i=1:md.mesh.numberoflayers-1,
-		pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
-	end
-end
-
-%Add water or air enum depending on the element
-pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))+ 0*md.mask.elementongroundedice(pressureload(:,end))];
-
-%plug onto model
-md.diagnostic.icefront=pressureload;
 
 %Create zeros basalforcings and surfaceforcings
@@ -93,5 +90,5 @@
 end
 
-md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 
@@ -101,5 +98,5 @@
 	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
 		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
-		md.basalforcings.geothermalflux(find(md.mask.vertexongroundedice))=50.*10.^-3; %50mW/m2
+		md.basalforcings.geothermalflux(find(md.mask.groundedice_levelset>0.))=50.*10.^-3; %50mW/m2
 	end
 else
Index: /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py	(revision 16136)
+++ /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py	(revision 16137)
@@ -5,9 +5,9 @@
 def SetMarineIceSheetBC(md,icefrontfile=''):
 	"""
-	SETICEMARINESHEETBC - Create the boundary conditions for diagnostic and thermal models for a  Marine Ice Sheet with Ice Front
+	SETICEMARINESHEETBC - Create the boundary conditions for stressbalance and thermal models for a  Marine Ice Sheet with Ice Front
 
 	   Neumann BC are used on the ice front (an ARGUS contour around the ice front
 	   can be given in input, or it will be deduced as onfloatingice & onboundary)
-	   Dirichlet BC are used elsewhere for diagnostic
+	   Dirichlet BC are used elsewhere for stressbalance
 
 	   Usage:
@@ -27,11 +27,12 @@
 		if not os.path.exists(icefrontfile):
 			raise IOError("SetMarineIceSheetBC error message: ice front file '%s' not found." % icefrontfile)
-		[nodeinsideicefront,dum]=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
-		vertexonicefront=numpy.logical_and(md.mesh.vertexonboundary,nodeinsideicefront.reshape(-1))
+		[incontour,dum]=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
+		vertexonicefront=numpy.logical_and(md.mesh.vertexonboundary,incontour.reshape(-1))
 	else:
 		#Guess where the ice front is
-		vertexonfloatingice=numpy.zeros((md.mesh.numberofvertices),bool)
-		vertexonfloatingice[md.mesh.elements[numpy.nonzero(md.mask.elementonfloatingice),:]-1]=True
-		vertexonicefront=numpy.logical_and(md.mesh.vertexonboundary,vertexonfloatingice)
+		vertexonfloatingice=numpy.zeros((md.mesh.numberofvertices,1))
+		pos=numpy.nonzero(numpy.sum(md.mask.groundedice_levelset[md.mesh.elements-1]<0.,axis=1) >0.)[0]
+		vertexonfloatingice[md.mesh.elements[pos].astype(int)-1]=1.
+		vertexonicefront=numpy.logical_and(numpy.reshape(md.mesh.vertexonboundary,(-1,1)),vertexonfloatingice>0.)
 
 #	pos=find(md.mesh.vertexonboundary & ~vertexonicefront);
@@ -40,44 +41,43 @@
 		print "SetMarineIceSheetBC warning: ice front all around the glacier, no dirichlet found. Dirichlet must be added manually."
 
-	md.diagnostic.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvx[pos]=0
-	md.diagnostic.spcvy[pos]=0
-	md.diagnostic.spcvz[pos]=0
-	md.diagnostic.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
-	md.diagnostic.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
+	md.stressbalance.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
+	md.stressbalance.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
+
+	#Position of ice front
+	pos=numpy.nonzero(vertexonicefront)[0]
+	md.mask.ice_levelset[pos]=0
+
+	#First find segments that are not completely on the front
+	if md.mesh.dimension==2:
+		numbernodesfront=2
+	else:
+		numbernodesfront=4
+	if any(md.mask.ice_levelset<=0):
+		values=md.mask.ice_levelset[md.mesh.segments[:,0:-1]-1]
+		segmentsfront=1-values
+		numpy.sum(segmentsfront,axis=1)!=numbernodesfront
+		segments=numpy.nonzero(numpy.sum(segmentsfront,axis=1)!=numbernodesfront)[0]
+		#Find all nodes for these segments and spc them
+		pos=md.mesh.segments[segments,0:-1]-1
+	else:
+		pos=numpy.nonzero(md.mesh.vertexonboundary)[0]
+	md.stressbalance.spcvx[pos[:]]=0
+	md.stressbalance.spcvy[pos[:]]=0
+	md.stressbalance.spcvz[pos[:]]=0
 
 	#Dirichlet Values
 	if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
-		print "      boundary conditions for diagnostic model: spc set as observed velocities"
-		md.diagnostic.spcvx[pos]=md.inversion.vx_obs[pos]
-		md.diagnostic.spcvy[pos]=md.inversion.vy_obs[pos]
+		print "      boundary conditions for stressbalance model: spc set as observed velocities"
+		md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos]
+		md.stressbalance.spcvy[pos]=md.inversion.vy_obs[pos]
 	else:
-		print "      boundary conditions for diagnostic model: spc set as zero"
+		print "      boundary conditions for stressbalance model: spc set as zero"
 
 	md.hydrology.spcwatercolumn=numpy.zeros((md.mesh.numberofvertices,2))
 	pos=numpy.nonzero(md.mesh.vertexonboundary)[0]
 	md.hydrology.spcwatercolumn[pos,0]=1
-
-	#segment on Neumann (Ice Front)
-#	pos=find(vertexonicefront(md.mesh.segments(:,1)) | vertexonicefront(md.mesh.segments(:,2)));
-	pos=numpy.nonzero(numpy.logical_or(vertexonicefront[md.mesh.segments[:,0]-1],vertexonicefront[md.mesh.segments[:,1]-1]))[0]
-	if   md.mesh.dimension==2:
-		pressureload=md.mesh.segments[pos,:]
-	elif md.mesh.dimension==3:
-#		pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
-		pressureload_layer1=numpy.hstack((md.mesh.segments[pos,0:2],md.mesh.segments[pos,1]+md.mesh.numberofvertices2d,md.mesh.segments[pos,0]+md.mesh.numberofvertices2d,md.mesh.segments[pos,2]))
-		pressureload=numpy.zeros((0,5),int)
-		for i in xrange(1,md.mesh.numberoflayers):
-#			pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
-			pressureload=numpy.vstack((pressureload,numpy.hstack((pressureload_layer1[:,0:4]+(i-1)*md.mesh.numberofvertices2d,pressureload_layer1[:,4]+(i-1)*md.mesh.numberofelements2d))))
-
-	#Add water or air enum depending on the element
-#	pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))+ 0*md.mask.elementongroundedice(pressureload(:,end))];
-	pressureload=numpy.hstack((pressureload,1*md.mask.elementonfloatingice[pressureload[:,-1]-1].reshape(-1,1)+0*md.mask.elementongroundedice[pressureload[:,-1]-1].reshape(-1,1)))
-
-	#plug onto model
-	md.diagnostic.icefront=pressureload
 
 	#Create zeros basalforcings and surfaceforcings
@@ -95,5 +95,5 @@
 		print "      no balancethickness.thickening_rate specified: values set as zero"
 
-	md.prognostic.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 
@@ -105,5 +105,5 @@
 		if not isinstance(md.basalforcings.geothermalflux,numpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:
 			md.basalforcings.geothermalflux=numpy.zeros((md.mesh.numberofvertices,1))
-			md.basalforcings.geothermalflux[numpy.nonzero(md.mask.vertexongroundedice)]=50.*10.**-3    #50mW/m2
+			md.basalforcings.geothermalflux[numpy.nonzero(md.mask.groundedice_levelset>0.)]=50.*10.**-3    #50mW/m2
 	else:
 		print "      no thermal boundary conditions created: no observed temperature found"
Index: /issm/trunk/src/m/classes/balancethickness.m
===================================================================
--- /issm/trunk/src/m/classes/balancethickness.m	(revision 16136)
+++ /issm/trunk/src/m/classes/balancethickness.m	(revision 16137)
@@ -38,5 +38,5 @@
 			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: MacAyeal''s artificial diffusivity, 3:DG');
+			fielddisplay(obj,'stabilization','0: None, 1: SU, 2: SSA''s artificial diffusivity, 3:DG');
 
 		end % }}}
Index: /issm/trunk/src/m/classes/balancethickness.py
===================================================================
--- /issm/trunk/src/m/classes/balancethickness.py	(revision 16136)
+++ /issm/trunk/src/m/classes/balancethickness.py	(revision 16137)
@@ -27,5 +27,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint) [m]'))
 		string="%s\n%s"%(string,fielddisplay(self,'thickening_rate','ice thickening rate used in the mass conservation (dh/dt) [m/yr]'))
-		string="%s\n%s"%(string,fielddisplay(self,'stabilization',"0: None, 1: SU, 2: MacAyeal's artificial diffusivity, 3:DG"))
+		string="%s\n%s"%(string,fielddisplay(self,'stabilization',"0: None, 1: SU, 2: SSA's artificial diffusivity, 3:DG"))
 		return string
 		#}}}
Index: /issm/trunk/src/m/classes/basalforcings.m
===================================================================
--- /issm/trunk/src/m/classes/basalforcings.m	(revision 16136)
+++ /issm/trunk/src/m/classes/basalforcings.m	(revision 16137)
@@ -24,5 +24,5 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			if ismember(PrognosticAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.isprognostic==0),
+			if ismember(MasstransportAnalysisEnum(),analyses) & ~(solution==TransientSolutionEnum() & md.transient.ismasstransport==0),
 				md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1);
 			end
Index: /issm/trunk/src/m/classes/basalforcings.py
===================================================================
--- /issm/trunk/src/m/classes/basalforcings.py	(revision 16136)
+++ /issm/trunk/src/m/classes/basalforcings.py	(revision 16137)
@@ -35,5 +35,5 @@
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
-		if PrognosticAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isprognostic):
+		if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
 			md = checkfield(md,'basalforcings.melting_rate','NaN',1,'forcing',1)
 
Index: /issm/trunk/src/m/classes/clusters/cloud.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/cloud.m	(revision 16136)
+++ /issm/trunk/src/m/classes/clusters/cloud.m	(revision 16137)
@@ -55,8 +55,11 @@
 			if cluster.interactive
 				fprintf(fid,'source %s%s\n',cluster.codepath,'/../etc/environment.sh');
-				fprintf(fid,'mpiexec -np %i -f /home/mpich2.hosts %s/issm.exe %s %s %s ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+				fprintf(fid,'cd %s\n',[cluster.executionpath '/' dirname]);
+				fprintf(fid,'mpiexec -np %i -f /home/mpich2.hosts %s/issm.exe %s %s %s 2> %s.errlog > /dev/stdout | tee %s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
 			else
 				fprintf(fid,'source %s%s\n',cluster.codepath,'/../etc/environment.sh');
-				fprintf(fid,'mpiexec -np %i -f /home/mpich2.hosts %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,'cd %s\n',[cluster.executionpath '/' dirname]);
+				fprintf(fid,'mpiexec -np %i -f /home/mpich2.hosts %s/issm.exe %s %s %s 2> %s.errlog > /dev/stdout | tee %s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+				%fprintf(fid,'mpiexec -np %i -f /home/mpich2.hosts %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
 			end
 		end
@@ -84,5 +87,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  && source  ' modelname '.queue '];
+					' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && qsub  ' modelname '.queue '];
 			end
 			issmstssh(cluster.name,cluster.login,launchcommand);
Index: /issm/trunk/src/m/classes/clusters/discover.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/discover.m	(revision 16136)
+++ /issm/trunk/src/m/classes/clusters/discover.m	(revision 16137)
@@ -13,5 +13,5 @@
 		 numnodes=20;
 		 cpuspernode=8; 
-		 port=1025;
+		 port=0;
 		 queue='general';
 		 time=12*60;
@@ -103,6 +103,6 @@
 			 fprintf(fid,'#PBS -W group_list=s1010\n');
 			 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 purge\n');
Index: /issm/trunk/src/m/classes/clusters/generic.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/generic.m	(revision 16136)
+++ /issm/trunk/src/m/classes/clusters/generic.m	(revision 16137)
@@ -70,5 +70,5 @@
 				if ~isvalgrind,
 					if cluster.interactive
-						if ismpi,
+						if IssmConfig('_HAVE_MPI_'),
 							fprintf(fid,'mpiexec -np %i %s/issm.exe %s %s %s ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
 						else
@@ -76,5 +76,5 @@
 						end
 					else
-						if ismpi,
+						if IssmConfig('_HAVE_MPI_'),
 							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);
 						else
@@ -88,5 +88,5 @@
 					fprintf(fid,'LD_PRELOAD=%s \\\n',cluster.valgrindlib);
 					if ismac, 
-						if ismpi,
+						if IssmConfig('_HAVE_MPI_'),
 							fprintf(fid,'mpiexec -np %i %s --leak-check=full --dsymutil=yes --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
 							cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname], modelname,modelname,modelname);
@@ -96,5 +96,5 @@
 						end
 					else
-						if ismpi,
+						if IssmConfig('_HAVE_MPI_'),
 							fprintf(fid,'mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',...
 							cluster.np,cluster.valgrind,cluster.valgrindsup,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
Index: /issm/trunk/src/m/classes/clusters/generic.py
===================================================================
--- /issm/trunk/src/m/classes/clusters/generic.py	(revision 16136)
+++ /issm/trunk/src/m/classes/clusters/generic.py	(revision 16137)
@@ -1,10 +1,9 @@
 import socket
-import os
 import math
 import subprocess
+from IssmConfig import IssmConfig
 from EnumToString import EnumToString
 from issmdir import *
 from pairoptions import *
-from ismpi import *
 from issmssh import *
 from issmscpin import *
@@ -81,10 +80,10 @@
 			if not isvalgrind:
 				if self.interactive: 
-					if ismpi():
+					if IssmConfig('_HAVE_MPI_')[0]:
 						fid.write('mpiexec -np %i %s/issm.exe %s %s/%s %s ' % (self.np,self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname))
 					else:
 						fid.write('%s/issm.exe %s %s/%s %s ' % (self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname))
 				else:
-					if ismpi():
+					if IssmConfig('_HAVE_MPI_')[0]:
 						fid.write('mpiexec -np %i %s/issm.exe %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
 					else:
@@ -95,5 +94,5 @@
 				#Add --gen-suppressions=all to get suppression lines
 				fid.write('LD_PRELOAD=%s \\\n' % self.valgrindlib)
-				if ismpi():
+				if IssmConfig('_HAVE_MPI_')[0]:
 					fid.write('mpiexec -np %i %s --leak-check=full --suppressions=%s %s/issm.exe %s %s/%s %s 2> %s.errlog >%s.outlog ' % \
 							(self.np,self.valgrind,self.valgrindsup,self.codepath,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
Index: /issm/trunk/src/m/classes/clusters/greenplanet.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/greenplanet.m	(revision 16136)
+++ /issm/trunk/src/m/classes/clusters/greenplanet.m	(revision 16137)
@@ -108,4 +108,6 @@
 			 fprintf(fid,'#PBS -o %s.outlog \n',modelname);
 			 fprintf(fid,'#PBS -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);
Index: /issm/trunk/src/m/classes/clusters/pfe.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/pfe.m	(revision 16136)
+++ /issm/trunk/src/m/classes/clusters/pfe.m	(revision 16137)
@@ -60,7 +60,7 @@
 		 function md = checkconsistency(cluster,md,solution,analyses) % {{{
 
-			 available_queues={'long','normal','debug','devel'};
-			 queue_requirements_time=[5*24*60 8*60 2*60 2*60];
-			 queue_requirements_np=[2048 2048 150 150];
+			 available_queues={'long','normal','debug','devel','alphatst@pbspl233'};
+			 queue_requirements_time=[5*24*60 8*60 2*60 2*60 24*60];
+			 queue_requirements_np=[2048 2048 150 150 2048];
 
 			 QueueRequirements(available_queues,queue_requirements_time,queue_requirements_np,cluster.queue,cluster.np,cluster.time)
@@ -120,5 +120,4 @@
 			 fprintf(fid,'module load comp-intel/2013.1.117\n');
 			 fprintf(fid,'module load mpi-sgi/mpt.2.06rp16\n');
-			 fprintf(fid,'module load math/intel_mkl_64_10.0.011\n\n');
 			 fprintf(fid,'export PATH="$PATH:."\n\n');
 			 fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
@@ -171,5 +170,4 @@
 			 fprintf(fid,'module load comp-intel/2013.1.117\n');
 			 fprintf(fid,'module load mpi-sgi/mpt.2.06rp16\n');
-			 fprintf(fid,'module load math/intel_mkl_64_10.0.011\n\n');
 			 fprintf(fid,'export PATH="$PATH:."\n');
 			 fprintf(fid,'export ISSM_DIR="%s/../"\n',cluster.codepath); %FIXME
Index: sm/trunk/src/m/classes/diagnostic.m
===================================================================
--- /issm/trunk/src/m/classes/diagnostic.m	(revision 16136)
+++ 	(revision )
@@ -1,182 +1,0 @@
-%DIAGNOSTIC class definition
-%
-%   Usage:
-%      diagnostic=diagnostic();
-
-classdef diagnostic
-	properties (SetAccess=public) 
-		spcvx                    = NaN;
-		spcvy                    = NaN;
-		spcvz                    = NaN;
-		restol                   = 0;
-		reltol                   = 0;
-		abstol                   = 0;
-		isnewton                 = 0;
-		stokesreconditioning     = 0;
-		viscosity_overshoot      = 0;
-		icefront                 = NaN;
-		maxiter                  = 0;
-		shelf_dampening          = 0;
-		vertex_pairing           = NaN;
-		penalty_factor           = NaN;
-		rift_penalty_lock        = NaN;
-		rift_penalty_threshold   = 0;
-		referential              = NaN;
-		loadingforce             = NaN;
-		requested_outputs        = NaN;
-	end
-	methods
-		function obj = diagnostic(varargin) % {{{
-			switch nargin
-				case 0
-					obj=setdefaultparameters(obj);
-				otherwise
-					error('constructor not supported');
-			end
-		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
-
-			 %maximum of non-linear iterations.
-			 obj.maxiter=100;
-
-			 %Convergence criterion: absolute, relative and residual
-			 obj.restol=10^-4; 
-			 obj.reltol=0.01;
-			 obj.abstol=10;
-
-			 obj.stokesreconditioning=10^13;
-			 obj.shelf_dampening=0;
-
-			 %Penalty factor applied kappa=max(stiffness matrix)*10^penalty_factor
-			 obj.penalty_factor=3;
-
-			 %coefficient to update the viscosity between each iteration of
-			 %a diagnostic according to the following formula
-			 %viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
-			 obj.viscosity_overshoot=0;
-
-			 %Stop the iterations of rift if below a threshold
-			 obj.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;
-
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
-
-			%Early return
-			if ~ismember(DiagnosticHorizAnalysisEnum(),analyses), return; end
-			%if ~ismember(DiagnosticHorizAnalysisEnum(),analyses) |  (solution==TransientSolutionEnum() & md.transient.isdiagnostic==0), return; end
-
-			md = checkfield(md,'diagnostic.spcvx','forcing',1);
-			md = checkfield(md,'diagnostic.spcvy','forcing',1);
-			if md.mesh.dimension==3, md = checkfield(md,'diagnostic.spcvz','forcing',1); end
-			md = checkfield(md,'diagnostic.restol','size',[1 1],'>',0,'NaN',1);
-			md = checkfield(md,'diagnostic.reltol','size',[1 1]);
-			md = checkfield(md,'diagnostic.abstol','size',[1 1]);
-			md = checkfield(md,'diagnostic.isnewton','numel',[1],'values',[0 1 2]);
-			md = checkfield(md,'diagnostic.stokesreconditioning','size',[1 1],'NaN',1);
-			md = checkfield(md,'diagnostic.viscosity_overshoot','size',[1 1],'NaN',1);
-			if md.mesh.dimension==2,
-				md = checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
-			else
-				md = checkfield(md,'diagnostic.icefront','size',[NaN 6],'NaN',1);
-			end
-			md = checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
-			md = checkfield(md,'diagnostic.maxiter','size',[1 1],'>=',1);
-			md = checkfield(md,'diagnostic.referential','size',[md.mesh.numberofvertices 6]);
-			md = checkfield(md,'diagnostic.loadingforce','size',[md.mesh.numberofvertices 3]);
-			if ~isempty(md.diagnostic.requested_outputs),
-				md = checkfield(md,'diagnostic.requested_outputs','size',[NaN 1]);
-			end
-
-			%singular solution
-			if ~(any(~isnan(md.diagnostic.spcvx)) & any(~isnan(md.diagnostic.spcvy))),
-				md = checkmessage(md,['model is not well posed (singular). You need at least one node with fixed velocity!']);
-			end
-			%CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
-			if any(sum(isnan(md.diagnostic.referential),2)~=0 & sum(isnan(md.diagnostic.referential),2)~=6),
-				md = checkmessage(md,['Each line of diagnostic.referential should contain either only NaN values or no NaN values']);
-			end
-			%CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
-			if any(sum(isnan(md.diagnostic.referential),2)==0),
-				pos=find(sum(isnan(md.diagnostic.referential),2)==0);
-				if any(abs(dot(md.diagnostic.referential(pos,1:3),md.diagnostic.referential(pos,4:6),2))>eps),
-					md = checkmessage(md,['Vectors in diagnostic.referential (columns 1 to 3 and 4 to 6) must be orthogonal']);
-				end
-			end
-			%CHECK THAT NO rotation specified for FS Grounded ice at base
-			if md.mesh.dimension==3 & md.flowequation.isstokes,
-				pos=find(md.mask.vertexongroundedice & md.mesh.vertexonbed);
-				if any(~isnan(md.diagnostic.referential(pos,:))),
-					md = checkmessage(md,['no referential should be specified for basal vertices of grounded ice']);
-				end
-			end
-		end % }}}
-		function disp(obj) % {{{
-
-			disp(sprintf('   Diagnostic 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)');
-
-			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(obj,'icefront','segments on ice front list (last column 0: Air, 1: Water, 2: Ice)');
-
-			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');
-
-			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');
-
-			disp(sprintf('\n      %s','Other:'));
-			fielddisplay(obj,'shelf_dampening','use dampening for floating ice ? Only for Stokes model');
-			fielddisplay(obj,'stokesreconditioning','multiplier for incompressibility equation. Only for Stokes 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) % {{{
-			WriteData(fid,'object',obj,'fieldname','spcvx','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'fieldname','spcvy','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'fieldname','spcvz','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'fieldname','restol','format','Double');
-			WriteData(fid,'object',obj,'fieldname','reltol','format','Double');
-			WriteData(fid,'object',obj,'fieldname','abstol','format','Double');
-			WriteData(fid,'object',obj,'fieldname','isnewton','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','stokesreconditioning','format','Double');
-			WriteData(fid,'object',obj,'fieldname','viscosity_overshoot','format','Double');
-			WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','shelf_dampening','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',obj,'fieldname','rift_penalty_lock','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','rift_penalty_threshold','format','Integer');
-			WriteData(fid,'object',obj,'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',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
-
-			%marshall ice front
-			data=obj.icefront;
-			pos=find(data(:,end)==0); data(pos,end)=AirEnum();
-			pos=find(data(:,end)==1); data(pos,end)=WaterEnum();
-			pos=find(data(:,end)==2); data(pos,end)=IceEnum();
-			WriteData(fid,'data',data,'enum',DiagnosticIcefrontEnum(),'format','DoubleMat','mattype',3);
-		end % }}}
-	end
-end
Index: sm/trunk/src/m/classes/diagnostic.py
===================================================================
--- /issm/trunk/src/m/classes/diagnostic.py	(revision 16136)
+++ 	(revision )
@@ -1,190 +1,0 @@
-import numpy
-import sys
-import copy
-from fielddisplay import fielddisplay
-from EnumDefinitions import *
-from checkfield import *
-from WriteData import *
-
-class diagnostic(object):
-	"""
-	DIAGNOSTIC class definition
-
-	   Usage:
-	      diagnostic=diagnostic();
-	"""
-
-	def __init__(self): # {{{
-		self.spcvx                    = float('NaN')
-		self.spcvy                    = float('NaN')
-		self.spcvz                    = float('NaN')
-		self.restol                   = 0
-		self.reltol                   = 0
-		self.abstol                   = 0
-		self.isnewton                 = 0
-		self.stokesreconditioning     = 0
-		self.viscosity_overshoot      = 0
-		self.icefront                 = float('NaN')
-		self.maxiter                  = 0
-		self.shelf_dampening          = 0
-		self.vertex_pairing           = float('NaN')
-		self.penalty_factor           = float('NaN')
-		self.rift_penalty_lock        = float('NaN')
-		self.rift_penalty_threshold   = 0
-		self.referential              = float('NaN')
-		self.loadingforce             = float('NaN')
-		self.requested_outputs        = float('NaN')
-
-		#set defaults
-		self.setdefaultparameters()
-
-		#}}}
-	def __repr__(self): # {{{
-		
-		string='   Diagnostic solution parameters:'
-		string="%s\n%s"%(string,'      Convergence criteria:')
-		string="%s\n%s"%(string,fielddisplay(self,'restol','mechanical equilibrium residual convergence criterion'))
-		string="%s\n%s"%(string,fielddisplay(self,'reltol','velocity relative convergence criterion, NaN: not applied'))
-		string="%s\n%s"%(string,fielddisplay(self,'abstol','velocity absolute convergence criterion, NaN: not applied'))
-		string="%s\n%s"%(string,fielddisplay(self,'isnewton',"0: Picard's fixed point, 1: Newton's method, 2: hybrid"))
-		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of nonlinear iterations'))
-		string="%s\n%s"%(string,fielddisplay(self,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)'))
-
-		string="%s\n%s"%(string,'\n      boundary conditions:')
-		string="%s\n%s"%(string,fielddisplay(self,'spcvx','x-axis velocity constraint (NaN means no constraint) [m/yr]'))
-		string="%s\n%s"%(string,fielddisplay(self,'spcvy','y-axis velocity constraint (NaN means no constraint) [m/yr]'))
-		string="%s\n%s"%(string,fielddisplay(self,'spcvz','z-axis velocity constraint (NaN means no constraint) [m/yr]'))
-		string="%s\n%s"%(string,fielddisplay(self,'icefront','segments on ice front list (last column 0: Air, 1: Water, 2: Ice'))
-
-		string="%s\n%s"%(string,'\n      Rift options:')
-		string="%s\n%s"%(string,fielddisplay(self,'rift_penalty_threshold','threshold for instability of mechanical constraints'))
-		string="%s\n%s"%(string,fielddisplay(self,'rift_penalty_lock','number of iterations before rift penalties are locked'))
-
-		string="%s\n%s"%(string,'\n      Penalty options:')
-		string="%s\n%s"%(string,fielddisplay(self,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset'))
-		string="%s\n%s"%(string,fielddisplay(self,'vertex_pairing','pairs of vertices that are penalized'))
-
-		string="%s\n%s"%(string,'\n      Other:')
-		string="%s\n%s"%(string,fielddisplay(self,'shelf_dampening','use dampening for floating ice ? Only for Stokes model'))
-		string="%s\n%s"%(string,fielddisplay(self,'stokesreconditioning','multiplier for incompressibility equation. Only for Stokes model'))
-		string="%s\n%s"%(string,fielddisplay(self,'referential','local referential'))
-		string="%s\n%s"%(string,fielddisplay(self,'loadingforce','loading force applied on each point [N/m^3]'))
-		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
-
-		return string
-		#}}}
-	def setdefaultparameters(self): # {{{
-		#maximum of non-linear iterations.
-		self.maxiter=100
-
-		#Convergence criterion: absolute, relative and residual
-		self.restol=10**-4
-		self.reltol=0.01
-		self.abstol=10
-
-		self.stokesreconditioning=10**13
-		self.shelf_dampening=0
-
-		#Penalty factor applied kappa=max(stiffness matrix)*10^penalty_factor
-		self.penalty_factor=3
-
-		#coefficient to update the viscosity between each iteration of
-		#a diagnostic according to the following formula
-		#viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
-		self.viscosity_overshoot=0
-
-		#Stop the iterations of rift if below a threshold
-		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.
-		self.rift_penalty_lock=10
-
-		return self
-	#}}}
-	def checkconsistency(self,md,solution,analyses):    # {{{
-
-		#Early return
-		if DiagnosticHorizAnalysisEnum() not in analyses:
-			return md
-		#if (DiagnosticHorizAnalysisEnum() not in analyses) | (solution==TransientSolutionEnum() and not md.transient.isdiagnostic):
-		#	return md
-
-		md = checkfield(md,'diagnostic.spcvx','forcing',1)
-		md = checkfield(md,'diagnostic.spcvy','forcing',1)
-		if md.mesh.dimension==3:
-			md = checkfield(md,'diagnostic.spcvz','forcing',1)
-		md = checkfield(md,'diagnostic.restol','size',[1],'>',0)
-		md = checkfield(md,'diagnostic.reltol','size',[1])
-		md = checkfield(md,'diagnostic.abstol','size',[1])
-		md = checkfield(md,'diagnostic.isnewton','numel',[1],'values',[0,1,2])
-		md = checkfield(md,'diagnostic.stokesreconditioning','size',[1],'NaN',1)
-		md = checkfield(md,'diagnostic.viscosity_overshoot','size',[1],'NaN',1)
-		if md.mesh.dimension==2:
-			md = checkfield(md,'diagnostic.icefront','size',[float('NaN'),4],'NaN',1)
-		else:
-			md = checkfield(md,'diagnostic.icefront','size',[float('NaN'),6],'NaN',1)
-		md = checkfield(md,'diagnostic.icefront[:,-1]','values',[0,1,2])
-		md = checkfield(md,'diagnostic.maxiter','size',[1],'>=',1)
-		md = checkfield(md,'diagnostic.referential','size',[md.mesh.numberofvertices,6])
-		md = checkfield(md,'diagnostic.loadingforce','size',[md.mesh.numberofvertices,3])
-		if not md.diagnostic.requested_outputs:
-			md = checkfield(md,'diagnostic.requested_outputs','size',[float('NaN'),1])
-
-		#singular solution
-#		if ~any((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy))==2),
-		if not numpy.any(numpy.logical_and(numpy.logical_not(numpy.isnan(md.diagnostic.spcvx)),numpy.logical_not(numpy.isnan(md.diagnostic.spcvy)))):
-			md.checkmessage("model is not well posed (singular). You need at least one node with fixed velocity!")
-		#CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
-#		if any(sum(isnan(md.diagnostic.referential),2)~=0 & sum(isnan(md.diagnostic.referential),2)~=6),
-		if numpy.any(numpy.logical_and(numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)!=0,numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)!=6)):
-			md.checkmessage("Each line of diagnostic.referential should contain either only NaN values or no NaN values")
-		#CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
-#		if any(sum(isnan(md.diagnostic.referential),2)==0),
-		if numpy.any(numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)==0):
-			pos=[i for i,item in enumerate(numpy.sum(numpy.isnan(md.diagnostic.referential),axis=1)) if item==0]
-#			numpy.inner (and numpy.dot) calculate all the dot product permutations, resulting in a full matrix multiply
-#			if numpy.any(numpy.abs(numpy.inner(md.diagnostic.referential[pos,0:2],md.diagnostic.referential[pos,3:5]).diagonal())>sys.float_info.epsilon):
-#				md.checkmessage("Vectors in diagnostic.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
-			for item in md.diagnostic.referential[pos,:]:
-				if numpy.abs(numpy.inner(item[0:2],item[3:5]))>sys.float_info.epsilon:
-					md.checkmessage("Vectors in diagnostic.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
-		#CHECK THAT NO rotation specified for FS Grounded ice at base
-#		if md.mesh.dimension==3 & md.flowequation.isstokes,
-		if md.mesh.dimension==3 and md.flowequation.isstokes:
-			pos=numpy.nonzero(numpy.logical_and(md.mask.vertexongroundedice,md.mesh.vertexonbed))
-			if numpy.any(numpy.logical_not(numpy.isnan(md.diagnostic.referential[pos,:]))):
-				md.checkmessage("no referential should be specified for basal vertices of grounded ice")
-
-		return md
-	# }}}
-	def marshall(self,md,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','spcvx','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'fieldname','spcvy','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'fieldname','spcvz','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'fieldname','restol','format','Double')
-		WriteData(fid,'object',self,'fieldname','reltol','format','Double')
-		WriteData(fid,'object',self,'fieldname','abstol','format','Double')
-		WriteData(fid,'object',self,'fieldname','isnewton','format','Integer')
-		WriteData(fid,'object',self,'fieldname','stokesreconditioning','format','Double')
-		WriteData(fid,'object',self,'fieldname','viscosity_overshoot','format','Double')
-		WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
-		WriteData(fid,'object',self,'fieldname','shelf_dampening','format','Integer')
-		WriteData(fid,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)
-		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
-		WriteData(fid,'object',self,'fieldname','rift_penalty_lock','format','Integer')
-		WriteData(fid,'object',self,'fieldname','rift_penalty_threshold','format','Integer')
-		WriteData(fid,'object',self,'fieldname','referential','format','DoubleMat','mattype',1)
-		WriteData(fid,'data',self.loadingforce[:,0],'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum())
-		WriteData(fid,'data',self.loadingforce[:,1],'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum())
-		WriteData(fid,'data',self.loadingforce[:,2],'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum())
-		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3)
-
-		#marshall ice front
-		data=copy.deepcopy(self.icefront)
-		data[numpy.nonzero(data[:,-1]==0),-1]=AirEnum()
-		data[numpy.nonzero(data[:,-1]==1),-1]=WaterEnum()
-		data[numpy.nonzero(data[:,-1]==2),-1]=IceEnum()
-		WriteData(fid,'data',data,'enum',DiagnosticIcefrontEnum(),'format','DoubleMat','mattype',3)
-	# }}}
Index: /issm/trunk/src/m/classes/flowequation.m
===================================================================
--- /issm/trunk/src/m/classes/flowequation.m	(revision 16136)
+++ /issm/trunk/src/m/classes/flowequation.m	(revision 16137)
@@ -6,13 +6,53 @@
 classdef flowequation
 	properties (SetAccess=public) 
-		ismacayealpattyn     = 0;
-		ishutter             = 0;
-		isl1l2               = 0;
-		isstokes             = 0;
-		vertex_equation      = NaN;
-		element_equation     = NaN;
-		bordermacayeal       = NaN;
-		borderpattyn         = NaN;
-		borderstokes         = NaN;
+		isSIA            = 0;
+		isSSA            = 0;
+		isL1L2           = 0;
+		isHO             = 0;
+		isFS             = 0;
+		fe_SSA           = '';
+		fe_HO            = '';
+		fe_FS            = '';
+		vertex_equation  = NaN;
+		element_equation = NaN;
+		borderSSA        = NaN;
+		borderHO         = NaN;
+		borderFS         = NaN;
+	end
+	methods (Static)
+		function obj = loadobj(obj) % {{{
+			% This function is directly called by matlab when a model object is
+			% loaded. If the input is a struct it is an old version of this class and
+			% old fields must be recovered (make sure they are in the deprecated
+			% model properties)
+
+			if verLessThan('matlab','7.9'),
+				disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
+				disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
+
+				% This is a Matlab bug: all the fields of md have their default value
+				% Example of error message:
+				% Warning: Error loading an object of class 'model':
+				% Undefined function or method 'exist' for input arguments of type 'cell'
+				%
+				% This has been fixed in MATLAB 7.9 (R2009b) and later versions
+			end
+
+			if isstruct(obj)
+				disp('Recovering flowequation from older version');
+				objstruct = obj;
+				obj = 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; 
+			end
+
+		end% }}}
 	end
 	methods
@@ -27,16 +67,28 @@
 		function obj = setdefaultparameters(obj) % {{{
 
+			%P1 for SSA
+			obj.fe_SSA= 'P1';
+
+			%P1 for HO
+			obj.fe_HO= 'P1';
+
+			%MINI condensed element for FS by default
+			obj.fe_FS = 'MINIcondensed';
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			if ismember(DiagnosticHorizAnalysisEnum(),analyses),
+			if ismember(StressbalanceAnalysisEnum(),analyses),
 
-				md = checkfield(md,'flowequation.ismacayealpattyn','numel',[1],'values',[0 1]);
-				md = checkfield(md,'flowequation.ishutter','numel',[1],'values',[0 1]);
-				md = checkfield(md,'flowequation.isl1l2','numel',[1],'values',[0 1]);
-				md = checkfield(md,'flowequation.isstokes','numel',[1],'values',[0 1]);
-				md = checkfield(md,'flowequation.bordermacayeal','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-				md = checkfield(md,'flowequation.borderpattyn','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-				md = checkfield(md,'flowequation.borderstokes','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				md = checkfield(md,'flowequation.isSIA','numel',[1],'values',[0 1]);
+				md = checkfield(md,'flowequation.isSSA','numel',[1],'values',[0 1]);
+				md = checkfield(md,'flowequation.isL1L2','numel',[1],'values',[0 1]);
+				md = checkfield(md,'flowequation.isHO','numel',[1],'values',[0 1]);
+				md = checkfield(md,'flowequation.isFS','numel',[1],'values',[0 1]);
+				md = checkfield(md,'flowequation.fe_SSA','values',{'P1','P1bubble','P1bubblecondensed','P2'});
+				md = checkfield(md,'flowequation.fe_HO' ,'values',{'P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2'});
+				md = checkfield(md,'flowequation.fe_FS' ,'values',{'P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood'});
+				md = checkfield(md,'flowequation.borderSSA','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				md = checkfield(md,'flowequation.borderHO','size',[md.mesh.numberofvertices 1],'values',[0 1]);
+				md = checkfield(md,'flowequation.borderFS','size',[md.mesh.numberofvertices 1],'values',[0 1]);
 				if (md.mesh.dimension==2),
 					md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices 1],'values',[1:2]);
@@ -46,12 +98,12 @@
 					md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements 1],'values',[0:8]);
 				end
-				if ~(obj.ismacayealpattyn || obj.ishutter || obj.isstokes || obj.isl1l2),
-					md = checkmessage(md,['no element types set for this model. At least one of ismacayealpattyn, ishutter or isstokes need to be =1']);
+				if ~(obj.isSIA || obj.isSSA || obj.isL1L2 || obj.isHO || obj.isFS),
+					md = checkmessage(md,['no element types set for this model']);
 				end
 			end
-			if ismember(DiagnosticHutterAnalysisEnum(),analyses),
+			if ismember(StressbalanceSIAAnalysisEnum(),analyses),
 				if any(obj.element_equation==1),
-					if(obj.element_equation & md.mask.elementonfloatingice),
-						disp(sprintf('\n !!! Warning: Hutter''s model is not consistent on ice shelves !!!\n'));
+					if(obj.vertex_equation & md.mask.groundedice_levelset<0.),
+						disp(sprintf('\n !!! Warning: SIA''s model is not consistent on ice shelves !!!\n'));
 					end
 				end
@@ -62,44 +114,52 @@
 			disp(sprintf('   flow equation parameters:'));
 
-			fielddisplay(obj,'ismacayealpattyn','is the macayeal or pattyn approximation used ?');
-			fielddisplay(obj,'ishutter','is the shallow ice approximation used ?');
-			fielddisplay(obj,'isl1l2','is the l1l2 approximation used ?');
-			fielddisplay(obj,'isstokes','are the Full-Stokes equations used ?');
+			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''');
 			fielddisplay(obj,'vertex_equation','flow equation for each vertex');
 			fielddisplay(obj,'element_equation','flow equation for each element');
-			fielddisplay(obj,'bordermacayeal','vertices on MacAyeal''s border (for tiling)');
-			fielddisplay(obj,'borderpattyn','vertices on Pattyn''s border (for tiling)');
-			fielddisplay(obj,'borderstokes','vertices on Stokes'' border (for tiling)');
+			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','ismacayealpattyn','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','ishutter','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isl1l2','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isstokes','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','bordermacayeal','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','borderpattyn','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','borderstokes','format','DoubleMat','mattype',1);
+			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,'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);
 			%convert approximations to enums
 			data=obj.vertex_equation;
 			pos=find(data==0); data(pos,end)=NoneApproximationEnum();
-			pos=find(data==1); data(pos,end)=HutterApproximationEnum();
-			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum();
-			pos=find(data==3); data(pos,end)=PattynApproximationEnum();
-			pos=find(data==4); data(pos,end)=StokesApproximationEnum();
-			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum();
-			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum();
-			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum();
+			pos=find(data==1); data(pos,end)=SIAApproximationEnum();
+			pos=find(data==2); data(pos,end)=SSAApproximationEnum();
+			pos=find(data==3); data(pos,end)=HOApproximationEnum();
+			pos=find(data==4); data(pos,end)=FSApproximationEnum();
+			pos=find(data==5); data(pos,end)=SSAHOApproximationEnum();
+			pos=find(data==6); data(pos,end)=SSAFSApproximationEnum();
+			pos=find(data==7); data(pos,end)=HOFSApproximationEnum();
 			pos=find(data==8); data(pos,end)=L1L2ApproximationEnum();
 			WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1);
 			data=obj.element_equation;
 			pos=find(data==0); data(pos,end)=NoneApproximationEnum();
-			pos=find(data==1); data(pos,end)=HutterApproximationEnum();
-			pos=find(data==2); data(pos,end)=MacAyealApproximationEnum();
-			pos=find(data==3); data(pos,end)=PattynApproximationEnum();
-			pos=find(data==4); data(pos,end)=StokesApproximationEnum();
-			pos=find(data==5); data(pos,end)=MacAyealPattynApproximationEnum();
-			pos=find(data==6); data(pos,end)=MacAyealStokesApproximationEnum();
-			pos=find(data==7); data(pos,end)=PattynStokesApproximationEnum();
+			pos=find(data==1); data(pos,end)=SIAApproximationEnum();
+			pos=find(data==2); data(pos,end)=SSAApproximationEnum();
+			pos=find(data==3); data(pos,end)=HOApproximationEnum();
+			pos=find(data==4); data(pos,end)=FSApproximationEnum();
+			pos=find(data==5); data(pos,end)=SSAHOApproximationEnum();
+			pos=find(data==6); data(pos,end)=SSAFSApproximationEnum();
+			pos=find(data==7); data(pos,end)=HOFSApproximationEnum();
 			pos=find(data==8); data(pos,end)=L1L2ApproximationEnum();
 			WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2);
Index: /issm/trunk/src/m/classes/flowequation.py
===================================================================
--- /issm/trunk/src/m/classes/flowequation.py	(revision 16136)
+++ /issm/trunk/src/m/classes/flowequation.py	(revision 16137)
@@ -16,13 +16,17 @@
 	def __init__(self): # {{{
 		
-		self.ismacayealpattyn     = 0
-		self.ishutter             = 0
-		self.isl1l2               = 0
-		self.isstokes             = 0
-		self.vertex_equation      = float('NaN')
-		self.element_equation     = float('NaN')
-		self.bordermacayeal       = float('NaN')
-		self.borderpattyn         = float('NaN')
-		self.borderstokes         = float('NaN')
+		self.isSIA            = 0
+		self.isSSA            = 0
+		self.isL1L2           = 0
+		self.isHO             = 0
+		self.isFS             = 0
+		self.fe_SSA           = ''
+		self.fe_HO            = ''
+		self.fe_FS            = ''
+		self.vertex_equation  = float('NaN')
+		self.element_equation = float('NaN')
+		self.borderSSA        = float('NaN')
+		self.borderHO         = float('NaN')
+		self.borderFS         = float('NaN')
 
 		#set defaults
@@ -33,73 +37,95 @@
 		string='   flow equation parameters:'
 
-		string="%s\n%s"%(string,fielddisplay(self,'ismacayealpattyn',"is the macayeal or pattyn approximation used ?"))
-		string="%s\n%s"%(string,fielddisplay(self,'ishutter',"is the shallow ice approximation used ?"))
-		string="%s\n%s"%(string,fielddisplay(self,'isl1l2',"are l1l2 equations used ?"))
-		string="%s\n%s"%(string,fielddisplay(self,'isstokes',"are the Full-Stokes equations used ?"))
+		string="%s\n%s"%(string,fielddisplay(self,'isSIA',"is the Shallow Ice Approximation (SIA) used ?"))
+		string="%s\n%s"%(string,fielddisplay(self,'isSSA',"is the Shelfy-Stream Approximation (SSA) used ?"))
+		string="%s\n%s"%(string,fielddisplay(self,'isL1L2',"are L1L2 equations used ?"))
+		string="%s\n%s"%(string,fielddisplay(self,'isHO',"is the Higher-Order (HO) approximation used ?"))
+		string="%s\n%s"%(string,fielddisplay(self,'isFS',"are the Full-FS (FS) equations used ?"))
+		string="%s\n%s"%(string,fielddisplay(self,'fe_SSA',"Finite Element for SSA: 'P1', 'P1bubble' 'P1bubblecondensed' 'P2'"))
+		string="%s\n%s"%(string,fielddisplay(self,'fe_HO' ,"Finite Element for HO:  'P1' 'P1bubble' 'P1bubblecondensed' 'P1xP2' 'P2xP1' 'P2'"))
+		string="%s\n%s"%(string,fielddisplay(self,'fe_FS' ,"Finite Element for FS:  'P1P1' (debugging only) 'P1P1GLS' 'MINIcondensed' 'MINI' 'TaylorHood'"))
 		string="%s\n%s"%(string,fielddisplay(self,'vertex_equation',"flow equation for each vertex"))
 		string="%s\n%s"%(string,fielddisplay(self,'element_equation',"flow equation for each element"))
-		string="%s\n%s"%(string,fielddisplay(self,'bordermacayeal',"vertices on MacAyeal's border (for tiling)"))
-		string="%s\n%s"%(string,fielddisplay(self,'borderpattyn',"vertices on Pattyn's border (for tiling)"))
-		string="%s\n%s"%(string,fielddisplay(self,'borderstokes',"vertices on Stokes' border (for tiling)"))
+		string="%s\n%s"%(string,fielddisplay(self,'borderSSA',"vertices on SSA's border (for tiling)"))
+		string="%s\n%s"%(string,fielddisplay(self,'borderHO',"vertices on HO's border (for tiling)"))
+		string="%s\n%s"%(string,fielddisplay(self,'borderFS',"vertices on FS' border (for tiling)"))
 		return string
 		#}}}
 	def setdefaultparameters(self): # {{{
+
+		#P1 for SSA
+		self.fe_SSA= 'P1';
+
+		#P1 for HO
+		self.fe_HO= 'P1';
+
+		#MINI condensed element for FS by default
+		self.fe_FS = 'MINIcondensed';
+
 		return self
 	#}}}
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
-		if DiagnosticHorizAnalysisEnum() in analyses:
-			md = checkfield(md,'flowequation.ismacayealpattyn','numel',[1],'values',[0,1])
-			md = checkfield(md,'flowequation.ishutter','numel',[1],'values',[0,1])
-			md = checkfield(md,'flowequation.isl1l2','numel',[1],'values',[0,1])
-			md = checkfield(md,'flowequation.isstokes','numel',[1],'values',[0,1])
-			md = checkfield(md,'flowequation.bordermacayeal','size',[md.mesh.numberofvertices],'values',[0,1])
-			md = checkfield(md,'flowequation.borderpattyn','size',[md.mesh.numberofvertices],'values',[0,1])
-			md = checkfield(md,'flowequation.borderstokes','size',[md.mesh.numberofvertices],'values',[0,1])
+		if StressbalanceAnalysisEnum() in analyses:
+			md = checkfield(md,'flowequation.isSIA','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.isSSA','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.isL1L2','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.isHO','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.isFS','numel',[1],'values',[0,1])
+			md = checkfield(md,'flowequation.fe_SSA','values',['P1','P1bubble','P1bubblecondensed','P2'])
+			md = checkfield(md,'flowequation.fe_HO' ,'values',['P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2'])
+			md = checkfield(md,'flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood'])
+			md = checkfield(md,'flowequation.borderSSA','size',[md.mesh.numberofvertices],'values',[0,1])
+			md = checkfield(md,'flowequation.borderHO','size',[md.mesh.numberofvertices],'values',[0,1])
+			md = checkfield(md,'flowequation.borderFS','size',[md.mesh.numberofvertices],'values',[0,1])
 			if md.mesh.dimension==2:
 				md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[1,2])
 				md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2])
 			else:
-				md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',numpy.arange(0,7+1))
-				md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',numpy.arange(0,7+1))
-			if not (self.ismacayealpattyn or self.ishutter or self.isstokes or self.isl1l2):
-				md.checkmessage("no element types set for this model. At least one of ismacayealpattyn, ishutter or isstokes need to be =1")
+				md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',numpy.arange(0,8+1))
+				md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',numpy.arange(0,8+1))
+			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 DiagnosticHutterAnalysisEnum() in analyses:
+		if StressbalanceSIAAnalysisEnum() in analyses:
 			if any(self.element_equation==1):
-				if numpy.any(numpy.logical_and(self.element_equation,md.mask.elementonfloatingice)):
-					print "\n !!! Warning: Hutter's model is not consistent on ice shelves !!!\n"
+				if numpy.any(numpy.logical_and(self.vertex_equation,md.mask.groundedice_levelset)):
+					print "\n !!! Warning: SIA's model is not consistent on ice shelves !!!\n"
 
 		return md
 	# }}}
 	def marshall(self,md,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','ismacayealpattyn','format','Boolean')
-		WriteData(fid,'object',self,'fieldname','ishutter','format','Boolean')
-		WriteData(fid,'object',self,'fieldname','isl1l2','format','Boolean')
-		WriteData(fid,'object',self,'fieldname','isstokes','format','Boolean')
-		WriteData(fid,'object',self,'fieldname','bordermacayeal','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','borderpattyn','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','borderstokes','format','DoubleMat','mattype',1)
+		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)[0],'format','Integer')
+		WriteData(fid,'enum',FlowequationFeHOEnum() ,'data',StringToEnum(self.fe_HO)[0] ,'format','Integer')
+		WriteData(fid,'enum',FlowequationFeFSEnum() ,'data',StringToEnum(self.fe_FS)[0] ,'format','Integer')
+		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=copy.deepcopy(self.vertex_equation)
 		data[numpy.nonzero(data==0)]=NoneApproximationEnum()
-		data[numpy.nonzero(data==1)]=HutterApproximationEnum()
-		data[numpy.nonzero(data==2)]=MacAyealApproximationEnum()
-		data[numpy.nonzero(data==3)]=PattynApproximationEnum()
-		data[numpy.nonzero(data==4)]=StokesApproximationEnum()
-		data[numpy.nonzero(data==5)]=MacAyealPattynApproximationEnum()
-		data[numpy.nonzero(data==6)]=MacAyealStokesApproximationEnum()
-		data[numpy.nonzero(data==7)]=PattynStokesApproximationEnum()
+		data[numpy.nonzero(data==1)]=SIAApproximationEnum()
+		data[numpy.nonzero(data==2)]=SSAApproximationEnum()
+		data[numpy.nonzero(data==3)]=HOApproximationEnum()
+		data[numpy.nonzero(data==4)]=FSApproximationEnum()
+		data[numpy.nonzero(data==5)]=SSAHOApproximationEnum()
+		data[numpy.nonzero(data==6)]=SSAFSApproximationEnum()
+		data[numpy.nonzero(data==7)]=HOFSApproximationEnum()
 		data[numpy.nonzero(data==8)]=L1L2ApproximationEnum()
 		WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1)
 		data=copy.deepcopy(self.element_equation)
 		data[numpy.nonzero(data==0)]=NoneApproximationEnum()
-		data[numpy.nonzero(data==1)]=HutterApproximationEnum()
-		data[numpy.nonzero(data==2)]=MacAyealApproximationEnum()
-		data[numpy.nonzero(data==3)]=PattynApproximationEnum()
-		data[numpy.nonzero(data==4)]=StokesApproximationEnum()
-		data[numpy.nonzero(data==5)]=MacAyealPattynApproximationEnum()
-		data[numpy.nonzero(data==6)]=MacAyealStokesApproximationEnum()
-		data[numpy.nonzero(data==7)]=PattynStokesApproximationEnum()
+		data[numpy.nonzero(data==1)]=SIAApproximationEnum()
+		data[numpy.nonzero(data==2)]=SSAApproximationEnum()
+		data[numpy.nonzero(data==3)]=HOApproximationEnum()
+		data[numpy.nonzero(data==4)]=FSApproximationEnum()
+		data[numpy.nonzero(data==5)]=SSAHOApproximationEnum()
+		data[numpy.nonzero(data==6)]=SSAFSApproximationEnum()
+		data[numpy.nonzero(data==7)]=HOFSApproximationEnum()
 		data[numpy.nonzero(data==8)]=L1L2ApproximationEnum()
 		WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2)
Index: /issm/trunk/src/m/classes/friction.m
===================================================================
--- /issm/trunk/src/m/classes/friction.m	(revision 16136)
+++ /issm/trunk/src/m/classes/friction.m	(revision 16137)
@@ -25,5 +25,5 @@
 
 			%Early return
-			if ~ismember(DiagnosticHorizAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
+			if ~ismember(StressbalanceAnalysisEnum(),analyses) & ~ismember(ThermalAnalysisEnum(),analyses), return; end
 
 			md = checkfield(md,'friction.coefficient','NaN',1,'size',[md.mesh.numberofvertices 1]);
Index: /issm/trunk/src/m/classes/friction.py
===================================================================
--- /issm/trunk/src/m/classes/friction.py	(revision 16136)
+++ /issm/trunk/src/m/classes/friction.py	(revision 16137)
@@ -35,5 +35,5 @@
 
 		#Early return
-		if DiagnosticHorizAnalysisEnum() not in analyses and ThermalAnalysisEnum() not in analyses:
+		if StressbalanceAnalysisEnum() not in analyses and ThermalAnalysisEnum() not in analyses:
 			return md
 
Index: /issm/trunk/src/m/classes/gia.m
===================================================================
--- /issm/trunk/src/m/classes/gia.m	(revision 16136)
+++ /issm/trunk/src/m/classes/gia.m	(revision 16137)
@@ -29,12 +29,12 @@
 			md = checkfield(md,'gia.cross_section_shape','numel',[1],'values',[1,2]);
 
-			%be sure that if we are running a prognostic ice flow model coupled with gia, that thickness forcings 
+			%be sure that if we are running a masstransport ice flow model coupled with gia, that thickness forcings 
 			%are not provided into the future.
-			if solution==TransientSolutionEnum() & md.transient.isprognostic & md.transient.isgia,
+			if solution==TransientSolutionEnum() & md.transient.ismasstransport & md.transient.isgia,
 				%figure out if thickness is a transient forcing: 
 				if size(md.geometry.thickness,1)==md.mesh.numberofvertices+1,
 					%recover the furthest time "in time": 
 					if(thickness(end,end)~=md.timestepping.start_time),
-						md = checkmessage(md,['if isprognostic is on, transient thickness forcing'...
+						md = checkmessage(md,['if ismasstransport is on, transient thickness forcing'...
 							' for the gia model should not be provided in the future.'...
 							' Synchronize your start_time to correspond to the most recent transient'...
Index: /issm/trunk/src/m/classes/gia.py
===================================================================
--- /issm/trunk/src/m/classes/gia.py	(revision 16136)
+++ /issm/trunk/src/m/classes/gia.py	(revision 16137)
@@ -46,5 +46,5 @@
 		md = checkfield(md,'gia.cross_section_shape','numel',[1],'values',[1,2])
 
-		#be sure that if we are running a prognostic ice flow model coupled with gia, that thickness forcings 
+		#be sure that if we are running a masstransport ice flow model coupled with gia, that thickness forcings 
 		#are not provided into the future.
 
Index: /issm/trunk/src/m/classes/groundingline.m
===================================================================
--- /issm/trunk/src/m/classes/groundingline.m	(revision 16136)
+++ /issm/trunk/src/m/classes/groundingline.m	(revision 16137)
@@ -35,9 +35,9 @@
 					md = checkmessage(md,['requesting grounding line migration, but bathymetry is absent!']);
 				end
-				pos=find(md.mask.vertexongroundedice);
+				pos=find(md.mask.groundedice_levelset>0.);
 				if any(abs(md.geometry.bed(pos)-md.geometry.bathymetry(pos))>10^-10),
 					md = checkmessage(md,['bathymetry not equal to bed on grounded ice!']);
 				end
-				pos=find(md.mask.vertexonfloatingice);
+				pos=find(md.mask.groundedice_levelset<0.);
 				if any(md.geometry.bathymetry(pos)-md.geometry.bed(pos)>10^-9),
 					md = checkmessage(md,['bathymetry superior to bed on floating ice!']);
Index: /issm/trunk/src/m/classes/groundingline.py
===================================================================
--- /issm/trunk/src/m/classes/groundingline.py	(revision 16136)
+++ /issm/trunk/src/m/classes/groundingline.py	(revision 16137)
@@ -47,8 +47,8 @@
 			if numpy.any(numpy.isnan(md.geometry.bathymetry)):
 				md.checkmessage("requesting grounding line migration, but bathymetry is absent!")
-			pos=numpy.nonzero(md.mask.vertexongroundedice)
+			pos=numpy.nonzero(md.mask.groundedice_levelset>0.)[0]
 			if any(numpy.abs(md.geometry.bed[pos]-md.geometry.bathymetry[pos])>10**-10):
 				md.checkmessage("bathymetry not equal to bed on grounded ice!")
-			pos=numpy.nonzero(md.mask.vertexonfloatingice)
+			pos=numpy.nonzero(md.mask.groundedice_levelset<0.)[0]
 			if any(md.geometry.bathymetry[pos]-md.geometry.bed[pos]>10**-9):
 				md.checkmessage("bathymetry superior to bed on floating ice!")
Index: /issm/trunk/src/m/classes/hydrologydc.m
===================================================================
--- /issm/trunk/src/m/classes/hydrologydc.m	(revision 16136)
+++ /issm/trunk/src/m/classes/hydrologydc.m	(revision 16137)
@@ -29,5 +29,6 @@
   end
 	methods
-		function obj = hydrologydc(varargin) % {{{ 
+		% {{{ function obj = hydrologydc(varargin) 
+		function obj = hydrologydc(varargin) 
 			switch nargin
 				case 0
Index: /issm/trunk/src/m/classes/initialization.m
===================================================================
--- /issm/trunk/src/m/classes/initialization.m	(revision 16136)
+++ /issm/trunk/src/m/classes/initialization.m	(revision 16137)
@@ -30,5 +30,5 @@
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
-			if ismember(DiagnosticHorizAnalysisEnum(),analyses)
+			if ismember(StressbalanceAnalysisEnum(),analyses)
 				if ~(isnan(md.initialization.vx) | isnan(md.initialization.vy)),
 					md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
@@ -36,5 +36,5 @@
 				end
 			end
-			if ismember(PrognosticAnalysisEnum(),analyses),
+			if ismember(MasstransportAnalysisEnum(),analyses),
 				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices 1]);
 				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices 1]);
@@ -56,4 +56,5 @@
 			if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy) | solution==EnthalpySolutionEnum(),
 				md = checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices 1]);
+				md = checkfield(md,'initialization.watercolumn'  ,'>=',0,'size',[md.mesh.numberofvertices 1]);
 			end
 			if ismember(HydrologyShreveAnalysisEnum(),analyses),
Index: /issm/trunk/src/m/classes/initialization.py
===================================================================
--- /issm/trunk/src/m/classes/initialization.py	(revision 16136)
+++ /issm/trunk/src/m/classes/initialization.py	(revision 16137)
@@ -48,9 +48,9 @@
 	#}}}
 	def checkconsistency(self,md,solution,analyses):    # {{{
-		if DiagnosticHorizAnalysisEnum() in analyses:
+		if StressbalanceAnalysisEnum() in analyses:
 			if not numpy.any(numpy.logical_or(numpy.isnan(md.initialization.vx),numpy.isnan(md.initialization.vy))):
 				md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
 				md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
-		if PrognosticAnalysisEnum() in analyses:
+		if MasstransportAnalysisEnum() in analyses:
 			md = checkfield(md,'initialization.vx','NaN',1,'size',[md.mesh.numberofvertices])
 			md = checkfield(md,'initialization.vy','NaN',1,'size',[md.mesh.numberofvertices])
@@ -69,4 +69,5 @@
 		if (EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy) or solution==EnthalpySolutionEnum():
 			md = checkfield(md,'initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices])
+			md = checkfield(md,'initialization.watercolumn'  ,'>=',0,'size',[md.mesh.numberofvertices])
 		if HydrologyShreveAnalysisEnum() in analyses:
 			md = checkfield(md,'initialization.watercolumn','NaN',1,'size',[md.mesh.numberofvertices])
Index: /issm/trunk/src/m/classes/inversion.m
===================================================================
--- /issm/trunk/src/m/classes/inversion.m	(revision 16136)
+++ /issm/trunk/src/m/classes/inversion.m	(revision 16137)
@@ -35,4 +35,5 @@
 						disp('converting taoinversion to inversion');
 						in=varargin{1};
+						obj=inversion();
 						obj.iscontrol                   = in.iscontrol;
 						obj.tao                         = 1;
@@ -54,4 +55,8 @@
 						obj.vel_obs                     = in.vel_obs;
 						obj.thickness_obs               = in.thickness_obs;
+					elseif isa(varargin{1},'inversion'),
+						obj = varargin{1};
+					else
+						error('constructor not supported');
 					end
 				otherwise
@@ -121,4 +126,11 @@
 			md = checkfield(md,'inversion.min_parameters','size',[md.mesh.numberofvertices num_controls]);
 			md = checkfield(md,'inversion.max_parameters','size',[md.mesh.numberofvertices num_controls]);
+
+			%Only SSA, HO and FS are supported right now
+			if solution==StressbalanceSolutionEnum()
+				if ~(md.flowequation.isSSA || md.flowequation.isHO || md.flowequation.isFS),
+					md = checkmessage(md,['inversion can only be performed for SSA, HO or FS ice flow models']);
+				end
+			end
 
 			if solution==BalancethicknessSolutionEnum()
Index: /issm/trunk/src/m/classes/inversion.py
===================================================================
--- /issm/trunk/src/m/classes/inversion.py	(revision 16136)
+++ /issm/trunk/src/m/classes/inversion.py	(revision 16137)
@@ -135,4 +135,9 @@
 		md = checkfield(md,'inversion.max_parameters','size',[md.mesh.numberofvertices,num_controls])
 
+		#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):
+				md.checkmessage("'inversion can only be performed for SSA, HO or FS ice flow models");
+
 		if solution==BalancethicknessSolutionEnum():
 			md = checkfield(md,'inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1)
Index: /issm/trunk/src/m/classes/mask.m
===================================================================
--- /issm/trunk/src/m/classes/mask.m	(revision 16136)
+++ /issm/trunk/src/m/classes/mask.m	(revision 16137)
@@ -6,11 +6,6 @@
 classdef mask
 	properties (SetAccess=public) 
-		elementonfloatingice = NaN;
-		elementongroundedice = NaN;
-		elementonwater       = NaN;
-		vertexonfloatingice  = NaN;
-		vertexongroundedice  = NaN;
-		vertexonwater        = NaN;
-		vertexonrock        = NaN;
+		groundedice_levelset = NaN;
+		ice_levelset         = NaN;
 	end
 	methods
@@ -28,30 +23,20 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			md = checkfield(md,'mask.elementonfloatingice','size',[md.mesh.numberofelements 1],'values',[0 1]);
-			md = checkfield(md,'mask.elementongroundedice','size',[md.mesh.numberofelements 1],'values',[0 1]);
-			md = checkfield(md,'mask.elementonwater'      ,'size',[md.mesh.numberofelements 1],'values',[0 1]);
-			md = checkfield(md,'mask.vertexonfloatingice','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-			md = checkfield(md,'mask.vertexongroundedice','size',[md.mesh.numberofvertices 1],'values',[0 1]);
-			md = checkfield(md,'mask.vertexonwater'      ,'size',[md.mesh.numberofvertices 1],'values',[0 1]);
-			%md = checkfield(md,'mask.vertexonrock'      ,'size',[md.mesh.numberofvertices 1],'values',[0 1]);
+			md = checkfield(md,'mask.groundedice_levelset','size',[md.mesh.numberofvertices 1]);
+			md = checkfield(md,'mask.ice_levelset'        ,'size',[md.mesh.numberofvertices 1]);
+			isice=(md.mask.ice_levelset>0);
+			if any(sum(isice(md.mesh.elements),2)==0),
+				error('elements with no ice not implemented yet, each element should have at least one vertex with md.mask.ice_levelset > 0');
+			end
 		end % }}}
 		function disp(obj) % {{{
 			disp(sprintf('   masks:'));
 
-			fielddisplay(obj,'elementonfloatingice','element on floating ice flags list');
-			fielddisplay(obj,'vertexonfloatingice','vertex on floating ice flags list');
-			fielddisplay(obj,'elementongroundedice','element on grounded ice  list');
-			fielddisplay(obj,'vertexongroundedice','vertex on grounded ice flags list');
-			fielddisplay(obj,'elementonwater','element on rock flags list');
-			fielddisplay(obj,'vertexonwater','vertex on water flags list');
-			fielddisplay(obj,'vertexonrock','vertex on rock flags list');
+			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');
 		end % }}}
 		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','elementonfloatingice','format','BooleanMat','mattype',2);
-			WriteData(fid,'object',obj,'fieldname','elementongroundedice','format','BooleanMat','mattype',2);
-			WriteData(fid,'object',obj,'fieldname','elementonwater','format','BooleanMat','mattype',2);
-			WriteData(fid,'object',obj,'fieldname','vertexonfloatingice','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','vertexongroundedice','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'fieldname','vertexonwater','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','groundedice_levelset','format','DoubleMat','mattype',1);
+			WriteData(fid,'object',obj,'fieldname','ice_levelset','format','DoubleMat','mattype',1);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/mask.py
===================================================================
--- /issm/trunk/src/m/classes/mask.py	(revision 16136)
+++ /issm/trunk/src/m/classes/mask.py	(revision 16137)
@@ -13,10 +13,6 @@
 
 	def __init__(self): # {{{
-		self.elementonfloatingice = float('NaN')
-		self.elementongroundedice = float('NaN')
-		self.elementonwater       = float('NaN')
-		self.vertexonfloatingice  = float('NaN')
-		self.vertexongroundedice  = float('NaN')
-		self.vertexonwater        = float('NaN')
+		self.ice_levelset         = float('NaN')
+		self.groundedice_levelset = float('NaN')
 
 		#set defaults
@@ -27,10 +23,6 @@
 		string="   masks:"
 
-		string="%s\n%s"%(string,fielddisplay(self,"elementonfloatingice","element on floating ice flags list"))
-		string="%s\n%s"%(string,fielddisplay(self,"vertexonfloatingice","vertex on floating ice flags list"))
-		string="%s\n%s"%(string,fielddisplay(self,"elementongroundedice","element on grounded ice list"))
-		string="%s\n%s"%(string,fielddisplay(self,"vertexongroundedice","vertex on grounded ice flags list"))
-		string="%s\n%s"%(string,fielddisplay(self,"elementonwater","element on water flags list"))
-		string="%s\n%s"%(string,fielddisplay(self,"vertexonwater","vertex on water flags list"))
+		string="%s\n%s"%(string,fielddisplay(self,"groundedice_levelset","is ice grounded ? grounded ice if > 0, grounding line position if = 0, floating ice if < 0"))
+		string="%s\n%s"%(string,fielddisplay(self,"ice_levelset","presence of ice if > 0, icefront position if = 0, no ice if < 0"))
 		return string
 		#}}}
@@ -40,19 +32,14 @@
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
-		md = checkfield(md,'mask.elementonfloatingice','size',[md.mesh.numberofelements],'values',[0,1])
-		md = checkfield(md,'mask.elementongroundedice','size',[md.mesh.numberofelements],'values',[0,1])
-		md = checkfield(md,'mask.elementonwater'      ,'size',[md.mesh.numberofelements],'values',[0,1])
-		md = checkfield(md,'mask.vertexonfloatingice' ,'size',[md.mesh.numberofvertices],'values',[0,1])
-		md = checkfield(md,'mask.vertexongroundedice' ,'size',[md.mesh.numberofvertices],'values',[0,1])
-		md = checkfield(md,'mask.vertexonwater'       ,'size',[md.mesh.numberofvertices],'values',[0,1])
+		md = checkfield(md,'mask.ice_levelset'        ,'size',[md.mesh.numberofvertices])
+		isice=numpy.array(md.mask.ice_levelset>0,int)
+		totallyicefree=(numpy.sum(isice[md.mesh.elements-1],axis=1)==0).astype(int)
+		if any(totallyicefree):
+			raise TypeError("elements with no ice not implemented yet, each element should have at least one vertex with md.mask.ice_levelset > 0")
 
 		return md
 	# }}}
 	def marshall(self,md,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','elementonfloatingice','format','BooleanMat','mattype',2)
-		WriteData(fid,'object',self,'fieldname','elementongroundedice','format','BooleanMat','mattype',2)
-		WriteData(fid,'object',self,'fieldname','elementonwater','format','BooleanMat','mattype',2)
-		WriteData(fid,'object',self,'fieldname','vertexonfloatingice','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','vertexongroundedice','format','DoubleMat','mattype',1)
-		WriteData(fid,'object',self,'fieldname','vertexonwater','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','groundedice_levelset','format','DoubleMat','mattype',1)
+		WriteData(fid,'object',self,'fieldname','ice_levelset','format','DoubleMat','mattype',1)
 	# }}}
Index: /issm/trunk/src/m/classes/masstransport.m
===================================================================
--- /issm/trunk/src/m/classes/masstransport.m	(revision 16137)
+++ /issm/trunk/src/m/classes/masstransport.m	(revision 16137)
@@ -0,0 +1,116 @@
+%MASSTRANSPORT class definition
+%
+%   Usage:
+%      masstransport=masstransport();
+
+classdef masstransport
+	properties (SetAccess=public) 
+		 spcthickness           = NaN;
+		 isfreesurface          = 0;
+		 min_thickness          = 0;
+		 hydrostatic_adjustment = 0;
+		 stabilization          = 0;
+		 vertex_pairing         = NaN;
+		 penalty_factor         = 0;
+		 requested_outputs      = NaN;
+	end
+	methods (Static)
+		function obj = loadobj(obj) % {{{
+			% This function is directly called by matlab when a model object is
+			% loaded. If the input is a struct it is an old version of this class and
+			% old fields must be recovered (make sure they are in the deprecated
+			% model properties)
+
+			if verLessThan('matlab','7.9'),
+				disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
+				disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
+
+				% This is a Matlab bug: all the fields of md have their default value
+				% Example of error message:
+				% Warning: Error loading an object of class 'model':
+				% Undefined function or method 'exist' for input arguments of type 'cell'
+				%
+				% This has been fixed in MATLAB 7.9 (R2009b) and later versions
+			end
+
+			if isstruct(obj)
+				disp('Recovering masstransport from older version');
+				objstruct = obj;
+				obj = structtoobj(masstransport(),objstruct);
+			end
+		end% }}}
+	end
+	methods
+		function obj = masstransport(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('masstransport');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
+			obj.stabilization=1;
+
+			%Factor applied to compute the penalties kappa=max(stiffness matrix)*10^penalty_factor
+			obj.penalty_factor=3;
+
+			%Minimum ice thickness that can be used
+			obj.min_thickness=1;
+
+			%Hydrostatic adjustment
+			obj.hydrostatic_adjustment='Absolute';
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(MasstransportAnalysisEnum(),analyses) |  (solution==TransientSolutionEnum() & md.transient.ismasstransport==0), return; end
+
+			md = checkfield(md,'masstransport.spcthickness','forcing',1);
+			md = checkfield(md,'masstransport.isfreesurface','values',[0 1]);
+			md = checkfield(md,'masstransport.hydrostatic_adjustment','values',{'Absolute' 'Incremental'});
+			md = checkfield(md,'masstransport.stabilization','values',[0 1 2 3]);
+			md = checkfield(md,'masstransport.min_thickness','>',0);
+			if ~isempty(md.masstransport.requested_outputs),
+				md = checkfield(md,'masstransport.requested_outputs','size',[NaN 1]);
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Masstransport solution parameters:'));
+			fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint) [m]');
+			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');
+
+			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');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			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',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/masstransport.py
===================================================================
--- /issm/trunk/src/m/classes/masstransport.py	(revision 16137)
+++ /issm/trunk/src/m/classes/masstransport.py	(revision 16137)
@@ -0,0 +1,81 @@
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
+
+class masstransport(object):
+	"""
+	MASSTRANSPORT class definition
+
+	   Usage:
+	      masstransport=masstransport();
+	"""
+
+	def __init__(self): # {{{
+		self.spcthickness           = float('NaN')
+		self.isfreesurface          = 0
+		self.min_thickness          = 0
+		self.hydrostatic_adjustment = 0
+		self.stabilization          = 0
+		self.vertex_pairing         = float('NaN')
+		self.penalty_factor         = 0
+		self.requested_outputs      = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		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,'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,'requested_outputs','additional outputs requested'))
+
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		
+		#Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
+		self.stabilization=1
+
+		#Factor applied to compute the penalties kappa=max(stiffness matrix)*10^penalty_factor
+		self.penalty_factor=3
+
+		#Minimum ice thickness that can be used
+		self.min_thickness=1
+
+		#Hydrostatic adjustment
+		self.hydrostatic_adjustment='Absolute'
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if (MasstransportAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
+			return md
+
+		md = checkfield(md,'masstransport.spcthickness','forcing',1)
+		md = checkfield(md,'masstransport.isfreesurface','values',[0,1])
+		md = checkfield(md,'masstransport.hydrostatic_adjustment','values',['Absolute','Incremental'])
+		md = checkfield(md,'masstransport.stabilization','values',[0,1,2,3])
+		md = checkfield(md,'masstransport.min_thickness','>',0)
+		if not md.masstransport.requested_outputs:
+			md = checkfield(md,'masstransport.requested_outputs','size',[float('NaN'),1])
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1,'forcinglength',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)[0],'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')
+		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
+	# }}}
Index: /issm/trunk/src/m/classes/matdamageice.m
===================================================================
--- /issm/trunk/src/m/classes/matdamageice.m	(revision 16136)
+++ /issm/trunk/src/m/classes/matdamageice.m	(revision 16137)
@@ -102,5 +102,5 @@
 			md = checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements 1]);
 			md = checkfield(md,'materials.rheology_Z','>',0,'size',[md.mesh.numberofvertices 1]);
-			md = checkfield(md,'materials.rheology_law','values',{'None' 'Paterson' 'Arrhenius'});
+			md = checkfield(md,'materials.rheology_law','values',{'None' 'Paterson' 'Arrhenius' 'LliboutryDuval'});
 
 			if ismember(GiaAnalysisEnum(),analyses),
@@ -129,5 +129,5 @@
 			fielddisplay(obj,'rheology_n','Glen''s flow law exponent');
 			fielddisplay(obj,'rheology_Z','rheology multiplier');
-			fielddisplay(obj,'rheology_law','law for the temperature dependance of the rheology: ''None'', ''Paterson'' or ''Arrhenius''');
+			fielddisplay(obj,'rheology_law',['law for the temperature dependance of the rheology: ''None'', ''Paterson'', ''Arrhenius'' or ''LliboutryDuval''']);
 			fielddisplay(obj,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
 			fielddisplay(obj,'lithosphere_density','Lithosphere density [g/cm^-3]');
Index: /issm/trunk/src/m/classes/matdamageice.py
===================================================================
--- /issm/trunk/src/m/classes/matdamageice.py	(revision 16136)
+++ /issm/trunk/src/m/classes/matdamageice.py	(revision 16137)
@@ -59,5 +59,5 @@
 		s+="%s\n" % fielddisplay(self,"rheology_n","Glen's flow law exponent")
 		s+="%s\n" % fielddisplay(self,"rheology_Z","rheology multiplier")
-		s+="%s\n" % fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Paterson' or 'Arrhenius'")
+		s+="%s\n" % fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Paterson', 'Arrhenius' or 'LliboutryDuval'")
 		s+="%s\n" % fielddisplay(self,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]")
 		s+="%s\n" % fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]")
@@ -117,8 +117,8 @@
 		md = checkfield(md,'materials.rho_freshwater','>',0)
 		md = checkfield(md,'materials.mu_water','>',0)
-		md = checkfield(md,'materials.rheology_B','>',0,'size',[md.mesh.numberofvertices,1])
-		md = checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements,1])
-		md = checkfield(md,'materials.rheology_Z','>',0,'size',[md.mesh.numberofvertices,1])
-		md = checkfield(md,'materials.rheology_law','values',['None','Paterson','Arrhenius'])
+		md = checkfield(md,'materials.rheology_B','>',0,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
+		md = checkfield(md,'materials.rheology_Z','>',0,'size',[md.mesh.numberofvertices])
+		md = checkfield(md,'materials.rheology_law','values',['None','Paterson','Arrhenius','LliboutryDuval'])
 		md = checkfield(md,'materials.lithosphere_shear_modulus','>',0,'numel',[1]);
 		md = checkfield(md,'materials.lithosphere_density','>',0,'numel',[1]);
Index: /issm/trunk/src/m/classes/matice.m
===================================================================
--- /issm/trunk/src/m/classes/matice.m	(revision 16136)
+++ /issm/trunk/src/m/classes/matice.m	(revision 16137)
@@ -100,5 +100,5 @@
 			md = checkfield(md,'materials.rheology_B','>',0,'size',[md.mesh.numberofvertices 1]);
 			md = checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements 1]);
-			md = checkfield(md,'materials.rheology_law','values',{'None' 'Paterson' 'Arrhenius'});
+			md = checkfield(md,'materials.rheology_law','values',{'None' 'Paterson' 'Arrhenius' 'LliboutryDuval'});
 
 			if ismember(GiaAnalysisEnum(),analyses),
@@ -126,5 +126,5 @@
 			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'', ''Paterson'' or ''Arrhenius''');
+			fielddisplay(obj,'rheology_law',['law for the temperature dependance of the rheology: ''None'', ''Paterson'',  ''Arrhenius'' or ''LliboutryDuval''']);
 			fielddisplay(obj,'lithosphere_shear_modulus','Lithosphere shear modulus [Pa]');
 			fielddisplay(obj,'lithosphere_density','Lithosphere density [g/cm^-3]');
Index: /issm/trunk/src/m/classes/matice.py
===================================================================
--- /issm/trunk/src/m/classes/matice.py	(revision 16136)
+++ /issm/trunk/src/m/classes/matice.py	(revision 16137)
@@ -53,5 +53,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]"))
 		string="%s\n%s"%(string,fielddisplay(self,"rheology_n","Glen's flow law exponent"))
-		string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Paterson' or 'Arrhenius'"))
+		string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Paterson', 'Arrhenius' or 'LliboutryDuval'"))
 		string="%s\n%s"%(string,fielddisplay(self,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]"))
 		string="%s\n%s"%(string,fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]"))
@@ -114,5 +114,5 @@
 		md = checkfield(md,'materials.rheology_B','>',0,'size',[md.mesh.numberofvertices])
 		md = checkfield(md,'materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
-		md = checkfield(md,'materials.rheology_law','values',['None','Paterson','Arrhenius'])
+		md = checkfield(md,'materials.rheology_law','values',['None','Paterson','Arrhenius','LliboutryDuval'])
 		md = checkfield(md,'materials.lithosphere_shear_modulus','>',0,'numel',[1]);
 		md = checkfield(md,'materials.lithosphere_density','>',0,'numel',[1]);
Index: /issm/trunk/src/m/classes/mesh.m
===================================================================
--- /issm/trunk/src/m/classes/mesh.m	(revision 16136)
+++ /issm/trunk/src/m/classes/mesh.m	(revision 16137)
@@ -109,25 +109,18 @@
 				md = checkfield(md,'mesh.average_vertex_connectivity','>=',24,'message','''mesh.average_vertex_connectivity'' should be at least 24 in 3d');
 			end
-			md = checkfield(md,'mesh.elementconnectivity','size',[md.mesh.numberofelements 3],'NaN',1);
 
 			%Solution specific checks
 			switch(solution),
-				case PrognosticSolutionEnum(),
-					if md.prognostic.stabilization==3,
+				case MasstransportSolutionEnum(),
+					if md.masstransport.stabilization==3,
 						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
-						md = checkfield(md,'mesh.edges','size',[NaN 4]);
-						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
 				case BalancethicknessSolutionEnum(),
 					if md.balancethickness.stabilization==3,
 						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
-						md = checkfield(md,'mesh.edges','size',[NaN 4]);
-						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
 				case TransientSolutionEnum(),
-					if md.transient.isprognostic & md.prognostic.stabilization==3,
+					if md.transient.ismasstransport & md.masstransport.stabilization==3,
 						md = checkfield(md,'mesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d meshes');
-						md = checkfield(md,'mesh.edges','size',[NaN 4]);
-						md = checkfield(md,'mesh.edges(:,1:3)','>',0);
 					end
 				case ThermalSolutionEnum(),
@@ -196,5 +189,4 @@
 			WriteData(fid,'object',obj,'fieldname','numberofelements','format','Integer');
 			WriteData(fid,'object',obj,'fieldname','numberofvertices','format','Integer');
-			WriteData(fid,'object',obj,'fieldname','numberofedges','format','Integer');
 			WriteData(fid,'object',obj,'fieldname','elementonbed','format','BooleanMat','mattype',2);
 			WriteData(fid,'object',obj,'fieldname','elementonsurface','format','BooleanMat','mattype',2);
@@ -203,6 +195,4 @@
 			WriteData(fid,'object',obj,'fieldname','lowerelements','format','DoubleMat','mattype',2);
 			WriteData(fid,'object',obj,'fieldname','upperelements','format','DoubleMat','mattype',2);
-			WriteData(fid,'object',obj,'fieldname','edges','format','DoubleMat','mattype',3);
-			WriteData(fid,'object',obj,'fieldname','elementconnectivity','format','DoubleMat','mattype',3);
 			WriteData(fid,'object',obj,'fieldname','average_vertex_connectivity','format','Integer');
 			WriteData(fid,'object',obj,'fieldname','elements2d','format','DoubleMat','mattype',3);
Index: /issm/trunk/src/m/classes/mesh.py
===================================================================
--- /issm/trunk/src/m/classes/mesh.py	(revision 16136)
+++ /issm/trunk/src/m/classes/mesh.py	(revision 16137)
@@ -147,22 +147,15 @@
 		else:
 			md = checkfield(md,'mesh.average_vertex_connectivity','>=',24,'message',"'mesh.average_vertex_connectivity' should be at least 24 in 3d")
-		md = checkfield(md,'mesh.elementconnectivity','size',[md.mesh.numberofelements,3],'NaN',1)
 
 		#Solution specific checks
-		if   solution==PrognosticSolutionEnum():
-			if md.prognostic.stabilization==3:
+		if   solution==MasstransportSolutionEnum():
+			if md.masstransport.stabilization==3:
 				md = checkfield(md,'mesh.dimension','values',2,'message',"Discontinuous Galerkin only supported for 2d meshes")
-				md = checkfield(md,'mesh.edges','size',[float('NaN'),4])
-				md = checkfield(md,'mesh.edges[:,1:3]','>',0)
 		elif solution==BalancethicknessSolutionEnum():
 			if md.balancethickness.stabilization==3:
 				md = checkfield(md,'mesh.dimension','values',2,'message',"Discontinuous Galerkin only supported for 2d meshes")
-				md = checkfield(md,'mesh.edges','size',[float('NaN'),4])
-				md = checkfield(md,'mesh.edges[:,1:3]','>',0)
 		elif solution==TransientSolutionEnum():
-			if md.transient.isprognostic and md.prognostic.stabilization==3:
+			if md.transient.ismasstransport and md.masstransport.stabilization==3:
 				md = checkfield(md,'mesh.dimension','values',2,'message',"Discontinuous Galerkin only supported for 2d meshes")
-				md = checkfield(md,'mesh.edges','size',[float('NaN'),4])
-				md = checkfield(md,'mesh.edges[:,1:3]','>',0)
 		elif solution==ThermalSolutionEnum():
 			md = checkfield(md,'mesh.dimension','values',3,'message','thermal solution only supported on 3d meshes')
@@ -179,5 +172,4 @@
 		WriteData(fid,'object',self,'fieldname','numberofelements','format','Integer')
 		WriteData(fid,'object',self,'fieldname','numberofvertices','format','Integer')
-		WriteData(fid,'object',self,'fieldname','numberofedges','format','Integer')
 		WriteData(fid,'object',self,'fieldname','elementonbed','format','BooleanMat','mattype',2)
 		WriteData(fid,'object',self,'fieldname','elementonsurface','format','BooleanMat','mattype',2)
@@ -186,6 +178,4 @@
 		WriteData(fid,'object',self,'fieldname','lowerelements','format','DoubleMat','mattype',2)
 		WriteData(fid,'object',self,'fieldname','upperelements','format','DoubleMat','mattype',2)
-		WriteData(fid,'object',self,'fieldname','edges','format','DoubleMat','mattype',3)
-		WriteData(fid,'object',self,'fieldname','elementconnectivity','format','DoubleMat','mattype',3)
 		WriteData(fid,'object',self,'fieldname','average_vertex_connectivity','format','Integer')
 		WriteData(fid,'object',self,'fieldname','elements2d','format','DoubleMat','mattype',3)
Index: /issm/trunk/src/m/classes/model/model.m
===================================================================
--- /issm/trunk/src/m/classes/model/model.m	(revision 16136)
+++ /issm/trunk/src/m/classes/model/model.m	(revision 16137)
@@ -29,8 +29,8 @@
 
 		balancethickness = 0;
-		diagnostic       = 0;
+		stressbalance       = 0;
 		groundingline    = 0;
 		hydrology        = 0;
-		prognostic       = 0;
+		masstransport       = 0;
 		thermal          = 0;
 		steadystate      = 0;
@@ -84,6 +84,6 @@
 			end
 			%2013 April 12
-			if numel(md.diagnostic.loadingforce==1)
-				md.diagnostic.loadingforce=0*ones(md.mesh.numberofvertices,3);
+			if numel(md.stressbalance.loadingforce==1)
+				md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
 			end
 			%2013 April 17
@@ -92,5 +92,4 @@
 				md.hydrology=hydrologyshreve(md.materials);
 			end
-
 		end% }}}
 	end
@@ -171,23 +170,17 @@
 				md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1);
 				md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1);
-				md.flowequation.bordermacayeal=project2d(md,md.flowequation.bordermacayeal,1);
-				md.flowequation.borderpattyn=project2d(md,md.flowequation.borderpattyn,1);
-				md.flowequation.borderstokes=project2d(md,md.flowequation.borderstokes,1);
+				md.flowequation.borderSSA=project2d(md,md.flowequation.borderSSA,1);
+				md.flowequation.borderHO=project2d(md,md.flowequation.borderHO,1);
+				md.flowequation.borderFS=project2d(md,md.flowequation.borderFS,1);
 			end	
 
 			%boundary conditions
-			md.diagnostic.spcvx=project2d(md,md.diagnostic.spcvx,md.mesh.numberoflayers);
-			md.diagnostic.spcvy=project2d(md,md.diagnostic.spcvy,md.mesh.numberoflayers);
-			md.diagnostic.spcvz=project2d(md,md.diagnostic.spcvz,md.mesh.numberoflayers);
-			md.diagnostic.referential=project2d(md,md.diagnostic.referential,md.mesh.numberoflayers);
-			md.diagnostic.loadingforce=project2d(md,md.diagnostic.loadingforce,md.mesh.numberoflayers);
-			md.prognostic.spcthickness=project2d(md,md.prognostic.spcthickness,md.mesh.numberoflayers);
+			md.stressbalance.spcvx=project2d(md,md.stressbalance.spcvx,md.mesh.numberoflayers);
+			md.stressbalance.spcvy=project2d(md,md.stressbalance.spcvy,md.mesh.numberoflayers);
+			md.stressbalance.spcvz=project2d(md,md.stressbalance.spcvz,md.mesh.numberoflayers);
+			md.stressbalance.referential=project2d(md,md.stressbalance.referential,md.mesh.numberoflayers);
+			md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers);
+			md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers);
 			md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
-
-			%Extrusion of Neumann BC
-			if ~isnan(md.diagnostic.icefront),
-				numberofneumann2d=size(md.diagnostic.icefront,1)/(md.mesh.numberoflayers-1);
-				md.diagnostic.icefront=[md.diagnostic.icefront(1:numberofneumann2d,1:2) md.diagnostic.icefront(1:numberofneumann2d,5:6)]; %Add two columns on the first layer 
-			end
 
 			%materials
@@ -216,11 +209,6 @@
 			md.mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1);
 			md.mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1);
-			md.mask.elementonfloatingice=project2d(md,md.mask.elementonfloatingice,1);
-			md.mask.vertexonfloatingice=project2d(md,md.mask.vertexonfloatingice,1);
-			md.mask.elementongroundedice=project2d(md,md.mask.elementongroundedice,1);
-			md.mask.vertexongroundedice=project2d(md,md.mask.vertexongroundedice,1);
-			md.mask.elementonwater=project2d(md,md.mask.elementonwater,1);
-			md.mask.vertexonwater=project2d(md,md.mask.vertexonwater,1);
-			%md.mask.vertexonrock=project2d(md,md.mask.vertexonrock,1);
+			md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1);
+			md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1);
 
 			%lat long
@@ -260,5 +248,5 @@
 			%   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
 			%   If user wants every element outside the domain to be 
-			%   extract2d, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+			%   extract2d, add '~' to the name of the domain file (ex: '~HO.exp');
 			%   an empty string '' will be considered as an empty domain
 			%   a string 'all' will be considered as the entire domain
@@ -269,5 +257,4 @@
 			%   Examples:
 			%      md2=extract(md,'Domain.exp');
-			%      md2=extract(md,md.mask.elementonfloatingice);
 			%
 			%   See also: EXTRUDE, COLLAPSE
@@ -440,15 +427,15 @@
 
 			%Penalties
-			if ~isnan(md2.diagnostic.vertex_pairing),
-				for i=1:size(md1.diagnostic.vertex_pairing,1);
-					md2.diagnostic.vertex_pairing(i,:)=Pnode(md1.diagnostic.vertex_pairing(i,:));
+			if ~isnan(md2.stressbalance.vertex_pairing),
+				for i=1:size(md1.stressbalance.vertex_pairing,1);
+					md2.stressbalance.vertex_pairing(i,:)=Pnode(md1.stressbalance.vertex_pairing(i,:));
 				end
-				md2.diagnostic.vertex_pairing=md2.diagnostic.vertex_pairing(find(md2.diagnostic.vertex_pairing(:,1)),:);
-			end
-			if ~isnan(md2.prognostic.vertex_pairing),
-				for i=1:size(md1.prognostic.vertex_pairing,1);
-					md2.prognostic.vertex_pairing(i,:)=Pnode(md1.prognostic.vertex_pairing(i,:));
+				md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing(find(md2.stressbalance.vertex_pairing(:,1)),:);
+			end
+			if ~isnan(md2.masstransport.vertex_pairing),
+				for i=1:size(md1.masstransport.vertex_pairing,1);
+					md2.masstransport.vertex_pairing(i,:)=Pnode(md1.masstransport.vertex_pairing(i,:));
 				end
-				md2.prognostic.vertex_pairing=md2.prognostic.vertex_pairing(find(md2.prognostic.vertex_pairing(:,1)),:);
+				md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing(find(md2.masstransport.vertex_pairing(:,1)),:);
 			end
 
@@ -478,11 +465,11 @@
 			nodestoflag1=intersect(orphans_node,pos_node);
 			nodestoflag2=Pnode(nodestoflag1);
-			if numel(md1.diagnostic.spcvx)>1 & numel(md1.diagnostic.spcvy)>2 & numel(md1.diagnostic.spcvz)>2,
+			if numel(md1.stressbalance.spcvx)>1 & numel(md1.stressbalance.spcvy)>2 & numel(md1.stressbalance.spcvz)>2,
 				if numel(md1.inversion.vx_obs)>1 & numel(md1.inversion.vy_obs)>1
-					md2.diagnostic.spcvx(nodestoflag2)=md2.inversion.vx_obs(nodestoflag2); 
-					md2.diagnostic.spcvy(nodestoflag2)=md2.inversion.vy_obs(nodestoflag2);
+					md2.stressbalance.spcvx(nodestoflag2)=md2.inversion.vx_obs(nodestoflag2); 
+					md2.stressbalance.spcvy(nodestoflag2)=md2.inversion.vy_obs(nodestoflag2);
 				else
-					md2.diagnostic.spcvx(nodestoflag2)=NaN;
-					md2.diagnostic.spcvy(nodestoflag2)=NaN;
+					md2.stressbalance.spcvx(nodestoflag2)=NaN;
+					md2.stressbalance.spcvy(nodestoflag2)=NaN;
 					disp(' ')
 					disp('!! extract warning: spc values should be checked !!')
@@ -490,20 +477,8 @@
 				end
 				%put 0 for vz
-				md2.diagnostic.spcvz(nodestoflag2)=0;
+				md2.stressbalance.spcvz(nodestoflag2)=0;
 			end
 			if ~isnan(md1.thermal.spctemperature),
 				md2.thermal.spctemperature(nodestoflag2,1)=1;
-			end
-
-			%Diagnostic
-			if ~isnan(md2.diagnostic.icefront)
-				md2.diagnostic.icefront(:,1)=Pnode(md1.diagnostic.icefront(:,1)); 
-				md2.diagnostic.icefront(:,2)=Pnode(md1.diagnostic.icefront(:,2)); 
-				md2.diagnostic.icefront(:,end-1)=Pelem(md1.diagnostic.icefront(:,end-1));
-				if md1.mesh.dimension==3
-					md2.diagnostic.icefront(:,3)=Pnode(md1.diagnostic.icefront(:,3)); 
-					md2.diagnostic.icefront(:,4)=Pnode(md1.diagnostic.icefront(:,4)); 
-				end
-				md2.diagnostic.icefront=md2.diagnostic.icefront(find(md2.diagnostic.icefront(:,1) & md2.diagnostic.icefront(:,2) & md2.diagnostic.icefront(:,end)),:);
 			end
 
@@ -696,4 +671,5 @@
 			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;
 
 			%bedinfo and surface info
@@ -716,25 +692,17 @@
 				md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node');
 			end
-			md.flowequation.bordermacayeal=project3d(md,'vector',md.flowequation.bordermacayeal,'type','node');
-			md.flowequation.borderpattyn=project3d(md,'vector',md.flowequation.borderpattyn,'type','node');
-			md.flowequation.borderstokes=project3d(md,'vector',md.flowequation.borderstokes,'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.diagnostic.spcvx=project3d(md,'vector',md.diagnostic.spcvx,'type','node');
-			md.diagnostic.spcvy=project3d(md,'vector',md.diagnostic.spcvy,'type','node');
-			md.diagnostic.spcvz=project3d(md,'vector',md.diagnostic.spcvz,'type','node');
+			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);
-			md.prognostic.spcthickness=project3d(md,'vector',md.prognostic.spcthickness,'type','node');
+			md.masstransport.spcthickness=project3d(md,'vector',md.masstransport.spcthickness,'type','node');
 			md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node');
-			md.diagnostic.referential=project3d(md,'vector',md.diagnostic.referential,'type','node');
-			md.diagnostic.loadingforce=project3d(md,'vector',md.diagnostic.loadingforce,'type','node');
-
-			%in 3d, pressureload: [node1 node2 node3 node4 element]
-			pressureload_layer1=[md.diagnostic.icefront(:,1:2)  md.diagnostic.icefront(:,2)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,1)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,3:4)]; %Add two columns on the first layer 
-			pressureload=[];
-			for i=1:numlayers-1,
-				pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d pressureload_layer1(:,6)];
-			end
-			md.diagnostic.icefront=pressureload;
+			md.stressbalance.referential=project3d(md,'vector',md.stressbalance.referential,'type','node');
+			md.stressbalance.loadingforce=project3d(md,'vector',md.stressbalance.loadingforce,'type','node');
 
 			%connectivity
@@ -763,11 +731,6 @@
 			md.geometry.bathymetry=project3d(md,'vector',md.geometry.bathymetry,'type','node');
 			md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node');
-			md.mask.elementonfloatingice=project3d(md,'vector',md.mask.elementonfloatingice,'type','element');
-			md.mask.vertexonfloatingice=project3d(md,'vector',md.mask.vertexonfloatingice,'type','node');
-			md.mask.elementongroundedice=project3d(md,'vector',md.mask.elementongroundedice,'type','element');
-			md.mask.vertexongroundedice=project3d(md,'vector',md.mask.vertexongroundedice,'type','node');
-			md.mask.elementonwater=project3d(md,'vector',md.mask.elementonwater,'type','element');
-			md.mask.vertexonwater=project3d(md,'vector',md.mask.vertexonwater,'type','node');
-			md.mask.vertexonrock=project3d(md,'vector',md.mask.vertexonrock,'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;
@@ -819,7 +782,4 @@
 			if isfield(structmd,'gridonsurface'), md.mesh.vertexonsurface=structmd.gridonsurface; end
 			if isfield(structmd,'extractedgrids'), md.mesh.extractedvertices=structmd.extractedgrids; end
-			if isfield(structmd,'gridoniceshelf'), md.mask.vertexonfloatingice=structmd.gridoniceshelf; end
-			if isfield(structmd,'gridonicesheet'), md.mask.vertexongroundedice=structmd.gridonicesheet; end
-			if isfield(structmd,'gridonwater'), md.mask.vertexonwater=structmd.gridonwater; end
 			if isfield(structmd,'gridonboundary'), md.mesh.vertexonboundary=structmd.gridonboundary; end
 			if isfield(structmd,'petscoptions') & ~isempty(structmd.petscoptions), md.toolkits=structmd.petscoptions; end
@@ -862,31 +822,24 @@
 			if isfield(structmd,'time_adapt'), md.timestepping.time_adapt=structmd.time_adapt; end
 			if isfield(structmd,'cfl_coefficient'), md.timestepping.cfl_coefficient=structmd.cfl_coefficient; end
-			if isfield(structmd,'spcthickness'), md.prognostic.spcthickness=structmd.spcthickness; end
-			if isfield(structmd,'artificial_diffusivity'), md.prognostic.stabilization=structmd.artificial_diffusivity; end
-			if isfield(structmd,'hydrostatic_adjustment'), md.prognostic.hydrostatic_adjustment=structmd.hydrostatic_adjustment; end
-			if isfield(structmd,'penalties'), md.prognostic.vertex_pairing=structmd.penalties; end
-			if isfield(structmd,'penalty_offset'), md.prognostic.penalty_factor=structmd.penalty_offset; end
+			if isfield(structmd,'spcthickness'), md.masstransport.spcthickness=structmd.spcthickness; end
+			if isfield(structmd,'artificial_diffusivity'), md.masstransport.stabilization=structmd.artificial_diffusivity; end
+			if isfield(structmd,'hydrostatic_adjustment'), md.masstransport.hydrostatic_adjustment=structmd.hydrostatic_adjustment; end
+			if isfield(structmd,'penalties'), md.masstransport.vertex_pairing=structmd.penalties; end
+			if isfield(structmd,'penalty_offset'), md.masstransport.penalty_factor=structmd.penalty_offset; end
 			if isfield(structmd,'B'), md.materials.rheology_B=structmd.B; end
 			if isfield(structmd,'n'), md.materials.rheology_n=structmd.n; end
 			if isfield(structmd,'rheology_B'), md.materials.rheology_B=structmd.rheology_B; end
 			if isfield(structmd,'rheology_n'), md.materials.rheology_n=structmd.rheology_n; end
-			if isfield(structmd,'elementoniceshelf'), md.mask.elementonfloatingice=structmd.elementoniceshelf; end
-			if isfield(structmd,'elementonicesheet'), md.mask.elementongroundedice=structmd.elementonicesheet; end
-			if isfield(structmd,'elementonwater'), md.mask.elementonwater=structmd.elementonwater; end
-			if isfield(structmd,'nodeoniceshelf'), md.mask.vertexonfloatingice=structmd.nodeoniceshelf; end
-			if isfield(structmd,'nodeonicesheet'), md.mask.vertexongroundedice=structmd.nodeonicesheet; end
-			if isfield(structmd,'nodeonwater'), md.mask.vertexonwater=structmd.nodeonwater; end
 			if isfield(structmd,'spcthickness'), md.balancethickness.spcthickness=structmd.spcthickness; end
 			if isfield(structmd,'artificial_diffusivity'), md.balancethickness.stabilization=structmd.artificial_diffusivity; end
 			if isfield(structmd,'dhdt'), md.balancethickness.thickening_rate=structmd.dhdt; end
-			if isfield(structmd,'ismacayealpattyn'), md.flowequation.ismacayealpattyn=structmd.ismacayealpattyn; end
-			if isfield(structmd,'ishutter'), md.flowequation.ishutter=structmd.ishutter; end
-			if isfield(structmd,'isstokes'), md.flowequation.isstokes=structmd.isstokes; end
+			if isfield(structmd,'isSIA'), md.flowequation.isSIA=structmd.isSIA; end
+			if isfield(structmd,'isFS'), md.flowequation.isFS=structmd.isFS; end
 			if isfield(structmd,'elements_type'), md.flowequation.element_equation=structmd.elements_type; end
 			if isfield(structmd,'vertices_type'), md.flowequation.vertex_equation=structmd.vertices_type; end
 			if isfield(structmd,'eps_rel'), md.steadystate.reltol=structmd.eps_rel; end
 			if isfield(structmd,'max_steadystate_iterations'), md.steadystate.maxiter=structmd.max_steadystate_iterations; end
-			if isfield(structmd,'isdiagnostic'), md.transient.isdiagnostic=structmd.isdiagnostic; end
-			if isfield(structmd,'isprognostic'), md.transient.isprognostic=structmd.isprognostic; end
+			if isfield(structmd,'isdiagnostic'), md.transient.isstressbalance=structmd.isdiagnostic; end
+			if isfield(structmd,'isprognostic'), md.transient.ismasstransport=structmd.isprognostic; end
 			if isfield(structmd,'isthermal'), md.transient.isthermal=structmd.isthermal; end
 			if isfield(structmd,'control_analysis'), md.inversion.iscontrol=structmd.control_analysis; end
@@ -952,6 +905,5 @@
 			if isfield(structmd,'z'), md.mesh.z=structmd.z; end
 			if isfield(structmd,'mask'), md.flaim.criterion=structmd.mask; end
-			if isfield(structmd,'pressureload'), md.diagnostic.icefront=structmd.pressureload; end
-			if isfield(structmd,'diagnostic_ref'), md.diagnostic.referential=structmd.diagnostic_ref; end
+			if isfield(structmd,'diagnostic_ref'), md.stressbalance.referential=structmd.diagnostic_ref; end
 			if isfield(structmd,'npart'); md.qmu.numberofpartitions=structmd.npart; end
 			if isfield(structmd,'part'); md.qmu.partition=structmd.part; end
@@ -965,33 +917,30 @@
 				md.verbose=verbose;
 			end
-			if size(md.diagnostic.icefront,2)==3 || size(md.diagnostic.icefront,2)==5,
-				front=md.diagnostic.icefront;
-				md.diagnostic.icefront=[front 1*md.mask.elementonfloatingice(front(:,end))];
-			end
+
 			if isfield(structmd,'spcvelocity'), 
-				md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-				md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-				md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
-				pos=find(structmd.spcvelocity(:,1)); md.diagnostic.spcvx(pos)=structmd.spcvelocity(pos,4); 
-				pos=find(structmd.spcvelocity(:,2)); md.diagnostic.spcvy(pos)=structmd.spcvelocity(pos,5); 
-				pos=find(structmd.spcvelocity(:,3)); md.diagnostic.spcvz(pos)=structmd.spcvelocity(pos,6); 
+				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);
+				pos=find(structmd.spcvelocity(:,1)); md.stressbalance.spcvx(pos)=structmd.spcvelocity(pos,4); 
+				pos=find(structmd.spcvelocity(:,2)); md.stressbalance.spcvy(pos)=structmd.spcvelocity(pos,5); 
+				pos=find(structmd.spcvelocity(:,3)); md.stressbalance.spcvz(pos)=structmd.spcvelocity(pos,6); 
 			end
 			if isfield(structmd,'spcvx'), 
-				md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-				pos=find(~isnan(structmd.spcvx)); md.diagnostic.spcvx(pos)=structmd.spcvx(pos); 
+				md.stressbalance.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvx)); md.stressbalance.spcvx(pos)=structmd.spcvx(pos); 
 			end
 			if isfield(structmd,'spcvy'),
-				md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-				pos=find(~isnan(structmd.spcvy)); md.diagnostic.spcvy(pos)=structmd.spcvy(pos);     
+				md.stressbalance.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvy)); md.stressbalance.spcvy(pos)=structmd.spcvy(pos);     
 			end
 			if isfield(structmd,'spcvz'),
-				md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
-				pos=find(~isnan(structmd.spcvz)); md.diagnostic.spcvz(pos)=structmd.spcvz(pos);     
+				md.stressbalance.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvz)); md.stressbalance.spcvz(pos)=structmd.spcvz(pos);     
 			end
 			if isfield(structmd,'pressureload'),
 				if ~isempty(structmd.pressureload) & ismember(structmd.pressureload(end,end),[118 119 120]),
-					pos=find(structmd.pressureload(:,end)==120); md.diagnostic.icefront(pos,end)=0;
-					pos=find(structmd.pressureload(:,end)==118); md.diagnostic.icefront(pos,end)=1;
-					pos=find(structmd.pressureload(:,end)==119); md.diagnostic.icefront(pos,end)=2;
+					pos=find(structmd.pressureload(:,end)==120); md.stressbalance.icefront(pos,end)=0;
+					pos=find(structmd.pressureload(:,end)==118); md.stressbalance.icefront(pos,end)=1;
+					pos=find(structmd.pressureload(:,end)==119); md.stressbalance.icefront(pos,end)=2;
 				end
 			end
@@ -1045,12 +994,12 @@
 			if isfield(structmd,'artificial_diffusivity') & structmd.artificial_diffusivity==2,
 					md.thermal.stabilization=2;
-					md.prognostic.stabilization=1;
+					md.masstransport.stabilization=1;
 					md.balancethickness.stabilization=1;
 			end
-			if isnumeric(md.prognostic.hydrostatic_adjustment)
-				if md.prognostic.hydrostatic_adjustment==269,
-					md.prognostic.hydrostatic_adjustment='Incremental';
+			if isnumeric(md.masstransport.hydrostatic_adjustment)
+				if md.masstransport.hydrostatic_adjustment==269,
+					md.masstransport.hydrostatic_adjustment='Incremental';
 				else
-					md.prognostic.hydrostatic_adjustment='Absolute';
+					md.masstransport.hydrostatic_adjustment='Absolute';
 				end
 			end
@@ -1065,11 +1014,20 @@
 				md.mesh.lowerelements(1:md.mesh.numberofelements2d)=NaN;
 			end
-
 			if ~isfield(structmd,'diagnostic_ref');
-				md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
-			end
-
+				md.stressbalance.referential=NaN*ones(md.mesh.numberofvertices,6);
+			end
 			if ~isfield(structmd,'loadingforce');
-				md.diagnostic.loadingforce=0*ones(md.mesh.numberofvertices,3);
+				md.stressbalance.loadingforce=0*ones(md.mesh.numberofvertices,3);
+			end
+
+			%2013 August 9
+			if isfield(structmd,'prognostic') & isa(structmd.prognostic,'prognostic'),
+				disp('Recovering old prognostic class');
+				md.masstransport=masstransport(structmd.prognostic);
+			end
+			%2013 August 9
+			if isfield(structmd,'diagnostic') & (isa(structmd.diagnostic,'diagnostic') || isa(structmd.diagnostic,'stressbalance')),
+				disp('Recovering old diagnostic class');
+				md.stressbalance=stressbalance(structmd.diagnostic);
 			end
 		end% }}}
@@ -1096,7 +1054,7 @@
 			md.cluster          = generic();
 			md.balancethickness = balancethickness();
-			md.diagnostic       = diagnostic();
+			md.stressbalance       = stressbalance();
 			md.hydrology        = hydrologyshreve();
-			md.prognostic       = prognostic();
+			md.masstransport       = masstransport();
 			md.thermal          = thermal();
 			md.steadystate      = steadystate();
@@ -1132,8 +1090,8 @@
 			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','diagnostic'      ,['[1x1 ' class(obj.diagnostic) ']'],'parameters for diagnostic 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','prognostic'      ,['[1x1 ' class(obj.prognostic) ']'],'parameters for prognostic 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'));
@@ -1220,11 +1178,10 @@
 		eval(['delete ' id]);
 
-
 		end % }}}
 		function md=download(md) % {{{
-		
+
 		%the goal of this routine is to download the internals of the current model from a server, because 
 		%this model is empty, except for the settings which tell us where to go and find this model!
-		
+
 		%Download the file: 
 		issmscpin(md.settings.upload_server, md.settings.upload_login, md.settings.upload_port, md.settings.upload_path, {md.settings.upload_filename});
Index: /issm/trunk/src/m/classes/model/model.py
===================================================================
--- /issm/trunk/src/m/classes/model/model.py	(revision 16136)
+++ /issm/trunk/src/m/classes/model/model.py	(revision 16137)
@@ -21,8 +21,8 @@
 from generic import generic
 from balancethickness import balancethickness
-from diagnostic import diagnostic
+from stressbalance import stressbalance
 from groundingline import groundingline
 from hydrologyshreve import hydrologyshreve
-from prognostic import prognostic
+from masstransport import masstransport
 from thermal import thermal
 from steadystate import steadystate
@@ -38,5 +38,4 @@
 from private import private
 from EnumDefinitions import *
-from ismumps import *
 from mumpsoptions import *
 from iluasmoptions import *
@@ -72,8 +71,8 @@
 
 		self.balancethickness = balancethickness()
-		self.diagnostic       = diagnostic()
+		self.stressbalance       = stressbalance()
 		self.groundingline    = groundingline()
 		self.hydrology        = hydrologyshreve()
-		self.prognostic       = prognostic()
+		self.masstransport       = masstransport()
 		self.thermal          = thermal()
 		self.steadystate      = steadystate()
@@ -111,8 +110,8 @@
 		        'cluster',\
 		        'balancethickness',\
-		        'diagnostic',\
+		        'stressbalance',\
 		        'groundingline',\
 		        'hydrology',\
-		        'prognostic',\
+		        'masstransport',\
 		        'thermal',\
 		        'steadystate',\
@@ -148,8 +147,8 @@
 		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" % ("diagnostic","[%s,%s]" % ("1x1",obj.diagnostic.__class__.__name__),"parameters for diagnostic 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" % ("prognostic","[%s,%s]" % ("1x1",obj.prognostic.__class__.__name__),"parameters for prognostic 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"))
@@ -177,5 +176,5 @@
 		   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
 		   If user wants every element outside the domain to be 
-		   extract2d, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+		   extract2d, add '~' to the name of the domain file (ex: '~HO.exp');
 		   an empty string '' will be considered as an empty domain
 		   a string 'all' will be considered as the entire domain
@@ -186,5 +185,4 @@
 		   Examples:
 		      md2=extract(md,'Domain.exp');
-		      md2=extract(md,md.mask.elementonfloatingice);
 
 		   See also: EXTRUDE, COLLAPSE
@@ -344,12 +342,12 @@
 
 		#Penalties
-		if numpy.any(numpy.logical_not(numpy.isnan(md2.diagnostic.vertex_pairing))):
-			for i in xrange(numpy.size(md1.diagnostic.vertex_pairing,axis=0)):
-				md2.diagnostic.vertex_pairing[i,:]=Pnode[md1.diagnostic.vertex_pairing[i,:]]
-			md2.diagnostic.vertex_pairing=md2.diagnostic.vertex_pairing[numpy.nonzero(md2.diagnostic.vertex_pairing[:,0])[0],:]
-		if numpy.any(numpy.logical_not(numpy.isnan(md2.prognostic.vertex_pairing))):
-			for i in xrange(numpy.size(md1.prognostic.vertex_pairing,axis=0)):
-				md2.prognostic.vertex_pairing[i,:]=Pnode[md1.prognostic.vertex_pairing[i,:]]
-			md2.prognostic.vertex_pairing=md2.prognostic.vertex_pairing[numpy.nonzero(md2.prognostic.vertex_pairing[:,0])[0],:]
+		if numpy.any(numpy.logical_not(numpy.isnan(md2.stressbalance.vertex_pairing))):
+			for i in xrange(numpy.size(md1.stressbalance.vertex_pairing,axis=0)):
+				md2.stressbalance.vertex_pairing[i,:]=Pnode[md1.stressbalance.vertex_pairing[i,:]]
+			md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing[numpy.nonzero(md2.stressbalance.vertex_pairing[:,0])[0],:]
+		if numpy.any(numpy.logical_not(numpy.isnan(md2.masstransport.vertex_pairing))):
+			for i in xrange(numpy.size(md1.masstransport.vertex_pairing,axis=0)):
+				md2.masstransport.vertex_pairing[i,:]=Pnode[md1.masstransport.vertex_pairing[i,:]]
+			md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing[numpy.nonzero(md2.masstransport.vertex_pairing[:,0])[0],:]
 
 		#recreate segments
@@ -379,26 +377,16 @@
 		nodestoflag1=numpy.intersect1d(orphans_node,pos_node)
 		nodestoflag2=Pnode[nodestoflag1].astype(int)-1
-		if numpy.size(md1.diagnostic.spcvx)>1 and numpy.size(md1.diagnostic.spcvy)>2 and numpy.size(md1.diagnostic.spcvz)>2:
+		if numpy.size(md1.stressbalance.spcvx)>1 and numpy.size(md1.stressbalance.spcvy)>2 and numpy.size(md1.stressbalance.spcvz)>2:
 			if numpy.size(md1.inversion.vx_obs)>1 and numpy.size(md1.inversion.vy_obs)>1:
-				md2.diagnostic.spcvx[nodestoflag2]=md2.inversion.vx_obs[nodestoflag2] 
-				md2.diagnostic.spcvy[nodestoflag2]=md2.inversion.vy_obs[nodestoflag2]
+				md2.stressbalance.spcvx[nodestoflag2]=md2.inversion.vx_obs[nodestoflag2] 
+				md2.stressbalance.spcvy[nodestoflag2]=md2.inversion.vy_obs[nodestoflag2]
 			else:
-				md2.diagnostic.spcvx[nodestoflag2]=float('NaN')
-				md2.diagnostic.spcvy[nodestoflag2]=float('NaN')
+				md2.stressbalance.spcvx[nodestoflag2]=float('NaN')
+				md2.stressbalance.spcvy[nodestoflag2]=float('NaN')
 				print "\n!! extract warning: spc values should be checked !!\n\n"
 			#put 0 for vz
-			md2.diagnostic.spcvz[nodestoflag2]=0
+			md2.stressbalance.spcvz[nodestoflag2]=0
 		if numpy.any(numpy.logical_not(numpy.isnan(md1.thermal.spctemperature))):
 			md2.thermal.spctemperature[nodestoflag2,0]=1
-
-		#Diagnostic
-		if numpy.any(numpy.logical_not(numpy.isnan(md2.diagnostic.icefront))):
-			md2.diagnostic.icefront[:,0]=Pnode[md1.diagnostic.icefront[:,0].astype(int)-1]
-			md2.diagnostic.icefront[:,1]=Pnode[md1.diagnostic.icefront[:,1].astype(int)-1]
-			md2.diagnostic.icefront[:,-2]=Pelem[md1.diagnostic.icefront[:,-2].astype(int)-1]
-			if md1.mesh.dimension==3:
-				md2.diagnostic.icefront[:,2]=Pnode[md1.diagnostic.icefront[:,2].astype(int)-1]
-				md2.diagnostic.icefront[:,3]=Pnode[md1.diagnostic.icefront[:,3].astype(int)-1]
-			md2.diagnostic.icefront=md2.diagnostic.icefront[numpy.nonzero(logical_and_n(md2.diagnostic.icefront[:,0],md2.diagnostic.icefront[:,1],md2.diagnostic.icefront[:,-1]))[0],:]
 
 		#Results fields
@@ -613,24 +601,17 @@
 			md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node')
 
-		md.flowequation.bordermacayeal=project3d(md,'vector',md.flowequation.bordermacayeal,'type','node')
-		md.flowequation.borderpattyn=project3d(md,'vector',md.flowequation.borderpattyn,'type','node')
-		md.flowequation.borderstokes=project3d(md,'vector',md.flowequation.borderstokes,'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.diagnostic.spcvx=project3d(md,'vector',md.diagnostic.spcvx,'type','node')
-		md.diagnostic.spcvy=project3d(md,'vector',md.diagnostic.spcvy,'type','node')
-		md.diagnostic.spcvz=project3d(md,'vector',md.diagnostic.spcvz,'type','node')
+		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',float('NaN'))
-		md.prognostic.spcthickness=project3d(md,'vector',md.prognostic.spcthickness,'type','node')
+		md.masstransport.spcthickness=project3d(md,'vector',md.masstransport.spcthickness,'type','node')
 		md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node')
-		md.diagnostic.referential=project3d(md,'vector',md.diagnostic.referential,'type','node')
-		md.diagnostic.loadingforce=project3d(md,'vector',md.diagnostic.loadingforce,'type','node')
-
-		#in 3d, pressureload: [node1 node2 node3 node4 element]
-		pressureload_layer1=numpy.hstack((md.diagnostic.icefront[:,0:2],md.diagnostic.icefront[:,1:2]+md.mesh.numberofvertices2d,md.diagnostic.icefront[:,0:1]+md.mesh.numberofvertices2d,md.diagnostic.icefront[:,2:4]))    #Add two columns on the first layer 
-		pressureload=numpy.empty((0,6),int)
-		for i in xrange(numlayers-1):
-			pressureload=numpy.vstack((pressureload,numpy.hstack((pressureload_layer1[:,0:4]+i*md.mesh.numberofvertices2d,pressureload_layer1[:,4:5]+i*md.mesh.numberofelements2d,pressureload_layer1[:,5:6]))))
-		md.diagnostic.icefront=pressureload
+		md.stressbalance.referential=project3d(md,'vector',md.stressbalance.referential,'type','node')
+		md.stressbalance.loadingforce=project3d(md,'vector',md.stressbalance.loadingforce,'type','node')
 
 		#connectivity
@@ -655,10 +636,6 @@
 		md.geometry.bathymetry=project3d(md,'vector',md.geometry.bathymetry,'type','node')
 		md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node')
-		md.mask.elementonfloatingice=project3d(md,'vector',md.mask.elementonfloatingice,'type','element')
-		md.mask.vertexonfloatingice=project3d(md,'vector',md.mask.vertexonfloatingice,'type','node')
-		md.mask.elementongroundedice=project3d(md,'vector',md.mask.elementongroundedice,'type','element')
-		md.mask.vertexongroundedice=project3d(md,'vector',md.mask.vertexongroundedice,'type','node')
-		md.mask.elementonwater=project3d(md,'vector',md.mask.elementonwater,'type','element')
-		md.mask.vertexonwater=project3d(md,'vector',md.mask.vertexonwater,'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');end;
Index: /issm/trunk/src/m/classes/model/planet.m
===================================================================
--- /issm/trunk/src/m/classes/model/planet.m	(revision 16136)
+++ /issm/trunk/src/m/classes/model/planet.m	(revision 16137)
@@ -38,14 +38,9 @@
 			 md.settings         = settings();
 			 md.solver           = solver();
-			 if ismumps(),
-				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),mumpsoptions());
-			 else
-				 md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),iluasmoptions());
-			 end
 			 md.cluster          = generic();
 			 md.balancethickness = balancethickness();
-			 md.diagnostic       = diagnostic();
+			 md.stressbalance       = stressbalance();
 			 md.hydrology        = hydrology();
-			 md.prognostic       = prognostic();
+			 md.masstransport       = masstransport();
 			 md.thermal          = thermal();
 			 md.steadystate      = steadystate();
Index: /issm/trunk/src/m/classes/modellist.m
===================================================================
--- /issm/trunk/src/m/classes/modellist.m	(revision 16136)
+++ /issm/trunk/src/m/classes/modellist.m	(revision 16137)
@@ -23,5 +23,5 @@
 			%
 			%   Examples:
-			%      md_list=modelsextract(md,md.mask.elementonfloatingice,1000);
+			%      md_list=modelsextract(md...,,1000);
 			%
 			%   See also: EXTRUDE, COLLAPSE, MODELEXTRACT
@@ -214,8 +214,8 @@
 			%      obj=solve(obj,varargin)
 			%      where varargin is a lit of paired arguments. 
-			%      arguments can be: 'analysis_type': 'diagnostic','thermal','prognostic','transient'
+			%      arguments can be: 'analysis_type': 'stressbalance','thermal','masstransport','transient'
 			%
 			%   Examples:
-			%      obj=solve(obj,'analysis_type','diagnostic');
+			%      obj=solve(obj,'analysis_type','stressbalance');
 
 			%recover options
Index: /issm/trunk/src/m/classes/oldclasses/diagnostic.m
===================================================================
--- /issm/trunk/src/m/classes/oldclasses/diagnostic.m	(revision 16137)
+++ /issm/trunk/src/m/classes/oldclasses/diagnostic.m	(revision 16137)
@@ -0,0 +1,132 @@
+%DIAGNOSTIC class definition
+%
+%   Usage:
+%      diagnostic=diagnostic();
+
+classdef diagnostic
+	properties (SetAccess=public) 
+		spcvx                    = NaN;
+		spcvy                    = NaN;
+		spcvz                    = NaN;
+		restol                   = 0;
+		reltol                   = 0;
+		abstol                   = 0;
+		isnewton                 = 0;
+		FSreconditioning     = 0;
+		viscosity_overshoot      = 0;
+		icefront                 = NaN;
+		maxiter                  = 0;
+		shelf_dampening          = 0;
+		vertex_pairing           = NaN;
+		penalty_factor           = NaN;
+		rift_penalty_lock        = NaN;
+		rift_penalty_threshold   = 0;
+		referential              = NaN;
+		loadingforce             = NaN;
+		requested_outputs        = NaN;
+	end
+	methods
+		function obj = diagnostic(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			 %maximum of non-linear iterations.
+			 obj.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;
+
+			 %Penalty factor applied kappa=max(stiffness matrix)*10^penalty_factor
+			 obj.penalty_factor=3;
+
+			 %coefficient to update the viscosity between each iteration of
+			 %a diagnostic according to the following formula
+			 %viscosity(n)=viscosity(n)+viscosity_overshoot(viscosity(n)-viscosity(n-1))
+			 obj.viscosity_overshoot=0;
+
+			 %Stop the iterations of rift if below a threshold
+			 obj.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;
+
+		end % }}}
+		function disp(obj) % {{{
+
+			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)');
+
+			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(obj,'icefront','segments on ice front list (last column 0: Air, 1: Water, 2: Ice)');
+
+			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');
+
+			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');
+
+			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) % {{{
+			WriteData(fid,'object',obj,'fieldname','spcvx','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','spcvy','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','spcvz','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','restol','format','Double');
+			WriteData(fid,'object',obj,'fieldname','reltol','format','Double');
+			WriteData(fid,'object',obj,'fieldname','abstol','format','Double');
+			WriteData(fid,'object',obj,'fieldname','isnewton','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','FSreconditioning','format','Double');
+			WriteData(fid,'object',obj,'fieldname','viscosity_overshoot','format','Double');
+			WriteData(fid,'object',obj,'fieldname','maxiter','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','shelf_dampening','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',obj,'fieldname','rift_penalty_lock','format','Integer');
+			WriteData(fid,'object',obj,'fieldname','rift_penalty_threshold','format','Integer');
+			WriteData(fid,'object',obj,'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',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
+
+			%marshall ice front
+			data=obj.icefront;
+			pos=find(data(:,end)==0); data(pos,end)=AirEnum();
+			pos=find(data(:,end)==1); data(pos,end)=WaterEnum();
+			pos=find(data(:,end)==2); data(pos,end)=IceEnum();
+			WriteData(fid,'data',data,'enum',StressbalanceIcefrontEnum(),'format','DoubleMat','mattype',3);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/oldclasses/prognostic.m
===================================================================
--- /issm/trunk/src/m/classes/oldclasses/prognostic.m	(revision 16137)
+++ /issm/trunk/src/m/classes/oldclasses/prognostic.m	(revision 16137)
@@ -0,0 +1,76 @@
+%MASSTRANSPORT class definition
+%
+%   Usage:
+%      prognostic=prognostic();
+
+classdef prognostic
+	properties (SetAccess=public) 
+		 spcthickness           = NaN;
+		 min_thickness          = 0;
+		 hydrostatic_adjustment = 0;
+		 stabilization          = 0;
+		 vertex_pairing         = NaN;
+		 penalty_factor         = 0;
+		 requested_outputs      = NaN;
+	end
+	methods
+		function obj = prognostic(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			%Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
+			obj.stabilization=1;
+
+			%Factor applied to compute the penalties kappa=max(stiffness matrix)*10^penalty_factor
+			obj.penalty_factor=3;
+
+			%Minimum ice thickness that can be used
+			obj.min_thickness=1;
+
+			%Hydrostatic adjustment
+			obj.hydrostatic_adjustment='Absolute';
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(PrognosticAnalysisEnum(),analyses) |  (solution==TransientSolutionEnum() & md.transient.isprognostic==0), return; end
+
+			md = checkfield(md,'prognostic.spcthickness','forcing',1);
+			md = checkfield(md,'prognostic.hydrostatic_adjustment','values',{'Absolute' 'Incremental'});
+			md = checkfield(md,'prognostic.stabilization','values',[0 1 2 3]);
+			md = checkfield(md,'prognostic.min_thickness','>',0);
+			if ~isempty(md.prognostic.requested_outputs),
+				md = checkfield(md,'prognostic.requested_outputs','size',[NaN 1]);
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   Prognostic solution parameters:'));
+			fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint) [m]');
+			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');
+
+			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');
+
+		end % }}}
+		function marshall(obj,md,fid) % {{{
+			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
+			WriteData(fid,'object',obj,'fieldname','min_thickness','format','Double');
+			WriteData(fid,'data',StringToEnum(obj.hydrostatic_adjustment),'format','Integer','enum',PrognosticHydrostaticAdjustmentEnum());
+			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',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/organizer.m
===================================================================
--- /issm/trunk/src/m/classes/organizer.m	(revision 16136)
+++ /issm/trunk/src/m/classes/organizer.m	(revision 16137)
@@ -24,4 +24,9 @@
 		steps         =[];
 		requestedsteps=[0];
+		upload_server='';
+		upload_path='';
+		upload_login='';
+		upload_port=0;
+		download=0;
 		%}}}
 	end
@@ -54,4 +59,12 @@
 				org.trunkprefix=trunkprefix;
 			end
+
+			%Get upload information, if provided
+			org.upload_server=getfieldvalue(options,'upload_server','');
+			org.upload_path=getfieldvalue(options,'upload_path','');
+			org.upload_login=getfieldvalue(options,'upload_login','');
+			org.upload_port=getfieldvalue(options,'upload_port',0);
+			org.download=getfieldvalue(options,'download',0);
+
 		end
 		%}}}
@@ -65,4 +78,12 @@
 					disp(sprintf('   step #%2i: ''%s''',org.steps(i).id,org.steps(i).string));
 				end
+			end
+			if isempty(org.upload_server),
+				disp('   no upload info');
+			else
+				disp(sprintf('   upload_server:     ''%s''',org.upload_server));
+				disp(sprintf('   upload_login:     ''%s''',org.upload_login));
+				disp(sprintf('   upload_path:     ''%s''',org.upload_path));
+				disp(sprintf('   upload_port:     ''%i''',org.upload_port));
 			end
 		end
@@ -112,5 +133,5 @@
 			end
 		end%}}}
-		function md=loaddata(org,string),% {{{
+		function loaddata(org,string),% {{{
 
 			%Get model path
@@ -168,4 +189,23 @@
 			end
 
+			%But if download is requested, we are downloading and skipping the step: 
+			if ismember(org.currentstep,org.requestedsteps) & org.download,
+				%load the model if it exists, and download
+				name=[org.repository '/' org.prefix org.steps(org.currentstep).string ];
+				if exist(name,'file'),
+					md=loadmodel(name); 
+					if isa(md,'model'),
+						if ~isempty(md.settings.upload_filename),
+							disp(sprintf('   downloading model'));
+							md=download(md);
+							save(name,'md','-v7.3');
+						end
+					end
+				end
+
+				%reset bool to false, so we stick with only downloading
+				bool=false;
+			end
+
 		end%}}}
 		function savemodel(org,md) % {{{
Index: /issm/trunk/src/m/classes/organizer.py
===================================================================
--- /issm/trunk/src/m/classes/organizer.py	(revision 16136)
+++ /issm/trunk/src/m/classes/organizer.py	(revision 16137)
@@ -6,4 +6,5 @@
 from savevars import *
 from model import model
+from whichdb import whichdb
 
 class organizer(object):
@@ -53,5 +54,5 @@
 		#Get steps
 		self.requestedsteps=options.getfieldvalue('steps',[0])
-
+		
 		#Get trunk prefix (only if provided by user)
 		if options.exist('trunkprefix'):
@@ -96,8 +97,8 @@
 		if not isinstance(string,(str,unicode)):
 			raise TypeError("argument provided is not a string")
-		path=os.path.join(self.repository,self.prefix+string)
+		path=os.path.join(self.repository,self.prefix+'.step#'+string+'.python')
 
 		#figure out if the model is there, otherwise, we have to use the default path supplied by user.
-		if os.path.exists(path):
+		if whichdb(path):
 			md=loadmodel(path)
 			return md
@@ -113,5 +114,5 @@
 				return md
 		else:
-			raise IOerror("Could not find '%s'" % path)
+			raise IOError("Could not find '%s'" % path)
 	#}}}
 	def perform(self,string):    # {{{
@@ -157,5 +158,5 @@
 			raise RuntimeError("Cannot save model because organizer (org) is not up to date!")
 
-		name=os.path.join(self.repository,self.prefix+self.steps[self._currentstep-1]['string'])
+		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/planetmesh.m
===================================================================
--- /issm/trunk/src/m/classes/planetmesh.m	(revision 16136)
+++ /issm/trunk/src/m/classes/planetmesh.m	(revision 16137)
@@ -70,10 +70,10 @@
 			%Solution specific checks
 			switch(solution),
-				case PrognosticSolutionEnum(),
-					if md.prognostic.stabilization==3,
+				case MasstransportSolutionEnum(),
+					if md.masstransport.stabilization==3,
 						md = checkfield(md,'planetmesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d planetmeshes');
 					end
 				case TransientSolutionEnum(),
-					if md.transient.isprognostic & md.prognostic.stabilization==3,
+					if md.transient.ismasstransport & md.masstransport.stabilization==3,
 						md = checkfield(md,'planetmesh.dimension','values',2,'message','Discontinuous Galerkin only supported for 2d planetmeshes');
 					end
Index: sm/trunk/src/m/classes/prognostic.m
===================================================================
--- /issm/trunk/src/m/classes/prognostic.m	(revision 16136)
+++ 	(revision )
@@ -1,76 +1,0 @@
-%PROGNOSTIC class definition
-%
-%   Usage:
-%      prognostic=prognostic();
-
-classdef prognostic
-	properties (SetAccess=public) 
-		 spcthickness           = NaN;
-		 min_thickness          = 0;
-		 hydrostatic_adjustment = 0;
-		 stabilization          = 0;
-		 vertex_pairing         = NaN;
-		 penalty_factor         = 0;
-		 requested_outputs      = NaN;
-	end
-	methods
-		function obj = prognostic(varargin) % {{{
-			switch nargin
-				case 0
-					obj=setdefaultparameters(obj);
-				otherwise
-					error('constructor not supported');
-			end
-		end % }}}
-		function obj = setdefaultparameters(obj) % {{{
-
-			%Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
-			obj.stabilization=1;
-
-			%Factor applied to compute the penalties kappa=max(stiffness matrix)*10^penalty_factor
-			obj.penalty_factor=3;
-
-			%Minimum ice thickness that can be used
-			obj.min_thickness=1;
-
-			%Hydrostatic adjustment
-			obj.hydrostatic_adjustment='Absolute';
-		end % }}}
-		function md = checkconsistency(obj,md,solution,analyses) % {{{
-
-			%Early return
-			if ~ismember(PrognosticAnalysisEnum(),analyses) |  (solution==TransientSolutionEnum() & md.transient.isprognostic==0), return; end
-
-			md = checkfield(md,'prognostic.spcthickness','forcing',1);
-			md = checkfield(md,'prognostic.hydrostatic_adjustment','values',{'Absolute' 'Incremental'});
-			md = checkfield(md,'prognostic.stabilization','values',[0 1 2 3]);
-			md = checkfield(md,'prognostic.min_thickness','>',0);
-			if ~isempty(md.prognostic.requested_outputs),
-				md = checkfield(md,'prognostic.requested_outputs','size',[NaN 1]);
-			end
-
-		end % }}}
-		function disp(obj) % {{{
-			disp(sprintf('   Prognostic solution parameters:'));
-			fielddisplay(obj,'spcthickness','thickness constraints (NaN means no constraint) [m]');
-			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');
-
-			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');
-
-		end % }}}
-		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','spcthickness','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1);
-			WriteData(fid,'object',obj,'fieldname','min_thickness','format','Double');
-			WriteData(fid,'data',StringToEnum(obj.hydrostatic_adjustment),'format','Integer','enum',PrognosticHydrostaticAdjustmentEnum());
-			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',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
-		end % }}}
-	end
-end
Index: sm/trunk/src/m/classes/prognostic.py
===================================================================
--- /issm/trunk/src/m/classes/prognostic.py	(revision 16136)
+++ 	(revision )
@@ -1,77 +1,0 @@
-from fielddisplay import fielddisplay
-from EnumDefinitions import *
-from StringToEnum import StringToEnum
-from checkfield import *
-from WriteData import *
-
-class prognostic(object):
-	"""
-	PROGNOSTIC class definition
-
-	   Usage:
-	      prognostic=prognostic();
-	"""
-
-	def __init__(self): # {{{
-		self.spcthickness           = float('NaN')
-		self.min_thickness          = 0
-		self.hydrostatic_adjustment = 0
-		self.stabilization          = 0
-		self.vertex_pairing         = float('NaN')
-		self.penalty_factor         = 0
-		self.requested_outputs      = float('NaN')
-
-		#set defaults
-		self.setdefaultparameters()
-
-		#}}}
-	def __repr__(self): # {{{
-		string='   Prognostic solution parameters:'
-		string="%s\n%s"%(string,fielddisplay(self,'spcthickness','thickness constraints (NaN means no constraint) [m]'))
-		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,'requested_outputs','additional outputs requested'))
-
-		return string
-		#}}}
-	def setdefaultparameters(self): # {{{
-		
-		#Type of stabilization to use 0:nothing 1:artificial_diffusivity 3:Discontinuous Galerkin
-		self.stabilization=1
-
-		#Factor applied to compute the penalties kappa=max(stiffness matrix)*10^penalty_factor
-		self.penalty_factor=3
-
-		#Minimum ice thickness that can be used
-		self.min_thickness=1
-
-		#Hydrostatic adjustment
-		self.hydrostatic_adjustment='Absolute'
-
-		return self
-	#}}}
-	def checkconsistency(self,md,solution,analyses):    # {{{
-
-		#Early return
-		if (PrognosticAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.isprognostic):
-			return md
-
-		md = checkfield(md,'prognostic.spcthickness','forcing',1)
-		md = checkfield(md,'prognostic.hydrostatic_adjustment','values',['Absolute','Incremental'])
-		md = checkfield(md,'prognostic.stabilization','values',[0,1,2,3])
-		md = checkfield(md,'prognostic.min_thickness','>',0)
-		if not md.prognostic.requested_outputs:
-			md = checkfield(md,'prognostic.requested_outputs','size',[float('NaN'),1])
-
-		return md
-	# }}}
-	def marshall(self,md,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1,'forcinglength',md.mesh.numberofvertices+1)
-		WriteData(fid,'object',self,'fieldname','min_thickness','format','Double')
-		WriteData(fid,'data',StringToEnum(self.hydrostatic_adjustment)[0],'format','Integer','enum',PrognosticHydrostaticAdjustmentEnum())
-		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')
-		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
-	# }}}
Index: /issm/trunk/src/m/classes/qmu/@dakota_method/dakota_method.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/@dakota_method/dakota_method.m	(revision 16136)
+++ /issm/trunk/src/m/classes/qmu/@dakota_method/dakota_method.m	(revision 16137)
@@ -560,5 +560,5 @@
                                 dm.params.initial_trust_radius=-1.;
                                 dm.params.covariance=0;
-                                dm.params.regression_diagnostics=false;
+                                dm.params.regression_stressbalances=false;
                             case {'nlssol_sqp'}
                                 dm.type     ='lsq';
Index: /issm/trunk/src/m/classes/qmu/@dakota_method/dmeth_params_write.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/@dakota_method/dmeth_params_write.m	(revision 16136)
+++ /issm/trunk/src/m/classes/qmu/@dakota_method/dmeth_params_write.m	(revision 16137)
@@ -300,5 +300,5 @@
                 param_write(fid,sbeg,'initial_trust_radius',' = ','\n',dm.params);
                 param_write(fid,sbeg,'covariance','           = ','\n',dm.params);
-                param_write(fid,sbeg,'regression_diagnostics','','\n',dm.params);
+                param_write(fid,sbeg,'regression_stressbalances','','\n',dm.params);
 
             case {'nlssol_sqp'}
@@ -350,5 +350,5 @@
                 param_write(fid,sbeg,'seed','             = ','\n',dm.params);
                 param_write(fid,sbeg,'fixed_seed','','\n',dm.params);
-                dver=textscan(dakotaversion(),'%[0123456789].%[0123456789].%[0123456789]');
+                dver=textscan(IssmConfig('_DAKOTA_VERSION_'),'%[0123456789].%[0123456789].%[0123456789]');
                 if ((str2num(dver{1}{1})==4 && str2num(dver{2}{1})>2) || str2num(dver{1}{1})>4)
                     param_write(fid,sbeg,'rng','                ','\n',dm.params);
Index: /issm/trunk/src/m/classes/settings.m
===================================================================
--- /issm/trunk/src/m/classes/settings.m	(revision 16136)
+++ /issm/trunk/src/m/classes/settings.m	(revision 16137)
@@ -46,5 +46,5 @@
 			%0 to deactivate
 			obj.waitonlock=Inf;
-		
+
 			%upload options: 
 			upload_port         = 0;
Index: /issm/trunk/src/m/classes/snowpack.m
===================================================================
--- /issm/trunk/src/m/classes/snowpack.m	(revision 16137)
+++ /issm/trunk/src/m/classes/snowpack.m	(revision 16137)
@@ -0,0 +1,480 @@
+%SNOWPACK class definition
+%
+%   Usage:
+%      snowpack=snowpack();
+
+classdef snowpack
+	properties (SetAccess=public) 
+
+		%first, the configuration fields, by category: 
+		%snowpack:  %{{{
+		snowpack_meas_tss = 0;
+		snowpack_enforce_measured_snow_heights = 0;
+		snowpack_sw_mode = 0;
+		snowpack_incoming_longwave = 0;
+		snowpack_height_of_wind_value = 0;
+		snowpack_height_of_meteo_values = 0;
+		snowpack_neutral = 0;
+		snowpack_roughness_length = 0;
+		snowpack_number_slopes = 0;
+		snowpack_snow_redistribution = 0;
+		snowpack_calculation_step_length = 0;
+		snowpack_change_bc = 0;
+		snowpack_thresh_change_bc = 0;
+		snowpack_snp_soil = 0;
+		snowpack_soil_flux = 0;
+		snowpack_geo_heat = 0;
+		snowpack_canopy = 0;
+		%}}}
+		%snowpackadvanced:  %{{{
+		snowpackadvanced_variant = ''; % use 320 kg m-3 for fixed density
+		snowpackadvanced_hn_density = '';
+		%}}}
+		%general:  %{{{
+		general_pluginpath = '';
+		general_buff_chunk_size = 0;
+		general_buff_before = 0;
+		%}}}
+		%input {{{
+		input_coordsys = '';
+		input_coordparam = '';
+		input_time_zone = 0;
+		input_meteo = '';
+		input_meteopath = '';
+		input_station1 = '';
+		input_snowfile1 = '';
+		%}}}
+		%output {{{
+		output_coordsys = '';
+		output_coordparam = '';
+		output_time_zone = 0;
+		output_meteopath = '';
+		output_experiment = '';
+		output_ts_write = 0;
+		output_ts_start = 0;
+		output_ts_days_between = 0;
+		output_profile = '';
+		output_prof_write = 0;
+		output_prof_start = 0;
+		output_prof_days_between = 0;
+		%}}}
+		%interpolations1d %{{{
+		interpolations1d_window_size = 0; %that is 5 d and 2 h; 1 d = 86400
+		interpolations1d_hnw_resample = '';
+		interpolations1d_hs_resample = '';
+		interpolations1d_tsg_resample = '';
+		interpolations1d_rho_hn_resample = '';
+		interpolations1d_vw_resample = '';
+		interpolations1d_vw_args = '';
+		%}}}
+		%filters {{{
+		filters={'TA::filter1',{'soft',[-20 10]}};
+		filters=NaN;
+		filter_values=NaN;
+
+		filters_ta_filter1 = '';
+		filters_ta_arg1 = NaN;
+		filters_rh_filter1 = '';
+		filters_rh_arg1 = NaN;
+		filters_rh_filter2 = '';
+		filters_rh_arg2 = NaN;
+		filters_iswr_filter1 = '';
+		filters_iswr_arg1 = NaN;
+		filters_iswr_filter2 = '';
+		filters_iswr_arg2 = NaN;
+		filters_rswr_filter1 = '';
+		filters_rswr_arg1 = NaN;
+		filters_rswr_filter2 = '';
+		filters_rswr_arg2 = NaN;
+
+		%for ta between 190 and 280 k;
+		filters_ilwr_filter1 = '';
+		filters_ilwr_arg1 = NaN;
+		filters_ilwr_filter2 = '';
+		filters_ilwr_arg2 = NaN;
+		filters_tss_filter1 = '';
+		filters_tss_arg1 = NaN;
+		filters_tsg_filter1 = '';
+		filters_tsg_arg1 = NaN;
+		filters_vw_filter1 = '';
+		filters_vw_arg1 = NaN;
+		filters_vw_filter2 = '';
+		filters_vw_arg2 = NaN;
+		%}}}
+
+	end
+	methods
+		function obj = snowpack(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('snowpack');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+	
+		%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;
+		%}}}
+		%snowpackadvanced:  %{{{
+		obj.snowpackadvanced_variant = 'ANTARCTICA'; % use 320 kg m-3 for fixed density
+		obj.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;
+		%}}}
+		%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';
+		%}}}
+		%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;
+		%}}}
+		%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';
+		%}}}
+		%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};
+
+		%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};
+		%}}}
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			%snowpack:  %{{{
+			md=checkfield(md,'snowpack.snowpack_meas_tss','values',[0 1]);
+			md=checkfield(md,'snowpack.snowpack_enforce_measured_snow_heights','values',[0 1]);
+			md=checkfield(md,'snowpack.snowpack_sw_mode','values',[0 1 2]);
+			md=checkfield(md,'snowpack.snowpack_incoming_longwave','values',[0 1]);
+			md=checkfield(md,'snowpack.snowpack_height_of_wind_value','>=',0);
+			md=checkfield(md,'snowpack.snowpack_height_of_meteo_values','>=',0);
+			md=checkfield(md,'snowpack.snowpack_neutral','values',[-1 0 1]);
+			md=checkfield(md,'snowpack.snowpack_roughness_length','>=',0);
+			md=checkfield(md,'snowpack.snowpack_number_slopes','values',[1 3 5 9]);
+			md=checkfield(md,'snowpack.snowpack_snow_redistribution','values',[0 1]);
+			md=checkfield(md,'snowpack.snowpack_calculation_step_length','>',0);
+			md=checkfield(md,'snowpack.snowpack_change_bc','values',[0 1]);
+			md=checkfield(md,'snowpack.snowpack_thresh_change_bc','<=',0);
+			md=checkfield(md,'snowpack.snowpack_snp_soil','values',[0 1]);
+			md=checkfield(md,'snowpack.snowpack_soil_flux','values',[0 1]);
+			md=checkfield(md,'snowpack.snowpack_geo_heat','>=',0);
+			md=checkfield(md,'snowpack.snowpack_canopy','values',[0 1]);
+			%}}}
+			%snowpackadvanced:  %{{{
+			md=checkfield(md,'snowpack.snowpackadvanced_variant','values',{'JAPAN','DEFAULT','ANTARCTICA'});
+			md=checkfield(md,'snowpack.snowpackadvanced_hn_density','values',{'PARAMETERIZED','EVENT','MEASURED'});
+			%}}}
+			%general:  %{{{
+			md=checkfield(md,'snowpack.general_buff_chunk_size','>',0);
+			md=checkfield(md,'snowpack.general_buff_before','>',0);
+			%}}}
+			%input {{{
+			md=checkfield(md,'snowpack.input_coordsys','values',{'CH1903','UTM','UPS','PROJ4','LOCAL'});
+			md=checkfield(md,'snowpack.input_coordparam','values','null');
+			md=checkfield(md,'snowpack.input_time_zone','>',-12,'<',12);
+			md=checkfield(md,'snowpack.input_meteo','values',{'BORMA','COSMO','GEOTOP','GRIB','GSN','IMIS','SMET','SNOWPACK'});
+			md=checkfield(md,'snowpack.input_meteopath','empty',1);
+			md=checkfield(md,'snowpack.input_station1 ','empty',1);
+			md=checkfield(md,'snowpack.input_snowfile1','empty',1);
+			%}}}
+			%output {{{
+			md=checkfield(md,'snowpack.output_coordsys','values',{'CH1903','UTM','UPS','PROJ4','LOCAL'});
+			md=checkfield(md,'snowpack.output_coordparam','values','null');
+			md=checkfield(md,'snowpack.output_time_zone','>',-12,'<',12);
+			md=checkfield(md,'snowpack.output_meteopath','empty',1);
+			md=checkfield(md,'snowpack.output_experiment','empty',1);
+			md=checkfield(md,'snowpack.output_ts_write','values',[0 1]);
+			md=checkfield(md,'snowpack.output_ts_start','>=',0);
+			md=checkfield(md,'snowpack.output_ts_days_between','>=',0);
+			md=checkfield(md,'snowpack.output_profile','values',{'ASCII','IMIS','ASCII IMIS'});
+			md=checkfield(md,'snowpack.output_prof_write','values',[0 1]);
+			md=checkfield(md,'snowpack.output_prof_start','>=',0);
+			md=checkfield(md,'snowpack.output_prof_days_between','>=',0);
+			%}}}
+			%interpolations1d %{{{
+			md=checkfield(md,'snowpack.interpolations1d_window_size','>',0);
+			md=checkfield(md,'snowpack.interpolations1d_hnw_resample','values',{'NONE','NEAREST_NEIGHBOUR','ACCUMULATE','LINEAR'});
+			md=checkfield(md,'snowpack.interpolations1d_hs_resample','values',{'NONE','NEAREST_NEIGHBOUR','ACCUMULATE','LINEAR'});
+			md=checkfield(md,'snowpack.interpolations1d_tsg_resample','values',{'NONE','NEAREST_NEIGHBOUR','ACCUMULATE','LINEAR'});
+			md=checkfield(md,'snowpack.interpolations1d_rho_hn_resample','values',{'NONE','NEAREST_NEIGHBOUR','ACCUMULATE','LINEAR'});
+			md=checkfield(md,'snowpack.interpolations1d_vw_resample','values',{'NONE','NEAREST_NEIGHBOUR','ACCUMULATE','LINEAR'});
+			md=checkfield(md,'snowpack.interpolations1d_vw_args','values',{'EXTRAPOLATE'});
+			%}}}
+			%filters {{{
+			filter_values={'MIN_MAX','RATE_FILTER1','RATE_FILTER2','UNHEATED_RAIN_GAUGE_FILTER','WMO_UNDERCATCH_FILTER','WMO_UNDERCATCH_FILTER-SIMPLIFIED','UNVENTILLATED_TEMPERATURE_SENSOR','ADD_AN_OFFSET'};
+
+
+			md=checkfield(md,'snowpack.filters_ta_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ta_filter1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_ta_filter1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_ta_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ta_arg1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_ta_arg1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_rh_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rh_filter1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_rh_filter1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_rh_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rh_arg1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_rh_arg1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_rh_filter2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rh_filter2,'MIN_MAX'), md=checkfield(md,'snowpack.filters_rh_filter2','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_rh_arg2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rh_arg2,'MIN_MAX'), md=checkfield(md,'snowpack.filters_rh_arg2','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_iswr_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_iswr_filter1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_iswr_filter1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_iswr_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_iswr_arg1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_iswr_arg1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_iswr_filter2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_iswr_filter2,'MIN_MAX'), md=checkfield(md,'snowpack.filters_iswr_filter2','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_iswr_arg2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_iswr_arg2,'MIN_MAX'), md=checkfield(md,'snowpack.filters_iswr_arg2','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_rswr_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rswr_filter1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_rswr_filter1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_rswr_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rswr_arg1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_rswr_arg1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_rswr_filter2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rswr_filter2,'MIN_MAX'), md=checkfield(md,'snowpack.filters_rswr_filter2','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_rswr_arg2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_rswr_arg2,'MIN_MAX'), md=checkfield(md,'snowpack.filters_rswr_arg2','size',[1 NaN]); end
+
+			%for ta between 190 and 280 k;
+			md=checkfield(md,'snowpack.filters_ilwr_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ilwr_filter1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_ilwr_filter1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_ilwr_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ilwr_arg1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_ilwr_arg1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_ilwr_filter2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ilwr_filter2,'MIN_MAX'), md=checkfield(md,'snowpack.filters_ilwr_filter2','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_ilwr_arg2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_ilwr_arg2,'MIN_MAX'), md=checkfield(md,'snowpack.filters_ilwr_arg2','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_tss_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_tss_filter1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_tss_filter1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_tss_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_tss_arg1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_tss_arg1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_tsg_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_tsg_filter1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_tsg_filter1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_tsg_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_tsg_arg1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_tsg_arg1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_vw_filter1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_vw_filter1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_vw_filter1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_vw_arg1','values',{filter_values});
+			if strcmpi(md.snowpack.filters_vw_arg1,'MIN_MAX'), md=checkfield(md,'snowpack.filters_vw_arg1','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_vw_filter2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_vw_filter2,'MIN_MAX'), md=checkfield(md,'snowpack.filters_vw_filter2','size',[1 NaN]); end
+			md=checkfield(md,'snowpack.filters_vw_arg2','values',{filter_values});
+			if strcmpi(md.snowpack.filters_vw_arg2,'MIN_MAX'), md=checkfield(md,'snowpack.filters_vw_arg2','size',[1 NaN]); end
+
+			%}}}
+		end % }}}
+		function disp(obj) % {{{
+
+			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:',...
+				'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 ',...
+				'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,',...
+				'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:',...
+				'-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;',...
+				'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,',...
+				'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.',...
+				'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 ',...
+				'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 ',...
+			'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)');
+			% }}}
+			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"'});
+			% }}}
+			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). ');
+			% }}}
+			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 #');
+			% }}}
+			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(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)');
+			% }}}
+			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(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''');
+			% }}}
+			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','');
+
+			%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','');
+			% }}}
+
+		end % }}}
+		function marshall(obj,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','DoubleMat','mattype',3);
+			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);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/steadystate.m
===================================================================
--- /issm/trunk/src/m/classes/steadystate.m	(revision 16136)
+++ /issm/trunk/src/m/classes/steadystate.m	(revision 16137)
@@ -35,6 +35,6 @@
 			end
 
-			if isnan(md.diagnostic.reltol),
-				md = checkmessage(md,['for a steadystate computation, diagnostic.reltol (relative convergence criterion) must be defined!']);
+			if isnan(md.stressbalance.reltol),
+				md = checkmessage(md,['for a steadystate computation, stressbalance.reltol (relative convergence criterion) must be defined!']);
 			end
 		end % }}}
Index: /issm/trunk/src/m/classes/steadystate.py
===================================================================
--- /issm/trunk/src/m/classes/steadystate.py	(revision 16136)
+++ /issm/trunk/src/m/classes/steadystate.py	(revision 16137)
@@ -48,6 +48,6 @@
 			md.checkmessage("for a steadystate computation, timestepping.time_step must be zero.")
 
-		if numpy.isnan(md.diagnostic.reltol):
-			md.checkmessage("for a steadystate computation, diagnostic.reltol (relative convergence criterion) must be defined!")
+		if numpy.isnan(md.stressbalance.reltol):
+			md.checkmessage("for a steadystate computation, stressbalance.reltol (relative convergence criterion) must be defined!")
 
 		return md
Index: /issm/trunk/src/m/classes/stressbalance.m
===================================================================
--- /issm/trunk/src/m/classes/stressbalance.m	(revision 16137)
+++ /issm/trunk/src/m/classes/stressbalance.m	(revision 16137)
@@ -0,0 +1,180 @@
+%STRESSBALANC Eclass definition
+%
+%   Usage:
+%      stressbalance=stressbalance();
+
+classdef stressbalance
+	properties (SetAccess=public) 
+		spcvx                  = NaN;
+		spcvy                  = NaN;
+		spcvz                  = NaN;
+		restol                 = 0;
+		reltol                 = 0;
+		abstol                 = 0;
+		isnewton               = 0;
+		FSreconditioning       = 0;
+		viscosity_overshoot    = 0;
+		maxiter                = 0;
+		shelf_dampening        = 0;
+		vertex_pairing         = NaN;
+		penalty_factor         = NaN;
+		rift_penalty_lock      = NaN;
+		rift_penalty_threshold = 0;
+		referential            = NaN;
+		loadingforce           = NaN;
+		requested_outputs      = NaN;
+	end
+	methods
+		function obj = stressbalance(varargin) % {{{
+			switch nargin
+				case 0
+					obj=setdefaultparameters(obj);
+				case 1
+					inputstruct=varargin{1};
+					list1 = properties('stressbalance');
+					list2 = fieldnames(inputstruct);
+					for i=1:length(list1)
+						fieldname = list1{i};
+						if ismember(fieldname,list2),
+							obj.(fieldname) = inputstruct.(fieldname);
+						end
+					end
+				otherwise
+					error('constructor not supported');
+			end
+		end % }}}
+		function obj = setdefaultparameters(obj) % {{{
+
+			 %maximum of non-linear iterations.
+			 obj.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;
+
+			 %Penalty factor applied kappa=max(stiffness matrix)*10^penalty_factor
+			 obj.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;
+
+			 %Stop the iterations of rift if below a threshold
+			 obj.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;
+
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+
+			%Early return
+			if ~ismember(StressbalanceAnalysisEnum(),analyses), return; end
+
+			md = checkfield(md,'stressbalance.spcvx','forcing',1);
+			md = checkfield(md,'stressbalance.spcvy','forcing',1);
+			if md.mesh.dimension==3, md = checkfield(md,'stressbalance.spcvz','forcing',1); end
+			md = checkfield(md,'stressbalance.restol','size',[1 1],'>',0,'NaN',1);
+			md = checkfield(md,'stressbalance.reltol','size',[1 1]);
+			md = checkfield(md,'stressbalance.abstol','size',[1 1]);
+			md = checkfield(md,'stressbalance.isnewton','numel',[1],'values',[0 1 2]);
+			md = checkfield(md,'stressbalance.FSreconditioning','size',[1 1],'NaN',1);
+			md = checkfield(md,'stressbalance.viscosity_overshoot','size',[1 1],'NaN',1);
+			md = checkfield(md,'stressbalance.maxiter','size',[1 1],'>=',1);
+			md = checkfield(md,'stressbalance.referential','size',[md.mesh.numberofvertices 6]);
+			md = checkfield(md,'stressbalance.loadingforce','size',[md.mesh.numberofvertices 3]);
+			if ~isempty(md.stressbalance.requested_outputs),
+				md = checkfield(md,'stressbalance.requested_outputs','size',[NaN 1]);
+			end
+
+			%singular solution
+			if ~(any(~isnan(md.stressbalance.spcvx)) & any(~isnan(md.stressbalance.spcvy))),
+				md = checkmessage(md,['model is not well posed (singular). You need at least one node with fixed velocity!']);
+			end
+			%CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
+			if any(sum(isnan(md.stressbalance.referential),2)~=0 & sum(isnan(md.stressbalance.referential),2)~=6),
+				md = checkmessage(md,['Each line of stressbalance.referential should contain either only NaN values or no NaN values']);
+			end
+			%CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
+			if any(sum(isnan(md.stressbalance.referential),2)==0),
+				pos=find(sum(isnan(md.stressbalance.referential),2)==0);
+				if any(abs(dot(md.stressbalance.referential(pos,1:3),md.stressbalance.referential(pos,4:6),2))>eps),
+					md = checkmessage(md,['Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal']);
+				end
+			end
+			%CHECK THAT NO rotation specified for FS Grounded ice at base
+			if md.mesh.dimension==3 & md.flowequation.isFS,
+				pos=find(md.mask.groundedice_levelset>0. & md.mesh.vertexonbed);
+				if any(~isnan(md.stressbalance.referential(pos,:))),
+					md = checkmessage(md,['no referential should be specified for basal vertices of grounded ice']);
+				end
+				md = checkfield(md,'stressbalance.FSreconditioning','>',0);
+			end
+		end % }}}
+		function disp(obj) % {{{
+
+			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)');
+
+			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]');
+
+			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');
+
+			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');
+
+			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) % {{{
+
+			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,'object',obj,'class','stressbalance','fieldname','requested_outputs','format','DoubleMat','mattype',3);
+			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);
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/stressbalance.py
===================================================================
--- /issm/trunk/src/m/classes/stressbalance.py	(revision 16137)
+++ /issm/trunk/src/m/classes/stressbalance.py	(revision 16137)
@@ -0,0 +1,179 @@
+import numpy
+import sys
+import copy
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from checkfield import *
+from WriteData import *
+
+class stressbalance(object):
+	"""
+	STRESSBALANCE class definition
+
+	   Usage:
+	      stressbalance=stressbalance();
+	"""
+
+	def __init__(self): # {{{
+		self.spcvx                    = float('NaN')
+		self.spcvy                    = float('NaN')
+		self.spcvz                    = float('NaN')
+		self.restol                   = 0
+		self.reltol                   = 0
+		self.abstol                   = 0
+		self.isnewton                 = 0
+		self.FSreconditioning     = 0
+		self.viscosity_overshoot      = 0
+		self.icefront                 = float('NaN')
+		self.maxiter                  = 0
+		self.shelf_dampening          = 0
+		self.vertex_pairing           = float('NaN')
+		self.penalty_factor           = float('NaN')
+		self.rift_penalty_lock        = float('NaN')
+		self.rift_penalty_threshold   = 0
+		self.referential              = float('NaN')
+		self.loadingforce             = float('NaN')
+		self.requested_outputs        = float('NaN')
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#}}}
+	def __repr__(self): # {{{
+		
+		string='   StressBalance solution parameters:'
+		string="%s\n%s"%(string,'      Convergence criteria:')
+		string="%s\n%s"%(string,fielddisplay(self,'restol','mechanical equilibrium residual convergence criterion'))
+		string="%s\n%s"%(string,fielddisplay(self,'reltol','velocity relative convergence criterion, NaN: not applied'))
+		string="%s\n%s"%(string,fielddisplay(self,'abstol','velocity absolute convergence criterion, NaN: not applied'))
+		string="%s\n%s"%(string,fielddisplay(self,'isnewton',"0: Picard's fixed point, 1: Newton's method, 2: hybrid"))
+		string="%s\n%s"%(string,fielddisplay(self,'maxiter','maximum number of nonlinear iterations'))
+		string="%s\n%s"%(string,fielddisplay(self,'viscosity_overshoot','over-shooting constant new=new+C*(new-old)'))
+
+		string="%s\n%s"%(string,'\n      boundary conditions:')
+		string="%s\n%s"%(string,fielddisplay(self,'spcvx','x-axis velocity constraint (NaN means no constraint) [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'spcvy','y-axis velocity constraint (NaN means no constraint) [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'spcvz','z-axis velocity constraint (NaN means no constraint) [m/yr]'))
+		string="%s\n%s"%(string,fielddisplay(self,'icefront','segments on ice front list (last column 0: Air, 1: Water, 2: Ice'))
+
+		string="%s\n%s"%(string,'\n      Rift options:')
+		string="%s\n%s"%(string,fielddisplay(self,'rift_penalty_threshold','threshold for instability of mechanical constraints'))
+		string="%s\n%s"%(string,fielddisplay(self,'rift_penalty_lock','number of iterations before rift penalties are locked'))
+
+		string="%s\n%s"%(string,'\n      Penalty options:')
+		string="%s\n%s"%(string,fielddisplay(self,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset'))
+		string="%s\n%s"%(string,fielddisplay(self,'vertex_pairing','pairs of vertices that are penalized'))
+
+		string="%s\n%s"%(string,'\n      Other:')
+		string="%s\n%s"%(string,fielddisplay(self,'shelf_dampening','use dampening for floating ice ? Only for FS model'))
+		string="%s\n%s"%(string,fielddisplay(self,'FSreconditioning','multiplier for incompressibility equation. Only for FS model'))
+		string="%s\n%s"%(string,fielddisplay(self,'referential','local referential'))
+		string="%s\n%s"%(string,fielddisplay(self,'loadingforce','loading force applied on each point [N/m^3]'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
+
+		return string
+		#}}}
+	def setdefaultparameters(self): # {{{
+		#maximum of non-linear iterations.
+		self.maxiter=100
+
+		#Convergence criterion: absolute, relative and residual
+		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
+		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))
+		self.viscosity_overshoot=0
+
+		#Stop the iterations of rift if below a threshold
+		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.
+		self.rift_penalty_lock=10
+
+		return self
+	#}}}
+	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return
+		if StressbalanceAnalysisEnum() not in analyses:
+			return md
+
+		md = checkfield(md,'stressbalance.spcvx','forcing',1)
+		md = checkfield(md,'stressbalance.spcvy','forcing',1)
+		if md.mesh.dimension==3:
+			md = checkfield(md,'stressbalance.spcvz','forcing',1)
+		md = checkfield(md,'stressbalance.restol','size',[1],'>',0)
+		md = checkfield(md,'stressbalance.reltol','size',[1])
+		md = checkfield(md,'stressbalance.abstol','size',[1])
+		md = checkfield(md,'stressbalance.isnewton','numel',[1],'values',[0,1,2])
+		md = checkfield(md,'stressbalance.FSreconditioning','size',[1],'NaN',1)
+		md = checkfield(md,'stressbalance.viscosity_overshoot','size',[1],'NaN',1)
+		md = checkfield(md,'stressbalance.maxiter','size',[1],'>=',1)
+		md = checkfield(md,'stressbalance.referential','size',[md.mesh.numberofvertices,6])
+		md = checkfield(md,'stressbalance.loadingforce','size',[md.mesh.numberofvertices,3])
+		if not md.stressbalance.requested_outputs:
+			md = checkfield(md,'stressbalance.requested_outputs','size',[float('NaN'),1])
+
+		#singular solution
+#		if ~any((~isnan(md.stressbalance.spcvx)+~isnan(md.stressbalance.spcvy))==2),
+		if not numpy.any(numpy.logical_and(numpy.logical_not(numpy.isnan(md.stressbalance.spcvx)),numpy.logical_not(numpy.isnan(md.stressbalance.spcvy)))):
+			md.checkmessage("model is not well posed (singular). You need at least one node with fixed velocity!")
+		#CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
+#		if any(sum(isnan(md.stressbalance.referential),2)~=0 & sum(isnan(md.stressbalance.referential),2)~=6),
+		if numpy.any(numpy.logical_and(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)!=0,numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)!=6)):
+			md.checkmessage("Each line of stressbalance.referential should contain either only NaN values or no NaN values")
+		#CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
+#		if any(sum(isnan(md.stressbalance.referential),2)==0),
+		if numpy.any(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)==0):
+			pos=[i for i,item in enumerate(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)) if item==0]
+#			numpy.inner (and numpy.dot) calculate all the dot product permutations, resulting in a full matrix multiply
+#			if numpy.any(numpy.abs(numpy.inner(md.stressbalance.referential[pos,0:2],md.stressbalance.referential[pos,3:5]).diagonal())>sys.float_info.epsilon):
+#				md.checkmessage("Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
+			for item in md.stressbalance.referential[pos,:]:
+				if numpy.abs(numpy.inner(item[0:2],item[3:5]))>sys.float_info.epsilon:
+					md.checkmessage("Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
+		#CHECK THAT NO rotation specified for FS Grounded ice at base
+#		if md.mesh.dimension==3 & md.flowequation.isFS,
+		if md.mesh.dimension==3 and md.flowequation.isFS:
+			pos=numpy.nonzero(numpy.logical_and(md.mask.groundedice_levelset,md.mesh.vertexonbed))
+			if numpy.any(numpy.logical_not(numpy.isnan(md.stressbalance.referential[pos,:]))):
+				md.checkmessage("no referential should be specified for basal vertices of grounded ice")
+
+		return md
+	# }}}
+	def marshall(self,md,fid):    # {{{
+
+		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','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','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','vertex_pairing','format','DoubleMat','mattype',3)
+		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,'object',self,'class','stressbalance','fieldname','requested_outputs','format','DoubleMat','mattype',3)
+		WriteData(fid,'data',self.loadingforce[:,0],'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum())
+		WriteData(fid,'data',self.loadingforce[:,1],'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum())
+		WriteData(fid,'data',self.loadingforce[:,2],'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum())
+	# }}}
Index: /issm/trunk/src/m/classes/surfaceforcings.m
===================================================================
--- /issm/trunk/src/m/classes/surfaceforcings.m	(revision 16136)
+++ /issm/trunk/src/m/classes/surfaceforcings.m	(revision 16137)
@@ -44,5 +44,5 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-			if ismember(PrognosticAnalysisEnum(),analyses),
+			if ismember(MasstransportAnalysisEnum(),analyses),
 				md = checkfield(md,'surfaceforcings.ispdd','numel',[1],'values',[0 1]);
 				md = checkfield(md,'surfaceforcings.issmbgradients','numel',[1],'values',[0 1]);
Index: /issm/trunk/src/m/classes/surfaceforcings.py
===================================================================
--- /issm/trunk/src/m/classes/surfaceforcings.py	(revision 16136)
+++ /issm/trunk/src/m/classes/surfaceforcings.py	(revision 16137)
@@ -72,5 +72,5 @@
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
-		if PrognosticAnalysisEnum() in analyses:
+		if MasstransportAnalysisEnum() in analyses:
 			md = checkfield(md,'surfaceforcings.ispdd','numel',[1],'values',[0,1])
 			md = checkfield(md,'surfaceforcings.issmbgradients','numel',[1],'values',[0,1])
Index: /issm/trunk/src/m/classes/taoinversion.m
===================================================================
--- /issm/trunk/src/m/classes/taoinversion.m	(revision 16136)
+++ /issm/trunk/src/m/classes/taoinversion.m	(revision 16137)
@@ -117,4 +117,6 @@
 		function marshall(obj,md,fid) % {{{
 
+			yts=365.0*24.0*3600.0;
+
 			WriteData(fid,'object',obj,'class','inversion','fieldname','iscontrol','format','Boolean');
 			WriteData(fid,'enum',InversionTaoEnum(),'data',true,'format','Boolean');
@@ -125,7 +127,7 @@
 			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);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1);
-			WriteData(fid,'object',obj,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1);
+			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);
 
Index: /issm/trunk/src/m/classes/thermal.m
===================================================================
--- /issm/trunk/src/m/classes/thermal.m	(revision 16136)
+++ /issm/trunk/src/m/classes/thermal.m	(revision 16137)
@@ -13,4 +13,5 @@
 		penalty_factor    = 0;
 		isenthalpy        = 0;
+        	isdynamicbasalspc = 0;
 	end
 	methods
@@ -39,4 +40,7 @@
 			%Should we use cold ice (default) or enthalpy formulation
 			obj.isenthalpy=0;
+            
+            		%will basal boundary conditions be set dynamically
+            		obj.isdynamicbasalspc=0;
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -52,4 +56,5 @@
 				md = checkfield(md,'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,'thermal.isenthalpy','numel',[1],'values',[0 1]);
+                		md = checkfield(md,'thermal.isdynamicbasalspc','numel',[1],'values',[0 1]);
 			end
 		end % }}}
@@ -63,5 +68,6 @@
 			fielddisplay(obj,'penalty_threshold','threshold to declare convergence of thermal solution (default is 0)');
 			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)']);
+            
 		end % }}}
 		function marshall(obj,md,fid) % {{{
@@ -73,5 +79,6 @@
 			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
 			WriteData(fid,'object',obj,'fieldname','isenthalpy','format','Boolean');
-		end % }}}
+            		WriteData(fid,'object',obj,'fieldname','isdynamicbasalspc','format','Boolean');
+        	end % }}}
 	end
 end
Index: /issm/trunk/src/m/classes/toolkits.m
===================================================================
--- /issm/trunk/src/m/classes/toolkits.m	(revision 16136)
+++ /issm/trunk/src/m/classes/toolkits.m	(revision 16137)
@@ -22,6 +22,6 @@
 		 function obj = addoptions(obj,analysis,varargin) % {{{
 		 % Usage example:
-		 %    md.toolkits=addoptions(md.toolkits,DiagnosticHorizAnalysisEnum(),stokesoptions());
-		 %    md.toolkits=addoptions(md.toolkits,DiagnosticHorizAnalysisEnum());
+		 %    md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum(),FSoptions());
+		 %    md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum());
 
 			 %Convert analysis from enum to string
@@ -40,7 +40,7 @@
 
 			 %default toolkits: 
-			 if ispetsc,
+			 if IssmConfig('_HAVE_PETSC_'),
 				 %MUMPS is the default toolkits
-				 if ismumps(),
+				 if IssmConfig('_HAVE_MUMPS_'),
 					 obj.DefaultAnalysis           = mumpsoptions();
 				 else
Index: /issm/trunk/src/m/classes/toolkits.py
===================================================================
--- /issm/trunk/src/m/classes/toolkits.py	(revision 16136)
+++ /issm/trunk/src/m/classes/toolkits.py	(revision 16137)
@@ -1,4 +1,3 @@
-from ismumps import *
-from ispetsc import *
+from IssmConfig import IssmConfig
 from mumpsoptions import *
 from iluasmoptions import *
@@ -19,7 +18,7 @@
 	def __init__(self):    # {{{
 		#default toolkits
-		if ispetsc():
+		if IssmConfig('_HAVE_PETSC_')[0]:
 			#MUMPS is the default toolkits
-			if ismumps():
+			if IssmConfig('_HAVE_MUMPS_')[0]:
 				self.DefaultAnalysis           = mumpsoptions()
 			else:
@@ -39,6 +38,6 @@
 	def addoptions(self,analysis,*args):    # {{{
 		# Usage example:
-		#    md.toolkits=addoptions(md.toolkits,DiagnosticHorizAnalysisEnum(),stokesoptions());
-		#    md.toolkits=addoptions(md.toolkits,DiagnosticHorizAnalysisEnum());
+		#    md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum(),FSoptions());
+		#    md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum());
 
 		#Convert analysis from enum to string
Index: /issm/trunk/src/m/classes/transient.m
===================================================================
--- /issm/trunk/src/m/classes/transient.m	(revision 16136)
+++ /issm/trunk/src/m/classes/transient.m	(revision 16137)
@@ -6,6 +6,6 @@
 classdef transient
 	properties (SetAccess=public) 
-		isprognostic      = 0;
-		isdiagnostic      = 0;
+		ismasstransport      = 0;
+		isstressbalance      = 0;
 		isthermal         = 0;
 		isgroundingline   = 0;
@@ -24,7 +24,7 @@
 		function obj = setdefaultparameters(obj) % {{{
 
-			%full analysis: Diagnostic, Prognostic and Thermal but no groundingline migration for now
-			obj.isprognostic=1;
-			obj.isdiagnostic=1;
+			%full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
+			obj.ismasstransport=1;
+			obj.isstressbalance=1;
 			obj.isthermal=1;
 			obj.isgroundingline=0;
@@ -37,6 +37,6 @@
 			if solution~=TransientSolutionEnum(), return; end
 
-			md = checkfield(md,'transient.isprognostic','numel',[1],'values',[0 1]);
-			md = checkfield(md,'transient.isdiagnostic','numel',[1],'values',[0 1]);
+			md = checkfield(md,'transient.ismasstransport','numel',[1],'values',[0 1]);
+			md = checkfield(md,'transient.isstressbalance','numel',[1],'values',[0 1]);
 			md = checkfield(md,'transient.isthermal','numel',[1],'values',[0 1]);
 			md = checkfield(md,'transient.isgroundingline','numel',[1],'values',[0 1]);
@@ -48,6 +48,6 @@
 			disp(sprintf('   transient solution parameters:'));
 
-			fielddisplay(obj,'isprognostic','indicates if a prognostic solution is used in the transient');
-			fielddisplay(obj,'isdiagnostic','indicates if a diagnostic solution is used in the transient');
+			fielddisplay(obj,'ismasstransport','indicates if a masstransport solution is used in the transient');
+			fielddisplay(obj,'isstressbalance','indicates if a stressbalance solution is used in the transient');
 			fielddisplay(obj,'isthermal','indicates if a thermal solution is used in the transient');
 			fielddisplay(obj,'isgroundingline','indicates if a groundingline migration is used in the transient');
@@ -57,6 +57,6 @@
 		end % }}}
 		function marshall(obj,md,fid) % {{{
-			WriteData(fid,'object',obj,'fieldname','isprognostic','format','Boolean');
-			WriteData(fid,'object',obj,'fieldname','isdiagnostic','format','Boolean');
+			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');
Index: /issm/trunk/src/m/classes/transient.py
===================================================================
--- /issm/trunk/src/m/classes/transient.py	(revision 16136)
+++ /issm/trunk/src/m/classes/transient.py	(revision 16137)
@@ -13,6 +13,6 @@
 
 	def __init__(self): # {{{
-		self.isprognostic      = False
-		self.isdiagnostic      = False
+		self.ismasstransport      = False
+		self.isstressbalance      = False
 		self.isthermal         = False
 		self.isgroundingline   = False
@@ -26,6 +26,6 @@
 	def __repr__(self): # {{{
 		string='   transient solution parameters:'
-		string="%s\n%s"%(string,fielddisplay(self,'isprognostic','indicates if a prognostic solution is used in the transient'))
-		string="%s\n%s"%(string,fielddisplay(self,'isdiagnostic','indicates if a diagnostic solution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'ismasstransport','indicates if a masstransport solution is used in the transient'))
+		string="%s\n%s"%(string,fielddisplay(self,'isstressbalance','indicates if a stressbalance solution is used in the transient'))
 		string="%s\n%s"%(string,fielddisplay(self,'isthermal','indicates if a thermal solution is used in the transient'))
 		string="%s\n%s"%(string,fielddisplay(self,'isgroundingline','indicates if a groundingline migration is used in the transient'))
@@ -36,7 +36,7 @@
 	def setdefaultparameters(self): # {{{
 		
-		#full analysis: Diagnostic, Prognostic and Thermal but no groundingline migration for now
-		self.isprognostic=True
-		self.isdiagnostic=True
+		#full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
+		self.ismasstransport=True
+		self.isstressbalance=True
 		self.isthermal=True
 		self.isgroundingline=False
@@ -51,6 +51,6 @@
 			return md
 
-		md = checkfield(md,'transient.isprognostic','numel',[1],'values',[0,1])
-		md = checkfield(md,'transient.isdiagnostic','numel',[1],'values',[0,1])
+		md = checkfield(md,'transient.ismasstransport','numel',[1],'values',[0,1])
+		md = checkfield(md,'transient.isstressbalance','numel',[1],'values',[0,1])
 		md = checkfield(md,'transient.isthermal','numel',[1],'values',[0,1])
 		md = checkfield(md,'transient.isgroundingline','numel',[1],'values',[0,1])
@@ -62,6 +62,6 @@
 	# }}}
 	def marshall(self,md,fid):    # {{{
-		WriteData(fid,'object',self,'fieldname','isprognostic','format','Boolean')
-		WriteData(fid,'object',self,'fieldname','isdiagnostic','format','Boolean')
+		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')
Index: /issm/trunk/src/m/classes/verbose.m
===================================================================
--- /issm/trunk/src/m/classes/verbose.m	(revision 16136)
+++ /issm/trunk/src/m/classes/verbose.m	(revision 16137)
@@ -14,4 +14,5 @@
 %      verbose=verbose();
 %      verbose=verbose(3);
+%      verbose=verbose('all');
 %      verbose=verbose('001100');
 %      verbose=verbose('module',true,'solver',false);
Index: /issm/trunk/src/m/consistency/checkfield.m
===================================================================
--- /issm/trunk/src/m/consistency/checkfield.m	(revision 16136)
+++ /issm/trunk/src/m/consistency/checkfield.m	(revision 16137)
@@ -23,6 +23,4 @@
 %   Example:
 %      md = checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
-%      md = checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
-%      md = checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
 
 %get options
Index: /issm/trunk/src/m/consistency/checkfield.py
===================================================================
--- /issm/trunk/src/m/consistency/checkfield.py	(revision 16136)
+++ /issm/trunk/src/m/consistency/checkfield.py	(revision 16137)
@@ -29,6 +29,4 @@
 	   Example:
 	      md = checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
-	      md = checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
-	      md = checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
 	"""
 
Index: /issm/trunk/src/m/consistency/comparemodels.m
===================================================================
--- /issm/trunk/src/m/consistency/comparemodels.m	(revision 16137)
+++ /issm/trunk/src/m/consistency/comparemodels.m	(revision 16137)
@@ -0,0 +1,33 @@
+function comparemodels(md1,md2);
+
+	%loop over model fields
+	model_fields=fields(md1);
+	for i=1:length(model_fields),
+		field1=md1.(model_fields{i});
+		field2=md2.(model_fields{i});
+		if isobject(field1), %recursive call
+			object_fields=fields(md1.(model_fields{i}));
+			for j=1:length(object_fields),
+				field1=md1.(model_fields{i}).(object_fields{j});
+				field2=md2.(model_fields{i}).(object_fields{j});
+				compare([model_fields{i} '.' object_fields{j}],field1,field2);
+			end
+		else
+			compare(model_fields{i},field1,field2);
+		end
+	end
+
+end
+
+function compare(fieldname,field1,field2),
+	if any(size(field1)~=size(field2)),
+		disp([fieldname ' do not have the same size']);
+	elseif isnumeric(field1),
+		if numel(field1)==1 & isnan(field1) & isnan(field2),
+			%Do not do anything
+		elseif any(field1~=field2),
+			disp([fieldname ' differs']);
+		end
+	end
+
+end
Index: /issm/trunk/src/m/consistency/ismodelselfconsistent.m
===================================================================
--- /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 16136)
+++ /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 16137)
@@ -45,11 +45,11 @@
 switch solutiontype,
 
-	case DiagnosticSolutionEnum(),
+	case StressbalanceSolutionEnum(),
 		numanalyses=5;
-		analyses=[DiagnosticHorizAnalysisEnum();DiagnosticVertAnalysisEnum();DiagnosticHutterAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum()];
+		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum()];
 
 	case SteadystateSolutionEnum(),
 		numanalyses=7; 
-		analyses=[DiagnosticHorizAnalysisEnum();DiagnosticVertAnalysisEnum();DiagnosticHutterAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum()];
+		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum()];
 
 	case ThermalSolutionEnum(),
@@ -61,7 +61,7 @@
 		analyses=[EnthalpyAnalysisEnum()];
 
-	case PrognosticSolutionEnum(),
+	case MasstransportSolutionEnum(),
 		numanalyses=1; 
-		analyses=[PrognosticAnalysisEnum()];
+		analyses=[MasstransportAnalysisEnum()];
 
 	case BalancethicknessSolutionEnum(),
@@ -72,4 +72,8 @@
 		numanalyses=1; 
 		analyses=[BalancethicknessAnalysisEnum()];
+
+	case BalancevelocitySolutionEnum(),
+		numanalyses=1; 
+		analyses=[BalancevelocityAnalysisEnum()];
 
 	case SurfaceSlopeSolutionEnum(),
@@ -87,5 +91,5 @@
 	case TransientSolutionEnum(),
 		numanalyses=9; 
-		analyses=[DiagnosticHorizAnalysisEnum();DiagnosticVertAnalysisEnum();DiagnosticHutterAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum();EnthalpyAnalysisEnum();PrognosticAnalysisEnum()];
+		analyses=[StressbalanceAnalysisEnum();StressbalanceVerticalAnalysisEnum();StressbalanceSIAAnalysisEnum();SurfaceSlopeAnalysisEnum();BedSlopeAnalysisEnum();ThermalAnalysisEnum();MeltingAnalysisEnum();EnthalpyAnalysisEnum();MasstransportAnalysisEnum()];
 
 	case FlaimSolutionEnum(),
Index: /issm/trunk/src/m/consistency/ismodelselfconsistent.py
===================================================================
--- /issm/trunk/src/m/consistency/ismodelselfconsistent.py	(revision 16136)
+++ /issm/trunk/src/m/consistency/ismodelselfconsistent.py	(revision 16137)
@@ -10,11 +10,11 @@
 	"""
 
-	if   solutiontype == DiagnosticSolutionEnum():
+	if   solutiontype == StressbalanceSolutionEnum():
 		numanalyses=5
-		analyses=[DiagnosticHorizAnalysisEnum(),DiagnosticVertAnalysisEnum(),DiagnosticHutterAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum()]
+		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum()]
 
 	elif solutiontype == SteadystateSolutionEnum():
 		numanalyses=7 
-		analyses=[DiagnosticHorizAnalysisEnum(),DiagnosticVertAnalysisEnum(),DiagnosticHutterAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]
+		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]
 
 	elif solutiontype == ThermalSolutionEnum():
@@ -26,7 +26,7 @@
 		analyses=[EnthalpyAnalysisEnum()]
 
-	elif solutiontype == PrognosticSolutionEnum():
+	elif solutiontype == MasstransportSolutionEnum():
 		numanalyses=1 
-		analyses=[PrognosticAnalysisEnum()]
+		analyses=[MasstransportAnalysisEnum()]
 
 	elif solutiontype == BalancethicknessSolutionEnum():
@@ -37,4 +37,8 @@
 		numanalyses=1 
 		analyses=[SurfaceSlopeAnalysisEnum()]
+
+	elif solutiontype == BalancevelocitySolutionEnum():
+		numanalyses=1 
+		analyses=[BalancevelocityAnalysisEnum()]
 
 	elif solutiontype == BedSlopeSolutionEnum():
@@ -48,5 +52,5 @@
 	elif solutiontype == TransientSolutionEnum():
 		numanalyses=9 
-		analyses=[DiagnosticHorizAnalysisEnum(),DiagnosticVertAnalysisEnum(),DiagnosticHutterAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum(),EnthalpyAnalysisEnum(),PrognosticAnalysisEnum()]
+		analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),SurfaceSlopeAnalysisEnum(),BedSlopeAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum(),EnthalpyAnalysisEnum(),MasstransportAnalysisEnum()]
 
 	elif solutiontype == FlaimSolutionEnum():
Index: /issm/trunk/src/m/contrib/bamg/BamgCall.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/BamgCall.m	(revision 16136)
+++ /issm/trunk/src/m/contrib/bamg/BamgCall.m	(revision 16137)
@@ -25,10 +25,5 @@
 %Compute metric
 t1=clock; fprintf('%s','      computing metric...');
-if length(md.nodeonwater)==md.mesh.numberofvertices,
-	pos=find(md.nodeonwater);
-else
-	pos=[];
-end
-metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,[]);
 t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
 
Index: /issm/trunk/src/m/contrib/bamg/YamsCall.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/YamsCall.m	(revision 16136)
+++ /issm/trunk/src/m/contrib/bamg/YamsCall.m	(revision 16137)
@@ -25,10 +25,5 @@
 %Compute metric
 t1=clock; fprintf('%s','      computing metric...');
-if length(md.mask.vertexonwater)==md.mesh.numberofvertices,
-	pos=find(md.mask.vertexonwater);
-else
-	pos=[];
-end
-metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,[]);
 t2=clock;fprintf('%s\n',[' done (' num2str(etime(t2,t1)) ' seconds)']);
 
Index: /issm/trunk/src/m/contrib/bamg/YamsCall.py
===================================================================
--- /issm/trunk/src/m/contrib/bamg/YamsCall.py	(revision 16136)
+++ /issm/trunk/src/m/contrib/bamg/YamsCall.py	(revision 16137)
@@ -38,9 +38,5 @@
 	t1=time.time()
 	print "%s" % '      computing metric...'
-	if numpy.size(md.mask.vertexonwater)==md.mesh.numberofvertices:
-		pos=numpy.nonzero(md.mask.vertexonwater)[0]
-	else:
-		pos=numpy.empty(0,int)
-	metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos)
+	metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,numpy.empty(0,int))
 	t2=time.time()
 	print "%s%d%s\n" % (' done (',t2-t1,' seconds)')
Index: /issm/trunk/src/m/contrib/bamg/yams.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/yams.m	(revision 16136)
+++ /issm/trunk/src/m/contrib/bamg/yams.m	(revision 16137)
@@ -79,13 +79,4 @@
 	field=sqrt(vx_obs.^2+vy_obs.^2);
 
-	%set mask.vertexonwater  field
-	if ~strcmp(groundeddomain,'N/A'),
-		nodeground=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,groundeddomain,'node',2);
-		md.mask.vertexonwater=ones(md.mesh.numberofvertices,1);
-		md.mask.vertexonwater(find(nodeground))=0;
-	else
-		md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
-	end
-
 	%adapt according to velocities
 	disp('   adapting...');
@@ -119,11 +110,4 @@
 md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
 md.mesh.elementonsurface=ones(md.mesh.numberofelements,1);
-if ~strcmp(groundeddomain,'N/A'),
-	nodeground=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,groundeddomain,'node',2);
-	md.mask.vertexonwater=ones(md.mesh.numberofvertices,1);
-	md.mask.vertexonwater(find(nodeground))=0;
-else
-	md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
-end
 if strcmpi(Names.interp,'node'),
 	md.inversion.vx_obs=InterpFromGridToMesh(Vel.(Names.xname),Vel.(Names.yname),Vel.(Names.vxname),md.mesh.x,md.mesh.y,0);
Index: /issm/trunk/src/m/contrib/ecco/MeltingGroundingLines.m
===================================================================
--- /issm/trunk/src/m/contrib/ecco/MeltingGroundingLines.m	(revision 16136)
+++ /issm/trunk/src/m/contrib/ecco/MeltingGroundingLines.m	(revision 16137)
@@ -7,5 +7,5 @@
 
 %get nodes on ice sheet and on ice shelf
-pos_shelf=find(~md.mask.vertexongroundedice);
+pos_shelf=find(md.mask.groundedice_levelset<0.);
 pos_GL=intersect(unique(md.mesh.elements(find(md.mask.elementongroundedice),:)),unique(md.mesh.elements(find(md.mask.elementonfloatingice),:)));
 
Index: /issm/trunk/src/m/contrib/gslib/pkriging.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/pkriging.m	(revision 16136)
+++ /issm/trunk/src/m/contrib/gslib/pkriging.m	(revision 16137)
@@ -38,6 +38,6 @@
 
 %Call waitonlock
-md=model; md.cluster=cluster; md.settings.waitonlock=Inf;
-waitonlock(md)
+md=model; md.cluster=cluster; md.settings.waitonlock=Inf; md.private.runtimename=name;md.miscellaneous.name=name;
+waitonlock(md);
 
 %Download
Index: /issm/trunk/src/m/contrib/hack/sia.m
===================================================================
--- /issm/trunk/src/m/contrib/hack/sia.m	(revision 16136)
+++ /issm/trunk/src/m/contrib/hack/sia.m	(revision 16137)
@@ -2,5 +2,5 @@
 %BALVEL - computation of Shallow Ice velocities
 %
-%   This routine uses the model of Hutter to compute the velocities
+%   This routine uses the model of SIA to compute the velocities
 %   of a 2d model using the surface slope
 %
Index: /issm/trunk/src/m/contrib/hack/tres.m
===================================================================
--- /issm/trunk/src/m/contrib/hack/tres.m	(revision 16136)
+++ /issm/trunk/src/m/contrib/hack/tres.m	(revision 16137)
@@ -4,25 +4,25 @@
 %    Usage: md=tres(md,string)
 %
-%    Example: md=tres(md,'diagnostic');
+%    Example: md=tres(md,'stressbalance');
 
 %check number of arguments
 
-if strcmpi(string,'diagnostic'),
+if strcmpi(string,'stressbalance'),
 	if md.mesh.dimension==2,
-		md.initialization.vx=md.results.DiagnosticSolution.Vx;
-		md.initialization.vy=md.results.DiagnosticSolution.Vy;
+		md.initialization.vx=md.results.StressbalanceSolution.Vx;
+		md.initialization.vy=md.results.StressbalanceSolution.Vy;
 	else 
-		md.initialization.vx=md.results.DiagnosticSolution.Vx;
-		md.initialization.vy=md.results.DiagnosticSolution.Vy;
-		md.initialization.vz=md.results.DiagnosticSolution.Vz;
+		md.initialization.vx=md.results.StressbalanceSolution.Vx;
+		md.initialization.vy=md.results.StressbalanceSolution.Vy;
+		md.initialization.vz=md.results.StressbalanceSolution.Vz;
 	end
-	md.initialization.vel=md.results.DiagnosticSolution.Vel;
+	md.initialization.vel=md.results.StressbalanceSolution.Vel;
 
-	if isfield(md.results.DiagnosticSolution,'Pressure'),
-		md.initialization.pressure=md.results.DiagnosticSolution.Pressure;
+	if isfield(md.results.StressbalanceSolution,'Pressure'),
+		md.initialization.pressure=md.results.StressbalanceSolution.Pressure;
 	end
 	if ~isempty(md.rifts.riftstruct),
-		if isfield(md.results.DiagnosticSolution,'riftproperties'),
-			md.rifts.riftproperties=md.results.DiagnosticSolution.riftproperties;
+		if isfield(md.results.StressbalanceSolution,'riftproperties'),
+			md.rifts.riftproperties=md.results.StressbalanceSolution.riftproperties;
 		end
 	end
Index: /issm/trunk/src/m/contrib/massbalance/contourmassbalance.m
===================================================================
--- /issm/trunk/src/m/contrib/massbalance/contourmassbalance.m	(revision 16136)
+++ /issm/trunk/src/m/contrib/massbalance/contourmassbalance.m	(revision 16137)
@@ -19,5 +19,5 @@
 %Get segments enveloping contour
 segments=contourenvelope(md,file);
-%md.diagnostic.icefront=segments; plotmodel(md,'data','pressureload','expdisp',file);
+%md.stressbalance.icefront=segments; plotmodel(md,'data','pressureload','expdisp',file);
 
 %get flag list of elements and nodes inside the contour
Index: /issm/trunk/src/m/contrib/paraview/exportVTK.m
===================================================================
--- /issm/trunk/src/m/contrib/paraview/exportVTK.m	(revision 16137)
+++ /issm/trunk/src/m/contrib/paraview/exportVTK.m	(revision 16137)
@@ -0,0 +1,129 @@
+function exportVTK(filename,model,Solution)
+% vtk export
+% function exportVTK(filename,model,Solution)
+% creates a directory with the vtk files for you simulation
+% (only work for triangle and wedges based on their number of nodes)
+% and additional cell data
+%
+% input: filename   destination 
+%                   (string)
+%------------------------------------------------------------------
+%        model      this is md 
+%------------------------------------------------------------------
+%        Solution   Put on the enum of the solution you want 
+%	                  to plot         
+% Basile de Fleurian:
+
+[path,name,ext]=fileparts(filename);
+separator=filesep;
+mkdir(filename);
+
+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);
+sol_enum=EnumToString(Solution);
+
+sol_struct=model.results.(sol_enum);
+
+%Select the type of element function of the number of nodes per elements
+if point_per_elt==3;
+	celltype=5; %triangles
+elseif point_per_elt==6;
+	celltype=13; %wedges
+else
+	error('Your Element definition is not taken into account \n');
+end
+
+%looking for multiple time steps
+num_of_timesteps=size(sol_struct,2);
+
+%getting the number of fields in the solution
+fieldnames=fields(sol_struct(1));
+num_of_fields=length(fieldnames);
+
+if num_of_timesteps==1; %just one timestep only write one file
+
+	FID = fopen(strcat(path,filesep,name,filesep,name,'.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*(point_per_elt+1));
+	s='%d';
+	for k=1:point_per_elt
+    s=horzcat(s,{' %d'});
+  end
+	s=cell2mat(horzcat(s,{'\n'}));
+	fprintf(FID,s,[(point_per_elt)*ones(num_of_elt,1) model.mesh.elements-1]');
+
+	fprintf(FID,'CELL_TYPES %d\n',num_of_elt);
+	s='%d\n';
+	fprintf(FID,s,celltype*ones(num_of_elt,1));
+
+	%check which field is a real result and print	
+	fprintf(FID,'POINT_DATA %s \n',num2str(num_of_points));
+	for j=1:num_of_fields
+
+		if (length(sol_struct(1).(fieldnames{j}))==num_of_points);
+			fprintf(FID,'SCALARS %s float 1 \n',fieldnames{j});
+			fprintf(FID,'LOOKUP_TABLE default\n');
+			s='%e\n';
+			fprintf(FID,s,sol_struct.(fieldnames{j}));
+	  end
+  end
+		fclose(FID);
+else
+	for i=1:num_of_timesteps;
+		timestep=sol_struct(i).step;
+		FID = fopen(strcat(path,filesep,name,filesep,name,'.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*(point_per_elt+1));
+		s='%d';
+		for k=1:point_per_elt
+			s=horzcat(s,{' %d'});
+  	end
+		s=cell2mat(horzcat(s,{'\n'}));
+		fprintf(FID,s,[(point_per_elt)*ones(num_of_elt,1) model.mesh.elements-1]');
+
+		fprintf(FID,'CELL_TYPES %d\n',num_of_elt);
+		s='%d\n';
+		fprintf(FID,s,celltype*ones(num_of_elt,1));
+
+		%check which field is a real result and print
+		fprintf(FID,'POINT_DATA %s \n',num2str(num_of_points));
+		for j=1:num_of_fields
+
+			if (length(sol_struct(1).(fieldnames{j}))==num_of_points);
+				fprintf(FID,'SCALARS %s float 1 \n',fieldnames{j});
+				fprintf(FID,'LOOKUP_TABLE default\n');
+				s='%e\n';
+				fprintf(FID,s,sol_struct(i).(fieldnames{j}));
+	    end		
+    end 
+		fclose(FID);
+  end
+end
Index: sm/trunk/src/m/contrib/paraview/writeVTKcell.m
===================================================================
--- /issm/trunk/src/m/contrib/paraview/writeVTKcell.m	(revision 16136)
+++ 	(revision )
@@ -1,122 +1,0 @@
-function writeVTKcell(filename,model,Solution)
-% vtk export
-% function writeVTKcell(filename,model,Solution)
-% creates a vtk-file filename.vtk containing simplicial mesh data
-% (only work for triangle now)
-% and additional cell data
-%
-% input: filename   destination 
-%                   (string)
-%------------------------------------------------------------------
-%        model      this is md 
-%------------------------------------------------------------------
-%        Solution   Put on the enum of the solution you want 
-%	                  to plot         
-% Basile de Fleurian, modified from:
-% (c) Daniel Peterseim, 2009-11-07
-
-[path,name,ext]=fileparts(filename);
-separator=filesep;
-mkdir(filename);
-
-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);
-sol_enum=EnumToString(Solution);
-
-sol_struct=model.results.(sol_enum);
-
-%Select the type of element function of the number of nodes per elements
-if point_per_elt==3;
-	celltype=5; %triangles
-elseif point_per_elt==6;
-	celltype=13; %wedges
-else
-	error('Your Element definition is not taken into account \n');
-end
-
-%looking for multiple time steps
-num_of_timesteps=size(sol_struct,2);
-
-%getting the number of fields in the solution
-fieldnames=fields(sol_struct(1));
-num_of_fields=length(fieldnames);
-
-if num_of_timesteps==1; %just one timestep only write one file
-
-	FID = fopen(strcat(path,filesep,name,filesep,name,'.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);
-	s='%f %f %f \n';
-	P=[points zeros(num_of_points,3-dim)];
-	fprintf(FID,s,P');
-
-	fprintf(FID,'CELLS %d %d\n',num_of_elt,num_of_elt*(point_per_elt+1));
-	s='%d';
-	for k=1:point_per_elt
-    s=horzcat(s,{' %d'});
-  end
-	s=cell2mat(horzcat(s,{'\n'}));
-	fprintf(FID,s,[(point_per_elt)*ones(num_of_elt,1) model.mesh.elements-1]');
-
-	fprintf(FID,'CELL_TYPES %d\n',num_of_elt);
-	s='%d\n';
-	fprintf(FID,s,celltype*ones(num_of_elt,1));
-
-	%check which field is a real result and print	
-	fprintf(FID,'POINT_DATA %s \n',num2str(num_of_points));
-	for j=1:num_of_fields
-
-		if (length(sol_struct(1).(fieldnames{j}))==num_of_points);
-			fprintf(FID,'SCALARS %s float 1 \n',fieldnames{j});
-			fprintf(FID,'LOOKUP_TABLE default\n');
-			s='%e\n';
-			fprintf(FID,s,sol_struct.(fieldnames{j}));
-	  end
-  end
-		fclose(FID);
-else
-	for i=1:num_of_timesteps;
-		timestep=sol_struct(i).step;
-		FID = fopen(strcat(path,filesep,name,filesep,name,'.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);
-		s='%f %f %f \n';
-		P=[points zeros(num_of_points,3-dim)];
-		fprintf(FID,s,P');
-
-		fprintf(FID,'CELLS %d %d\n',num_of_elt,num_of_elt*(point_per_elt+1));
-		s='%d';
-		for k=1:point_per_elt
-			s=horzcat(s,{' %d'});
-  	end
-		s=cell2mat(horzcat(s,{'\n'}));
-		fprintf(FID,s,[(point_per_elt)*ones(num_of_elt,1) model.mesh.elements-1]');
-
-		fprintf(FID,'CELL_TYPES %d\n',num_of_elt);
-		s='%d\n';
-		fprintf(FID,s,celltype*ones(num_of_elt,1));
-
-		%check which field is a real result and print
-		fprintf(FID,'POINT_DATA %s \n',num2str(num_of_points));
-		for j=1:num_of_fields
-
-			if (length(sol_struct(1).(fieldnames{j}))==num_of_points);
-				fprintf(FID,'SCALARS %s float 1 \n',fieldnames{j});
-				fprintf(FID,'LOOKUP_TABLE default\n');
-				s='%e\n';
-				fprintf(FID,s,sol_struct(i).(fieldnames{j}));
-	    end		
-    end 
-		fclose(FID);
-  end
-end
Index: /issm/trunk/src/m/coordsystems/lambert2xy.m
===================================================================
--- /issm/trunk/src/m/coordsystems/lambert2xy.m	(revision 16136)
+++ /issm/trunk/src/m/coordsystems/lambert2xy.m	(revision 16137)
@@ -67,3 +67,2 @@
 	y=(B/D)*((cos(b0)*sin(b))-(sin(b0)*cos(b)*cos(lam-lam0)));
 end
-
Index: /issm/trunk/src/m/coordsystems/xy2lambert.m
===================================================================
--- /issm/trunk/src/m/coordsystems/xy2lambert.m	(revision 16136)
+++ /issm/trunk/src/m/coordsystems/xy2lambert.m	(revision 16137)
@@ -67,3 +67,2 @@
 	lon=lon_rad*180/pi;
 end
-
Index: /issm/trunk/src/m/coordsystems/xy2ll.py
===================================================================
--- /issm/trunk/src/m/coordsystems/xy2ll.py	(revision 16137)
+++ /issm/trunk/src/m/coordsystems/xy2ll.py	(revision 16137)
@@ -0,0 +1,82 @@
+import numpy as npy
+from math import pi
+
+def xy2ll(x, y, sgn, *args):
+	'''
+	XY2LL - converts xy to lat long
+	
+	Converts Polar  Stereographic (X, Y) coordinates for the polar regions to
+	latitude and longitude Stereographic (X, Y) coordinates for the polar
+	regions.
+	Author: Michael P. Schodlok, December 2003 (map2xy.m)
+	
+	Usage:
+	   [lat, lon] = xy2ll(x, y, sgn);
+	   [lat, lon] = xy2ll(x, y, sgn, central_meridian, standard_parallel);
+	
+	   - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
+	                            -1 : south latitude (default is mer=0  lat=71)
+	'''
+
+	#Get central_meridian and standard_parallel depending on hemisphere
+	if len(args) == 2:
+		delta = args[0]
+		slat  = args[1]
+	elif len(args) == 0:
+		if sgn == 1:
+			delta = 45 
+			slat = 70
+			print 'Warning: expecting coordinates in polar stereographic (Std Latitude: 70degN Meridian: 45deg)'
+		elif sgn == -1:
+			delta = 0  
+			slat = 71
+			print 'Warning: expecting coordinates in polar stereographic (Std Latitude: 71degS Meridian: 0deg)'
+		else:
+			raise ValueError('sgn should be either +1 or -1')
+	else:
+		raise StandardError('bad usage: type "help(xy2ll)" for details')
+
+	# if x,y passed as lists, convert to numpy arrays
+	if type(x) != "numpy.ndarray":
+		x=npy.array(x)
+	if type(y) != "numpy.ndarray":
+		y=npy.array(y)
+
+	## Conversion constant from degrees to radians
+	cde = 57.29577951
+	## Radius of the earth in meters
+	re = 6378.273*10**3
+	## Eccentricity of the Hughes ellipsoid squared
+	ex2 = .006693883
+	## Eccentricity of the Hughes ellipsoid
+	ex = npy.sqrt(ex2)
+	
+	sl = slat*pi/180.
+	rho = npy.sqrt(x**2 + y**2)
+	cm = npy.cos(sl) / npy.sqrt(1.0 - ex2 * (npy.sin(sl)**2))
+	T = npy.tan((pi/4.0) - (sl/2.0)) / ((1.0 - ex*npy.sin(sl)) / (1.0 + ex*npy.sin(sl)))**(ex / 2.0)
+	
+	if abs(slat-90.) < 1.e-5:
+		T = rho*npy.sqrt((1. + ex)**(1. + ex) * (1. - ex)**(1. - ex)) / 2. / re
+	else:
+		T = rho * T / (re * cm)
+	
+	chi = (pi / 2.0) - 2.0 * npy.arctan(T)
+	lat = chi + ((ex2 / 2.0) + (5.0 * ex2**2.0 / 24.0) + (ex2**3.0 / 12.0)) * \
+		npy.sin(2 * chi) + ((7.0 * ex2**2.0 / 48.0) + (29.0 * ex2**3 / 240.0)) * \
+		npy.sin(4.0 * chi) + (7.0 * ex2**3.0 / 120.0) * npy.sin(6.0 * chi) 
+	
+	lat = sgn * lat
+	lon = npy.arctan2(sgn * x,-sgn * y)
+	lon = sgn * lon
+	
+	res1 = npy.nonzero(rho <= 0.1)
+	if len(res1[0] > 0):
+		lat[res1] = 90. * sgn
+		lon[res1] = 0.0
+	
+	lon = lon * 180. / pi
+	lat = lat * 180. / pi
+	lon = lon - delta 
+
+	return lat, lon
Index: /issm/trunk/src/m/dev/devpath.m
===================================================================
--- /issm/trunk/src/m/dev/devpath.m	(revision 16137)
+++ /issm/trunk/src/m/dev/devpath.m	(revision 16137)
@@ -0,0 +1,40 @@
+% clear the last warning to focus on the warnings of the ISSM path
+lastwarn(''); 
+
+%Recover ISSM_DIR , or if on a Windows machine, ISSM_DIR_WIN
+if ~ispc,
+	ISSM_DIR=getenv('ISSM_DIR');
+else
+	ISSM_DIR=getenv('ISSM_DIR_WIN');
+end
+if (isempty(ISSM_DIR)),
+	error('''ISSM_DIR'' environment variable is empty! You should define ISSM_DIR 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_DIR in this file, in case it is not correctly setup. 
+
+%ISSM path
+addpath([ISSM_DIR '/src/m/os/']); %load recursivepath
+addpath([ISSM_DIR '/lib']);       %load mex
+addpath(recursivepath([ISSM_DIR '/src/m']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/scotch']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/canos']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/kml']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/export_fig']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/googleearthtoolbox']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/howatmask']));
+addpath(recursivepath([ISSM_DIR '/externalpackages/dem']));
+clear ISSM_DIR;
+
+%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_DIR variable in your .cshrc or .bashrc!\n');
+	fprintf('  ''ISSM'' will not  work at all until this is resolved\n\n');
+else
+	fprintf('\n  ISSM development path correctly loaded\n\n');
+end
+
+%disable matlab bell!
+beep off;
Index: /issm/trunk/src/m/dev/devpath.py
===================================================================
--- /issm/trunk/src/m/dev/devpath.py	(revision 16137)
+++ /issm/trunk/src/m/dev/devpath.py	(revision 16137)
@@ -0,0 +1,26 @@
+#!/usr/bin/env python
+
+import os,sys
+
+#Recover ISSM_DIR and USERNAME
+ISSM_DIR=os.getenv('ISSM_DIR')
+USERNAME =os.getenv('USER')
+if(ISSM_DIR==None):
+	raise NameError('"ISSM_DIR" environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!')
+
+#Go through src/m and append any directory that contains a *.py file to PATH 
+for root,dirs,files in os.walk(ISSM_DIR+ '/src/m'):
+	if '.svn' in dirs:
+		dirs.remove('.svn')
+	for file in files:
+		if file.find(".py") != -1:
+			if file.find(".pyc") == -1:
+				if root not in sys.path:
+					sys.path.append(root)
+				
+sys.path.append(ISSM_DIR + '/lib')
+
+#Manual imports for commonly used functions
+from plotmodel import plotmodel
+
+print("\n  ISSM development path correctly loaded\n\n")
Index: /issm/trunk/src/m/enum/BalancevelocityAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancevelocityAnalysisEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/BalancevelocityAnalysisEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=BalancevelocityAnalysisEnum()
+%BALANCEVELOCITYANALYSISENUM - Enum of BalancevelocityAnalysis
+%
+%   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=BalancevelocityAnalysisEnum()
+
+macro=StringToEnum('BalancevelocityAnalysis');
Index: /issm/trunk/src/m/enum/BalancevelocitySolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/BalancevelocitySolutionEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/BalancevelocitySolutionEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=BalancevelocitySolutionEnum()
+%BALANCEVELOCITYSOLUTIONENUM - Enum of BalancevelocitySolution
+%
+%   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=BalancevelocitySolutionEnum()
+
+macro=StringToEnum('BalancevelocitySolution');
Index: sm/trunk/src/m/enum/DiagnosticAbstolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticAbstolEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticAbstolEnum()
-%DIAGNOSTICABSTOLENUM - Enum of DiagnosticAbstol
-%
-%   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=DiagnosticAbstolEnum()
-
-macro=StringToEnum('DiagnosticAbstol');
Index: sm/trunk/src/m/enum/DiagnosticHorizAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticHorizAnalysisEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticHorizAnalysisEnum()
-%DIAGNOSTICHORIZANALYSISENUM - Enum of DiagnosticHorizAnalysis
-%
-%   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=DiagnosticHorizAnalysisEnum()
-
-macro=StringToEnum('DiagnosticHorizAnalysis');
Index: sm/trunk/src/m/enum/DiagnosticHutterAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticHutterAnalysisEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticHutterAnalysisEnum()
-%DIAGNOSTICHUTTERANALYSISENUM - Enum of DiagnosticHutterAnalysis
-%
-%   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=DiagnosticHutterAnalysisEnum()
-
-macro=StringToEnum('DiagnosticHutterAnalysis');
Index: sm/trunk/src/m/enum/DiagnosticIcefrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticIcefrontEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticIcefrontEnum()
-%DIAGNOSTICICEFRONTENUM - Enum of DiagnosticIcefront
-%
-%   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=DiagnosticIcefrontEnum()
-
-macro=StringToEnum('DiagnosticIcefront');
Index: sm/trunk/src/m/enum/DiagnosticIsnewtonEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticIsnewtonEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticIsnewtonEnum()
-%DIAGNOSTICISNEWTONENUM - Enum of DiagnosticIsnewton
-%
-%   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=DiagnosticIsnewtonEnum()
-
-macro=StringToEnum('DiagnosticIsnewton');
Index: sm/trunk/src/m/enum/DiagnosticMaxiterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticMaxiterEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticMaxiterEnum()
-%DIAGNOSTICMAXITERENUM - Enum of DiagnosticMaxiter
-%
-%   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=DiagnosticMaxiterEnum()
-
-macro=StringToEnum('DiagnosticMaxiter');
Index: sm/trunk/src/m/enum/DiagnosticNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticNumRequestedOutputsEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticNumRequestedOutputsEnum()
-%DIAGNOSTICNUMREQUESTEDOUTPUTSENUM - Enum of DiagnosticNumRequestedOutputs
-%
-%   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=DiagnosticNumRequestedOutputsEnum()
-
-macro=StringToEnum('DiagnosticNumRequestedOutputs');
Index: sm/trunk/src/m/enum/DiagnosticPenaltyFactorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticPenaltyFactorEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticPenaltyFactorEnum()
-%DIAGNOSTICPENALTYFACTORENUM - Enum of DiagnosticPenaltyFactor
-%
-%   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=DiagnosticPenaltyFactorEnum()
-
-macro=StringToEnum('DiagnosticPenaltyFactor');
Index: sm/trunk/src/m/enum/DiagnosticReferentialEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticReferentialEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticReferentialEnum()
-%DIAGNOSTICREFERENTIALENUM - Enum of DiagnosticReferential
-%
-%   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=DiagnosticReferentialEnum()
-
-macro=StringToEnum('DiagnosticReferential');
Index: sm/trunk/src/m/enum/DiagnosticReltolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticReltolEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticReltolEnum()
-%DIAGNOSTICRELTOLENUM - Enum of DiagnosticReltol
-%
-%   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=DiagnosticReltolEnum()
-
-macro=StringToEnum('DiagnosticReltol');
Index: sm/trunk/src/m/enum/DiagnosticRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticRequestedOutputsEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticRequestedOutputsEnum()
-%DIAGNOSTICREQUESTEDOUTPUTSENUM - Enum of DiagnosticRequestedOutputs
-%
-%   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=DiagnosticRequestedOutputsEnum()
-
-macro=StringToEnum('DiagnosticRequestedOutputs');
Index: sm/trunk/src/m/enum/DiagnosticRestolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticRestolEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticRestolEnum()
-%DIAGNOSTICRESTOLENUM - Enum of DiagnosticRestol
-%
-%   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=DiagnosticRestolEnum()
-
-macro=StringToEnum('DiagnosticRestol');
Index: sm/trunk/src/m/enum/DiagnosticRiftPenaltyLockEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticRiftPenaltyLockEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticRiftPenaltyLockEnum()
-%DIAGNOSTICRIFTPENALTYLOCKENUM - Enum of DiagnosticRiftPenaltyLock
-%
-%   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=DiagnosticRiftPenaltyLockEnum()
-
-macro=StringToEnum('DiagnosticRiftPenaltyLock');
Index: sm/trunk/src/m/enum/DiagnosticRiftPenaltyThresholdEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticRiftPenaltyThresholdEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticRiftPenaltyThresholdEnum()
-%DIAGNOSTICRIFTPENALTYTHRESHOLDENUM - Enum of DiagnosticRiftPenaltyThreshold
-%
-%   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=DiagnosticRiftPenaltyThresholdEnum()
-
-macro=StringToEnum('DiagnosticRiftPenaltyThreshold');
Index: sm/trunk/src/m/enum/DiagnosticShelfDampeningEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticShelfDampeningEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticShelfDampeningEnum()
-%DIAGNOSTICSHELFDAMPENINGENUM - Enum of DiagnosticShelfDampening
-%
-%   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=DiagnosticShelfDampeningEnum()
-
-macro=StringToEnum('DiagnosticShelfDampening');
Index: sm/trunk/src/m/enum/DiagnosticSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticSolutionEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticSolutionEnum()
-%DIAGNOSTICSOLUTIONENUM - Enum of DiagnosticSolution
-%
-%   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=DiagnosticSolutionEnum()
-
-macro=StringToEnum('DiagnosticSolution');
Index: sm/trunk/src/m/enum/DiagnosticSpcvxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticSpcvxEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticSpcvxEnum()
-%DIAGNOSTICSPCVXENUM - Enum of DiagnosticSpcvx
-%
-%   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=DiagnosticSpcvxEnum()
-
-macro=StringToEnum('DiagnosticSpcvx');
Index: sm/trunk/src/m/enum/DiagnosticSpcvyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticSpcvyEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticSpcvyEnum()
-%DIAGNOSTICSPCVYENUM - Enum of DiagnosticSpcvy
-%
-%   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=DiagnosticSpcvyEnum()
-
-macro=StringToEnum('DiagnosticSpcvy');
Index: sm/trunk/src/m/enum/DiagnosticSpcvzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticSpcvzEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticSpcvzEnum()
-%DIAGNOSTICSPCVZENUM - Enum of DiagnosticSpcvz
-%
-%   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=DiagnosticSpcvzEnum()
-
-macro=StringToEnum('DiagnosticSpcvz');
Index: sm/trunk/src/m/enum/DiagnosticStokesreconditioningEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticStokesreconditioningEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticStokesreconditioningEnum()
-%DIAGNOSTICSTOKESRECONDITIONINGENUM - Enum of DiagnosticStokesreconditioning
-%
-%   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=DiagnosticStokesreconditioningEnum()
-
-macro=StringToEnum('DiagnosticStokesreconditioning');
Index: sm/trunk/src/m/enum/DiagnosticVertAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticVertAnalysisEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticVertAnalysisEnum()
-%DIAGNOSTICVERTANALYSISENUM - Enum of DiagnosticVertAnalysis
-%
-%   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=DiagnosticVertAnalysisEnum()
-
-macro=StringToEnum('DiagnosticVertAnalysis');
Index: sm/trunk/src/m/enum/DiagnosticVertexPairingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticVertexPairingEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticVertexPairingEnum()
-%DIAGNOSTICVERTEXPAIRINGENUM - Enum of DiagnosticVertexPairing
-%
-%   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=DiagnosticVertexPairingEnum()
-
-macro=StringToEnum('DiagnosticVertexPairing');
Index: sm/trunk/src/m/enum/DiagnosticViscosityOvershootEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DiagnosticViscosityOvershootEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=DiagnosticViscosityOvershootEnum()
-%DIAGNOSTICVISCOSITYOVERSHOOTENUM - Enum of DiagnosticViscosityOvershoot
-%
-%   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=DiagnosticViscosityOvershootEnum()
-
-macro=StringToEnum('DiagnosticViscosityOvershoot');
Index: /issm/trunk/src/m/enum/EnumDefinitions.py
===================================================================
--- /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 16136)
+++ /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 16137)
@@ -3,7862 +3,584 @@
 """
 
-   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
+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
 
 """
 
-def AutodiffIsautodiffEnum():
-	"""
-	AUTODIFFISAUTODIFFENUM - Enum of AutodiffIsautodiff
-
-	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=AutodiffIsautodiffEnum()
-	"""
-
-	return StringToEnum('AutodiffIsautodiff')[0]
-
-def AutodiffNumDependentsEnum():
-	"""
-	AUTODIFFNUMDEPENDENTSENUM - Enum of AutodiffNumDependents
-
-	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=AutodiffNumDependentsEnum()
-	"""
-
-	return StringToEnum('AutodiffNumDependents')[0]
-
-def AutodiffNumDependentObjectsEnum():
-	"""
-	AUTODIFFNUMDEPENDENTOBJECTSENUM - Enum of AutodiffNumDependentObjects
-
-	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=AutodiffNumDependentObjectsEnum()
-	"""
-
-	return StringToEnum('AutodiffNumDependentObjects')[0]
-
-def AutodiffDependentObjectNamesEnum():
-	"""
-	AUTODIFFDEPENDENTOBJECTNAMESENUM - Enum of AutodiffDependentObjectNames
-
-	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=AutodiffDependentObjectNamesEnum()
-	"""
-
-	return StringToEnum('AutodiffDependentObjectNames')[0]
-
-def AutodiffDependentObjectTypesEnum():
-	"""
-	AUTODIFFDEPENDENTOBJECTTYPESENUM - Enum of AutodiffDependentObjectTypes
-
-	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=AutodiffDependentObjectTypesEnum()
-	"""
-
-	return StringToEnum('AutodiffDependentObjectTypes')[0]
-
-def AutodiffDependentObjectIndicesEnum():
-	"""
-	AUTODIFFDEPENDENTOBJECTINDICESENUM - Enum of AutodiffDependentObjectIndices
-
-	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=AutodiffDependentObjectIndicesEnum()
-	"""
-
-	return StringToEnum('AutodiffDependentObjectIndices')[0]
-
-def AutodiffDependentObjectsEnum():
-	"""
-	AUTODIFFDEPENDENTOBJECTSENUM - Enum of AutodiffDependentObjects
-
-	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=AutodiffDependentObjectsEnum()
-	"""
-
-	return StringToEnum('AutodiffDependentObjects')[0]
-
-def AutodiffNumIndependentsEnum():
-	"""
-	AUTODIFFNUMINDEPENDENTSENUM - Enum of AutodiffNumIndependents
-
-	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=AutodiffNumIndependentsEnum()
-	"""
-
-	return StringToEnum('AutodiffNumIndependents')[0]
-
-def AutodiffNumIndependentObjectsEnum():
-	"""
-	AUTODIFFNUMINDEPENDENTOBJECTSENUM - Enum of AutodiffNumIndependentObjects
-
-	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=AutodiffNumIndependentObjectsEnum()
-	"""
-
-	return StringToEnum('AutodiffNumIndependentObjects')[0]
-
-def AutodiffIndependentObjectNamesEnum():
-	"""
-	AUTODIFFINDEPENDENTOBJECTNAMESENUM - Enum of AutodiffIndependentObjectNames
-
-	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=AutodiffIndependentObjectNamesEnum()
-	"""
-
-	return StringToEnum('AutodiffIndependentObjectNames')[0]
-
-def AutodiffIndependentObjectTypesEnum():
-	"""
-	AUTODIFFINDEPENDENTOBJECTTYPESENUM - Enum of AutodiffIndependentObjectTypes
-
-	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=AutodiffIndependentObjectTypesEnum()
-	"""
-
-	return StringToEnum('AutodiffIndependentObjectTypes')[0]
-
-def AutodiffIndependentObjectsEnum():
-	"""
-	AUTODIFFINDEPENDENTOBJECTSENUM - Enum of AutodiffIndependentObjects
-
-	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=AutodiffIndependentObjectsEnum()
-	"""
-
-	return StringToEnum('AutodiffIndependentObjects')[0]
-
-def AutodiffJacobianEnum():
-	"""
-	AUTODIFFJACOBIANENUM - Enum of AutodiffJacobian
-
-	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=AutodiffJacobianEnum()
-	"""
-
-	return StringToEnum('AutodiffJacobian')[0]
-
-def AutodiffXpEnum():
-	"""
-	AUTODIFFXPENUM - Enum of AutodiffXp
-
-	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=AutodiffXpEnum()
-	"""
-
-	return StringToEnum('AutodiffXp')[0]
-
-def AutodiffDriverEnum():
-	"""
-	AUTODIFFDRIVERENUM - Enum of AutodiffDriver
-
-	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=AutodiffDriverEnum()
-	"""
-
-	return StringToEnum('AutodiffDriver')[0]
-
-def AutodiffFosForwardIndexEnum():
-	"""
-	AUTODIFFFOSFORWARDINDEXENUM - Enum of AutodiffFosForwardIndex
-
-	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=AutodiffFosForwardIndexEnum()
-	"""
-
-	return StringToEnum('AutodiffFosForwardIndex')[0]
-
-def AutodiffFovForwardIndicesEnum():
-	"""
-	AUTODIFFFOVFORWARDINDICESENUM - Enum of AutodiffFovForwardIndices
-
-	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=AutodiffFovForwardIndicesEnum()
-	"""
-
-	return StringToEnum('AutodiffFovForwardIndices')[0]
-
-def AutodiffFosReverseIndexEnum():
-	"""
-	AUTODIFFFOSREVERSEINDEXENUM - Enum of AutodiffFosReverseIndex
-
-	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=AutodiffFosReverseIndexEnum()
-	"""
-
-	return StringToEnum('AutodiffFosReverseIndex')[0]
-
-def AutodiffMassFluxSegmentsPresentEnum():
-	"""
-	AUTODIFFMASSFLUXSEGMENTSPRESENTENUM - Enum of AutodiffMassFluxSegmentsPresent
-
-	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=AutodiffMassFluxSegmentsPresentEnum()
-	"""
-
-	return StringToEnum('AutodiffMassFluxSegmentsPresent')[0]
-
-def AutodiffKeepEnum():
-	"""
-	AUTODIFFKEEPENUM - Enum of AutodiffKeep
-
-	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=AutodiffKeepEnum()
-	"""
-
-	return StringToEnum('AutodiffKeep')[0]
-
-def BalancethicknessSpcthicknessEnum():
-	"""
-	BALANCETHICKNESSSPCTHICKNESSENUM - Enum of BalancethicknessSpcthickness
-
-	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=BalancethicknessSpcthicknessEnum()
-	"""
-
-	return StringToEnum('BalancethicknessSpcthickness')[0]
-
-def BalancethicknessStabilizationEnum():
-	"""
-	BALANCETHICKNESSSTABILIZATIONENUM - Enum of BalancethicknessStabilization
-
-	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=BalancethicknessStabilizationEnum()
-	"""
-
-	return StringToEnum('BalancethicknessStabilization')[0]
-
-def BalancethicknessThickeningRateEnum():
-	"""
-	BALANCETHICKNESSTHICKENINGRATEENUM - Enum of BalancethicknessThickeningRate
-
-	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=BalancethicknessThickeningRateEnum()
-	"""
-
-	return StringToEnum('BalancethicknessThickeningRate')[0]
-
-def BasalforcingsGeothermalfluxEnum():
-	"""
-	BASALFORCINGSGEOTHERMALFLUXENUM - Enum of BasalforcingsGeothermalflux
-
-	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=BasalforcingsGeothermalfluxEnum()
-	"""
-
-	return StringToEnum('BasalforcingsGeothermalflux')[0]
-
-def BasalforcingsMeltingRateCorrectionEnum():
-	"""
-	BASALFORCINGSMELTINGRATECORRECTIONENUM - Enum of BasalforcingsMeltingRateCorrection
-
-	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=BasalforcingsMeltingRateCorrectionEnum()
-	"""
-
-	return StringToEnum('BasalforcingsMeltingRateCorrection')[0]
-
-def BasalforcingsMeltingRateEnum():
-	"""
-	BASALFORCINGSMELTINGRATEENUM - Enum of BasalforcingsMeltingRate
-
-	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=BasalforcingsMeltingRateEnum()
-	"""
-
-	return StringToEnum('BasalforcingsMeltingRate')[0]
-
-def BathymetryEnum():
-	"""
-	BATHYMETRYENUM - Enum of Bathymetry
-
-	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=BathymetryEnum()
-	"""
-
-	return StringToEnum('Bathymetry')[0]
-
-def BedEnum():
-	"""
-	BEDENUM - Enum of Bed
-
-	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=BedEnum()
-	"""
-
-	return StringToEnum('Bed')[0]
-
-def ConstantsGEnum():
-	"""
-	CONSTANTSGENUM - Enum of ConstantsG
-
-	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=ConstantsGEnum()
-	"""
-
-	return StringToEnum('ConstantsG')[0]
-
-def ConstantsReferencetemperatureEnum():
-	"""
-	CONSTANTSREFERENCETEMPERATUREENUM - Enum of ConstantsReferencetemperature
-
-	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=ConstantsReferencetemperatureEnum()
-	"""
-
-	return StringToEnum('ConstantsReferencetemperature')[0]
-
-def ConstantsYtsEnum():
-	"""
-	CONSTANTSYTSENUM - Enum of ConstantsYts
-
-	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=ConstantsYtsEnum()
-	"""
-
-	return StringToEnum('ConstantsYts')[0]
-
-def DependentObjectEnum():
-	"""
-	DEPENDENTOBJECTENUM - Enum of DependentObject
-
-	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=DependentObjectEnum()
-	"""
-
-	return StringToEnum('DependentObject')[0]
-
-def DiagnosticAbstolEnum():
-	"""
-	DIAGNOSTICABSTOLENUM - Enum of DiagnosticAbstol
-
-	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=DiagnosticAbstolEnum()
-	"""
-
-	return StringToEnum('DiagnosticAbstol')[0]
-
-def DiagnosticIcefrontEnum():
-	"""
-	DIAGNOSTICICEFRONTENUM - Enum of DiagnosticIcefront
-
-	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=DiagnosticIcefrontEnum()
-	"""
-
-	return StringToEnum('DiagnosticIcefront')[0]
-
-def DiagnosticIsnewtonEnum():
-	"""
-	DIAGNOSTICISNEWTONENUM - Enum of DiagnosticIsnewton
-
-	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=DiagnosticIsnewtonEnum()
-	"""
-
-	return StringToEnum('DiagnosticIsnewton')[0]
-
-def DiagnosticMaxiterEnum():
-	"""
-	DIAGNOSTICMAXITERENUM - Enum of DiagnosticMaxiter
-
-	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=DiagnosticMaxiterEnum()
-	"""
-
-	return StringToEnum('DiagnosticMaxiter')[0]
-
-def DiagnosticNumRequestedOutputsEnum():
-	"""
-	DIAGNOSTICNUMREQUESTEDOUTPUTSENUM - Enum of DiagnosticNumRequestedOutputs
-
-	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=DiagnosticNumRequestedOutputsEnum()
-	"""
-
-	return StringToEnum('DiagnosticNumRequestedOutputs')[0]
-
-def DiagnosticPenaltyFactorEnum():
-	"""
-	DIAGNOSTICPENALTYFACTORENUM - Enum of DiagnosticPenaltyFactor
-
-	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=DiagnosticPenaltyFactorEnum()
-	"""
-
-	return StringToEnum('DiagnosticPenaltyFactor')[0]
-
-def DiagnosticReferentialEnum():
-	"""
-	DIAGNOSTICREFERENTIALENUM - Enum of DiagnosticReferential
-
-	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=DiagnosticReferentialEnum()
-	"""
-
-	return StringToEnum('DiagnosticReferential')[0]
-
-def DiagnosticReltolEnum():
-	"""
-	DIAGNOSTICRELTOLENUM - Enum of DiagnosticReltol
-
-	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=DiagnosticReltolEnum()
-	"""
-
-	return StringToEnum('DiagnosticReltol')[0]
-
-def DiagnosticRequestedOutputsEnum():
-	"""
-	DIAGNOSTICREQUESTEDOUTPUTSENUM - Enum of DiagnosticRequestedOutputs
-
-	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=DiagnosticRequestedOutputsEnum()
-	"""
-
-	return StringToEnum('DiagnosticRequestedOutputs')[0]
-
-def DiagnosticRestolEnum():
-	"""
-	DIAGNOSTICRESTOLENUM - Enum of DiagnosticRestol
-
-	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=DiagnosticRestolEnum()
-	"""
-
-	return StringToEnum('DiagnosticRestol')[0]
-
-def DiagnosticRiftPenaltyLockEnum():
-	"""
-	DIAGNOSTICRIFTPENALTYLOCKENUM - Enum of DiagnosticRiftPenaltyLock
-
-	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=DiagnosticRiftPenaltyLockEnum()
-	"""
-
-	return StringToEnum('DiagnosticRiftPenaltyLock')[0]
-
-def DiagnosticRiftPenaltyThresholdEnum():
-	"""
-	DIAGNOSTICRIFTPENALTYTHRESHOLDENUM - Enum of DiagnosticRiftPenaltyThreshold
-
-	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=DiagnosticRiftPenaltyThresholdEnum()
-	"""
-
-	return StringToEnum('DiagnosticRiftPenaltyThreshold')[0]
-
-def DiagnosticShelfDampeningEnum():
-	"""
-	DIAGNOSTICSHELFDAMPENINGENUM - Enum of DiagnosticShelfDampening
-
-	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=DiagnosticShelfDampeningEnum()
-	"""
-
-	return StringToEnum('DiagnosticShelfDampening')[0]
-
-def DiagnosticSpcvxEnum():
-	"""
-	DIAGNOSTICSPCVXENUM - Enum of DiagnosticSpcvx
-
-	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=DiagnosticSpcvxEnum()
-	"""
-
-	return StringToEnum('DiagnosticSpcvx')[0]
-
-def DiagnosticSpcvyEnum():
-	"""
-	DIAGNOSTICSPCVYENUM - Enum of DiagnosticSpcvy
-
-	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=DiagnosticSpcvyEnum()
-	"""
-
-	return StringToEnum('DiagnosticSpcvy')[0]
-
-def DiagnosticSpcvzEnum():
-	"""
-	DIAGNOSTICSPCVZENUM - Enum of DiagnosticSpcvz
-
-	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=DiagnosticSpcvzEnum()
-	"""
-
-	return StringToEnum('DiagnosticSpcvz')[0]
-
-def DiagnosticStokesreconditioningEnum():
-	"""
-	DIAGNOSTICSTOKESRECONDITIONINGENUM - Enum of DiagnosticStokesreconditioning
-
-	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=DiagnosticStokesreconditioningEnum()
-	"""
-
-	return StringToEnum('DiagnosticStokesreconditioning')[0]
-
-def DiagnosticVertexPairingEnum():
-	"""
-	DIAGNOSTICVERTEXPAIRINGENUM - Enum of DiagnosticVertexPairing
-
-	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=DiagnosticVertexPairingEnum()
-	"""
-
-	return StringToEnum('DiagnosticVertexPairing')[0]
-
-def DiagnosticViscosityOvershootEnum():
-	"""
-	DIAGNOSTICVISCOSITYOVERSHOOTENUM - Enum of DiagnosticViscosityOvershoot
-
-	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=DiagnosticViscosityOvershootEnum()
-	"""
-
-	return StringToEnum('DiagnosticViscosityOvershoot')[0]
-
-def LoadingforceXEnum():
-	"""
-	LOADINGFORCEXENUM - Enum of LoadingforceX
-
-	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=LoadingforceXEnum()
-	"""
-
-	return StringToEnum('LoadingforceX')[0]
-
-def LoadingforceYEnum():
-	"""
-	LOADINGFORCEYENUM - Enum of LoadingforceY
-
-	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=LoadingforceYEnum()
-	"""
-
-	return StringToEnum('LoadingforceY')[0]
-
-def LoadingforceZEnum():
-	"""
-	LOADINGFORCEZENUM - Enum of LoadingforceZ
-
-	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=LoadingforceZEnum()
-	"""
-
-	return StringToEnum('LoadingforceZ')[0]
-
-def FlowequationBordermacayealEnum():
-	"""
-	FLOWEQUATIONBORDERMACAYEALENUM - Enum of FlowequationBordermacayeal
-
-	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=FlowequationBordermacayealEnum()
-	"""
-
-	return StringToEnum('FlowequationBordermacayeal')[0]
-
-def FlowequationBorderpattynEnum():
-	"""
-	FLOWEQUATIONBORDERPATTYNENUM - Enum of FlowequationBorderpattyn
-
-	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=FlowequationBorderpattynEnum()
-	"""
-
-	return StringToEnum('FlowequationBorderpattyn')[0]
-
-def FlowequationBorderstokesEnum():
-	"""
-	FLOWEQUATIONBORDERSTOKESENUM - Enum of FlowequationBorderstokes
-
-	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=FlowequationBorderstokesEnum()
-	"""
-
-	return StringToEnum('FlowequationBorderstokes')[0]
-
-def FlowequationElementEquationEnum():
-	"""
-	FLOWEQUATIONELEMENTEQUATIONENUM - Enum of FlowequationElementEquation
-
-	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=FlowequationElementEquationEnum()
-	"""
-
-	return StringToEnum('FlowequationElementEquation')[0]
-
-def FlowequationIshutterEnum():
-	"""
-	FLOWEQUATIONISHUTTERENUM - Enum of FlowequationIshutter
-
-	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=FlowequationIshutterEnum()
-	"""
-
-	return StringToEnum('FlowequationIshutter')[0]
-
-def FlowequationIsl1l2Enum():
-	"""
-	FLOWEQUATIONISL1L2ENUM - Enum of FlowequationIsl1l2
-
-	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=FlowequationIsl1l2Enum()
-	"""
-
-	return StringToEnum('FlowequationIsl1l2')[0]
-
-def FlowequationIsmacayealpattynEnum():
-	"""
-	FLOWEQUATIONISMACAYEALPATTYNENUM - Enum of FlowequationIsmacayealpattyn
-
-	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=FlowequationIsmacayealpattynEnum()
-	"""
-
-	return StringToEnum('FlowequationIsmacayealpattyn')[0]
-
-def FlowequationIsstokesEnum():
-	"""
-	FLOWEQUATIONISSTOKESENUM - Enum of FlowequationIsstokes
-
-	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=FlowequationIsstokesEnum()
-	"""
-
-	return StringToEnum('FlowequationIsstokes')[0]
-
-def FlowequationVertexEquationEnum():
-	"""
-	FLOWEQUATIONVERTEXEQUATIONENUM - Enum of FlowequationVertexEquation
-
-	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=FlowequationVertexEquationEnum()
-	"""
-
-	return StringToEnum('FlowequationVertexEquation')[0]
-
-def FrictionCoefficientEnum():
-	"""
-	FRICTIONCOEFFICIENTENUM - Enum of FrictionCoefficient
-
-	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=FrictionCoefficientEnum()
-	"""
-
-	return StringToEnum('FrictionCoefficient')[0]
-
-def FrictionPEnum():
-	"""
-	FRICTIONPENUM - Enum of FrictionP
-
-	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=FrictionPEnum()
-	"""
-
-	return StringToEnum('FrictionP')[0]
-
-def FrictionQEnum():
-	"""
-	FRICTIONQENUM - Enum of FrictionQ
-
-	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=FrictionQEnum()
-	"""
-
-	return StringToEnum('FrictionQ')[0]
-
-def GeometryHydrostaticRatioEnum():
-	"""
-	GEOMETRYHYDROSTATICRATIOENUM - Enum of GeometryHydrostaticRatio
-
-	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=GeometryHydrostaticRatioEnum()
-	"""
-
-	return StringToEnum('GeometryHydrostaticRatio')[0]
-
-def HydrologyModelEnum():
-	"""
-	HYDROLOGYMODELENUM - Enum of HydrologyModel
-
-	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=HydrologyModelEnum()
-	"""
-
-	return StringToEnum('HydrologyModel')[0]
-
-def HydrologyshreveEnum():
-	"""
-	HYDROLOGYSHREVEENUM - Enum of Hydrologyshreve
-
-	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=HydrologyshreveEnum()
-	"""
-
-	return StringToEnum('Hydrologyshreve')[0]
-
-def HydrologyshreveCREnum():
-	"""
-	HYDROLOGYSHREVECRENUM - Enum of HydrologyshreveCR
-
-	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=HydrologyshreveCREnum()
-	"""
-
-	return StringToEnum('HydrologyshreveCR')[0]
-
-def HydrologyshreveKnEnum():
-	"""
-	HYDROLOGYSHREVEKNENUM - Enum of HydrologyshreveKn
-
-	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=HydrologyshreveKnEnum()
-	"""
-
-	return StringToEnum('HydrologyshreveKn')[0]
-
-def HydrologyshreveNEnum():
-	"""
-	HYDROLOGYSHREVENENUM - Enum of HydrologyshreveN
-
-	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=HydrologyshreveNEnum()
-	"""
-
-	return StringToEnum('HydrologyshreveN')[0]
-
-def HydrologyshrevePEnum():
-	"""
-	HYDROLOGYSHREVEPENUM - Enum of HydrologyshreveP
-
-	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=HydrologyshrevePEnum()
-	"""
-
-	return StringToEnum('HydrologyshreveP')[0]
-
-def HydrologyshreveQEnum():
-	"""
-	HYDROLOGYSHREVEQENUM - Enum of HydrologyshreveQ
-
-	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=HydrologyshreveQEnum()
-	"""
-
-	return StringToEnum('HydrologyshreveQ')[0]
-
-def HydrologyshreveSpcwatercolumnEnum():
-	"""
-	HYDROLOGYSHREVESPCWATERCOLUMNENUM - Enum of HydrologyshreveSpcwatercolumn
-
-	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=HydrologyshreveSpcwatercolumnEnum()
-	"""
-
-	return StringToEnum('HydrologyshreveSpcwatercolumn')[0]
-
-def HydrologyshreveStabilizationEnum():
-	"""
-	HYDROLOGYSHREVESTABILIZATIONENUM - Enum of HydrologyshreveStabilization
-
-	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=HydrologyshreveStabilizationEnum()
-	"""
-
-	return StringToEnum('HydrologyshreveStabilization')[0]
-
-def HydrologydcEnum():
-	"""
-	HYDROLOGYDCENUM - Enum of Hydrologydc
-
-	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=HydrologydcEnum()
-	"""
-
-	return StringToEnum('Hydrologydc')[0]
-
-def SedimentHeadEnum():
-	"""
-	SEDIMENTHEADENUM - Enum of SedimentHead
-
-	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=SedimentHeadEnum()
-	"""
-
-	return StringToEnum('SedimentHead')[0]
-
-def SedimentHeadOldEnum():
-	"""
-	SEDIMENTHEADOLDENUM - Enum of SedimentHeadOld
-
-	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=SedimentHeadOldEnum()
-	"""
-
-	return StringToEnum('SedimentHeadOld')[0]
-
-def SedimentHeadResidualEnum():
-	"""
-	SEDIMENTHEADRESIDUALENUM - Enum of SedimentHeadResidual
-
-	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=SedimentHeadResidualEnum()
-	"""
-
-	return StringToEnum('SedimentHeadResidual')[0]
-
-def EplHeadEnum():
-	"""
-	EPLHEADENUM - Enum of EplHead
-
-	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=EplHeadEnum()
-	"""
-
-	return StringToEnum('EplHead')[0]
-
-def EplHeadOldEnum():
-	"""
-	EPLHEADOLDENUM - Enum of EplHeadOld
-
-	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=EplHeadOldEnum()
-	"""
-
-	return StringToEnum('EplHeadOld')[0]
-
-def HydrologydcRelTolEnum():
-	"""
-	HYDROLOGYDCRELTOLENUM - Enum of HydrologydcRelTol
-
-	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=HydrologydcRelTolEnum()
-	"""
-
-	return StringToEnum('HydrologydcRelTol')[0]
-
-def HydrologydcSpcsedimentHeadEnum():
-	"""
-	HYDROLOGYDCSPCSEDIMENTHEADENUM - Enum of HydrologydcSpcsedimentHead
-
-	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=HydrologydcSpcsedimentHeadEnum()
-	"""
-
-	return StringToEnum('HydrologydcSpcsedimentHead')[0]
-
-def HydrologydcSedimentCompressibilityEnum():
-	"""
-	HYDROLOGYDCSEDIMENTCOMPRESSIBILITYENUM - Enum of HydrologydcSedimentCompressibility
-
-	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=HydrologydcSedimentCompressibilityEnum()
-	"""
-
-	return StringToEnum('HydrologydcSedimentCompressibility')[0]
-
-def HydrologydcSedimentPorosityEnum():
-	"""
-	HYDROLOGYDCSEDIMENTPOROSITYENUM - Enum of HydrologydcSedimentPorosity
-
-	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=HydrologydcSedimentPorosityEnum()
-	"""
-
-	return StringToEnum('HydrologydcSedimentPorosity')[0]
-
-def HydrologydcSedimentThicknessEnum():
-	"""
-	HYDROLOGYDCSEDIMENTTHICKNESSENUM - Enum of HydrologydcSedimentThickness
-
-	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=HydrologydcSedimentThicknessEnum()
-	"""
-
-	return StringToEnum('HydrologydcSedimentThickness')[0]
-
-def HydrologydcSedimentTransmitivityEnum():
-	"""
-	HYDROLOGYDCSEDIMENTTRANSMITIVITYENUM - Enum of HydrologydcSedimentTransmitivity
-
-	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=HydrologydcSedimentTransmitivityEnum()
-	"""
-
-	return StringToEnum('HydrologydcSedimentTransmitivity')[0]
-
-def HydrologydcWaterCompressibilityEnum():
-	"""
-	HYDROLOGYDCWATERCOMPRESSIBILITYENUM - Enum of HydrologydcWaterCompressibility
-
-	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=HydrologydcWaterCompressibilityEnum()
-	"""
-
-	return StringToEnum('HydrologydcWaterCompressibility')[0]
-
-def HydrologydcSpceplHeadEnum():
-	"""
-	HYDROLOGYDCSPCEPLHEADENUM - Enum of HydrologydcSpceplHead
-
-	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=HydrologydcSpceplHeadEnum()
-	"""
-
-	return StringToEnum('HydrologydcSpceplHead')[0]
-
-def HydrologydcMaskEplactiveEnum():
-	"""
-	HYDROLOGYDCMASKEPLACTIVEENUM - Enum of HydrologydcMaskEplactive
-
-	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=HydrologydcMaskEplactiveEnum()
-	"""
-
-	return StringToEnum('HydrologydcMaskEplactive')[0]
-
-def HydrologydcEplCompressibilityEnum():
-	"""
-	HYDROLOGYDCEPLCOMPRESSIBILITYENUM - Enum of HydrologydcEplCompressibility
-
-	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=HydrologydcEplCompressibilityEnum()
-	"""
-
-	return StringToEnum('HydrologydcEplCompressibility')[0]
-
-def HydrologydcEplPorosityEnum():
-	"""
-	HYDROLOGYDCEPLPOROSITYENUM - Enum of HydrologydcEplPorosity
-
-	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=HydrologydcEplPorosityEnum()
-	"""
-
-	return StringToEnum('HydrologydcEplPorosity')[0]
-
-def HydrologydcEplThicknessEnum():
-	"""
-	HYDROLOGYDCEPLTHICKNESSENUM - Enum of HydrologydcEplThickness
-
-	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=HydrologydcEplThicknessEnum()
-	"""
-
-	return StringToEnum('HydrologydcEplThickness')[0]
-
-def HydrologydcEplTransmitivityEnum():
-	"""
-	HYDROLOGYDCEPLTRANSMITIVITYENUM - Enum of HydrologydcEplTransmitivity
-
-	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=HydrologydcEplTransmitivityEnum()
-	"""
-
-	return StringToEnum('HydrologydcEplTransmitivity')[0]
-
-def HydrologydcIsefficientlayerEnum():
-	"""
-	HYDROLOGYDCISEFFICIENTLAYERENUM - Enum of HydrologydcIsefficientlayer
-
-	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=HydrologydcIsefficientlayerEnum()
-	"""
-
-	return StringToEnum('HydrologydcIsefficientlayer')[0]
-
-def HydrologydcSedimentlimitFlagEnum():
-	"""
-	HYDROLOGYDCSEDIMENTLIMITFLAGENUM - Enum of HydrologydcSedimentlimitFlag
-
-	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=HydrologydcSedimentlimitFlagEnum()
-	"""
-
-	return StringToEnum('HydrologydcSedimentlimitFlag')[0]
-
-def HydrologydcSedimentlimitEnum():
-	"""
-	HYDROLOGYDCSEDIMENTLIMITENUM - Enum of HydrologydcSedimentlimit
-
-	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=HydrologydcSedimentlimitEnum()
-	"""
-
-	return StringToEnum('HydrologydcSedimentlimit')[0]
-
-def HydrologydcTransferFlagEnum():
-	"""
-	HYDROLOGYDCTRANSFERFLAGENUM - Enum of HydrologydcTransferFlag
-
-	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=HydrologydcTransferFlagEnum()
-	"""
-
-	return StringToEnum('HydrologydcTransferFlag')[0]
-
-def HydrologydcLeakageFactorEnum():
-	"""
-	HYDROLOGYDCLEAKAGEFACTORENUM - Enum of HydrologydcLeakageFactor
-
-	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=HydrologydcLeakageFactorEnum()
-	"""
-
-	return StringToEnum('HydrologydcLeakageFactor')[0]
-
-def HydrologydcPenaltyFactorEnum():
-	"""
-	HYDROLOGYDCPENALTYFACTORENUM - Enum of HydrologydcPenaltyFactor
-
-	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=HydrologydcPenaltyFactorEnum()
-	"""
-
-	return StringToEnum('HydrologydcPenaltyFactor')[0]
-
-def HydrologyLayerEnum():
-	"""
-	HYDROLOGYLAYERENUM - Enum of HydrologyLayer
-
-	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=HydrologyLayerEnum()
-	"""
-
-	return StringToEnum('HydrologyLayer')[0]
-
-def HydrologySedimentEnum():
-	"""
-	HYDROLOGYSEDIMENTENUM - Enum of HydrologySediment
-
-	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=HydrologySedimentEnum()
-	"""
-
-	return StringToEnum('HydrologySediment')[0]
-
-def HydrologyEfficientEnum():
-	"""
-	HYDROLOGYEFFICIENTENUM - Enum of HydrologyEfficient
-
-	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=HydrologyEfficientEnum()
-	"""
-
-	return StringToEnum('HydrologyEfficient')[0]
-
-def HydrologySedimentKmaxEnum():
-	"""
-	HYDROLOGYSEDIMENTKMAXENUM - Enum of HydrologySedimentKmax
-
-	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=HydrologySedimentKmaxEnum()
-	"""
-
-	return StringToEnum('HydrologySedimentKmax')[0]
-
-def BasisIntegralEnum():
-	"""
-	BASISINTEGRALENUM - Enum of BasisIntegral
-
-	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=BasisIntegralEnum()
-	"""
-
-	return StringToEnum('BasisIntegral')[0]
-
-def WaterTransferEnum():
-	"""
-	WATERTRANSFERENUM - Enum of WaterTransfer
-
-	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=WaterTransferEnum()
-	"""
-
-	return StringToEnum('WaterTransfer')[0]
-
-def IndependentObjectEnum():
-	"""
-	INDEPENDENTOBJECTENUM - Enum of IndependentObject
-
-	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=IndependentObjectEnum()
-	"""
-
-	return StringToEnum('IndependentObject')[0]
-
-def InversionControlParametersEnum():
-	"""
-	INVERSIONCONTROLPARAMETERSENUM - Enum of InversionControlParameters
-
-	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=InversionControlParametersEnum()
-	"""
-
-	return StringToEnum('InversionControlParameters')[0]
-
-def InversionCostFunctionThresholdEnum():
-	"""
-	INVERSIONCOSTFUNCTIONTHRESHOLDENUM - Enum of InversionCostFunctionThreshold
-
-	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=InversionCostFunctionThresholdEnum()
-	"""
-
-	return StringToEnum('InversionCostFunctionThreshold')[0]
-
-def InversionCostFunctionsCoefficientsEnum():
-	"""
-	INVERSIONCOSTFUNCTIONSCOEFFICIENTSENUM - Enum of InversionCostFunctionsCoefficients
-
-	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=InversionCostFunctionsCoefficientsEnum()
-	"""
-
-	return StringToEnum('InversionCostFunctionsCoefficients')[0]
-
-def InversionCostFunctionsEnum():
-	"""
-	INVERSIONCOSTFUNCTIONSENUM - Enum of InversionCostFunctions
-
-	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=InversionCostFunctionsEnum()
-	"""
-
-	return StringToEnum('InversionCostFunctions')[0]
-
-def InversionGradientOnlyEnum():
-	"""
-	INVERSIONGRADIENTONLYENUM - Enum of InversionGradientOnly
-
-	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=InversionGradientOnlyEnum()
-	"""
-
-	return StringToEnum('InversionGradientOnly')[0]
-
-def InversionGradientScalingEnum():
-	"""
-	INVERSIONGRADIENTSCALINGENUM - Enum of InversionGradientScaling
-
-	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=InversionGradientScalingEnum()
-	"""
-
-	return StringToEnum('InversionGradientScaling')[0]
-
-def InversionIscontrolEnum():
-	"""
-	INVERSIONISCONTROLENUM - Enum of InversionIscontrol
-
-	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=InversionIscontrolEnum()
-	"""
-
-	return StringToEnum('InversionIscontrol')[0]
-
-def InversionTaoEnum():
-	"""
-	INVERSIONTAOENUM - Enum of InversionTao
-
-	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=InversionTaoEnum()
-	"""
-
-	return StringToEnum('InversionTao')[0]
-
-def InversionIncompleteAdjointEnum():
-	"""
-	INVERSIONINCOMPLETEADJOINTENUM - Enum of InversionIncompleteAdjoint
-
-	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=InversionIncompleteAdjointEnum()
-	"""
-
-	return StringToEnum('InversionIncompleteAdjoint')[0]
-
-def InversionMaxParametersEnum():
-	"""
-	INVERSIONMAXPARAMETERSENUM - Enum of InversionMaxParameters
-
-	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=InversionMaxParametersEnum()
-	"""
-
-	return StringToEnum('InversionMaxParameters')[0]
-
-def InversionMaxiterPerStepEnum():
-	"""
-	INVERSIONMAXITERPERSTEPENUM - Enum of InversionMaxiterPerStep
-
-	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=InversionMaxiterPerStepEnum()
-	"""
-
-	return StringToEnum('InversionMaxiterPerStep')[0]
-
-def InversionMinParametersEnum():
-	"""
-	INVERSIONMINPARAMETERSENUM - Enum of InversionMinParameters
-
-	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=InversionMinParametersEnum()
-	"""
-
-	return StringToEnum('InversionMinParameters')[0]
-
-def InversionNstepsEnum():
-	"""
-	INVERSIONNSTEPSENUM - Enum of InversionNsteps
-
-	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=InversionNstepsEnum()
-	"""
-
-	return StringToEnum('InversionNsteps')[0]
-
-def InversionNumControlParametersEnum():
-	"""
-	INVERSIONNUMCONTROLPARAMETERSENUM - Enum of InversionNumControlParameters
-
-	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=InversionNumControlParametersEnum()
-	"""
-
-	return StringToEnum('InversionNumControlParameters')[0]
-
-def InversionNumCostFunctionsEnum():
-	"""
-	INVERSIONNUMCOSTFUNCTIONSENUM - Enum of InversionNumCostFunctions
-
-	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=InversionNumCostFunctionsEnum()
-	"""
-
-	return StringToEnum('InversionNumCostFunctions')[0]
-
-def InversionStepThresholdEnum():
-	"""
-	INVERSIONSTEPTHRESHOLDENUM - Enum of InversionStepThreshold
-
-	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=InversionStepThresholdEnum()
-	"""
-
-	return StringToEnum('InversionStepThreshold')[0]
-
-def InversionThicknessObsEnum():
-	"""
-	INVERSIONTHICKNESSOBSENUM - Enum of InversionThicknessObs
-
-	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=InversionThicknessObsEnum()
-	"""
-
-	return StringToEnum('InversionThicknessObs')[0]
-
-def InversionVelObsEnum():
-	"""
-	INVERSIONVELOBSENUM - Enum of InversionVelObs
-
-	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=InversionVelObsEnum()
-	"""
-
-	return StringToEnum('InversionVelObs')[0]
-
-def InversionVxObsEnum():
-	"""
-	INVERSIONVXOBSENUM - Enum of InversionVxObs
-
-	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=InversionVxObsEnum()
-	"""
-
-	return StringToEnum('InversionVxObs')[0]
-
-def InversionVyObsEnum():
-	"""
-	INVERSIONVYOBSENUM - Enum of InversionVyObs
-
-	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=InversionVyObsEnum()
-	"""
-
-	return StringToEnum('InversionVyObs')[0]
-
-def InversionVzObsEnum():
-	"""
-	INVERSIONVZOBSENUM - Enum of InversionVzObs
-
-	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=InversionVzObsEnum()
-	"""
-
-	return StringToEnum('InversionVzObs')[0]
-
-def MaskElementonfloatingiceEnum():
-	"""
-	MASKELEMENTONFLOATINGICEENUM - Enum of MaskElementonfloatingice
-
-	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=MaskElementonfloatingiceEnum()
-	"""
-
-	return StringToEnum('MaskElementonfloatingice')[0]
-
-def MaskElementongroundediceEnum():
-	"""
-	MASKELEMENTONGROUNDEDICEENUM - Enum of MaskElementongroundedice
-
-	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=MaskElementongroundediceEnum()
-	"""
-
-	return StringToEnum('MaskElementongroundedice')[0]
-
-def MaskElementonwaterEnum():
-	"""
-	MASKELEMENTONWATERENUM - Enum of MaskElementonwater
-
-	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=MaskElementonwaterEnum()
-	"""
-
-	return StringToEnum('MaskElementonwater')[0]
-
-def MaskVertexonfloatingiceEnum():
-	"""
-	MASKVERTEXONFLOATINGICEENUM - Enum of MaskVertexonfloatingice
-
-	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=MaskVertexonfloatingiceEnum()
-	"""
-
-	return StringToEnum('MaskVertexonfloatingice')[0]
-
-def MaskVertexongroundediceEnum():
-	"""
-	MASKVERTEXONGROUNDEDICEENUM - Enum of MaskVertexongroundedice
-
-	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=MaskVertexongroundediceEnum()
-	"""
-
-	return StringToEnum('MaskVertexongroundedice')[0]
-
-def MaskVertexonwaterEnum():
-	"""
-	MASKVERTEXONWATERENUM - Enum of MaskVertexonwater
-
-	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=MaskVertexonwaterEnum()
-	"""
-
-	return StringToEnum('MaskVertexonwater')[0]
-
-def MaterialsBetaEnum():
-	"""
-	MATERIALSBETAENUM - Enum of MaterialsBeta
-
-	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=MaterialsBetaEnum()
-	"""
-
-	return StringToEnum('MaterialsBeta')[0]
-
-def MaterialsHeatcapacityEnum():
-	"""
-	MATERIALSHEATCAPACITYENUM - Enum of MaterialsHeatcapacity
-
-	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=MaterialsHeatcapacityEnum()
-	"""
-
-	return StringToEnum('MaterialsHeatcapacity')[0]
-
-def MaterialsLatentheatEnum():
-	"""
-	MATERIALSLATENTHEATENUM - Enum of MaterialsLatentheat
-
-	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=MaterialsLatentheatEnum()
-	"""
-
-	return StringToEnum('MaterialsLatentheat')[0]
-
-def MaterialsMeltingpointEnum():
-	"""
-	MATERIALSMELTINGPOINTENUM - Enum of MaterialsMeltingpoint
-
-	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=MaterialsMeltingpointEnum()
-	"""
-
-	return StringToEnum('MaterialsMeltingpoint')[0]
-
-def MaterialsMixedLayerCapacityEnum():
-	"""
-	MATERIALSMIXEDLAYERCAPACITYENUM - Enum of MaterialsMixedLayerCapacity
-
-	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=MaterialsMixedLayerCapacityEnum()
-	"""
-
-	return StringToEnum('MaterialsMixedLayerCapacity')[0]
-
-def MaterialsRheologyBEnum():
-	"""
-	MATERIALSRHEOLOGYBENUM - Enum of MaterialsRheologyB
-
-	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=MaterialsRheologyBEnum()
-	"""
-
-	return StringToEnum('MaterialsRheologyB')[0]
-
-def MaterialsRheologyBbarEnum():
-	"""
-	MATERIALSRHEOLOGYBBARENUM - Enum of MaterialsRheologyBbar
-
-	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=MaterialsRheologyBbarEnum()
-	"""
-
-	return StringToEnum('MaterialsRheologyBbar')[0]
-
-def MaterialsRheologyLawEnum():
-	"""
-	MATERIALSRHEOLOGYLAWENUM - Enum of MaterialsRheologyLaw
-
-	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=MaterialsRheologyLawEnum()
-	"""
-
-	return StringToEnum('MaterialsRheologyLaw')[0]
-
-def MaterialsRheologyNEnum():
-	"""
-	MATERIALSRHEOLOGYNENUM - Enum of MaterialsRheologyN
-
-	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=MaterialsRheologyNEnum()
-	"""
-
-	return StringToEnum('MaterialsRheologyN')[0]
-
-def MaterialsRheologyZEnum():
-	"""
-	MATERIALSRHEOLOGYZENUM - Enum of MaterialsRheologyZ
-
-	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=MaterialsRheologyZEnum()
-	"""
-
-	return StringToEnum('MaterialsRheologyZ')[0]
-
-def MaterialsRheologyZbarEnum():
-	"""
-	MATERIALSRHEOLOGYZBARENUM - Enum of MaterialsRheologyZbar
-
-	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=MaterialsRheologyZbarEnum()
-	"""
-
-	return StringToEnum('MaterialsRheologyZbar')[0]
-
-def MaterialsRhoIceEnum():
-	"""
-	MATERIALSRHOICEENUM - Enum of MaterialsRhoIce
-
-	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=MaterialsRhoIceEnum()
-	"""
-
-	return StringToEnum('MaterialsRhoIce')[0]
-
-def MaterialsRhoWaterEnum():
-	"""
-	MATERIALSRHOWATERENUM - Enum of MaterialsRhoWater
-
-	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=MaterialsRhoWaterEnum()
-	"""
-
-	return StringToEnum('MaterialsRhoWater')[0]
-
-def MaterialsRhoFreshwaterEnum():
-	"""
-	MATERIALSRHOFRESHWATERENUM - Enum of MaterialsRhoFreshwater
-
-	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=MaterialsRhoFreshwaterEnum()
-	"""
-
-	return StringToEnum('MaterialsRhoFreshwater')[0]
-
-def MaterialsMuWaterEnum():
-	"""
-	MATERIALSMUWATERENUM - Enum of MaterialsMuWater
-
-	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=MaterialsMuWaterEnum()
-	"""
-
-	return StringToEnum('MaterialsMuWater')[0]
-
-def MaterialsThermalExchangeVelocityEnum():
-	"""
-	MATERIALSTHERMALEXCHANGEVELOCITYENUM - Enum of MaterialsThermalExchangeVelocity
-
-	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=MaterialsThermalExchangeVelocityEnum()
-	"""
-
-	return StringToEnum('MaterialsThermalExchangeVelocity')[0]
-
-def MaterialsThermalconductivityEnum():
-	"""
-	MATERIALSTHERMALCONDUCTIVITYENUM - Enum of MaterialsThermalconductivity
-
-	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=MaterialsThermalconductivityEnum()
-	"""
-
-	return StringToEnum('MaterialsThermalconductivity')[0]
-
-def MaterialsLithosphereShearModulusEnum():
-	"""
-	MATERIALSLITHOSPHERESHEARMODULUSENUM - Enum of MaterialsLithosphereShearModulus
-
-	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=MaterialsLithosphereShearModulusEnum()
-	"""
-
-	return StringToEnum('MaterialsLithosphereShearModulus')[0]
-
-def MaterialsLithosphereDensityEnum():
-	"""
-	MATERIALSLITHOSPHEREDENSITYENUM - Enum of MaterialsLithosphereDensity
-
-	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=MaterialsLithosphereDensityEnum()
-	"""
-
-	return StringToEnum('MaterialsLithosphereDensity')[0]
-
-def MaterialsMantleShearModulusEnum():
-	"""
-	MATERIALSMANTLESHEARMODULUSENUM - Enum of MaterialsMantleShearModulus
-
-	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=MaterialsMantleShearModulusEnum()
-	"""
-
-	return StringToEnum('MaterialsMantleShearModulus')[0]
-
-def MaterialsMantleDensityEnum():
-	"""
-	MATERIALSMANTLEDENSITYENUM - Enum of MaterialsMantleDensity
-
-	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=MaterialsMantleDensityEnum()
-	"""
-
-	return StringToEnum('MaterialsMantleDensity')[0]
-
-def MeshAverageVertexConnectivityEnum():
-	"""
-	MESHAVERAGEVERTEXCONNECTIVITYENUM - Enum of MeshAverageVertexConnectivity
-
-	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=MeshAverageVertexConnectivityEnum()
-	"""
-
-	return StringToEnum('MeshAverageVertexConnectivity')[0]
-
-def MeshDimensionEnum():
-	"""
-	MESHDIMENSIONENUM - Enum of MeshDimension
-
-	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=MeshDimensionEnum()
-	"""
-
-	return StringToEnum('MeshDimension')[0]
-
-def MeshEdgesEnum():
-	"""
-	MESHEDGESENUM - Enum of MeshEdges
-
-	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=MeshEdgesEnum()
-	"""
-
-	return StringToEnum('MeshEdges')[0]
-
-def MeshElementconnectivityEnum():
-	"""
-	MESHELEMENTCONNECTIVITYENUM - Enum of MeshElementconnectivity
-
-	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=MeshElementconnectivityEnum()
-	"""
-
-	return StringToEnum('MeshElementconnectivity')[0]
-
-def MeshElementonbedEnum():
-	"""
-	MESHELEMENTONBEDENUM - Enum of MeshElementonbed
-
-	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=MeshElementonbedEnum()
-	"""
-
-	return StringToEnum('MeshElementonbed')[0]
-
-def MeshElementonsurfaceEnum():
-	"""
-	MESHELEMENTONSURFACEENUM - Enum of MeshElementonsurface
-
-	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=MeshElementonsurfaceEnum()
-	"""
-
-	return StringToEnum('MeshElementonsurface')[0]
-
-def MeshElements2dEnum():
-	"""
-	MESHELEMENTS2DENUM - Enum of MeshElements2d
-
-	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=MeshElements2dEnum()
-	"""
-
-	return StringToEnum('MeshElements2d')[0]
-
-def MeshElementsEnum():
-	"""
-	MESHELEMENTSENUM - Enum of MeshElements
-
-	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=MeshElementsEnum()
-	"""
-
-	return StringToEnum('MeshElements')[0]
-
-def MeshLowerelementsEnum():
-	"""
-	MESHLOWERELEMENTSENUM - Enum of MeshLowerelements
-
-	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=MeshLowerelementsEnum()
-	"""
-
-	return StringToEnum('MeshLowerelements')[0]
-
-def MeshNumberofedgesEnum():
-	"""
-	MESHNUMBEROFEDGESENUM - Enum of MeshNumberofedges
-
-	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=MeshNumberofedgesEnum()
-	"""
-
-	return StringToEnum('MeshNumberofedges')[0]
-
-def MeshNumberofelements2dEnum():
-	"""
-	MESHNUMBEROFELEMENTS2DENUM - Enum of MeshNumberofelements2d
-
-	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=MeshNumberofelements2dEnum()
-	"""
-
-	return StringToEnum('MeshNumberofelements2d')[0]
-
-def MeshNumberofelementsEnum():
-	"""
-	MESHNUMBEROFELEMENTSENUM - Enum of MeshNumberofelements
-
-	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=MeshNumberofelementsEnum()
-	"""
-
-	return StringToEnum('MeshNumberofelements')[0]
-
-def MeshNumberoflayersEnum():
-	"""
-	MESHNUMBEROFLAYERSENUM - Enum of MeshNumberoflayers
-
-	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=MeshNumberoflayersEnum()
-	"""
-
-	return StringToEnum('MeshNumberoflayers')[0]
-
-def MeshNumberofvertices2dEnum():
-	"""
-	MESHNUMBEROFVERTICES2DENUM - Enum of MeshNumberofvertices2d
-
-	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=MeshNumberofvertices2dEnum()
-	"""
-
-	return StringToEnum('MeshNumberofvertices2d')[0]
-
-def MeshNumberofverticesEnum():
-	"""
-	MESHNUMBEROFVERTICESENUM - Enum of MeshNumberofvertices
-
-	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=MeshNumberofverticesEnum()
-	"""
-
-	return StringToEnum('MeshNumberofvertices')[0]
-
-def MeshUpperelementsEnum():
-	"""
-	MESHUPPERELEMENTSENUM - Enum of MeshUpperelements
-
-	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=MeshUpperelementsEnum()
-	"""
-
-	return StringToEnum('MeshUpperelements')[0]
-
-def MeshVertexonbedEnum():
-	"""
-	MESHVERTEXONBEDENUM - Enum of MeshVertexonbed
-
-	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=MeshVertexonbedEnum()
-	"""
-
-	return StringToEnum('MeshVertexonbed')[0]
-
-def MeshVertexonsurfaceEnum():
-	"""
-	MESHVERTEXONSURFACEENUM - Enum of MeshVertexonsurface
-
-	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=MeshVertexonsurfaceEnum()
-	"""
-
-	return StringToEnum('MeshVertexonsurface')[0]
-
-def MeshXEnum():
-	"""
-	MESHXENUM - Enum of MeshX
-
-	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=MeshXEnum()
-	"""
-
-	return StringToEnum('MeshX')[0]
-
-def MeshYEnum():
-	"""
-	MESHYENUM - Enum of MeshY
-
-	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=MeshYEnum()
-	"""
-
-	return StringToEnum('MeshY')[0]
-
-def MeshZEnum():
-	"""
-	MESHZENUM - Enum of MeshZ
-
-	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=MeshZEnum()
-	"""
-
-	return StringToEnum('MeshZ')[0]
-
-def MiscellaneousNameEnum():
-	"""
-	MISCELLANEOUSNAMEENUM - Enum of MiscellaneousName
-
-	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=MiscellaneousNameEnum()
-	"""
-
-	return StringToEnum('MiscellaneousName')[0]
-
-def PrognosticHydrostaticAdjustmentEnum():
-	"""
-	PROGNOSTICHYDROSTATICADJUSTMENTENUM - Enum of PrognosticHydrostaticAdjustment
-
-	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=PrognosticHydrostaticAdjustmentEnum()
-	"""
-
-	return StringToEnum('PrognosticHydrostaticAdjustment')[0]
-
-def PrognosticMinThicknessEnum():
-	"""
-	PROGNOSTICMINTHICKNESSENUM - Enum of PrognosticMinThickness
-
-	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=PrognosticMinThicknessEnum()
-	"""
-
-	return StringToEnum('PrognosticMinThickness')[0]
-
-def PrognosticPenaltyFactorEnum():
-	"""
-	PROGNOSTICPENALTYFACTORENUM - Enum of PrognosticPenaltyFactor
-
-	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=PrognosticPenaltyFactorEnum()
-	"""
-
-	return StringToEnum('PrognosticPenaltyFactor')[0]
-
-def PrognosticSpcthicknessEnum():
-	"""
-	PROGNOSTICSPCTHICKNESSENUM - Enum of PrognosticSpcthickness
-
-	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=PrognosticSpcthicknessEnum()
-	"""
-
-	return StringToEnum('PrognosticSpcthickness')[0]
-
-def PrognosticStabilizationEnum():
-	"""
-	PROGNOSTICSTABILIZATIONENUM - Enum of PrognosticStabilization
-
-	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=PrognosticStabilizationEnum()
-	"""
-
-	return StringToEnum('PrognosticStabilization')[0]
-
-def PrognosticVertexPairingEnum():
-	"""
-	PROGNOSTICVERTEXPAIRINGENUM - Enum of PrognosticVertexPairing
-
-	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=PrognosticVertexPairingEnum()
-	"""
-
-	return StringToEnum('PrognosticVertexPairing')[0]
-
-def PrognosticNumRequestedOutputsEnum():
-	"""
-	PROGNOSTICNUMREQUESTEDOUTPUTSENUM - Enum of PrognosticNumRequestedOutputs
-
-	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=PrognosticNumRequestedOutputsEnum()
-	"""
-
-	return StringToEnum('PrognosticNumRequestedOutputs')[0]
-
-def PrognosticRequestedOutputsEnum():
-	"""
-	PROGNOSTICREQUESTEDOUTPUTSENUM - Enum of PrognosticRequestedOutputs
-
-	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=PrognosticRequestedOutputsEnum()
-	"""
-
-	return StringToEnum('PrognosticRequestedOutputs')[0]
-
-def QmuIsdakotaEnum():
-	"""
-	QMUISDAKOTAENUM - Enum of QmuIsdakota
-
-	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=QmuIsdakotaEnum()
-	"""
-
-	return StringToEnum('QmuIsdakota')[0]
-
-def MassFluxSegmentsEnum():
-	"""
-	MASSFLUXSEGMENTSENUM - Enum of MassFluxSegments
-
-	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=MassFluxSegmentsEnum()
-	"""
-
-	return StringToEnum('MassFluxSegments')[0]
-
-def MassFluxSegmentsPresentEnum():
-	"""
-	MASSFLUXSEGMENTSPRESENTENUM - Enum of MassFluxSegmentsPresent
-
-	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=MassFluxSegmentsPresentEnum()
-	"""
-
-	return StringToEnum('MassFluxSegmentsPresent')[0]
-
-def QmuMassFluxSegmentsPresentEnum():
-	"""
-	QMUMASSFLUXSEGMENTSPRESENTENUM - Enum of QmuMassFluxSegmentsPresent
-
-	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=QmuMassFluxSegmentsPresentEnum()
-	"""
-
-	return StringToEnum('QmuMassFluxSegmentsPresent')[0]
-
-def QmuNumberofpartitionsEnum():
-	"""
-	QMUNUMBEROFPARTITIONSENUM - Enum of QmuNumberofpartitions
-
-	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=QmuNumberofpartitionsEnum()
-	"""
-
-	return StringToEnum('QmuNumberofpartitions')[0]
-
-def QmuNumberofresponsesEnum():
-	"""
-	QMUNUMBEROFRESPONSESENUM - Enum of QmuNumberofresponses
-
-	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=QmuNumberofresponsesEnum()
-	"""
-
-	return StringToEnum('QmuNumberofresponses')[0]
-
-def QmuPartitionEnum():
-	"""
-	QMUPARTITIONENUM - Enum of QmuPartition
-
-	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=QmuPartitionEnum()
-	"""
-
-	return StringToEnum('QmuPartition')[0]
-
-def QmuResponsedescriptorsEnum():
-	"""
-	QMURESPONSEDESCRIPTORSENUM - Enum of QmuResponsedescriptors
-
-	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=QmuResponsedescriptorsEnum()
-	"""
-
-	return StringToEnum('QmuResponsedescriptors')[0]
-
-def QmuVariabledescriptorsEnum():
-	"""
-	QMUVARIABLEDESCRIPTORSENUM - Enum of QmuVariabledescriptors
-
-	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=QmuVariabledescriptorsEnum()
-	"""
-
-	return StringToEnum('QmuVariabledescriptors')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuMaterialsRheologyB')[0]
-
-def RiftsNumriftsEnum():
-	"""
-	RIFTSNUMRIFTSENUM - Enum of RiftsNumrifts
-
-	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=RiftsNumriftsEnum()
-	"""
-
-	return StringToEnum('RiftsNumrifts')[0]
-
-def RiftsRiftstructEnum():
-	"""
-	RIFTSRIFTSTRUCTENUM - Enum of RiftsRiftstruct
-
-	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=RiftsRiftstructEnum()
-	"""
-
-	return StringToEnum('RiftsRiftstruct')[0]
-
-def SettingsIoGatherEnum():
-	"""
-	SETTINGSIOGATHERENUM - Enum of SettingsIoGather
-
-	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=SettingsIoGatherEnum()
-	"""
-
-	return StringToEnum('SettingsIoGather')[0]
-
-def SettingsLowmemEnum():
-	"""
-	SETTINGSLOWMEMENUM - Enum of SettingsLowmem
-
-	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=SettingsLowmemEnum()
-	"""
-
-	return StringToEnum('SettingsLowmem')[0]
-
-def SettingsOutputFrequencyEnum():
-	"""
-	SETTINGSOUTPUTFREQUENCYENUM - Enum of SettingsOutputFrequency
-
-	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=SettingsOutputFrequencyEnum()
-	"""
-
-	return StringToEnum('SettingsOutputFrequency')[0]
-
-def SettingsResultsAsPatchesEnum():
-	"""
-	SETTINGSRESULTSASPATCHESENUM - Enum of SettingsResultsAsPatches
-
-	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=SettingsResultsAsPatchesEnum()
-	"""
-
-	return StringToEnum('SettingsResultsAsPatches')[0]
-
-def SettingsWaitonlockEnum():
-	"""
-	SETTINGSWAITONLOCKENUM - Enum of SettingsWaitonlock
-
-	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=SettingsWaitonlockEnum()
-	"""
-
-	return StringToEnum('SettingsWaitonlock')[0]
-
-def SurfaceforcingsDelta18oEnum():
-	"""
-	SURFACEFORCINGSDELTA18OENUM - Enum of SurfaceforcingsDelta18o
-
-	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=SurfaceforcingsDelta18oEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsDelta18o')[0]
-
-def SurfaceforcingsDelta18oSurfaceEnum():
-	"""
-	SURFACEFORCINGSDELTA18OSURFACEENUM - Enum of SurfaceforcingsDelta18oSurface
-
-	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=SurfaceforcingsDelta18oSurfaceEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsDelta18oSurface')[0]
-
-def SurfaceforcingsIsdelta18oEnum():
-	"""
-	SURFACEFORCINGSISDELTA18OENUM - Enum of SurfaceforcingsIsdelta18o
-
-	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=SurfaceforcingsIsdelta18oEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsIsdelta18o')[0]
-
-def SurfaceforcingsPrecipitationsPresentdayEnum():
-	"""
-	SURFACEFORCINGSPRECIPITATIONSPRESENTDAYENUM - Enum of SurfaceforcingsPrecipitationsPresentday
-
-	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=SurfaceforcingsPrecipitationsPresentdayEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsPrecipitationsPresentday')[0]
-
-def SurfaceforcingsTemperaturesPresentdayEnum():
-	"""
-	SURFACEFORCINGSTEMPERATURESPRESENTDAYENUM - Enum of SurfaceforcingsTemperaturesPresentday
-
-	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=SurfaceforcingsTemperaturesPresentdayEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsTemperaturesPresentday')[0]
-
-def SurfaceforcingsTemperaturesLgmEnum():
-	"""
-	SURFACEFORCINGSTEMPERATURESLGMENUM - Enum of SurfaceforcingsTemperaturesLgm
-
-	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=SurfaceforcingsTemperaturesLgmEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsTemperaturesLgm')[0]
-
-def DebugProfilingEnum():
-	"""
-	DEBUGPROFILINGENUM - Enum of DebugProfiling
-
-	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=DebugProfilingEnum()
-	"""
-
-	return StringToEnum('DebugProfiling')[0]
-
-def ProfilingCurrentMemEnum():
-	"""
-	PROFILINGCURRENTMEMENUM - Enum of ProfilingCurrentMem
-
-	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=ProfilingCurrentMemEnum()
-	"""
-
-	return StringToEnum('ProfilingCurrentMem')[0]
-
-def ProfilingCurrentFlopsEnum():
-	"""
-	PROFILINGCURRENTFLOPSENUM - Enum of ProfilingCurrentFlops
-
-	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=ProfilingCurrentFlopsEnum()
-	"""
-
-	return StringToEnum('ProfilingCurrentFlops')[0]
-
-def ProfilingSolutionTimeEnum():
-	"""
-	PROFILINGSOLUTIONTIMEENUM - Enum of ProfilingSolutionTime
-
-	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=ProfilingSolutionTimeEnum()
-	"""
-
-	return StringToEnum('ProfilingSolutionTime')[0]
-
-def MaxIterationConvergenceFlagEnum():
-	"""
-	MAXITERATIONCONVERGENCEFLAGENUM - Enum of MaxIterationConvergenceFlag
-
-	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=MaxIterationConvergenceFlagEnum()
-	"""
-
-	return StringToEnum('MaxIterationConvergenceFlag')[0]
-
-def SteadystateMaxiterEnum():
-	"""
-	STEADYSTATEMAXITERENUM - Enum of SteadystateMaxiter
-
-	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=SteadystateMaxiterEnum()
-	"""
-
-	return StringToEnum('SteadystateMaxiter')[0]
-
-def SteadystateNumRequestedOutputsEnum():
-	"""
-	STEADYSTATENUMREQUESTEDOUTPUTSENUM - Enum of SteadystateNumRequestedOutputs
-
-	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=SteadystateNumRequestedOutputsEnum()
-	"""
-
-	return StringToEnum('SteadystateNumRequestedOutputs')[0]
-
-def SteadystateReltolEnum():
-	"""
-	STEADYSTATERELTOLENUM - Enum of SteadystateReltol
-
-	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=SteadystateReltolEnum()
-	"""
-
-	return StringToEnum('SteadystateReltol')[0]
-
-def SteadystateRequestedOutputsEnum():
-	"""
-	STEADYSTATEREQUESTEDOUTPUTSENUM - Enum of SteadystateRequestedOutputs
-
-	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=SteadystateRequestedOutputsEnum()
-	"""
-
-	return StringToEnum('SteadystateRequestedOutputs')[0]
-
-def SurfaceEnum():
-	"""
-	SURFACEENUM - Enum of Surface
-
-	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=SurfaceEnum()
-	"""
-
-	return StringToEnum('Surface')[0]
-
-def SurfaceforcingsPrecipitationEnum():
-	"""
-	SURFACEFORCINGSPRECIPITATIONENUM - Enum of SurfaceforcingsPrecipitation
-
-	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=SurfaceforcingsPrecipitationEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsPrecipitation')[0]
-
-def SurfaceforcingsMassBalanceEnum():
-	"""
-	SURFACEFORCINGSMASSBALANCEENUM - Enum of SurfaceforcingsMassBalance
-
-	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=SurfaceforcingsMassBalanceEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsMassBalance')[0]
-
-def SurfaceforcingsIspddEnum():
-	"""
-	SURFACEFORCINGSISPDDENUM - Enum of SurfaceforcingsIspdd
-
-	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=SurfaceforcingsIspddEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsIspdd')[0]
-
-def SurfaceforcingsDesfacEnum():
-	"""
-	SURFACEFORCINGSDESFACENUM - Enum of SurfaceforcingsDesfac
-
-	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=SurfaceforcingsDesfacEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsDesfac')[0]
-
-def SurfaceforcingsS0pEnum():
-	"""
-	SURFACEFORCINGSS0PENUM - Enum of SurfaceforcingsS0p
-
-	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=SurfaceforcingsS0pEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsS0p')[0]
-
-def SurfaceforcingsIssmbgradientsEnum():
-	"""
-	SURFACEFORCINGSISSMBGRADIENTSENUM - Enum of SurfaceforcingsIssmbgradients
-
-	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=SurfaceforcingsIssmbgradientsEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsIssmbgradients')[0]
-
-def SurfaceforcingsMonthlytemperaturesEnum():
-	"""
-	SURFACEFORCINGSMONTHLYTEMPERATURESENUM - Enum of SurfaceforcingsMonthlytemperatures
-
-	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=SurfaceforcingsMonthlytemperaturesEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsMonthlytemperatures')[0]
-
-def SurfaceforcingsHrefEnum():
-	"""
-	SURFACEFORCINGSHREFENUM - Enum of SurfaceforcingsHref
-
-	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=SurfaceforcingsHrefEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsHref')[0]
-
-def SurfaceforcingsSmbrefEnum():
-	"""
-	SURFACEFORCINGSSMBREFENUM - Enum of SurfaceforcingsSmbref
-
-	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=SurfaceforcingsSmbrefEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsSmbref')[0]
-
-def SurfaceforcingsBPosEnum():
-	"""
-	SURFACEFORCINGSBPOSENUM - Enum of SurfaceforcingsBPos
-
-	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=SurfaceforcingsBPosEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsBPos')[0]
-
-def SurfaceforcingsBNegEnum():
-	"""
-	SURFACEFORCINGSBNEGENUM - Enum of SurfaceforcingsBNeg
-
-	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=SurfaceforcingsBNegEnum()
-	"""
-
-	return StringToEnum('SurfaceforcingsBNeg')[0]
-
-def ThermalMaxiterEnum():
-	"""
-	THERMALMAXITERENUM - Enum of ThermalMaxiter
-
-	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=ThermalMaxiterEnum()
-	"""
-
-	return StringToEnum('ThermalMaxiter')[0]
-
-def ThermalPenaltyFactorEnum():
-	"""
-	THERMALPENALTYFACTORENUM - Enum of ThermalPenaltyFactor
-
-	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=ThermalPenaltyFactorEnum()
-	"""
-
-	return StringToEnum('ThermalPenaltyFactor')[0]
-
-def ThermalPenaltyLockEnum():
-	"""
-	THERMALPENALTYLOCKENUM - Enum of ThermalPenaltyLock
-
-	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=ThermalPenaltyLockEnum()
-	"""
-
-	return StringToEnum('ThermalPenaltyLock')[0]
-
-def ThermalPenaltyThresholdEnum():
-	"""
-	THERMALPENALTYTHRESHOLDENUM - Enum of ThermalPenaltyThreshold
-
-	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=ThermalPenaltyThresholdEnum()
-	"""
-
-	return StringToEnum('ThermalPenaltyThreshold')[0]
-
-def ThermalSpctemperatureEnum():
-	"""
-	THERMALSPCTEMPERATUREENUM - Enum of ThermalSpctemperature
-
-	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=ThermalSpctemperatureEnum()
-	"""
-
-	return StringToEnum('ThermalSpctemperature')[0]
-
-def ThermalStabilizationEnum():
-	"""
-	THERMALSTABILIZATIONENUM - Enum of ThermalStabilization
-
-	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=ThermalStabilizationEnum()
-	"""
-
-	return StringToEnum('ThermalStabilization')[0]
-
-def ThermalIsenthalpyEnum():
-	"""
-	THERMALISENTHALPYENUM - Enum of ThermalIsenthalpy
-
-	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=ThermalIsenthalpyEnum()
-	"""
-
-	return StringToEnum('ThermalIsenthalpy')[0]
-
-def GiaMantleViscosityEnum():
-	"""
-	GIAMANTLEVISCOSITYENUM - Enum of GiaMantleViscosity
-
-	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=GiaMantleViscosityEnum()
-	"""
-
-	return StringToEnum('GiaMantleViscosity')[0]
-
-def GiaLithosphereThicknessEnum():
-	"""
-	GIALITHOSPHERETHICKNESSENUM - Enum of GiaLithosphereThickness
-
-	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=GiaLithosphereThicknessEnum()
-	"""
-
-	return StringToEnum('GiaLithosphereThickness')[0]
-
-def ThicknessEnum():
-	"""
-	THICKNESSENUM - Enum of Thickness
-
-	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=ThicknessEnum()
-	"""
-
-	return StringToEnum('Thickness')[0]
-
-def TimesteppingStartTimeEnum():
-	"""
-	TIMESTEPPINGSTARTTIMEENUM - Enum of TimesteppingStartTime
-
-	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=TimesteppingStartTimeEnum()
-	"""
-
-	return StringToEnum('TimesteppingStartTime')[0]
-
-def TimesteppingFinalTimeEnum():
-	"""
-	TIMESTEPPINGFINALTIMEENUM - Enum of TimesteppingFinalTime
-
-	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=TimesteppingFinalTimeEnum()
-	"""
-
-	return StringToEnum('TimesteppingFinalTime')[0]
-
-def TimesteppingCflCoefficientEnum():
-	"""
-	TIMESTEPPINGCFLCOEFFICIENTENUM - Enum of TimesteppingCflCoefficient
-
-	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=TimesteppingCflCoefficientEnum()
-	"""
-
-	return StringToEnum('TimesteppingCflCoefficient')[0]
-
-def TimesteppingTimeAdaptEnum():
-	"""
-	TIMESTEPPINGTIMEADAPTENUM - Enum of TimesteppingTimeAdapt
-
-	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=TimesteppingTimeAdaptEnum()
-	"""
-
-	return StringToEnum('TimesteppingTimeAdapt')[0]
-
-def TimesteppingTimeStepEnum():
-	"""
-	TIMESTEPPINGTIMESTEPENUM - Enum of TimesteppingTimeStep
-
-	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=TimesteppingTimeStepEnum()
-	"""
-
-	return StringToEnum('TimesteppingTimeStep')[0]
-
-def TransientIsdiagnosticEnum():
-	"""
-	TRANSIENTISDIAGNOSTICENUM - Enum of TransientIsdiagnostic
-
-	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=TransientIsdiagnosticEnum()
-	"""
-
-	return StringToEnum('TransientIsdiagnostic')[0]
-
-def TransientIsgroundinglineEnum():
-	"""
-	TRANSIENTISGROUNDINGLINEENUM - Enum of TransientIsgroundingline
-
-	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=TransientIsgroundinglineEnum()
-	"""
-
-	return StringToEnum('TransientIsgroundingline')[0]
-
-def TransientIsprognosticEnum():
-	"""
-	TRANSIENTISPROGNOSTICENUM - Enum of TransientIsprognostic
-
-	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=TransientIsprognosticEnum()
-	"""
-
-	return StringToEnum('TransientIsprognostic')[0]
-
-def TransientIsthermalEnum():
-	"""
-	TRANSIENTISTHERMALENUM - Enum of TransientIsthermal
-
-	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=TransientIsthermalEnum()
-	"""
-
-	return StringToEnum('TransientIsthermal')[0]
-
-def TransientIsgiaEnum():
-	"""
-	TRANSIENTISGIAENUM - Enum of TransientIsgia
-
-	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=TransientIsgiaEnum()
-	"""
-
-	return StringToEnum('TransientIsgia')[0]
-
-def TransientNumRequestedOutputsEnum():
-	"""
-	TRANSIENTNUMREQUESTEDOUTPUTSENUM - Enum of TransientNumRequestedOutputs
-
-	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=TransientNumRequestedOutputsEnum()
-	"""
-
-	return StringToEnum('TransientNumRequestedOutputs')[0]
-
-def TransientRequestedOutputsEnum():
-	"""
-	TRANSIENTREQUESTEDOUTPUTSENUM - Enum of TransientRequestedOutputs
-
-	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=TransientRequestedOutputsEnum()
-	"""
-
-	return StringToEnum('TransientRequestedOutputs')[0]
-
-def SolutionTypeEnum():
-	"""
-	SOLUTIONTYPEENUM - Enum of SolutionType
-
-	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=SolutionTypeEnum()
-	"""
-
-	return StringToEnum('SolutionType')[0]
-
-def AnalysisTypeEnum():
-	"""
-	ANALYSISTYPEENUM - Enum of AnalysisType
-
-	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=AnalysisTypeEnum()
-	"""
-
-	return StringToEnum('AnalysisType')[0]
-
-def ConfigurationTypeEnum():
-	"""
-	CONFIGURATIONTYPEENUM - Enum of ConfigurationType
-
-	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=ConfigurationTypeEnum()
-	"""
-
-	return StringToEnum('ConfigurationType')[0]
-
-def AdjointBalancethicknessAnalysisEnum():
-	"""
-	ADJOINTBALANCETHICKNESSANALYSISENUM - Enum of AdjointBalancethicknessAnalysis
-
-	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=AdjointBalancethicknessAnalysisEnum()
-	"""
-
-	return StringToEnum('AdjointBalancethicknessAnalysis')[0]
-
-def AdjointHorizAnalysisEnum():
-	"""
-	ADJOINTHORIZANALYSISENUM - Enum of AdjointHorizAnalysis
-
-	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=AdjointHorizAnalysisEnum()
-	"""
-
-	return StringToEnum('AdjointHorizAnalysis')[0]
-
-def AdjointSolutionEnum():
-	"""
-	ADJOINTSOLUTIONENUM - Enum of AdjointSolution
-
-	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=AdjointSolutionEnum()
-	"""
-
-	return StringToEnum('AdjointSolution')[0]
-
-def AnalysisCounterEnum():
-	"""
-	ANALYSISCOUNTERENUM - Enum of AnalysisCounter
-
-	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=AnalysisCounterEnum()
-	"""
-
-	return StringToEnum('AnalysisCounter')[0]
-
-def NoneAnalysisEnum():
-	"""
-	NONEANALYSISENUM - Enum of NoneAnalysis
-
-	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=NoneAnalysisEnum()
-	"""
-
-	return StringToEnum('NoneAnalysis')[0]
-
-def DefaultAnalysisEnum():
-	"""
-	DEFAULTANALYSISENUM - Enum of DefaultAnalysis
-
-	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=DefaultAnalysisEnum()
-	"""
-
-	return StringToEnum('DefaultAnalysis')[0]
-
-def BalancethicknessAnalysisEnum():
-	"""
-	BALANCETHICKNESSANALYSISENUM - Enum of BalancethicknessAnalysis
-
-	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=BalancethicknessAnalysisEnum()
-	"""
-
-	return StringToEnum('BalancethicknessAnalysis')[0]
-
-def BalancethicknessSolutionEnum():
-	"""
-	BALANCETHICKNESSSOLUTIONENUM - Enum of BalancethicknessSolution
-
-	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=BalancethicknessSolutionEnum()
-	"""
-
-	return StringToEnum('BalancethicknessSolution')[0]
-
-def BalancethicknessSoftAnalysisEnum():
-	"""
-	BALANCETHICKNESSSOFTANALYSISENUM - Enum of BalancethicknessSoftAnalysis
-
-	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=BalancethicknessSoftAnalysisEnum()
-	"""
-
-	return StringToEnum('BalancethicknessSoftAnalysis')[0]
-
-def BalancethicknessSoftSolutionEnum():
-	"""
-	BALANCETHICKNESSSOFTSOLUTIONENUM - Enum of BalancethicknessSoftSolution
-
-	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=BalancethicknessSoftSolutionEnum()
-	"""
-
-	return StringToEnum('BalancethicknessSoftSolution')[0]
-
-def BedSlopeAnalysisEnum():
-	"""
-	BEDSLOPEANALYSISENUM - Enum of BedSlopeAnalysis
-
-	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=BedSlopeAnalysisEnum()
-	"""
-
-	return StringToEnum('BedSlopeAnalysis')[0]
-
-def BedSlopeSolutionEnum():
-	"""
-	BEDSLOPESOLUTIONENUM - Enum of BedSlopeSolution
-
-	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=BedSlopeSolutionEnum()
-	"""
-
-	return StringToEnum('BedSlopeSolution')[0]
-
-def BedSlopeXAnalysisEnum():
-	"""
-	BEDSLOPEXANALYSISENUM - Enum of BedSlopeXAnalysis
-
-	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=BedSlopeXAnalysisEnum()
-	"""
-
-	return StringToEnum('BedSlopeXAnalysis')[0]
-
-def BedSlopeYAnalysisEnum():
-	"""
-	BEDSLOPEYANALYSISENUM - Enum of BedSlopeYAnalysis
-
-	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=BedSlopeYAnalysisEnum()
-	"""
-
-	return StringToEnum('BedSlopeYAnalysis')[0]
-
-def DiagnosticHorizAnalysisEnum():
-	"""
-	DIAGNOSTICHORIZANALYSISENUM - Enum of DiagnosticHorizAnalysis
-
-	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=DiagnosticHorizAnalysisEnum()
-	"""
-
-	return StringToEnum('DiagnosticHorizAnalysis')[0]
-
-def DiagnosticHutterAnalysisEnum():
-	"""
-	DIAGNOSTICHUTTERANALYSISENUM - Enum of DiagnosticHutterAnalysis
-
-	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=DiagnosticHutterAnalysisEnum()
-	"""
-
-	return StringToEnum('DiagnosticHutterAnalysis')[0]
-
-def DiagnosticSolutionEnum():
-	"""
-	DIAGNOSTICSOLUTIONENUM - Enum of DiagnosticSolution
-
-	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=DiagnosticSolutionEnum()
-	"""
-
-	return StringToEnum('DiagnosticSolution')[0]
-
-def DiagnosticVertAnalysisEnum():
-	"""
-	DIAGNOSTICVERTANALYSISENUM - Enum of DiagnosticVertAnalysis
-
-	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=DiagnosticVertAnalysisEnum()
-	"""
-
-	return StringToEnum('DiagnosticVertAnalysis')[0]
-
-def EnthalpyAnalysisEnum():
-	"""
-	ENTHALPYANALYSISENUM - Enum of EnthalpyAnalysis
-
-	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=EnthalpyAnalysisEnum()
-	"""
-
-	return StringToEnum('EnthalpyAnalysis')[0]
-
-def EnthalpySolutionEnum():
-	"""
-	ENTHALPYSOLUTIONENUM - Enum of EnthalpySolution
-
-	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=EnthalpySolutionEnum()
-	"""
-
-	return StringToEnum('EnthalpySolution')[0]
-
-def FlaimAnalysisEnum():
-	"""
-	FLAIMANALYSISENUM - Enum of FlaimAnalysis
-
-	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=FlaimAnalysisEnum()
-	"""
-
-	return StringToEnum('FlaimAnalysis')[0]
-
-def FlaimSolutionEnum():
-	"""
-	FLAIMSOLUTIONENUM - Enum of FlaimSolution
-
-	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=FlaimSolutionEnum()
-	"""
-
-	return StringToEnum('FlaimSolution')[0]
-
-def HydrologyShreveAnalysisEnum():
-	"""
-	HYDROLOGYSHREVEANALYSISENUM - Enum of HydrologyShreveAnalysis
-
-	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=HydrologyShreveAnalysisEnum()
-	"""
-
-	return StringToEnum('HydrologyShreveAnalysis')[0]
-
-def HydrologyDCInefficientAnalysisEnum():
-	"""
-	HYDROLOGYDCINEFFICIENTANALYSISENUM - Enum of HydrologyDCInefficientAnalysis
-
-	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=HydrologyDCInefficientAnalysisEnum()
-	"""
-
-	return StringToEnum('HydrologyDCInefficientAnalysis')[0]
-
-def HydrologyDCEfficientAnalysisEnum():
-	"""
-	HYDROLOGYDCEFFICIENTANALYSISENUM - Enum of HydrologyDCEfficientAnalysis
-
-	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=HydrologyDCEfficientAnalysisEnum()
-	"""
-
-	return StringToEnum('HydrologyDCEfficientAnalysis')[0]
-
-def HydrologySolutionEnum():
-	"""
-	HYDROLOGYSOLUTIONENUM - Enum of HydrologySolution
-
-	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=HydrologySolutionEnum()
-	"""
-
-	return StringToEnum('HydrologySolution')[0]
-
-def MeltingAnalysisEnum():
-	"""
-	MELTINGANALYSISENUM - Enum of MeltingAnalysis
-
-	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=MeltingAnalysisEnum()
-	"""
-
-	return StringToEnum('MeltingAnalysis')[0]
-
-def PrognosticAnalysisEnum():
-	"""
-	PROGNOSTICANALYSISENUM - Enum of PrognosticAnalysis
-
-	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=PrognosticAnalysisEnum()
-	"""
-
-	return StringToEnum('PrognosticAnalysis')[0]
-
-def PrognosticSolutionEnum():
-	"""
-	PROGNOSTICSOLUTIONENUM - Enum of PrognosticSolution
-
-	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=PrognosticSolutionEnum()
-	"""
-
-	return StringToEnum('PrognosticSolution')[0]
-
-def SteadystateSolutionEnum():
-	"""
-	STEADYSTATESOLUTIONENUM - Enum of SteadystateSolution
-
-	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=SteadystateSolutionEnum()
-	"""
-
-	return StringToEnum('SteadystateSolution')[0]
-
-def SurfaceSlopeAnalysisEnum():
-	"""
-	SURFACESLOPEANALYSISENUM - Enum of SurfaceSlopeAnalysis
-
-	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=SurfaceSlopeAnalysisEnum()
-	"""
-
-	return StringToEnum('SurfaceSlopeAnalysis')[0]
-
-def SurfaceSlopeSolutionEnum():
-	"""
-	SURFACESLOPESOLUTIONENUM - Enum of SurfaceSlopeSolution
-
-	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=SurfaceSlopeSolutionEnum()
-	"""
-
-	return StringToEnum('SurfaceSlopeSolution')[0]
-
-def SurfaceSlopeXAnalysisEnum():
-	"""
-	SURFACESLOPEXANALYSISENUM - Enum of SurfaceSlopeXAnalysis
-
-	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=SurfaceSlopeXAnalysisEnum()
-	"""
-
-	return StringToEnum('SurfaceSlopeXAnalysis')[0]
-
-def SurfaceSlopeYAnalysisEnum():
-	"""
-	SURFACESLOPEYANALYSISENUM - Enum of SurfaceSlopeYAnalysis
-
-	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=SurfaceSlopeYAnalysisEnum()
-	"""
-
-	return StringToEnum('SurfaceSlopeYAnalysis')[0]
-
-def ThermalAnalysisEnum():
-	"""
-	THERMALANALYSISENUM - Enum of ThermalAnalysis
-
-	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=ThermalAnalysisEnum()
-	"""
-
-	return StringToEnum('ThermalAnalysis')[0]
-
-def ThermalSolutionEnum():
-	"""
-	THERMALSOLUTIONENUM - Enum of ThermalSolution
-
-	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=ThermalSolutionEnum()
-	"""
-
-	return StringToEnum('ThermalSolution')[0]
-
-def TransientSolutionEnum():
-	"""
-	TRANSIENTSOLUTIONENUM - Enum of TransientSolution
-
-	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=TransientSolutionEnum()
-	"""
-
-	return StringToEnum('TransientSolution')[0]
-
-def GiaSolutionEnum():
-	"""
-	GIASOLUTIONENUM - Enum of GiaSolution
-
-	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=GiaSolutionEnum()
-	"""
-
-	return StringToEnum('GiaSolution')[0]
-
-def GiaAnalysisEnum():
-	"""
-	GIAANALYSISENUM - Enum of GiaAnalysis
-
-	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=GiaAnalysisEnum()
-	"""
-
-	return StringToEnum('GiaAnalysis')[0]
-
-def ApproximationEnum():
-	"""
-	APPROXIMATIONENUM - Enum of Approximation
-
-	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=ApproximationEnum()
-	"""
-
-	return StringToEnum('Approximation')[0]
-
-def NoneApproximationEnum():
-	"""
-	NONEAPPROXIMATIONENUM - Enum of NoneApproximation
-
-	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=NoneApproximationEnum()
-	"""
-
-	return StringToEnum('NoneApproximation')[0]
-
-def HutterApproximationEnum():
-	"""
-	HUTTERAPPROXIMATIONENUM - Enum of HutterApproximation
-
-	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=HutterApproximationEnum()
-	"""
-
-	return StringToEnum('HutterApproximation')[0]
-
-def MacAyealApproximationEnum():
-	"""
-	MACAYEALAPPROXIMATIONENUM - Enum of MacAyealApproximation
-
-	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=MacAyealApproximationEnum()
-	"""
-
-	return StringToEnum('MacAyealApproximation')[0]
-
-def MacAyealPattynApproximationEnum():
-	"""
-	MACAYEALPATTYNAPPROXIMATIONENUM - Enum of MacAyealPattynApproximation
-
-	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=MacAyealPattynApproximationEnum()
-	"""
-
-	return StringToEnum('MacAyealPattynApproximation')[0]
-
-def MacAyealStokesApproximationEnum():
-	"""
-	MACAYEALSTOKESAPPROXIMATIONENUM - Enum of MacAyealStokesApproximation
-
-	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=MacAyealStokesApproximationEnum()
-	"""
-
-	return StringToEnum('MacAyealStokesApproximation')[0]
-
-def L1L2ApproximationEnum():
-	"""
-	L1L2APPROXIMATIONENUM - Enum of L1L2Approximation
-
-	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=L1L2ApproximationEnum()
-	"""
-
-	return StringToEnum('L1L2Approximation')[0]
-
-def PattynApproximationEnum():
-	"""
-	PATTYNAPPROXIMATIONENUM - Enum of PattynApproximation
-
-	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=PattynApproximationEnum()
-	"""
-
-	return StringToEnum('PattynApproximation')[0]
-
-def PattynStokesApproximationEnum():
-	"""
-	PATTYNSTOKESAPPROXIMATIONENUM - Enum of PattynStokesApproximation
-
-	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=PattynStokesApproximationEnum()
-	"""
-
-	return StringToEnum('PattynStokesApproximation')[0]
-
-def StokesApproximationEnum():
-	"""
-	STOKESAPPROXIMATIONENUM - Enum of StokesApproximation
-
-	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=StokesApproximationEnum()
-	"""
-
-	return StringToEnum('StokesApproximation')[0]
-
-def ConstraintsEnum():
-	"""
-	CONSTRAINTSENUM - Enum of Constraints
-
-	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=ConstraintsEnum()
-	"""
-
-	return StringToEnum('Constraints')[0]
-
-def LoadsEnum():
-	"""
-	LOADSENUM - Enum of Loads
-
-	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=LoadsEnum()
-	"""
-
-	return StringToEnum('Loads')[0]
-
-def MaterialsEnum():
-	"""
-	MATERIALSENUM - Enum of Materials
-
-	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=MaterialsEnum()
-	"""
-
-	return StringToEnum('Materials')[0]
-
-def NodesEnum():
-	"""
-	NODESENUM - Enum of Nodes
-
-	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=NodesEnum()
-	"""
-
-	return StringToEnum('Nodes')[0]
-
-def ContoursEnum():
-	"""
-	CONTOURSENUM - Enum of Contours
-
-	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=ContoursEnum()
-	"""
-
-	return StringToEnum('Contours')[0]
-
-def ParametersEnum():
-	"""
-	PARAMETERSENUM - Enum of Parameters
-
-	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=ParametersEnum()
-	"""
-
-	return StringToEnum('Parameters')[0]
-
-def VerticesEnum():
-	"""
-	VERTICESENUM - Enum of Vertices
-
-	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=VerticesEnum()
-	"""
-
-	return StringToEnum('Vertices')[0]
-
-def ResultsEnum():
-	"""
-	RESULTSENUM - Enum of Results
-
-	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=ResultsEnum()
-	"""
-
-	return StringToEnum('Results')[0]
-
-def GenericParamEnum():
-	"""
-	GENERICPARAMENUM - Enum of GenericParam
-
-	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=GenericParamEnum()
-	"""
-
-	return StringToEnum('GenericParam')[0]
-
-def AdolcParamEnum():
-	"""
-	ADOLCPARAMENUM - Enum of AdolcParam
-
-	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=AdolcParamEnum()
-	"""
-
-	return StringToEnum('AdolcParam')[0]
-
-def BoolInputEnum():
-	"""
-	BOOLINPUTENUM - Enum of BoolInput
-
-	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=BoolInputEnum()
-	"""
-
-	return StringToEnum('BoolInput')[0]
-
-def BoolParamEnum():
-	"""
-	BOOLPARAMENUM - Enum of BoolParam
-
-	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=BoolParamEnum()
-	"""
-
-	return StringToEnum('BoolParam')[0]
-
-def ContourEnum():
-	"""
-	CONTOURENUM - Enum of Contour
-
-	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=ContourEnum()
-	"""
-
-	return StringToEnum('Contour')[0]
-
-def ControlInputEnum():
-	"""
-	CONTROLINPUTENUM - Enum of ControlInput
-
-	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=ControlInputEnum()
-	"""
-
-	return StringToEnum('ControlInput')[0]
-
-def DatasetInputEnum():
-	"""
-	DATASETINPUTENUM - Enum of DatasetInput
-
-	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=DatasetInputEnum()
-	"""
-
-	return StringToEnum('DatasetInput')[0]
-
-def DofIndexingEnum():
-	"""
-	DOFINDEXINGENUM - Enum of DofIndexing
-
-	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=DofIndexingEnum()
-	"""
-
-	return StringToEnum('DofIndexing')[0]
-
-def DoubleInputEnum():
-	"""
-	DOUBLEINPUTENUM - Enum of DoubleInput
-
-	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=DoubleInputEnum()
-	"""
-
-	return StringToEnum('DoubleInput')[0]
-
-def DataSetParamEnum():
-	"""
-	DATASETPARAMENUM - Enum of DataSetParam
-
-	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=DataSetParamEnum()
-	"""
-
-	return StringToEnum('DataSetParam')[0]
-
-def DoubleMatArrayParamEnum():
-	"""
-	DOUBLEMATARRAYPARAMENUM - Enum of DoubleMatArrayParam
-
-	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=DoubleMatArrayParamEnum()
-	"""
-
-	return StringToEnum('DoubleMatArrayParam')[0]
-
-def DoubleMatParamEnum():
-	"""
-	DOUBLEMATPARAMENUM - Enum of DoubleMatParam
-
-	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=DoubleMatParamEnum()
-	"""
-
-	return StringToEnum('DoubleMatParam')[0]
-
-def DoubleParamEnum():
-	"""
-	DOUBLEPARAMENUM - Enum of DoubleParam
-
-	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=DoubleParamEnum()
-	"""
-
-	return StringToEnum('DoubleParam')[0]
-
-def DoubleVecParamEnum():
-	"""
-	DOUBLEVECPARAMENUM - Enum of DoubleVecParam
-
-	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=DoubleVecParamEnum()
-	"""
-
-	return StringToEnum('DoubleVecParam')[0]
-
-def ElementEnum():
-	"""
-	ELEMENTENUM - Enum of Element
-
-	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=ElementEnum()
-	"""
-
-	return StringToEnum('Element')[0]
-
-def ElementResultEnum():
-	"""
-	ELEMENTRESULTENUM - Enum of ElementResult
-
-	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=ElementResultEnum()
-	"""
-
-	return StringToEnum('ElementResult')[0]
-
-def ExternalResultEnum():
-	"""
-	EXTERNALRESULTENUM - Enum of ExternalResult
-
-	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=ExternalResultEnum()
-	"""
-
-	return StringToEnum('ExternalResult')[0]
-
-def FileParamEnum():
-	"""
-	FILEPARAMENUM - Enum of FileParam
-
-	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=FileParamEnum()
-	"""
-
-	return StringToEnum('FileParam')[0]
-
-def HookEnum():
-	"""
-	HOOKENUM - Enum of Hook
-
-	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=HookEnum()
-	"""
-
-	return StringToEnum('Hook')[0]
-
-def IcefrontEnum():
-	"""
-	ICEFRONTENUM - Enum of Icefront
-
-	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=IcefrontEnum()
-	"""
-
-	return StringToEnum('Icefront')[0]
-
-def InputEnum():
-	"""
-	INPUTENUM - Enum of Input
-
-	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=InputEnum()
-	"""
-
-	return StringToEnum('Input')[0]
-
-def IntInputEnum():
-	"""
-	INTINPUTENUM - Enum of IntInput
-
-	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=IntInputEnum()
-	"""
-
-	return StringToEnum('IntInput')[0]
-
-def IntParamEnum():
-	"""
-	INTPARAMENUM - Enum of IntParam
-
-	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=IntParamEnum()
-	"""
-
-	return StringToEnum('IntParam')[0]
-
-def IntVecParamEnum():
-	"""
-	INTVECPARAMENUM - Enum of IntVecParam
-
-	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=IntVecParamEnum()
-	"""
-
-	return StringToEnum('IntVecParam')[0]
-
-def TransientParamEnum():
-	"""
-	TRANSIENTPARAMENUM - Enum of TransientParam
-
-	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=TransientParamEnum()
-	"""
-
-	return StringToEnum('TransientParam')[0]
-
-def IceFrontTypeEnum():
-	"""
-	ICEFRONTTYPEENUM - Enum of IceFrontType
-
-	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=IceFrontTypeEnum()
-	"""
-
-	return StringToEnum('IceFrontType')[0]
-
-def MacAyeal2dIceFrontEnum():
-	"""
-	MACAYEAL2DICEFRONTENUM - Enum of MacAyeal2dIceFront
-
-	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=MacAyeal2dIceFrontEnum()
-	"""
-
-	return StringToEnum('MacAyeal2dIceFront')[0]
-
-def MacAyeal3dIceFrontEnum():
-	"""
-	MACAYEAL3DICEFRONTENUM - Enum of MacAyeal3dIceFront
-
-	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=MacAyeal3dIceFrontEnum()
-	"""
-
-	return StringToEnum('MacAyeal3dIceFront')[0]
-
-def MaticeEnum():
-	"""
-	MATICEENUM - Enum of Matice
-
-	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=MaticeEnum()
-	"""
-
-	return StringToEnum('Matice')[0]
-
-def MatdamageiceEnum():
-	"""
-	MATDAMAGEICEENUM - Enum of Matdamageice
-
-	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=MatdamageiceEnum()
-	"""
-
-	return StringToEnum('Matdamageice')[0]
-
-def MatparEnum():
-	"""
-	MATPARENUM - Enum of Matpar
-
-	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=MatparEnum()
-	"""
-
-	return StringToEnum('Matpar')[0]
-
-def NodeEnum():
-	"""
-	NODEENUM - Enum of Node
-
-	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=NodeEnum()
-	"""
-
-	return StringToEnum('Node')[0]
-
-def NumericalfluxEnum():
-	"""
-	NUMERICALFLUXENUM - Enum of Numericalflux
-
-	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=NumericalfluxEnum()
-	"""
-
-	return StringToEnum('Numericalflux')[0]
-
-def NumericalfluxTypeEnum():
-	"""
-	NUMERICALFLUXTYPEENUM - Enum of NumericalfluxType
-
-	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=NumericalfluxTypeEnum()
-	"""
-
-	return StringToEnum('NumericalfluxType')[0]
-
-def ParamEnum():
-	"""
-	PARAMENUM - Enum of Param
-
-	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=ParamEnum()
-	"""
-
-	return StringToEnum('Param')[0]
-
-def L1L2IceFrontEnum():
-	"""
-	L1L2ICEFRONTENUM - Enum of L1L2IceFront
-
-	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=L1L2IceFrontEnum()
-	"""
-
-	return StringToEnum('L1L2IceFront')[0]
-
-def PattynIceFrontEnum():
-	"""
-	PATTYNICEFRONTENUM - Enum of PattynIceFront
-
-	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=PattynIceFrontEnum()
-	"""
-
-	return StringToEnum('PattynIceFront')[0]
-
-def PengridEnum():
-	"""
-	PENGRIDENUM - Enum of Pengrid
-
-	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=PengridEnum()
-	"""
-
-	return StringToEnum('Pengrid')[0]
-
-def PenpairEnum():
-	"""
-	PENPAIRENUM - Enum of Penpair
-
-	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=PenpairEnum()
-	"""
-
-	return StringToEnum('Penpair')[0]
-
-def PentaEnum():
-	"""
-	PENTAENUM - Enum of Penta
-
-	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=PentaEnum()
-	"""
-
-	return StringToEnum('Penta')[0]
-
-def PentaP1InputEnum():
-	"""
-	PENTAP1INPUTENUM - Enum of PentaP1Input
-
-	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=PentaP1InputEnum()
-	"""
-
-	return StringToEnum('PentaP1Input')[0]
-
-def ProfilerEnum():
-	"""
-	PROFILERENUM - Enum of Profiler
-
-	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=ProfilerEnum()
-	"""
-
-	return StringToEnum('Profiler')[0]
-
-def MatrixParamEnum():
-	"""
-	MATRIXPARAMENUM - Enum of MatrixParam
-
-	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=MatrixParamEnum()
-	"""
-
-	return StringToEnum('MatrixParam')[0]
-
-def NodeSIdEnum():
-	"""
-	NODESIDENUM - Enum of NodeSId
-
-	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=NodeSIdEnum()
-	"""
-
-	return StringToEnum('NodeSId')[0]
-
-def VectorParamEnum():
-	"""
-	VECTORPARAMENUM - Enum of VectorParam
-
-	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=VectorParamEnum()
-	"""
-
-	return StringToEnum('VectorParam')[0]
-
-def RiftfrontEnum():
-	"""
-	RIFTFRONTENUM - Enum of Riftfront
-
-	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=RiftfrontEnum()
-	"""
-
-	return StringToEnum('Riftfront')[0]
-
-def RiftfrontTypeEnum():
-	"""
-	RIFTFRONTTYPEENUM - Enum of RiftfrontType
-
-	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=RiftfrontTypeEnum()
-	"""
-
-	return StringToEnum('RiftfrontType')[0]
-
-def SegmentEnum():
-	"""
-	SEGMENTENUM - Enum of Segment
-
-	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=SegmentEnum()
-	"""
-
-	return StringToEnum('Segment')[0]
-
-def SegmentRiftfrontEnum():
-	"""
-	SEGMENTRIFTFRONTENUM - Enum of SegmentRiftfront
-
-	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=SegmentRiftfrontEnum()
-	"""
-
-	return StringToEnum('SegmentRiftfront')[0]
-
-def SpcDynamicEnum():
-	"""
-	SPCDYNAMICENUM - Enum of SpcDynamic
-
-	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=SpcDynamicEnum()
-	"""
-
-	return StringToEnum('SpcDynamic')[0]
-
-def SpcStaticEnum():
-	"""
-	SPCSTATICENUM - Enum of SpcStatic
-
-	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=SpcStaticEnum()
-	"""
-
-	return StringToEnum('SpcStatic')[0]
-
-def SpcTransientEnum():
-	"""
-	SPCTRANSIENTENUM - Enum of SpcTransient
-
-	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=SpcTransientEnum()
-	"""
-
-	return StringToEnum('SpcTransient')[0]
-
-def StokesIceFrontEnum():
-	"""
-	STOKESICEFRONTENUM - Enum of StokesIceFront
-
-	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=StokesIceFrontEnum()
-	"""
-
-	return StringToEnum('StokesIceFront')[0]
-
-def StringArrayParamEnum():
-	"""
-	STRINGARRAYPARAMENUM - Enum of StringArrayParam
-
-	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=StringArrayParamEnum()
-	"""
-
-	return StringToEnum('StringArrayParam')[0]
-
-def StringParamEnum():
-	"""
-	STRINGPARAMENUM - Enum of StringParam
-
-	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=StringParamEnum()
-	"""
-
-	return StringToEnum('StringParam')[0]
-
-def TriaEnum():
-	"""
-	TRIAENUM - Enum of Tria
-
-	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=TriaEnum()
-	"""
-
-	return StringToEnum('Tria')[0]
-
-def TriaInputEnum():
-	"""
-	TRIAINPUTENUM - Enum of TriaInput
-
-	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=TriaInputEnum()
-	"""
-
-	return StringToEnum('TriaInput')[0]
-
-def VertexEnum():
-	"""
-	VERTEXENUM - Enum of Vertex
-
-	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=VertexEnum()
-	"""
-
-	return StringToEnum('Vertex')[0]
-
-def VertexPIdEnum():
-	"""
-	VERTEXPIDENUM - Enum of VertexPId
-
-	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=VertexPIdEnum()
-	"""
-
-	return StringToEnum('VertexPId')[0]
-
-def VertexSIdEnum():
-	"""
-	VERTEXSIDENUM - Enum of VertexSId
-
-	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=VertexSIdEnum()
-	"""
-
-	return StringToEnum('VertexSId')[0]
-
-def AirEnum():
-	"""
-	AIRENUM - Enum of Air
-
-	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=AirEnum()
-	"""
-
-	return StringToEnum('Air')[0]
-
-def IceEnum():
-	"""
-	ICEENUM - Enum of Ice
-
-	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=IceEnum()
-	"""
-
-	return StringToEnum('Ice')[0]
-
-def MelangeEnum():
-	"""
-	MELANGEENUM - Enum of Melange
-
-	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=MelangeEnum()
-	"""
-
-	return StringToEnum('Melange')[0]
-
-def WaterEnum():
-	"""
-	WATERENUM - Enum of Water
-
-	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=WaterEnum()
-	"""
-
-	return StringToEnum('Water')[0]
-
-def ClosedEnum():
-	"""
-	CLOSEDENUM - Enum of Closed
-
-	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=ClosedEnum()
-	"""
-
-	return StringToEnum('Closed')[0]
-
-def FreeEnum():
-	"""
-	FREEENUM - Enum of Free
-
-	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=FreeEnum()
-	"""
-
-	return StringToEnum('Free')[0]
-
-def OpenEnum():
-	"""
-	OPENENUM - Enum of Open
-
-	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=OpenEnum()
-	"""
-
-	return StringToEnum('Open')[0]
-
-def AdjointpEnum():
-	"""
-	ADJOINTPENUM - Enum of Adjointp
-
-	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=AdjointpEnum()
-	"""
-
-	return StringToEnum('Adjointp')[0]
-
-def AdjointxEnum():
-	"""
-	ADJOINTXENUM - Enum of Adjointx
-
-	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=AdjointxEnum()
-	"""
-
-	return StringToEnum('Adjointx')[0]
-
-def AdjointyEnum():
-	"""
-	ADJOINTYENUM - Enum of Adjointy
-
-	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=AdjointyEnum()
-	"""
-
-	return StringToEnum('Adjointy')[0]
-
-def AdjointzEnum():
-	"""
-	ADJOINTZENUM - Enum of Adjointz
-
-	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=AdjointzEnum()
-	"""
-
-	return StringToEnum('Adjointz')[0]
-
-def BalancethicknessMisfitEnum():
-	"""
-	BALANCETHICKNESSMISFITENUM - Enum of BalancethicknessMisfit
-
-	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=BalancethicknessMisfitEnum()
-	"""
-
-	return StringToEnum('BalancethicknessMisfit')[0]
-
-def BedSlopeXEnum():
-	"""
-	BEDSLOPEXENUM - Enum of BedSlopeX
-
-	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=BedSlopeXEnum()
-	"""
-
-	return StringToEnum('BedSlopeX')[0]
-
-def BedSlopeYEnum():
-	"""
-	BEDSLOPEYENUM - Enum of BedSlopeY
-
-	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=BedSlopeYEnum()
-	"""
-
-	return StringToEnum('BedSlopeY')[0]
-
-def BoundaryEnum():
-	"""
-	BOUNDARYENUM - Enum of Boundary
-
-	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=BoundaryEnum()
-	"""
-
-	return StringToEnum('Boundary')[0]
-
-def ConstantEnum():
-	"""
-	CONSTANTENUM - Enum of Constant
-
-	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=ConstantEnum()
-	"""
-
-	return StringToEnum('Constant')[0]
-
-def ConvergedEnum():
-	"""
-	CONVERGEDENUM - Enum of Converged
-
-	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=ConvergedEnum()
-	"""
-
-	return StringToEnum('Converged')[0]
-
-def FillEnum():
-	"""
-	FILLENUM - Enum of Fill
-
-	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=FillEnum()
-	"""
-
-	return StringToEnum('Fill')[0]
-
-def FractionIncrementEnum():
-	"""
-	FRACTIONINCREMENTENUM - Enum of FractionIncrement
-
-	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=FractionIncrementEnum()
-	"""
-
-	return StringToEnum('FractionIncrement')[0]
-
-def FrictionEnum():
-	"""
-	FRICTIONENUM - Enum of Friction
-
-	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=FrictionEnum()
-	"""
-
-	return StringToEnum('Friction')[0]
-
-def GroundinglineMeltingRateEnum():
-	"""
-	GROUNDINGLINEMELTINGRATEENUM - Enum of GroundinglineMeltingRate
-
-	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=GroundinglineMeltingRateEnum()
-	"""
-
-	return StringToEnum('GroundinglineMeltingRate')[0]
-
-def InternalEnum():
-	"""
-	INTERNALENUM - Enum of Internal
-
-	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=InternalEnum()
-	"""
-
-	return StringToEnum('Internal')[0]
-
-def MassFluxEnum():
-	"""
-	MASSFLUXENUM - Enum of MassFlux
-
-	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=MassFluxEnum()
-	"""
-
-	return StringToEnum('MassFlux')[0]
-
-def MaxPenetrationEnum():
-	"""
-	MAXPENETRATIONENUM - Enum of MaxPenetration
-
-	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=MaxPenetrationEnum()
-	"""
-
-	return StringToEnum('MaxPenetration')[0]
-
-def MeltingOffsetEnum():
-	"""
-	MELTINGOFFSETENUM - Enum of MeltingOffset
-
-	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=MeltingOffsetEnum()
-	"""
-
-	return StringToEnum('MeltingOffset')[0]
-
-def MisfitEnum():
-	"""
-	MISFITENUM - Enum of Misfit
-
-	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=MisfitEnum()
-	"""
-
-	return StringToEnum('Misfit')[0]
-
-def NumberNodeToElementConnectivityEnum():
-	"""
-	NUMBERNODETOELEMENTCONNECTIVITYENUM - Enum of NumberNodeToElementConnectivity
-
-	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=NumberNodeToElementConnectivityEnum()
-	"""
-
-	return StringToEnum('NumberNodeToElementConnectivity')[0]
-
-def PressureEnum():
-	"""
-	PRESSUREENUM - Enum of Pressure
-
-	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=PressureEnum()
-	"""
-
-	return StringToEnum('Pressure')[0]
-
-def PressurePicardEnum():
-	"""
-	PRESSUREPICARDENUM - Enum of PressurePicard
-
-	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=PressurePicardEnum()
-	"""
-
-	return StringToEnum('PressurePicard')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuPressure')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuVx')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuVy')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuVz')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuThickness')[0]
-
-def QmuBedEnum():
-	"""
-	QMUBEDENUM - Enum of QmuBed
-
-	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=QmuBedEnum()
-	"""
-
-	return StringToEnum('QmuBed')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuSurface')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuMelting')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuVxMesh')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuVyMesh')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuVzMesh')[0]
-
-def AndroidFrictionCoefficientEnum():
-	"""
-	ANDROIDFRICTIONCOEFFICIENTENUM - Enum of AndroidFrictionCoefficient
-
-	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=AndroidFrictionCoefficientEnum()
-	"""
-
-	return StringToEnum('AndroidFrictionCoefficient')[0]
-
-def ResetPenaltiesEnum():
-	"""
-	RESETPENALTIESENUM - Enum of ResetPenalties
-
-	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=ResetPenaltiesEnum()
-	"""
-
-	return StringToEnum('ResetPenalties')[0]
-
-def SegmentOnIceShelfEnum():
-	"""
-	SEGMENTONICESHELFENUM - Enum of SegmentOnIceShelf
-
-	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=SegmentOnIceShelfEnum()
-	"""
-
-	return StringToEnum('SegmentOnIceShelf')[0]
-
-def SurfaceAbsVelMisfitEnum():
-	"""
-	SURFACEABSVELMISFITENUM - Enum of SurfaceAbsVelMisfit
-
-	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=SurfaceAbsVelMisfitEnum()
-	"""
-
-	return StringToEnum('SurfaceAbsVelMisfit')[0]
-
-def SurfaceAreaEnum():
-	"""
-	SURFACEAREAENUM - Enum of SurfaceArea
-
-	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=SurfaceAreaEnum()
-	"""
-
-	return StringToEnum('SurfaceArea')[0]
-
-def SurfaceAverageVelMisfitEnum():
-	"""
-	SURFACEAVERAGEVELMISFITENUM - Enum of SurfaceAverageVelMisfit
-
-	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=SurfaceAverageVelMisfitEnum()
-	"""
-
-	return StringToEnum('SurfaceAverageVelMisfit')[0]
-
-def SurfaceLogVelMisfitEnum():
-	"""
-	SURFACELOGVELMISFITENUM - Enum of SurfaceLogVelMisfit
-
-	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=SurfaceLogVelMisfitEnum()
-	"""
-
-	return StringToEnum('SurfaceLogVelMisfit')[0]
-
-def SurfaceLogVxVyMisfitEnum():
-	"""
-	SURFACELOGVXVYMISFITENUM - Enum of SurfaceLogVxVyMisfit
-
-	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=SurfaceLogVxVyMisfitEnum()
-	"""
-
-	return StringToEnum('SurfaceLogVxVyMisfit')[0]
-
-def SurfaceRelVelMisfitEnum():
-	"""
-	SURFACERELVELMISFITENUM - Enum of SurfaceRelVelMisfit
-
-	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=SurfaceRelVelMisfitEnum()
-	"""
-
-	return StringToEnum('SurfaceRelVelMisfit')[0]
-
-def SurfaceSlopeXEnum():
-	"""
-	SURFACESLOPEXENUM - Enum of SurfaceSlopeX
-
-	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=SurfaceSlopeXEnum()
-	"""
-
-	return StringToEnum('SurfaceSlopeX')[0]
-
-def SurfaceSlopeYEnum():
-	"""
-	SURFACESLOPEYENUM - Enum of SurfaceSlopeY
-
-	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=SurfaceSlopeYEnum()
-	"""
-
-	return StringToEnum('SurfaceSlopeY')[0]
-
-def TemperatureEnum():
-	"""
-	TEMPERATUREENUM - Enum of Temperature
-
-	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=TemperatureEnum()
-	"""
-
-	return StringToEnum('Temperature')[0]
-
-def TemperatureOldEnum():
-	"""
-	TEMPERATUREOLDENUM - Enum of TemperatureOld
-
-	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=TemperatureOldEnum()
-	"""
-
-	return StringToEnum('TemperatureOld')[0]
-
-def TemperaturePicardEnum():
-	"""
-	TEMPERATUREPICARDENUM - Enum of TemperaturePicard
-
-	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=TemperaturePicardEnum()
-	"""
-
-	return StringToEnum('TemperaturePicard')[0]
-
-def ThicknessAbsMisfitEnum():
-	"""
-	THICKNESSABSMISFITENUM - Enum of ThicknessAbsMisfit
-
-	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=ThicknessAbsMisfitEnum()
-	"""
-
-	return StringToEnum('ThicknessAbsMisfit')[0]
-
-def VelEnum():
-	"""
-	VELENUM - Enum of Vel
-
-	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=VelEnum()
-	"""
-
-	return StringToEnum('Vel')[0]
-
-def VelocityEnum():
-	"""
-	VELOCITYENUM - Enum of Velocity
-
-	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=VelocityEnum()
-	"""
-
-	return StringToEnum('Velocity')[0]
-
-def VxAverageEnum():
-	"""
-	VXAVERAGEENUM - Enum of VxAverage
-
-	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=VxAverageEnum()
-	"""
-
-	return StringToEnum('VxAverage')[0]
-
-def VxEnum():
-	"""
-	VXENUM - Enum of Vx
-
-	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=VxEnum()
-	"""
-
-	return StringToEnum('Vx')[0]
-
-def VxPicardEnum():
-	"""
-	VXPICARDENUM - Enum of VxPicard
-
-	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=VxPicardEnum()
-	"""
-
-	return StringToEnum('VxPicard')[0]
-
-def VyAverageEnum():
-	"""
-	VYAVERAGEENUM - Enum of VyAverage
-
-	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=VyAverageEnum()
-	"""
-
-	return StringToEnum('VyAverage')[0]
-
-def VyEnum():
-	"""
-	VYENUM - Enum of Vy
-
-	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=VyEnum()
-	"""
-
-	return StringToEnum('Vy')[0]
-
-def VyPicardEnum():
-	"""
-	VYPICARDENUM - Enum of VyPicard
-
-	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=VyPicardEnum()
-	"""
-
-	return StringToEnum('VyPicard')[0]
-
-def VzEnum():
-	"""
-	VZENUM - Enum of Vz
-
-	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=VzEnum()
-	"""
-
-	return StringToEnum('Vz')[0]
-
-def VzMacAyealEnum():
-	"""
-	VZMACAYEALENUM - Enum of VzMacAyeal
-
-	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=VzMacAyealEnum()
-	"""
-
-	return StringToEnum('VzMacAyeal')[0]
-
-def VzPattynEnum():
-	"""
-	VZPATTYNENUM - Enum of VzPattyn
-
-	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=VzPattynEnum()
-	"""
-
-	return StringToEnum('VzPattyn')[0]
-
-def VzPicardEnum():
-	"""
-	VZPICARDENUM - Enum of VzPicard
-
-	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=VzPicardEnum()
-	"""
-
-	return StringToEnum('VzPicard')[0]
-
-def VzStokesEnum():
-	"""
-	VZSTOKESENUM - Enum of VzStokes
-
-	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=VzStokesEnum()
-	"""
-
-	return StringToEnum('VzStokes')[0]
-
-def VxMeshEnum():
-	"""
-	VXMESHENUM - Enum of VxMesh
-
-	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=VxMeshEnum()
-	"""
-
-	return StringToEnum('VxMesh')[0]
-
-def VyMeshEnum():
-	"""
-	VYMESHENUM - Enum of VyMesh
-
-	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=VyMeshEnum()
-	"""
-
-	return StringToEnum('VyMesh')[0]
-
-def VzMeshEnum():
-	"""
-	VZMESHENUM - Enum of VzMesh
-
-	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=VzMeshEnum()
-	"""
-
-	return StringToEnum('VzMesh')[0]
-
-def EnthalpyEnum():
-	"""
-	ENTHALPYENUM - Enum of Enthalpy
-
-	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=EnthalpyEnum()
-	"""
-
-	return StringToEnum('Enthalpy')[0]
-
-def EnthalpyPicardEnum():
-	"""
-	ENTHALPYPICARDENUM - Enum of EnthalpyPicard
-
-	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=EnthalpyPicardEnum()
-	"""
-
-	return StringToEnum('EnthalpyPicard')[0]
-
-def ThicknessAbsGradientEnum():
-	"""
-	THICKNESSABSGRADIENTENUM - Enum of ThicknessAbsGradient
-
-	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=ThicknessAbsGradientEnum()
-	"""
-
-	return StringToEnum('ThicknessAbsGradient')[0]
-
-def ThicknessAlongGradientEnum():
-	"""
-	THICKNESSALONGGRADIENTENUM - Enum of ThicknessAlongGradient
-
-	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=ThicknessAlongGradientEnum()
-	"""
-
-	return StringToEnum('ThicknessAlongGradient')[0]
-
-def ThicknessAcrossGradientEnum():
-	"""
-	THICKNESSACROSSGRADIENTENUM - Enum of ThicknessAcrossGradient
-
-	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=ThicknessAcrossGradientEnum()
-	"""
-
-	return StringToEnum('ThicknessAcrossGradient')[0]
-
-def StepResponsesEnum():
-	"""
-	STEPRESPONSESENUM - Enum of StepResponses
-
-	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=StepResponsesEnum()
-	"""
-
-	return StringToEnum('StepResponses')[0]
-
-def IntMatParamEnum():
-	"""
-	INTMATPARAMENUM - Enum of IntMatParam
-
-	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=IntMatParamEnum()
-	"""
-
-	return StringToEnum('IntMatParam')[0]
-
-def RheologyBbarAbsGradientEnum():
-	"""
-	RHEOLOGYBBARABSGRADIENTENUM - Enum of RheologyBbarAbsGradient
-
-	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=RheologyBbarAbsGradientEnum()
-	"""
-
-	return StringToEnum('RheologyBbarAbsGradient')[0]
-
-def DragCoefficientAbsGradientEnum():
-	"""
-	DRAGCOEFFICIENTABSGRADIENTENUM - Enum of DragCoefficientAbsGradient
-
-	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=DragCoefficientAbsGradientEnum()
-	"""
-
-	return StringToEnum('DragCoefficientAbsGradient')[0]
-
-def TransientInputEnum():
-	"""
-	TRANSIENTINPUTENUM - Enum of TransientInput
-
-	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=TransientInputEnum()
-	"""
-
-	return StringToEnum('TransientInput')[0]
-
-def WaterfractionEnum():
-	"""
-	WATERFRACTIONENUM - Enum of Waterfraction
-
-	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=WaterfractionEnum()
-	"""
-
-	return StringToEnum('Waterfraction')[0]
-
-def WatercolumnEnum():
-	"""
-	WATERCOLUMNENUM - Enum of Watercolumn
-
-	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=WatercolumnEnum()
-	"""
-
-	return StringToEnum('Watercolumn')[0]
-
-def BasalFrictionEnum():
-	"""
-	BASALFRICTIONENUM - Enum of BasalFriction
-
-	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=BasalFrictionEnum()
-	"""
-
-	return StringToEnum('BasalFriction')[0]
-
-def ViscousHeatingEnum():
-	"""
-	VISCOUSHEATINGENUM - Enum of ViscousHeating
-
-	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=ViscousHeatingEnum()
-	"""
-
-	return StringToEnum('ViscousHeating')[0]
-
-def 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()
-	"""
-
-	return StringToEnum('QmuTemperature')[0]
-
-def HydrologyWaterVxEnum():
-	"""
-	HYDROLOGYWATERVXENUM - Enum of HydrologyWaterVx
-
-	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=HydrologyWaterVxEnum()
-	"""
-
-	return StringToEnum('HydrologyWaterVx')[0]
-
-def HydrologyWaterVyEnum():
-	"""
-	HYDROLOGYWATERVYENUM - Enum of HydrologyWaterVy
-
-	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=HydrologyWaterVyEnum()
-	"""
-
-	return StringToEnum('HydrologyWaterVy')[0]
-
-def StressTensorEnum():
-	"""
-	STRESSTENSORENUM - Enum of StressTensor
-
-	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=StressTensorEnum()
-	"""
-
-	return StringToEnum('StressTensor')[0]
-
-def StressTensorxxEnum():
-	"""
-	STRESSTENSORXXENUM - Enum of StressTensorxx
-
-	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=StressTensorxxEnum()
-	"""
-
-	return StringToEnum('StressTensorxx')[0]
-
-def StressTensorxyEnum():
-	"""
-	STRESSTENSORXYENUM - Enum of StressTensorxy
-
-	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=StressTensorxyEnum()
-	"""
-
-	return StringToEnum('StressTensorxy')[0]
-
-def StressTensorxzEnum():
-	"""
-	STRESSTENSORXZENUM - Enum of StressTensorxz
-
-	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=StressTensorxzEnum()
-	"""
-
-	return StringToEnum('StressTensorxz')[0]
-
-def StressTensoryyEnum():
-	"""
-	STRESSTENSORYYENUM - Enum of StressTensoryy
-
-	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=StressTensoryyEnum()
-	"""
-
-	return StringToEnum('StressTensoryy')[0]
-
-def StressTensoryzEnum():
-	"""
-	STRESSTENSORYZENUM - Enum of StressTensoryz
-
-	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=StressTensoryzEnum()
-	"""
-
-	return StringToEnum('StressTensoryz')[0]
-
-def StressTensorzzEnum():
-	"""
-	STRESSTENSORZZENUM - Enum of StressTensorzz
-
-	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=StressTensorzzEnum()
-	"""
-
-	return StringToEnum('StressTensorzz')[0]
-
-def GiaCrossSectionShapeEnum():
-	"""
-	GIACROSSSECTIONSHAPEENUM - Enum of GiaCrossSectionShape
-
-	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=GiaCrossSectionShapeEnum()
-	"""
-
-	return StringToEnum('GiaCrossSectionShape')[0]
-
-def GiadWdtEnum():
-	"""
-	GIADWDTENUM - Enum of GiadWdt
-
-	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=GiadWdtEnum()
-	"""
-
-	return StringToEnum('GiadWdt')[0]
-
-def GiaWEnum():
-	"""
-	GIAWENUM - Enum of GiaW
-
-	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=GiaWEnum()
-	"""
-
-	return StringToEnum('GiaW')[0]
-
-def P0Enum():
-	"""
-	P0ENUM - Enum of P0
-
-	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=P0Enum()
-	"""
-
-	return StringToEnum('P0')[0]
-
-def P1Enum():
-	"""
-	P1ENUM - Enum of P1
-
-	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=P1Enum()
-	"""
-
-	return StringToEnum('P1')[0]
-
-def P1DGEnum():
-	"""
-	P1DGENUM - Enum of P1DG
-
-	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=P1DGEnum()
-	"""
-
-	return StringToEnum('P1DG')[0]
-
-def MINIEnum():
-	"""
-	MINIENUM - Enum of MINI
-
-	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=MINIEnum()
-	"""
-
-	return StringToEnum('MINI')[0]
-
-def P2Enum():
-	"""
-	P2ENUM - Enum of P2
-
-	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=P2Enum()
-	"""
-
-	return StringToEnum('P2')[0]
-
-def SaveResultsEnum():
-	"""
-	SAVERESULTSENUM - Enum of SaveResults
-
-	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=SaveResultsEnum()
-	"""
-
-	return StringToEnum('SaveResults')[0]
-
-def BoolElementResultEnum():
-	"""
-	BOOLELEMENTRESULTENUM - Enum of BoolElementResult
-
-	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=BoolElementResultEnum()
-	"""
-
-	return StringToEnum('BoolElementResult')[0]
-
-def BoolExternalResultEnum():
-	"""
-	BOOLEXTERNALRESULTENUM - Enum of BoolExternalResult
-
-	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=BoolExternalResultEnum()
-	"""
-
-	return StringToEnum('BoolExternalResult')[0]
-
-def DoubleElementResultEnum():
-	"""
-	DOUBLEELEMENTRESULTENUM - Enum of DoubleElementResult
-
-	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=DoubleElementResultEnum()
-	"""
-
-	return StringToEnum('DoubleElementResult')[0]
-
-def DoubleExternalResultEnum():
-	"""
-	DOUBLEEXTERNALRESULTENUM - Enum of DoubleExternalResult
-
-	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=DoubleExternalResultEnum()
-	"""
-
-	return StringToEnum('DoubleExternalResult')[0]
-
-def DoubleMatExternalResultEnum():
-	"""
-	DOUBLEMATEXTERNALRESULTENUM - Enum of DoubleMatExternalResult
-
-	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=DoubleMatExternalResultEnum()
-	"""
-
-	return StringToEnum('DoubleMatExternalResult')[0]
-
-def IntExternalResultEnum():
-	"""
-	INTEXTERNALRESULTENUM - Enum of IntExternalResult
-
-	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=IntExternalResultEnum()
-	"""
-
-	return StringToEnum('IntExternalResult')[0]
-
-def JEnum():
-	"""
-	JENUM - Enum of J
-
-	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=JEnum()
-	"""
-
-	return StringToEnum('J')[0]
-
-def PatchEnum():
-	"""
-	PATCHENUM - Enum of Patch
-
-	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=PatchEnum()
-	"""
-
-	return StringToEnum('Patch')[0]
-
-def PatchNodesEnum():
-	"""
-	PATCHNODESENUM - Enum of PatchNodes
-
-	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=PatchNodesEnum()
-	"""
-
-	return StringToEnum('PatchNodes')[0]
-
-def PatchVerticesEnum():
-	"""
-	PATCHVERTICESENUM - Enum of PatchVertices
-
-	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=PatchVerticesEnum()
-	"""
-
-	return StringToEnum('PatchVertices')[0]
-
-def PentaP1ElementResultEnum():
-	"""
-	PENTAP1ELEMENTRESULTENUM - Enum of PentaP1ElementResult
-
-	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=PentaP1ElementResultEnum()
-	"""
-
-	return StringToEnum('PentaP1ElementResult')[0]
-
-def StringExternalResultEnum():
-	"""
-	STRINGEXTERNALRESULTENUM - Enum of StringExternalResult
-
-	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=StringExternalResultEnum()
-	"""
-
-	return StringToEnum('StringExternalResult')[0]
-
-def StepEnum():
-	"""
-	STEPENUM - Enum of Step
-
-	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=StepEnum()
-	"""
-
-	return StringToEnum('Step')[0]
-
-def TimeEnum():
-	"""
-	TIMEENUM - Enum of Time
-
-	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=TimeEnum()
-	"""
-
-	return StringToEnum('Time')[0]
-
-def TriaP1ElementResultEnum():
-	"""
-	TRIAP1ELEMENTRESULTENUM - Enum of TriaP1ElementResult
-
-	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=TriaP1ElementResultEnum()
-	"""
-
-	return StringToEnum('TriaP1ElementResult')[0]
-
-def WaterColumnOldEnum():
-	"""
-	WATERCOLUMNOLDENUM - Enum of WaterColumnOld
-
-	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=WaterColumnOldEnum()
-	"""
-
-	return StringToEnum('WaterColumnOld')[0]
-
-def MinVelEnum():
-	"""
-	MINVELENUM - Enum of MinVel
-
-	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=MinVelEnum()
-	"""
-
-	return StringToEnum('MinVel')[0]
-
-def MaxVelEnum():
-	"""
-	MAXVELENUM - Enum of MaxVel
-
-	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=MaxVelEnum()
-	"""
-
-	return StringToEnum('MaxVel')[0]
-
-def MinVxEnum():
-	"""
-	MINVXENUM - Enum of MinVx
-
-	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=MinVxEnum()
-	"""
-
-	return StringToEnum('MinVx')[0]
-
-def MaxVxEnum():
-	"""
-	MAXVXENUM - Enum of MaxVx
-
-	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=MaxVxEnum()
-	"""
-
-	return StringToEnum('MaxVx')[0]
-
-def MaxAbsVxEnum():
-	"""
-	MAXABSVXENUM - Enum of MaxAbsVx
-
-	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=MaxAbsVxEnum()
-	"""
-
-	return StringToEnum('MaxAbsVx')[0]
-
-def MinVyEnum():
-	"""
-	MINVYENUM - Enum of MinVy
-
-	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=MinVyEnum()
-	"""
-
-	return StringToEnum('MinVy')[0]
-
-def MaxVyEnum():
-	"""
-	MAXVYENUM - Enum of MaxVy
-
-	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=MaxVyEnum()
-	"""
-
-	return StringToEnum('MaxVy')[0]
-
-def MaxAbsVyEnum():
-	"""
-	MAXABSVYENUM - Enum of MaxAbsVy
-
-	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=MaxAbsVyEnum()
-	"""
-
-	return StringToEnum('MaxAbsVy')[0]
-
-def MinVzEnum():
-	"""
-	MINVZENUM - Enum of MinVz
-
-	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=MinVzEnum()
-	"""
-
-	return StringToEnum('MinVz')[0]
-
-def MaxVzEnum():
-	"""
-	MAXVZENUM - Enum of MaxVz
-
-	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=MaxVzEnum()
-	"""
-
-	return StringToEnum('MaxVz')[0]
-
-def MaxAbsVzEnum():
-	"""
-	MAXABSVZENUM - Enum of MaxAbsVz
-
-	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=MaxAbsVzEnum()
-	"""
-
-	return StringToEnum('MaxAbsVz')[0]
-
-def IceVolumeEnum():
-	"""
-	ICEVOLUMEENUM - Enum of IceVolume
-
-	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=IceVolumeEnum()
-	"""
-
-	return StringToEnum('IceVolume')[0]
-
-def TotalSmbEnum():
-	"""
-	TOTALSMBENUM - Enum of TotalSmb
-
-	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=TotalSmbEnum()
-	"""
-
-	return StringToEnum('TotalSmb')[0]
-
-def AbsoluteEnum():
-	"""
-	ABSOLUTEENUM - Enum of Absolute
-
-	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=AbsoluteEnum()
-	"""
-
-	return StringToEnum('Absolute')[0]
-
-def IncrementalEnum():
-	"""
-	INCREMENTALENUM - Enum of Incremental
-
-	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=IncrementalEnum()
-	"""
-
-	return StringToEnum('Incremental')[0]
-
-def AgressiveMigrationEnum():
-	"""
-	AGRESSIVEMIGRATIONENUM - Enum of AgressiveMigration
-
-	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=AgressiveMigrationEnum()
-	"""
-
-	return StringToEnum('AgressiveMigration')[0]
-
-def NoneEnum():
-	"""
-	NONEENUM - Enum of None
-
-	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=NoneEnum()
-	"""
-
-	return StringToEnum('None')[0]
-
-def SoftMigrationEnum():
-	"""
-	SOFTMIGRATIONENUM - Enum of SoftMigration
-
-	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=SoftMigrationEnum()
-	"""
-
-	return StringToEnum('SoftMigration')[0]
-
-def SubelementMigrationEnum():
-	"""
-	SUBELEMENTMIGRATIONENUM - Enum of SubelementMigration
-
-	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=SubelementMigrationEnum()
-	"""
-
-	return StringToEnum('SubelementMigration')[0]
-
-def SubelementMigration2Enum():
-	"""
-	SUBELEMENTMIGRATION2ENUM - Enum of SubelementMigration2
-
-	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=SubelementMigration2Enum()
-	"""
-
-	return StringToEnum('SubelementMigration2')[0]
-
-def GLlevelsetEnum():
-	"""
-	GLLEVELSETENUM - Enum of GLlevelset
-
-	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=GLlevelsetEnum()
-	"""
-
-	return StringToEnum('GLlevelset')[0]
-
-def StokesSolverEnum():
-	"""
-	STOKESSOLVERENUM - Enum of StokesSolver
-
-	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=StokesSolverEnum()
-	"""
-
-	return StringToEnum('StokesSolver')[0]
-
-def AdjointEnum():
-	"""
-	ADJOINTENUM - Enum of Adjoint
-
-	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=AdjointEnum()
-	"""
-
-	return StringToEnum('Adjoint')[0]
-
-def ColinearEnum():
-	"""
-	COLINEARENUM - Enum of Colinear
-
-	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=ColinearEnum()
-	"""
-
-	return StringToEnum('Colinear')[0]
-
-def ControlSteadyEnum():
-	"""
-	CONTROLSTEADYENUM - Enum of ControlSteady
-
-	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=ControlSteadyEnum()
-	"""
-
-	return StringToEnum('ControlSteady')[0]
-
-def FsetEnum():
-	"""
-	FSETENUM - Enum of Fset
-
-	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=FsetEnum()
-	"""
-
-	return StringToEnum('Fset')[0]
-
-def Gradient1Enum():
-	"""
-	GRADIENT1ENUM - Enum of Gradient1
-
-	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=Gradient1Enum()
-	"""
-
-	return StringToEnum('Gradient1')[0]
-
-def Gradient2Enum():
-	"""
-	GRADIENT2ENUM - Enum of Gradient2
-
-	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=Gradient2Enum()
-	"""
-
-	return StringToEnum('Gradient2')[0]
-
-def Gradient3Enum():
-	"""
-	GRADIENT3ENUM - Enum of Gradient3
-
-	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=Gradient3Enum()
-	"""
-
-	return StringToEnum('Gradient3')[0]
-
-def GradientEnum():
-	"""
-	GRADIENTENUM - Enum of Gradient
-
-	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=GradientEnum()
-	"""
-
-	return StringToEnum('Gradient')[0]
-
-def GroundinglineMigrationEnum():
-	"""
-	GROUNDINGLINEMIGRATIONENUM - Enum of GroundinglineMigration
-
-	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=GroundinglineMigrationEnum()
-	"""
-
-	return StringToEnum('GroundinglineMigration')[0]
-
-def GsetEnum():
-	"""
-	GSETENUM - Enum of Gset
-
-	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=GsetEnum()
-	"""
-
-	return StringToEnum('Gset')[0]
-
-def IndexEnum():
-	"""
-	INDEXENUM - Enum of Index
-
-	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=IndexEnum()
-	"""
-
-	return StringToEnum('Index')[0]
-
-def IndexedEnum():
-	"""
-	INDEXEDENUM - Enum of Indexed
-
-	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=IndexedEnum()
-	"""
-
-	return StringToEnum('Indexed')[0]
-
-def IntersectEnum():
-	"""
-	INTERSECTENUM - Enum of Intersect
-
-	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=IntersectEnum()
-	"""
-
-	return StringToEnum('Intersect')[0]
-
-def NodalEnum():
-	"""
-	NODALENUM - Enum of Nodal
-
-	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=NodalEnum()
-	"""
-
-	return StringToEnum('Nodal')[0]
-
-def OldGradientEnum():
-	"""
-	OLDGRADIENTENUM - Enum of OldGradient
-
-	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=OldGradientEnum()
-	"""
-
-	return StringToEnum('OldGradient')[0]
-
-def OutputFilePointerEnum():
-	"""
-	OUTPUTFILEPOINTERENUM - Enum of OutputFilePointer
-
-	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=OutputFilePointerEnum()
-	"""
-
-	return StringToEnum('OutputFilePointer')[0]
-
-def OutputFileNameEnum():
-	"""
-	OUTPUTFILENAMEENUM - Enum of OutputFileName
-
-	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=OutputFileNameEnum()
-	"""
-
-	return StringToEnum('OutputFileName')[0]
-
-def LockFileNameEnum():
-	"""
-	LOCKFILENAMEENUM - Enum of LockFileName
-
-	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=LockFileNameEnum()
-	"""
-
-	return StringToEnum('LockFileName')[0]
-
-def ToolkitsOptionsAnalysesEnum():
-	"""
-	TOOLKITSOPTIONSANALYSESENUM - Enum of ToolkitsOptionsAnalyses
-
-	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=ToolkitsOptionsAnalysesEnum()
-	"""
-
-	return StringToEnum('ToolkitsOptionsAnalyses')[0]
-
-def ToolkitsOptionsStringsEnum():
-	"""
-	TOOLKITSOPTIONSSTRINGSENUM - Enum of ToolkitsOptionsStrings
-
-	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=ToolkitsOptionsStringsEnum()
-	"""
-
-	return StringToEnum('ToolkitsOptionsStrings')[0]
-
-def QmuErrNameEnum():
-	"""
-	QMUERRNAMEENUM - Enum of QmuErrName
-
-	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=QmuErrNameEnum()
-	"""
-
-	return StringToEnum('QmuErrName')[0]
-
-def QmuInNameEnum():
-	"""
-	QMUINNAMEENUM - Enum of QmuInName
-
-	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=QmuInNameEnum()
-	"""
-
-	return StringToEnum('QmuInName')[0]
-
-def QmuOutNameEnum():
-	"""
-	QMUOUTNAMEENUM - Enum of QmuOutName
-
-	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=QmuOutNameEnum()
-	"""
-
-	return StringToEnum('QmuOutName')[0]
-
-def RegularEnum():
-	"""
-	REGULARENUM - Enum of Regular
-
-	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=RegularEnum()
-	"""
-
-	return StringToEnum('Regular')[0]
-
-def ScaledEnum():
-	"""
-	SCALEDENUM - Enum of Scaled
-
-	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=ScaledEnum()
-	"""
-
-	return StringToEnum('Scaled')[0]
-
-def SeparateEnum():
-	"""
-	SEPARATEENUM - Enum of Separate
-
-	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=SeparateEnum()
-	"""
-
-	return StringToEnum('Separate')[0]
-
-def SsetEnum():
-	"""
-	SSETENUM - Enum of Sset
-
-	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=SsetEnum()
-	"""
-
-	return StringToEnum('Sset')[0]
-
-def VerboseEnum():
-	"""
-	VERBOSEENUM - Enum of Verbose
-
-	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=VerboseEnum()
-	"""
-
-	return StringToEnum('Verbose')[0]
-
-def TriangleInterpEnum():
-	"""
-	TRIANGLEINTERPENUM - Enum of TriangleInterp
-
-	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=TriangleInterpEnum()
-	"""
-
-	return StringToEnum('TriangleInterp')[0]
-
-def BilinearInterpEnum():
-	"""
-	BILINEARINTERPENUM - Enum of BilinearInterp
-
-	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=BilinearInterpEnum()
-	"""
-
-	return StringToEnum('BilinearInterp')[0]
-
-def NearestInterpEnum():
-	"""
-	NEARESTINTERPENUM - Enum of NearestInterp
-
-	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=NearestInterpEnum()
-	"""
-
-	return StringToEnum('NearestInterp')[0]
-
-def XYEnum():
-	"""
-	XYENUM - Enum of XY
-
-	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=XYEnum()
-	"""
-
-	return StringToEnum('XY')[0]
-
-def XYZPEnum():
-	"""
-	XYZPENUM - Enum of XYZP
-
-	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=XYZPEnum()
-	"""
-
-	return StringToEnum('XYZP')[0]
-
-def DenseEnum():
-	"""
-	DENSEENUM - Enum of Dense
-
-	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=DenseEnum()
-	"""
-
-	return StringToEnum('Dense')[0]
-
-def MpiDenseEnum():
-	"""
-	MPIDENSEENUM - Enum of MpiDense
-
-	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=MpiDenseEnum()
-	"""
-
-	return StringToEnum('MpiDense')[0]
-
-def SeqEnum():
-	"""
-	SEQENUM - Enum of Seq
-
-	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=SeqEnum()
-	"""
-
-	return StringToEnum('Seq')[0]
-
-def MpiEnum():
-	"""
-	MPIENUM - Enum of Mpi
-
-	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=MpiEnum()
-	"""
-
-	return StringToEnum('Mpi')[0]
-
-def OptionEnum():
-	"""
-	OPTIONENUM - Enum of Option
-
-	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=OptionEnum()
-	"""
-
-	return StringToEnum('Option')[0]
-
-def GenericOptionEnum():
-	"""
-	GENERICOPTIONENUM - Enum of GenericOption
-
-	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=GenericOptionEnum()
-	"""
-
-	return StringToEnum('GenericOption')[0]
-
-def OptionCellEnum():
-	"""
-	OPTIONCELLENUM - Enum of OptionCell
-
-	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=OptionCellEnum()
-	"""
-
-	return StringToEnum('OptionCell')[0]
-
-def OptionCharEnum():
-	"""
-	OPTIONCHARENUM - Enum of OptionChar
-
-	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=OptionCharEnum()
-	"""
-
-	return StringToEnum('OptionChar')[0]
-
-def OptionStructEnum():
-	"""
-	OPTIONSTRUCTENUM - Enum of OptionStruct
-
-	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=OptionStructEnum()
-	"""
-
-	return StringToEnum('OptionStruct')[0]
-
-def OptionDoubleEnum():
-	"""
-	OPTIONDOUBLEENUM - Enum of OptionDouble
-
-	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=OptionDoubleEnum()
-	"""
-
-	return StringToEnum('OptionDouble')[0]
-
-def OptionLogicalEnum():
-	"""
-	OPTIONLOGICALENUM - Enum of OptionLogical
-
-	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=OptionLogicalEnum()
-	"""
-
-	return StringToEnum('OptionLogical')[0]
-
-def PatersonEnum():
-	"""
-	PATERSONENUM - Enum of Paterson
-
-	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=PatersonEnum()
-	"""
-
-	return StringToEnum('Paterson')[0]
-
-def ArrheniusEnum():
-	"""
-	ARRHENIUSENUM - Enum of Arrhenius
-
-	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=ArrheniusEnum()
-	"""
-
-	return StringToEnum('Arrhenius')[0]
-
-def MaximumNumberOfEnums():
-	"""
-	MAXIMUMNUMBEROFENUMS - Enum of MaximumNumberOfEnums
-
-	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=MaximumNumberOfEnums()
-	"""
-
-	return 560
-
+def AutodiffIsautodiffEnum(): return StringToEnum("AutodiffIsautodiff")[0]
+def AutodiffNumDependentsEnum(): return StringToEnum("AutodiffNumDependents")[0]
+def AutodiffNumDependentObjectsEnum(): return StringToEnum("AutodiffNumDependentObjects")[0]
+def AutodiffDependentObjectNamesEnum(): return StringToEnum("AutodiffDependentObjectNames")[0]
+def AutodiffDependentObjectTypesEnum(): return StringToEnum("AutodiffDependentObjectTypes")[0]
+def AutodiffDependentObjectIndicesEnum(): return StringToEnum("AutodiffDependentObjectIndices")[0]
+def AutodiffDependentObjectsEnum(): return StringToEnum("AutodiffDependentObjects")[0]
+def AutodiffNumIndependentsEnum(): return StringToEnum("AutodiffNumIndependents")[0]
+def AutodiffNumIndependentObjectsEnum(): return StringToEnum("AutodiffNumIndependentObjects")[0]
+def AutodiffIndependentObjectNamesEnum(): return StringToEnum("AutodiffIndependentObjectNames")[0]
+def AutodiffIndependentObjectTypesEnum(): return StringToEnum("AutodiffIndependentObjectTypes")[0]
+def AutodiffIndependentObjectsEnum(): return StringToEnum("AutodiffIndependentObjects")[0]
+def AutodiffJacobianEnum(): return StringToEnum("AutodiffJacobian")[0]
+def AutodiffXpEnum(): return StringToEnum("AutodiffXp")[0]
+def AutodiffDriverEnum(): return StringToEnum("AutodiffDriver")[0]
+def AutodiffFosForwardIndexEnum(): return StringToEnum("AutodiffFosForwardIndex")[0]
+def AutodiffFovForwardIndicesEnum(): return StringToEnum("AutodiffFovForwardIndices")[0]
+def AutodiffFosReverseIndexEnum(): return StringToEnum("AutodiffFosReverseIndex")[0]
+def AutodiffMassFluxSegmentsPresentEnum(): return StringToEnum("AutodiffMassFluxSegmentsPresent")[0]
+def AutodiffKeepEnum(): return StringToEnum("AutodiffKeep")[0]
+def BalancethicknessSpcthicknessEnum(): return StringToEnum("BalancethicknessSpcthickness")[0]
+def BalancethicknessStabilizationEnum(): return StringToEnum("BalancethicknessStabilization")[0]
+def BalancethicknessThickeningRateEnum(): return StringToEnum("BalancethicknessThickeningRate")[0]
+def BasalforcingsGeothermalfluxEnum(): return StringToEnum("BasalforcingsGeothermalflux")[0]
+def BasalforcingsMeltingRateCorrectionEnum(): return StringToEnum("BasalforcingsMeltingRateCorrection")[0]
+def BasalforcingsMeltingRateEnum(): return StringToEnum("BasalforcingsMeltingRate")[0]
+def BathymetryEnum(): return StringToEnum("Bathymetry")[0]
+def BedEnum(): return StringToEnum("Bed")[0]
+def ConstantsGEnum(): return StringToEnum("ConstantsG")[0]
+def ConstantsReferencetemperatureEnum(): return StringToEnum("ConstantsReferencetemperature")[0]
+def ConstantsYtsEnum(): return StringToEnum("ConstantsYts")[0]
+def DependentObjectEnum(): return StringToEnum("DependentObject")[0]
+def StressbalanceAbstolEnum(): return StringToEnum("StressbalanceAbstol")[0]
+def StressbalanceIcefrontEnum(): return StringToEnum("StressbalanceIcefront")[0]
+def StressbalanceIsnewtonEnum(): return StringToEnum("StressbalanceIsnewton")[0]
+def StressbalanceMaxiterEnum(): return StringToEnum("StressbalanceMaxiter")[0]
+def StressbalanceNumRequestedOutputsEnum(): return StringToEnum("StressbalanceNumRequestedOutputs")[0]
+def StressbalancePenaltyFactorEnum(): return StringToEnum("StressbalancePenaltyFactor")[0]
+def StressbalanceReferentialEnum(): return StringToEnum("StressbalanceReferential")[0]
+def StressbalanceReltolEnum(): return StringToEnum("StressbalanceReltol")[0]
+def StressbalanceRequestedOutputsEnum(): return StringToEnum("StressbalanceRequestedOutputs")[0]
+def StressbalanceRestolEnum(): return StringToEnum("StressbalanceRestol")[0]
+def StressbalanceRiftPenaltyLockEnum(): return StringToEnum("StressbalanceRiftPenaltyLock")[0]
+def StressbalanceRiftPenaltyThresholdEnum(): return StringToEnum("StressbalanceRiftPenaltyThreshold")[0]
+def StressbalanceShelfDampeningEnum(): return StringToEnum("StressbalanceShelfDampening")[0]
+def StressbalanceSpcvxEnum(): return StringToEnum("StressbalanceSpcvx")[0]
+def StressbalanceSpcvyEnum(): return StringToEnum("StressbalanceSpcvy")[0]
+def StressbalanceSpcvzEnum(): return StringToEnum("StressbalanceSpcvz")[0]
+def StressbalanceFSreconditioningEnum(): return StringToEnum("StressbalanceFSreconditioning")[0]
+def StressbalanceVertexPairingEnum(): return StringToEnum("StressbalanceVertexPairing")[0]
+def StressbalanceViscosityOvershootEnum(): return StringToEnum("StressbalanceViscosityOvershoot")[0]
+def LoadingforceXEnum(): return StringToEnum("LoadingforceX")[0]
+def LoadingforceYEnum(): return StringToEnum("LoadingforceY")[0]
+def LoadingforceZEnum(): return StringToEnum("LoadingforceZ")[0]
+def FlowequationBorderSSAEnum(): return StringToEnum("FlowequationBorderSSA")[0]
+def FlowequationBorderHOEnum(): return StringToEnum("FlowequationBorderHO")[0]
+def FlowequationBorderFSEnum(): return StringToEnum("FlowequationBorderFS")[0]
+def FlowequationElementEquationEnum(): return StringToEnum("FlowequationElementEquation")[0]
+def FlowequationIsSIAEnum(): return StringToEnum("FlowequationIsSIA")[0]
+def FlowequationIsSSAEnum(): return StringToEnum("FlowequationIsSSA")[0]
+def FlowequationIsL1L2Enum(): return StringToEnum("FlowequationIsL1L2")[0]
+def FlowequationIsHOEnum(): return StringToEnum("FlowequationIsHO")[0]
+def FlowequationIsFSEnum(): return StringToEnum("FlowequationIsFS")[0]
+def FlowequationFeSSAEnum(): return StringToEnum("FlowequationFeSSA")[0]
+def FlowequationFeHOEnum(): return StringToEnum("FlowequationFeHO")[0]
+def FlowequationFeFSEnum(): return StringToEnum("FlowequationFeFS")[0]
+def FlowequationVertexEquationEnum(): return StringToEnum("FlowequationVertexEquation")[0]
+def FrictionCoefficientEnum(): return StringToEnum("FrictionCoefficient")[0]
+def FrictionPEnum(): return StringToEnum("FrictionP")[0]
+def FrictionQEnum(): return StringToEnum("FrictionQ")[0]
+def GeometryHydrostaticRatioEnum(): return StringToEnum("GeometryHydrostaticRatio")[0]
+def HydrologyModelEnum(): return StringToEnum("HydrologyModel")[0]
+def HydrologyshreveEnum(): return StringToEnum("Hydrologyshreve")[0]
+def HydrologyshreveCREnum(): return StringToEnum("HydrologyshreveCR")[0]
+def HydrologyshreveKnEnum(): return StringToEnum("HydrologyshreveKn")[0]
+def HydrologyshreveNEnum(): return StringToEnum("HydrologyshreveN")[0]
+def HydrologyshrevePEnum(): return StringToEnum("HydrologyshreveP")[0]
+def HydrologyshreveQEnum(): return StringToEnum("HydrologyshreveQ")[0]
+def HydrologyshreveSpcwatercolumnEnum(): return StringToEnum("HydrologyshreveSpcwatercolumn")[0]
+def HydrologyshreveStabilizationEnum(): return StringToEnum("HydrologyshreveStabilization")[0]
+def HydrologydcEnum(): return StringToEnum("Hydrologydc")[0]
+def SedimentHeadEnum(): return StringToEnum("SedimentHead")[0]
+def SedimentHeadOldEnum(): return StringToEnum("SedimentHeadOld")[0]
+def SedimentHeadResidualEnum(): return StringToEnum("SedimentHeadResidual")[0]
+def EplHeadEnum(): return StringToEnum("EplHead")[0]
+def EplHeadOldEnum(): return StringToEnum("EplHeadOld")[0]
+def HydrologydcRelTolEnum(): return StringToEnum("HydrologydcRelTol")[0]
+def HydrologydcSpcsedimentHeadEnum(): return StringToEnum("HydrologydcSpcsedimentHead")[0]
+def HydrologydcSedimentCompressibilityEnum(): return StringToEnum("HydrologydcSedimentCompressibility")[0]
+def HydrologydcSedimentPorosityEnum(): return StringToEnum("HydrologydcSedimentPorosity")[0]
+def HydrologydcSedimentThicknessEnum(): return StringToEnum("HydrologydcSedimentThickness")[0]
+def HydrologydcSedimentTransmitivityEnum(): return StringToEnum("HydrologydcSedimentTransmitivity")[0]
+def HydrologydcWaterCompressibilityEnum(): return StringToEnum("HydrologydcWaterCompressibility")[0]
+def HydrologydcSpceplHeadEnum(): return StringToEnum("HydrologydcSpceplHead")[0]
+def HydrologydcMaskEplactiveEnum(): return StringToEnum("HydrologydcMaskEplactive")[0]
+def HydrologydcEplCompressibilityEnum(): return StringToEnum("HydrologydcEplCompressibility")[0]
+def HydrologydcEplPorosityEnum(): return StringToEnum("HydrologydcEplPorosity")[0]
+def HydrologydcEplThicknessEnum(): return StringToEnum("HydrologydcEplThickness")[0]
+def HydrologydcEplTransmitivityEnum(): return StringToEnum("HydrologydcEplTransmitivity")[0]
+def HydrologydcIsefficientlayerEnum(): return StringToEnum("HydrologydcIsefficientlayer")[0]
+def HydrologydcSedimentlimitFlagEnum(): return StringToEnum("HydrologydcSedimentlimitFlag")[0]
+def HydrologydcSedimentlimitEnum(): return StringToEnum("HydrologydcSedimentlimit")[0]
+def HydrologydcTransferFlagEnum(): return StringToEnum("HydrologydcTransferFlag")[0]
+def HydrologydcLeakageFactorEnum(): return StringToEnum("HydrologydcLeakageFactor")[0]
+def HydrologydcPenaltyFactorEnum(): return StringToEnum("HydrologydcPenaltyFactor")[0]
+def HydrologyLayerEnum(): return StringToEnum("HydrologyLayer")[0]
+def HydrologySedimentEnum(): return StringToEnum("HydrologySediment")[0]
+def HydrologyEfficientEnum(): return StringToEnum("HydrologyEfficient")[0]
+def HydrologySedimentKmaxEnum(): return StringToEnum("HydrologySedimentKmax")[0]
+def BasisIntegralEnum(): return StringToEnum("BasisIntegral")[0]
+def WaterTransferEnum(): return StringToEnum("WaterTransfer")[0]
+def IndependentObjectEnum(): return StringToEnum("IndependentObject")[0]
+def InversionControlParametersEnum(): return StringToEnum("InversionControlParameters")[0]
+def InversionCostFunctionThresholdEnum(): return StringToEnum("InversionCostFunctionThreshold")[0]
+def InversionCostFunctionsCoefficientsEnum(): return StringToEnum("InversionCostFunctionsCoefficients")[0]
+def InversionCostFunctionsEnum(): return StringToEnum("InversionCostFunctions")[0]
+def InversionGradientOnlyEnum(): return StringToEnum("InversionGradientOnly")[0]
+def InversionGradientScalingEnum(): return StringToEnum("InversionGradientScaling")[0]
+def InversionIscontrolEnum(): return StringToEnum("InversionIscontrol")[0]
+def InversionTaoEnum(): return StringToEnum("InversionTao")[0]
+def InversionIncompleteAdjointEnum(): return StringToEnum("InversionIncompleteAdjoint")[0]
+def InversionMaxParametersEnum(): return StringToEnum("InversionMaxParameters")[0]
+def InversionMaxiterPerStepEnum(): return StringToEnum("InversionMaxiterPerStep")[0]
+def InversionMinParametersEnum(): return StringToEnum("InversionMinParameters")[0]
+def InversionNstepsEnum(): return StringToEnum("InversionNsteps")[0]
+def InversionNumControlParametersEnum(): return StringToEnum("InversionNumControlParameters")[0]
+def InversionNumCostFunctionsEnum(): return StringToEnum("InversionNumCostFunctions")[0]
+def InversionStepThresholdEnum(): return StringToEnum("InversionStepThreshold")[0]
+def InversionThicknessObsEnum(): return StringToEnum("InversionThicknessObs")[0]
+def InversionVelObsEnum(): return StringToEnum("InversionVelObs")[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 MaterialsBetaEnum(): return StringToEnum("MaterialsBeta")[0]
+def MaterialsHeatcapacityEnum(): return StringToEnum("MaterialsHeatcapacity")[0]
+def MaterialsLatentheatEnum(): return StringToEnum("MaterialsLatentheat")[0]
+def MaterialsMeltingpointEnum(): return StringToEnum("MaterialsMeltingpoint")[0]
+def MaterialsMixedLayerCapacityEnum(): return StringToEnum("MaterialsMixedLayerCapacity")[0]
+def MaterialsRheologyBEnum(): return StringToEnum("MaterialsRheologyB")[0]
+def MaterialsRheologyBbarEnum(): return StringToEnum("MaterialsRheologyBbar")[0]
+def MaterialsRheologyLawEnum(): return StringToEnum("MaterialsRheologyLaw")[0]
+def MaterialsRheologyNEnum(): return StringToEnum("MaterialsRheologyN")[0]
+def MaterialsRheologyZEnum(): return StringToEnum("MaterialsRheologyZ")[0]
+def MaterialsRheologyZbarEnum(): return StringToEnum("MaterialsRheologyZbar")[0]
+def MaterialsRhoIceEnum(): return StringToEnum("MaterialsRhoIce")[0]
+def MaterialsRhoWaterEnum(): return StringToEnum("MaterialsRhoWater")[0]
+def MaterialsRhoFreshwaterEnum(): return StringToEnum("MaterialsRhoFreshwater")[0]
+def MaterialsMuWaterEnum(): return StringToEnum("MaterialsMuWater")[0]
+def MaterialsThermalExchangeVelocityEnum(): return StringToEnum("MaterialsThermalExchangeVelocity")[0]
+def MaterialsThermalconductivityEnum(): return StringToEnum("MaterialsThermalconductivity")[0]
+def MaterialsLithosphereShearModulusEnum(): return StringToEnum("MaterialsLithosphereShearModulus")[0]
+def MaterialsLithosphereDensityEnum(): return StringToEnum("MaterialsLithosphereDensity")[0]
+def MaterialsMantleShearModulusEnum(): return StringToEnum("MaterialsMantleShearModulus")[0]
+def MaterialsMantleDensityEnum(): return StringToEnum("MaterialsMantleDensity")[0]
+def MeshAverageVertexConnectivityEnum(): return StringToEnum("MeshAverageVertexConnectivity")[0]
+def MeshDimensionEnum(): return StringToEnum("MeshDimension")[0]
+def MeshElementonbedEnum(): return StringToEnum("MeshElementonbed")[0]
+def MeshElementonsurfaceEnum(): return StringToEnum("MeshElementonsurface")[0]
+def MeshElements2dEnum(): return StringToEnum("MeshElements2d")[0]
+def MeshElementsEnum(): return StringToEnum("MeshElements")[0]
+def MeshLowerelementsEnum(): return StringToEnum("MeshLowerelements")[0]
+def MeshNumberofelements2dEnum(): return StringToEnum("MeshNumberofelements2d")[0]
+def MeshNumberofelementsEnum(): return StringToEnum("MeshNumberofelements")[0]
+def MeshNumberoflayersEnum(): return StringToEnum("MeshNumberoflayers")[0]
+def MeshNumberofvertices2dEnum(): return StringToEnum("MeshNumberofvertices2d")[0]
+def MeshNumberofverticesEnum(): return StringToEnum("MeshNumberofvertices")[0]
+def MeshUpperelementsEnum(): return StringToEnum("MeshUpperelements")[0]
+def MeshVertexonbedEnum(): return StringToEnum("MeshVertexonbed")[0]
+def MeshVertexonsurfaceEnum(): return StringToEnum("MeshVertexonsurface")[0]
+def MeshXEnum(): return StringToEnum("MeshX")[0]
+def MeshYEnum(): return StringToEnum("MeshY")[0]
+def MeshZEnum(): return StringToEnum("MeshZ")[0]
+def MiscellaneousNameEnum(): return StringToEnum("MiscellaneousName")[0]
+def MasstransportHydrostaticAdjustmentEnum(): return StringToEnum("MasstransportHydrostaticAdjustment")[0]
+def MasstransportIsfreesurfaceEnum(): return StringToEnum("MasstransportIsfreesurface")[0]
+def MasstransportMinThicknessEnum(): return StringToEnum("MasstransportMinThickness")[0]
+def MasstransportPenaltyFactorEnum(): return StringToEnum("MasstransportPenaltyFactor")[0]
+def MasstransportSpcthicknessEnum(): return StringToEnum("MasstransportSpcthickness")[0]
+def MasstransportStabilizationEnum(): return StringToEnum("MasstransportStabilization")[0]
+def MasstransportVertexPairingEnum(): return StringToEnum("MasstransportVertexPairing")[0]
+def MasstransportNumRequestedOutputsEnum(): return StringToEnum("MasstransportNumRequestedOutputs")[0]
+def MasstransportRequestedOutputsEnum(): return StringToEnum("MasstransportRequestedOutputs")[0]
+def QmuIsdakotaEnum(): return StringToEnum("QmuIsdakota")[0]
+def MassFluxSegmentsEnum(): return StringToEnum("MassFluxSegments")[0]
+def MassFluxSegmentsPresentEnum(): return StringToEnum("MassFluxSegmentsPresent")[0]
+def QmuMassFluxSegmentsPresentEnum(): return StringToEnum("QmuMassFluxSegmentsPresent")[0]
+def QmuNumberofpartitionsEnum(): return StringToEnum("QmuNumberofpartitions")[0]
+def QmuNumberofresponsesEnum(): return StringToEnum("QmuNumberofresponses")[0]
+def QmuPartitionEnum(): return StringToEnum("QmuPartition")[0]
+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]
+def SettingsIoGatherEnum(): return StringToEnum("SettingsIoGather")[0]
+def SettingsLowmemEnum(): return StringToEnum("SettingsLowmem")[0]
+def SettingsOutputFrequencyEnum(): return StringToEnum("SettingsOutputFrequency")[0]
+def SettingsResultsAsPatchesEnum(): return StringToEnum("SettingsResultsAsPatches")[0]
+def SettingsWaitonlockEnum(): return StringToEnum("SettingsWaitonlock")[0]
+def SurfaceforcingsDelta18oEnum(): return StringToEnum("SurfaceforcingsDelta18o")[0]
+def SurfaceforcingsDelta18oSurfaceEnum(): return StringToEnum("SurfaceforcingsDelta18oSurface")[0]
+def SurfaceforcingsIsdelta18oEnum(): return StringToEnum("SurfaceforcingsIsdelta18o")[0]
+def SurfaceforcingsPrecipitationsPresentdayEnum(): return StringToEnum("SurfaceforcingsPrecipitationsPresentday")[0]
+def SurfaceforcingsTemperaturesPresentdayEnum(): return StringToEnum("SurfaceforcingsTemperaturesPresentday")[0]
+def SurfaceforcingsTemperaturesLgmEnum(): return StringToEnum("SurfaceforcingsTemperaturesLgm")[0]
+def DebugProfilingEnum(): return StringToEnum("DebugProfiling")[0]
+def ProfilingCurrentMemEnum(): return StringToEnum("ProfilingCurrentMem")[0]
+def ProfilingCurrentFlopsEnum(): return StringToEnum("ProfilingCurrentFlops")[0]
+def ProfilingSolutionTimeEnum(): return StringToEnum("ProfilingSolutionTime")[0]
+def MaxIterationConvergenceFlagEnum(): return StringToEnum("MaxIterationConvergenceFlag")[0]
+def SteadystateMaxiterEnum(): return StringToEnum("SteadystateMaxiter")[0]
+def SteadystateNumRequestedOutputsEnum(): return StringToEnum("SteadystateNumRequestedOutputs")[0]
+def SteadystateReltolEnum(): return StringToEnum("SteadystateReltol")[0]
+def SteadystateRequestedOutputsEnum(): return StringToEnum("SteadystateRequestedOutputs")[0]
+def SurfaceEnum(): return StringToEnum("Surface")[0]
+def SurfaceforcingsPrecipitationEnum(): return StringToEnum("SurfaceforcingsPrecipitation")[0]
+def SurfaceforcingsMassBalanceEnum(): return StringToEnum("SurfaceforcingsMassBalance")[0]
+def SurfaceforcingsIspddEnum(): return StringToEnum("SurfaceforcingsIspdd")[0]
+def SurfaceforcingsDesfacEnum(): return StringToEnum("SurfaceforcingsDesfac")[0]
+def SurfaceforcingsS0pEnum(): return StringToEnum("SurfaceforcingsS0p")[0]
+def SurfaceforcingsIssmbgradientsEnum(): return StringToEnum("SurfaceforcingsIssmbgradients")[0]
+def SurfaceforcingsMonthlytemperaturesEnum(): return StringToEnum("SurfaceforcingsMonthlytemperatures")[0]
+def SurfaceforcingsHrefEnum(): return StringToEnum("SurfaceforcingsHref")[0]
+def SurfaceforcingsSmbrefEnum(): return StringToEnum("SurfaceforcingsSmbref")[0]
+def SurfaceforcingsBPosEnum(): return StringToEnum("SurfaceforcingsBPos")[0]
+def SurfaceforcingsBNegEnum(): return StringToEnum("SurfaceforcingsBNeg")[0]
+def ThermalIsenthalpyEnum(): return StringToEnum("ThermalIsenthalpy")[0]
+def ThermalIsdynamicbasalspcEnum(): return StringToEnum("ThermalIsdynamicbasalspc")[0]
+def ThermalMaxiterEnum(): return StringToEnum("ThermalMaxiter")[0]
+def ThermalPenaltyFactorEnum(): return StringToEnum("ThermalPenaltyFactor")[0]
+def ThermalPenaltyLockEnum(): return StringToEnum("ThermalPenaltyLock")[0]
+def ThermalPenaltyThresholdEnum(): return StringToEnum("ThermalPenaltyThreshold")[0]
+def ThermalSpctemperatureEnum(): return StringToEnum("ThermalSpctemperature")[0]
+def ThermalStabilizationEnum(): return StringToEnum("ThermalStabilization")[0]
+def GiaMantleViscosityEnum(): return StringToEnum("GiaMantleViscosity")[0]
+def GiaLithosphereThicknessEnum(): return StringToEnum("GiaLithosphereThickness")[0]
+def ThicknessEnum(): return StringToEnum("Thickness")[0]
+def TimesteppingStartTimeEnum(): return StringToEnum("TimesteppingStartTime")[0]
+def TimesteppingFinalTimeEnum(): return StringToEnum("TimesteppingFinalTime")[0]
+def TimesteppingCflCoefficientEnum(): return StringToEnum("TimesteppingCflCoefficient")[0]
+def TimesteppingTimeAdaptEnum(): return StringToEnum("TimesteppingTimeAdapt")[0]
+def TimesteppingTimeStepEnum(): return StringToEnum("TimesteppingTimeStep")[0]
+def TransientIsstressbalanceEnum(): return StringToEnum("TransientIsstressbalance")[0]
+def TransientIsgroundinglineEnum(): return StringToEnum("TransientIsgroundingline")[0]
+def TransientIsmasstransportEnum(): return StringToEnum("TransientIsmasstransport")[0]
+def TransientIsthermalEnum(): return StringToEnum("TransientIsthermal")[0]
+def TransientIsgiaEnum(): return StringToEnum("TransientIsgia")[0]
+def TransientNumRequestedOutputsEnum(): return StringToEnum("TransientNumRequestedOutputs")[0]
+def TransientRequestedOutputsEnum(): return StringToEnum("TransientRequestedOutputs")[0]
+def SolutionTypeEnum(): return StringToEnum("SolutionType")[0]
+def AnalysisTypeEnum(): return StringToEnum("AnalysisType")[0]
+def ConfigurationTypeEnum(): return StringToEnum("ConfigurationType")[0]
+def AdjointBalancethicknessAnalysisEnum(): return StringToEnum("AdjointBalancethicknessAnalysis")[0]
+def AdjointHorizAnalysisEnum(): return StringToEnum("AdjointHorizAnalysis")[0]
+def AdjointSolutionEnum(): return StringToEnum("AdjointSolution")[0]
+def AnalysisCounterEnum(): return StringToEnum("AnalysisCounter")[0]
+def NoneAnalysisEnum(): return StringToEnum("NoneAnalysis")[0]
+def DefaultAnalysisEnum(): return StringToEnum("DefaultAnalysis")[0]
+def BalancethicknessAnalysisEnum(): return StringToEnum("BalancethicknessAnalysis")[0]
+def BalancethicknessSolutionEnum(): return StringToEnum("BalancethicknessSolution")[0]
+def BalancethicknessSoftAnalysisEnum(): return StringToEnum("BalancethicknessSoftAnalysis")[0]
+def BalancethicknessSoftSolutionEnum(): return StringToEnum("BalancethicknessSoftSolution")[0]
+def BalancevelocityAnalysisEnum(): return StringToEnum("BalancevelocityAnalysis")[0]
+def BalancevelocitySolutionEnum(): return StringToEnum("BalancevelocitySolution")[0]
+def BedSlopeAnalysisEnum(): return StringToEnum("BedSlopeAnalysis")[0]
+def BedSlopeSolutionEnum(): return StringToEnum("BedSlopeSolution")[0]
+def BedSlopeXAnalysisEnum(): return StringToEnum("BedSlopeXAnalysis")[0]
+def BedSlopeYAnalysisEnum(): return StringToEnum("BedSlopeYAnalysis")[0]
+def StressbalanceAnalysisEnum(): return StringToEnum("StressbalanceAnalysis")[0]
+def StressbalanceSIAAnalysisEnum(): return StringToEnum("StressbalanceSIAAnalysis")[0]
+def StressbalanceSolutionEnum(): return StringToEnum("StressbalanceSolution")[0]
+def StressbalanceVerticalAnalysisEnum(): return StringToEnum("StressbalanceVerticalAnalysis")[0]
+def EnthalpyAnalysisEnum(): return StringToEnum("EnthalpyAnalysis")[0]
+def EnthalpySolutionEnum(): return StringToEnum("EnthalpySolution")[0]
+def FlaimAnalysisEnum(): return StringToEnum("FlaimAnalysis")[0]
+def FlaimSolutionEnum(): return StringToEnum("FlaimSolution")[0]
+def HydrologyShreveAnalysisEnum(): return StringToEnum("HydrologyShreveAnalysis")[0]
+def HydrologyDCInefficientAnalysisEnum(): return StringToEnum("HydrologyDCInefficientAnalysis")[0]
+def HydrologyDCEfficientAnalysisEnum(): return StringToEnum("HydrologyDCEfficientAnalysis")[0]
+def HydrologySolutionEnum(): return StringToEnum("HydrologySolution")[0]
+def MeltingAnalysisEnum(): return StringToEnum("MeltingAnalysis")[0]
+def MasstransportAnalysisEnum(): return StringToEnum("MasstransportAnalysis")[0]
+def MasstransportSolutionEnum(): return StringToEnum("MasstransportSolution")[0]
+def FreeSurfaceBaseAnalysisEnum(): return StringToEnum("FreeSurfaceBaseAnalysis")[0]
+def FreeSurfaceTopAnalysisEnum(): return StringToEnum("FreeSurfaceTopAnalysis")[0]
+def SteadystateSolutionEnum(): return StringToEnum("SteadystateSolution")[0]
+def SurfaceSlopeAnalysisEnum(): return StringToEnum("SurfaceSlopeAnalysis")[0]
+def SurfaceSlopeSolutionEnum(): return StringToEnum("SurfaceSlopeSolution")[0]
+def SurfaceSlopeXAnalysisEnum(): return StringToEnum("SurfaceSlopeXAnalysis")[0]
+def SurfaceSlopeYAnalysisEnum(): return StringToEnum("SurfaceSlopeYAnalysis")[0]
+def SmoothedSurfaceSlopeXAnalysisEnum(): return StringToEnum("SmoothedSurfaceSlopeXAnalysis")[0]
+def SmoothedSurfaceSlopeYAnalysisEnum(): return StringToEnum("SmoothedSurfaceSlopeYAnalysis")[0]
+def ThermalAnalysisEnum(): return StringToEnum("ThermalAnalysis")[0]
+def ThermalSolutionEnum(): return StringToEnum("ThermalSolution")[0]
+def TransientSolutionEnum(): return StringToEnum("TransientSolution")[0]
+def GiaSolutionEnum(): return StringToEnum("GiaSolution")[0]
+def GiaAnalysisEnum(): return StringToEnum("GiaAnalysis")[0]
+def ApproximationEnum(): return StringToEnum("Approximation")[0]
+def NoneApproximationEnum(): return StringToEnum("NoneApproximation")[0]
+def SIAApproximationEnum(): return StringToEnum("SIAApproximation")[0]
+def SSAApproximationEnum(): return StringToEnum("SSAApproximation")[0]
+def SSAHOApproximationEnum(): return StringToEnum("SSAHOApproximation")[0]
+def SSAFSApproximationEnum(): return StringToEnum("SSAFSApproximation")[0]
+def L1L2ApproximationEnum(): return StringToEnum("L1L2Approximation")[0]
+def HOApproximationEnum(): return StringToEnum("HOApproximation")[0]
+def HOFSApproximationEnum(): return StringToEnum("HOFSApproximation")[0]
+def FSApproximationEnum(): return StringToEnum("FSApproximation")[0]
+def FSvelocityEnum(): return StringToEnum("FSvelocity")[0]
+def FSpressureEnum(): return StringToEnum("FSpressure")[0]
+def ConstraintsEnum(): return StringToEnum("Constraints")[0]
+def LoadsEnum(): return StringToEnum("Loads")[0]
+def MaterialsEnum(): return StringToEnum("Materials")[0]
+def NodesEnum(): return StringToEnum("Nodes")[0]
+def ContoursEnum(): return StringToEnum("Contours")[0]
+def ParametersEnum(): return StringToEnum("Parameters")[0]
+def VerticesEnum(): return StringToEnum("Vertices")[0]
+def ResultsEnum(): return StringToEnum("Results")[0]
+def GenericParamEnum(): return StringToEnum("GenericParam")[0]
+def AdolcParamEnum(): return StringToEnum("AdolcParam")[0]
+def BoolInputEnum(): return StringToEnum("BoolInput")[0]
+def BoolParamEnum(): return StringToEnum("BoolParam")[0]
+def ContourEnum(): return StringToEnum("Contour")[0]
+def ControlInputEnum(): return StringToEnum("ControlInput")[0]
+def DatasetInputEnum(): return StringToEnum("DatasetInput")[0]
+def DofIndexingEnum(): return StringToEnum("DofIndexing")[0]
+def DoubleInputEnum(): return StringToEnum("DoubleInput")[0]
+def DataSetParamEnum(): return StringToEnum("DataSetParam")[0]
+def DoubleMatArrayParamEnum(): return StringToEnum("DoubleMatArrayParam")[0]
+def DoubleMatParamEnum(): return StringToEnum("DoubleMatParam")[0]
+def DoubleParamEnum(): return StringToEnum("DoubleParam")[0]
+def DoubleVecParamEnum(): return StringToEnum("DoubleVecParam")[0]
+def ElementEnum(): return StringToEnum("Element")[0]
+def ElementResultEnum(): return StringToEnum("ElementResult")[0]
+def ExternalResultEnum(): return StringToEnum("ExternalResult")[0]
+def FileParamEnum(): return StringToEnum("FileParam")[0]
+def HookEnum(): return StringToEnum("Hook")[0]
+def IcefrontEnum(): return StringToEnum("Icefront")[0]
+def InputEnum(): return StringToEnum("Input")[0]
+def IntInputEnum(): return StringToEnum("IntInput")[0]
+def IntParamEnum(): return StringToEnum("IntParam")[0]
+def IntVecParamEnum(): return StringToEnum("IntVecParam")[0]
+def TransientParamEnum(): return StringToEnum("TransientParam")[0]
+def IceFrontTypeEnum(): return StringToEnum("IceFrontType")[0]
+def SSA2dIceFrontEnum(): return StringToEnum("SSA2dIceFront")[0]
+def SSA3dIceFrontEnum(): return StringToEnum("SSA3dIceFront")[0]
+def MaticeEnum(): return StringToEnum("Matice")[0]
+def MatdamageiceEnum(): return StringToEnum("Matdamageice")[0]
+def MatparEnum(): return StringToEnum("Matpar")[0]
+def NodeEnum(): return StringToEnum("Node")[0]
+def NumericalfluxEnum(): return StringToEnum("Numericalflux")[0]
+def NumericalfluxTypeEnum(): return StringToEnum("NumericalfluxType")[0]
+def ParamEnum(): return StringToEnum("Param")[0]
+def L1L2IceFrontEnum(): return StringToEnum("L1L2IceFront")[0]
+def HOIceFrontEnum(): return StringToEnum("HOIceFront")[0]
+def PengridEnum(): return StringToEnum("Pengrid")[0]
+def PenpairEnum(): return StringToEnum("Penpair")[0]
+def PentaEnum(): return StringToEnum("Penta")[0]
+def PentaInputEnum(): return StringToEnum("PentaInput")[0]
+def ProfilerEnum(): return StringToEnum("Profiler")[0]
+def MatrixParamEnum(): return StringToEnum("MatrixParam")[0]
+def NodeSIdEnum(): return StringToEnum("NodeSId")[0]
+def VectorParamEnum(): return StringToEnum("VectorParam")[0]
+def RiftfrontEnum(): return StringToEnum("Riftfront")[0]
+def RiftfrontTypeEnum(): return StringToEnum("RiftfrontType")[0]
+def SegmentEnum(): return StringToEnum("Segment")[0]
+def SegmentRiftfrontEnum(): return StringToEnum("SegmentRiftfront")[0]
+def SpcDynamicEnum(): return StringToEnum("SpcDynamic")[0]
+def SpcStaticEnum(): return StringToEnum("SpcStatic")[0]
+def SpcTransientEnum(): return StringToEnum("SpcTransient")[0]
+def FSIceFrontEnum(): return StringToEnum("FSIceFront")[0]
+def StringArrayParamEnum(): return StringToEnum("StringArrayParam")[0]
+def StringParamEnum(): return StringToEnum("StringParam")[0]
+def TriaEnum(): return StringToEnum("Tria")[0]
+def TriaInputEnum(): return StringToEnum("TriaInput")[0]
+def VertexEnum(): return StringToEnum("Vertex")[0]
+def VertexPIdEnum(): return StringToEnum("VertexPId")[0]
+def VertexSIdEnum(): return StringToEnum("VertexSId")[0]
+def AirEnum(): return StringToEnum("Air")[0]
+def IceEnum(): return StringToEnum("Ice")[0]
+def MelangeEnum(): return StringToEnum("Melange")[0]
+def WaterEnum(): return StringToEnum("Water")[0]
+def ClosedEnum(): return StringToEnum("Closed")[0]
+def FreeEnum(): return StringToEnum("Free")[0]
+def OpenEnum(): return StringToEnum("Open")[0]
+def AdjointpEnum(): return StringToEnum("Adjointp")[0]
+def AdjointxEnum(): return StringToEnum("Adjointx")[0]
+def AdjointyEnum(): return StringToEnum("Adjointy")[0]
+def AdjointzEnum(): return StringToEnum("Adjointz")[0]
+def BalancethicknessMisfitEnum(): return StringToEnum("BalancethicknessMisfit")[0]
+def BedSlopeXEnum(): return StringToEnum("BedSlopeX")[0]
+def BedSlopeYEnum(): return StringToEnum("BedSlopeY")[0]
+def BoundaryEnum(): return StringToEnum("Boundary")[0]
+def ConstantEnum(): return StringToEnum("Constant")[0]
+def ConvergedEnum(): return StringToEnum("Converged")[0]
+def FillEnum(): return StringToEnum("Fill")[0]
+def FractionIncrementEnum(): return StringToEnum("FractionIncrement")[0]
+def FrictionEnum(): return StringToEnum("Friction")[0]
+def GroundinglineMeltingRateEnum(): return StringToEnum("GroundinglineMeltingRate")[0]
+def InternalEnum(): return StringToEnum("Internal")[0]
+def MassFluxEnum(): return StringToEnum("MassFlux")[0]
+def MaxPenetrationEnum(): return StringToEnum("MaxPenetration")[0]
+def MeltingOffsetEnum(): return StringToEnum("MeltingOffset")[0]
+def MisfitEnum(): return StringToEnum("Misfit")[0]
+def NumberNodeToElementConnectivityEnum(): return StringToEnum("NumberNodeToElementConnectivity")[0]
+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 QmuBedEnum(): return StringToEnum("QmuBed")[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]
+def SegmentOnIceShelfEnum(): return StringToEnum("SegmentOnIceShelf")[0]
+def SurfaceAbsVelMisfitEnum(): return StringToEnum("SurfaceAbsVelMisfit")[0]
+def SurfaceAreaEnum(): return StringToEnum("SurfaceArea")[0]
+def SurfaceAverageVelMisfitEnum(): return StringToEnum("SurfaceAverageVelMisfit")[0]
+def SurfaceLogVelMisfitEnum(): return StringToEnum("SurfaceLogVelMisfit")[0]
+def SurfaceLogVxVyMisfitEnum(): return StringToEnum("SurfaceLogVxVyMisfit")[0]
+def SurfaceRelVelMisfitEnum(): return StringToEnum("SurfaceRelVelMisfit")[0]
+def SurfaceSlopeXEnum(): return StringToEnum("SurfaceSlopeX")[0]
+def SurfaceSlopeYEnum(): return StringToEnum("SurfaceSlopeY")[0]
+def TemperatureEnum(): return StringToEnum("Temperature")[0]
+def TemperatureOldEnum(): return StringToEnum("TemperatureOld")[0]
+def TemperaturePicardEnum(): return StringToEnum("TemperaturePicard")[0]
+def ThicknessAbsMisfitEnum(): return StringToEnum("ThicknessAbsMisfit")[0]
+def VelEnum(): return StringToEnum("Vel")[0]
+def VelocityEnum(): return StringToEnum("Velocity")[0]
+def VxAverageEnum(): return StringToEnum("VxAverage")[0]
+def VxEnum(): return StringToEnum("Vx")[0]
+def VxPicardEnum(): return StringToEnum("VxPicard")[0]
+def VyAverageEnum(): return StringToEnum("VyAverage")[0]
+def VyEnum(): return StringToEnum("Vy")[0]
+def VyPicardEnum(): return StringToEnum("VyPicard")[0]
+def VzEnum(): return StringToEnum("Vz")[0]
+def VzSSAEnum(): return StringToEnum("VzSSA")[0]
+def VzHOEnum(): return StringToEnum("VzHO")[0]
+def VzPicardEnum(): return StringToEnum("VzPicard")[0]
+def VzFSEnum(): return StringToEnum("VzFS")[0]
+def VxMeshEnum(): return StringToEnum("VxMesh")[0]
+def VyMeshEnum(): return StringToEnum("VyMesh")[0]
+def VzMeshEnum(): return StringToEnum("VzMesh")[0]
+def EnthalpyEnum(): return StringToEnum("Enthalpy")[0]
+def EnthalpyPicardEnum(): return StringToEnum("EnthalpyPicard")[0]
+def ThicknessAbsGradientEnum(): return StringToEnum("ThicknessAbsGradient")[0]
+def ThicknessAlongGradientEnum(): return StringToEnum("ThicknessAlongGradient")[0]
+def ThicknessAcrossGradientEnum(): return StringToEnum("ThicknessAcrossGradient")[0]
+def StepResponsesEnum(): return StringToEnum("StepResponses")[0]
+def IntMatParamEnum(): return StringToEnum("IntMatParam")[0]
+def RheologyBbarAbsGradientEnum(): return StringToEnum("RheologyBbarAbsGradient")[0]
+def DragCoefficientAbsGradientEnum(): return StringToEnum("DragCoefficientAbsGradient")[0]
+def TransientInputEnum(): return StringToEnum("TransientInput")[0]
+def WaterfractionEnum(): return StringToEnum("Waterfraction")[0]
+def WatercolumnEnum(): return StringToEnum("Watercolumn")[0]
+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 StressTensorEnum(): return StringToEnum("StressTensor")[0]
+def StressTensorxxEnum(): return StringToEnum("StressTensorxx")[0]
+def StressTensorxyEnum(): return StringToEnum("StressTensorxy")[0]
+def StressTensorxzEnum(): return StringToEnum("StressTensorxz")[0]
+def StressTensoryyEnum(): return StringToEnum("StressTensoryy")[0]
+def StressTensoryzEnum(): return StringToEnum("StressTensoryz")[0]
+def StressTensorzzEnum(): return StringToEnum("StressTensorzz")[0]
+def GiaCrossSectionShapeEnum(): return StringToEnum("GiaCrossSectionShape")[0]
+def GiadWdtEnum(): return StringToEnum("GiadWdt")[0]
+def GiaWEnum(): return StringToEnum("GiaW")[0]
+def P0Enum(): return StringToEnum("P0")[0]
+def P1Enum(): return StringToEnum("P1")[0]
+def P1DGEnum(): return StringToEnum("P1DG")[0]
+def P1bubbleEnum(): return StringToEnum("P1bubble")[0]
+def P1bubblecondensedEnum(): return StringToEnum("P1bubblecondensed")[0]
+def P2Enum(): return StringToEnum("P2")[0]
+def P2xP1Enum(): return StringToEnum("P2xP1")[0]
+def P1xP2Enum(): return StringToEnum("P1xP2")[0]
+def P1P1Enum(): return StringToEnum("P1P1")[0]
+def P1P1GLSEnum(): return StringToEnum("P1P1GLS")[0]
+def MINIEnum(): return StringToEnum("MINI")[0]
+def MINIcondensedEnum(): return StringToEnum("MINIcondensed")[0]
+def TaylorHoodEnum(): return StringToEnum("TaylorHood")[0]
+def SaveResultsEnum(): return StringToEnum("SaveResults")[0]
+def BoolElementResultEnum(): return StringToEnum("BoolElementResult")[0]
+def BoolExternalResultEnum(): return StringToEnum("BoolExternalResult")[0]
+def DoubleElementResultEnum(): return StringToEnum("DoubleElementResult")[0]
+def DoubleExternalResultEnum(): return StringToEnum("DoubleExternalResult")[0]
+def DoubleMatExternalResultEnum(): return StringToEnum("DoubleMatExternalResult")[0]
+def IntExternalResultEnum(): return StringToEnum("IntExternalResult")[0]
+def JEnum(): return StringToEnum("J")[0]
+def PatchEnum(): return StringToEnum("Patch")[0]
+def PatchNodesEnum(): return StringToEnum("PatchNodes")[0]
+def PatchVerticesEnum(): return StringToEnum("PatchVertices")[0]
+def PentaP1ElementResultEnum(): return StringToEnum("PentaP1ElementResult")[0]
+def StringExternalResultEnum(): return StringToEnum("StringExternalResult")[0]
+def StepEnum(): return StringToEnum("Step")[0]
+def TimeEnum(): return StringToEnum("Time")[0]
+def TriaP1ElementResultEnum(): return StringToEnum("TriaP1ElementResult")[0]
+def WaterColumnOldEnum(): return StringToEnum("WaterColumnOld")[0]
+def MinVelEnum(): return StringToEnum("MinVel")[0]
+def MaxVelEnum(): return StringToEnum("MaxVel")[0]
+def MinVxEnum(): return StringToEnum("MinVx")[0]
+def MaxVxEnum(): return StringToEnum("MaxVx")[0]
+def MaxAbsVxEnum(): return StringToEnum("MaxAbsVx")[0]
+def MinVyEnum(): return StringToEnum("MinVy")[0]
+def MaxVyEnum(): return StringToEnum("MaxVy")[0]
+def MaxAbsVyEnum(): return StringToEnum("MaxAbsVy")[0]
+def MinVzEnum(): return StringToEnum("MinVz")[0]
+def MaxVzEnum(): return StringToEnum("MaxVz")[0]
+def MaxAbsVzEnum(): return StringToEnum("MaxAbsVz")[0]
+def IceVolumeEnum(): return StringToEnum("IceVolume")[0]
+def TotalSmbEnum(): return StringToEnum("TotalSmb")[0]
+def AbsoluteEnum(): return StringToEnum("Absolute")[0]
+def IncrementalEnum(): return StringToEnum("Incremental")[0]
+def AgressiveMigrationEnum(): return StringToEnum("AgressiveMigration")[0]
+def NoneEnum(): return StringToEnum("None")[0]
+def SoftMigrationEnum(): return StringToEnum("SoftMigration")[0]
+def SubelementMigrationEnum(): return StringToEnum("SubelementMigration")[0]
+def SubelementMigration2Enum(): return StringToEnum("SubelementMigration2")[0]
+def MaskGroundediceLevelsetEnum(): return StringToEnum("MaskGroundediceLevelset")[0]
+def FSSolverEnum(): return StringToEnum("FSSolver")[0]
+def AdjointEnum(): return StringToEnum("Adjoint")[0]
+def ColinearEnum(): return StringToEnum("Colinear")[0]
+def ControlSteadyEnum(): return StringToEnum("ControlSteady")[0]
+def FsetEnum(): return StringToEnum("Fset")[0]
+def Gradient1Enum(): return StringToEnum("Gradient1")[0]
+def Gradient2Enum(): return StringToEnum("Gradient2")[0]
+def Gradient3Enum(): return StringToEnum("Gradient3")[0]
+def GradientEnum(): return StringToEnum("Gradient")[0]
+def GroundinglineMigrationEnum(): return StringToEnum("GroundinglineMigration")[0]
+def GsetEnum(): return StringToEnum("Gset")[0]
+def IndexEnum(): return StringToEnum("Index")[0]
+def IndexedEnum(): return StringToEnum("Indexed")[0]
+def IntersectEnum(): return StringToEnum("Intersect")[0]
+def NodalEnum(): return StringToEnum("Nodal")[0]
+def OldGradientEnum(): return StringToEnum("OldGradient")[0]
+def OutputFilePointerEnum(): return StringToEnum("OutputFilePointer")[0]
+def OutputFileNameEnum(): return StringToEnum("OutputFileName")[0]
+def LockFileNameEnum(): return StringToEnum("LockFileName")[0]
+def ToolkitsOptionsAnalysesEnum(): return StringToEnum("ToolkitsOptionsAnalyses")[0]
+def ToolkitsOptionsStringsEnum(): return StringToEnum("ToolkitsOptionsStrings")[0]
+def QmuErrNameEnum(): return StringToEnum("QmuErrName")[0]
+def QmuInNameEnum(): return StringToEnum("QmuInName")[0]
+def QmuOutNameEnum(): return StringToEnum("QmuOutName")[0]
+def RegularEnum(): return StringToEnum("Regular")[0]
+def ScaledEnum(): return StringToEnum("Scaled")[0]
+def SeparateEnum(): return StringToEnum("Separate")[0]
+def SsetEnum(): return StringToEnum("Sset")[0]
+def VerboseEnum(): return StringToEnum("Verbose")[0]
+def TriangleInterpEnum(): return StringToEnum("TriangleInterp")[0]
+def BilinearInterpEnum(): return StringToEnum("BilinearInterp")[0]
+def NearestInterpEnum(): return StringToEnum("NearestInterp")[0]
+def XYEnum(): return StringToEnum("XY")[0]
+def XYZEnum(): return StringToEnum("XYZ")[0]
+def DenseEnum(): return StringToEnum("Dense")[0]
+def MpiDenseEnum(): return StringToEnum("MpiDense")[0]
+def SeqEnum(): return StringToEnum("Seq")[0]
+def MpiEnum(): return StringToEnum("Mpi")[0]
+def OptionEnum(): return StringToEnum("Option")[0]
+def GenericOptionEnum(): return StringToEnum("GenericOption")[0]
+def OptionCellEnum(): return StringToEnum("OptionCell")[0]
+def OptionCharEnum(): return StringToEnum("OptionChar")[0]
+def OptionStructEnum(): return StringToEnum("OptionStruct")[0]
+def OptionDoubleEnum(): return StringToEnum("OptionDouble")[0]
+def OptionLogicalEnum(): return StringToEnum("OptionLogical")[0]
+def PatersonEnum(): return StringToEnum("Paterson")[0]
+def ArrheniusEnum(): return StringToEnum("Arrhenius")[0]
+def LliboutryDuvalEnum(): return StringToEnum("LliboutryDuval")[0]
+def MaximumNumberOfDefinitionsEnum(): return StringToEnum("MaximumNumberOfDefinitions")[0]
Index: /issm/trunk/src/m/enum/FSApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FSApproximationEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FSApproximationEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FSApproximationEnum()
+%FSAPPROXIMATIONENUM - Enum of FSApproximation
+%
+%   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=FSApproximationEnum()
+
+macro=StringToEnum('FSApproximation');
Index: /issm/trunk/src/m/enum/FSIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FSIceFrontEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FSIceFrontEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FSIceFrontEnum()
+%FSICEFRONTENUM - Enum of FSIceFront
+%
+%   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=FSIceFrontEnum()
+
+macro=StringToEnum('FSIceFront');
Index: /issm/trunk/src/m/enum/FSSolverEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FSSolverEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FSSolverEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FSSolverEnum()
+%FSSOLVERENUM - Enum of FSSolver
+%
+%   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=FSSolverEnum()
+
+macro=StringToEnum('FSSolver');
Index: /issm/trunk/src/m/enum/FSpressureEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FSpressureEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FSpressureEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FSpressureEnum()
+%FSPRESSUREENUM - Enum of FSpressure
+%
+%   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=FSpressureEnum()
+
+macro=StringToEnum('FSpressure');
Index: /issm/trunk/src/m/enum/FSvelocityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FSvelocityEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FSvelocityEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FSvelocityEnum()
+%FSVELOCITYENUM - Enum of FSvelocity
+%
+%   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=FSvelocityEnum()
+
+macro=StringToEnum('FSvelocity');
Index: /issm/trunk/src/m/enum/FlowequationBorderFSEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationBorderFSEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FlowequationBorderFSEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FlowequationBorderFSEnum()
+%FLOWEQUATIONBORDERFSENUM - Enum of FlowequationBorderFS
+%
+%   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=FlowequationBorderFSEnum()
+
+macro=StringToEnum('FlowequationBorderFS');
Index: /issm/trunk/src/m/enum/FlowequationBorderHOEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationBorderHOEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FlowequationBorderHOEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FlowequationBorderHOEnum()
+%FLOWEQUATIONBORDERHOENUM - Enum of FlowequationBorderHO
+%
+%   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=FlowequationBorderHOEnum()
+
+macro=StringToEnum('FlowequationBorderHO');
Index: /issm/trunk/src/m/enum/FlowequationBorderSSAEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationBorderSSAEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FlowequationBorderSSAEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FlowequationBorderSSAEnum()
+%FLOWEQUATIONBORDERSSAENUM - Enum of FlowequationBorderSSA
+%
+%   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=FlowequationBorderSSAEnum()
+
+macro=StringToEnum('FlowequationBorderSSA');
Index: sm/trunk/src/m/enum/FlowequationBordermacayealEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationBordermacayealEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=FlowequationBordermacayealEnum()
-%FLOWEQUATIONBORDERMACAYEALENUM - Enum of FlowequationBordermacayeal
-%
-%   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=FlowequationBordermacayealEnum()
-
-macro=StringToEnum('FlowequationBordermacayeal');
Index: sm/trunk/src/m/enum/FlowequationBorderpattynEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationBorderpattynEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=FlowequationBorderpattynEnum()
-%FLOWEQUATIONBORDERPATTYNENUM - Enum of FlowequationBorderpattyn
-%
-%   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=FlowequationBorderpattynEnum()
-
-macro=StringToEnum('FlowequationBorderpattyn');
Index: sm/trunk/src/m/enum/FlowequationBorderstokesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationBorderstokesEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=FlowequationBorderstokesEnum()
-%FLOWEQUATIONBORDERSTOKESENUM - Enum of FlowequationBorderstokes
-%
-%   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=FlowequationBorderstokesEnum()
-
-macro=StringToEnum('FlowequationBorderstokes');
Index: /issm/trunk/src/m/enum/FlowequationFeFSEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationFeFSEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FlowequationFeFSEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FlowequationFeFSEnum()
+%FLOWEQUATIONFEFSENUM - Enum of FlowequationFeFS
+%
+%   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=FlowequationFeFSEnum()
+
+macro=StringToEnum('FlowequationFeFS');
Index: /issm/trunk/src/m/enum/FlowequationFeHOEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationFeHOEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FlowequationFeHOEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FlowequationFeHOEnum()
+%FLOWEQUATIONFEHOENUM - Enum of FlowequationFeHO
+%
+%   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=FlowequationFeHOEnum()
+
+macro=StringToEnum('FlowequationFeHO');
Index: /issm/trunk/src/m/enum/FlowequationFeSSAEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationFeSSAEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FlowequationFeSSAEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FlowequationFeSSAEnum()
+%FLOWEQUATIONFESSAENUM - Enum of FlowequationFeSSA
+%
+%   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=FlowequationFeSSAEnum()
+
+macro=StringToEnum('FlowequationFeSSA');
Index: /issm/trunk/src/m/enum/FlowequationIsFSEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsFSEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FlowequationIsFSEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsFSEnum()
+%FLOWEQUATIONISFSENUM - Enum of FlowequationIsFS
+%
+%   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=FlowequationIsFSEnum()
+
+macro=StringToEnum('FlowequationIsFS');
Index: /issm/trunk/src/m/enum/FlowequationIsHOEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsHOEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FlowequationIsHOEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsHOEnum()
+%FLOWEQUATIONISHOENUM - Enum of FlowequationIsHO
+%
+%   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=FlowequationIsHOEnum()
+
+macro=StringToEnum('FlowequationIsHO');
Index: /issm/trunk/src/m/enum/FlowequationIsL1L2Enum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsL1L2Enum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FlowequationIsL1L2Enum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsL1L2Enum()
+%FLOWEQUATIONISL1L2ENUM - Enum of FlowequationIsL1L2
+%
+%   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=FlowequationIsL1L2Enum()
+
+macro=StringToEnum('FlowequationIsL1L2');
Index: /issm/trunk/src/m/enum/FlowequationIsSIAEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsSIAEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FlowequationIsSIAEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsSIAEnum()
+%FLOWEQUATIONISSIAENUM - Enum of FlowequationIsSIA
+%
+%   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=FlowequationIsSIAEnum()
+
+macro=StringToEnum('FlowequationIsSIA');
Index: /issm/trunk/src/m/enum/FlowequationIsSSAEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsSSAEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FlowequationIsSSAEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FlowequationIsSSAEnum()
+%FLOWEQUATIONISSSAENUM - Enum of FlowequationIsSSA
+%
+%   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=FlowequationIsSSAEnum()
+
+macro=StringToEnum('FlowequationIsSSA');
Index: sm/trunk/src/m/enum/FlowequationIshutterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIshutterEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=FlowequationIshutterEnum()
-%FLOWEQUATIONISHUTTERENUM - Enum of FlowequationIshutter
-%
-%   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=FlowequationIshutterEnum()
-
-macro=StringToEnum('FlowequationIshutter');
Index: sm/trunk/src/m/enum/FlowequationIsl1l2Enum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsl1l2Enum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=FlowequationIsl1l2Enum()
-%FLOWEQUATIONISL1L2ENUM - Enum of FlowequationIsl1l2
-%
-%   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=FlowequationIsl1l2Enum()
-
-macro=StringToEnum('FlowequationIsl1l2');
Index: sm/trunk/src/m/enum/FlowequationIsmacayealpattynEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsmacayealpattynEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=FlowequationIsmacayealpattynEnum()
-%FLOWEQUATIONISMACAYEALPATTYNENUM - Enum of FlowequationIsmacayealpattyn
-%
-%   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=FlowequationIsmacayealpattynEnum()
-
-macro=StringToEnum('FlowequationIsmacayealpattyn');
Index: sm/trunk/src/m/enum/FlowequationIsstokesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FlowequationIsstokesEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=FlowequationIsstokesEnum()
-%FLOWEQUATIONISSTOKESENUM - Enum of FlowequationIsstokes
-%
-%   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=FlowequationIsstokesEnum()
-
-macro=StringToEnum('FlowequationIsstokes');
Index: /issm/trunk/src/m/enum/FreeSurfaceBaseAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FreeSurfaceBaseAnalysisEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FreeSurfaceBaseAnalysisEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FreeSurfaceBaseAnalysisEnum()
+%FREESURFACEBASEANALYSISENUM - Enum of FreeSurfaceBaseAnalysis
+%
+%   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=FreeSurfaceBaseAnalysisEnum()
+
+macro=StringToEnum('FreeSurfaceBaseAnalysis');
Index: /issm/trunk/src/m/enum/FreeSurfaceTopAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/FreeSurfaceTopAnalysisEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/FreeSurfaceTopAnalysisEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=FreeSurfaceTopAnalysisEnum()
+%FREESURFACETOPANALYSISENUM - Enum of FreeSurfaceTopAnalysis
+%
+%   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=FreeSurfaceTopAnalysisEnum()
+
+macro=StringToEnum('FreeSurfaceTopAnalysis');
Index: sm/trunk/src/m/enum/GLlevelsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/GLlevelsetEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=GLlevelsetEnum()
-%GLLEVELSETENUM - Enum of GLlevelset
-%
-%   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=GLlevelsetEnum()
-
-macro=StringToEnum('GLlevelset');
Index: /issm/trunk/src/m/enum/HOApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HOApproximationEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/HOApproximationEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=HOApproximationEnum()
+%HOAPPROXIMATIONENUM - Enum of HOApproximation
+%
+%   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=HOApproximationEnum()
+
+macro=StringToEnum('HOApproximation');
Index: /issm/trunk/src/m/enum/HOFSApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HOFSApproximationEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/HOFSApproximationEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=HOFSApproximationEnum()
+%HOFSAPPROXIMATIONENUM - Enum of HOFSApproximation
+%
+%   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=HOFSApproximationEnum()
+
+macro=StringToEnum('HOFSApproximation');
Index: /issm/trunk/src/m/enum/HOIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HOIceFrontEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/HOIceFrontEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=HOIceFrontEnum()
+%HOICEFRONTENUM - Enum of HOIceFront
+%
+%   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=HOIceFrontEnum()
+
+macro=StringToEnum('HOIceFront');
Index: sm/trunk/src/m/enum/HutterApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/HutterApproximationEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=HutterApproximationEnum()
-%HUTTERAPPROXIMATIONENUM - Enum of HutterApproximation
-%
-%   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=HutterApproximationEnum()
-
-macro=StringToEnum('HutterApproximation');
Index: /issm/trunk/src/m/enum/LliboutryDuvalEnum.m
===================================================================
--- /issm/trunk/src/m/enum/LliboutryDuvalEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/LliboutryDuvalEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=LliboutryDuvalEnum()
+%LLIBOUTRYDUVALENUM - Enum of LliboutryDuval
+%
+%   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=LliboutryDuvalEnum()
+
+macro=StringToEnum('LliboutryDuval');
Index: /issm/trunk/src/m/enum/MINIcondensedEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MINIcondensedEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MINIcondensedEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MINIcondensedEnum()
+%MINICONDENSEDENUM - Enum of MINIcondensed
+%
+%   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=MINIcondensedEnum()
+
+macro=StringToEnum('MINIcondensed');
Index: sm/trunk/src/m/enum/MacAyeal2dIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MacAyeal2dIceFrontEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MacAyeal2dIceFrontEnum()
-%MACAYEAL2DICEFRONTENUM - Enum of MacAyeal2dIceFront
-%
-%   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=MacAyeal2dIceFrontEnum()
-
-macro=StringToEnum('MacAyeal2dIceFront');
Index: sm/trunk/src/m/enum/MacAyeal3dIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MacAyeal3dIceFrontEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MacAyeal3dIceFrontEnum()
-%MACAYEAL3DICEFRONTENUM - Enum of MacAyeal3dIceFront
-%
-%   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=MacAyeal3dIceFrontEnum()
-
-macro=StringToEnum('MacAyeal3dIceFront');
Index: sm/trunk/src/m/enum/MacAyealApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MacAyealApproximationEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MacAyealApproximationEnum()
-%MACAYEALAPPROXIMATIONENUM - Enum of MacAyealApproximation
-%
-%   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=MacAyealApproximationEnum()
-
-macro=StringToEnum('MacAyealApproximation');
Index: sm/trunk/src/m/enum/MacAyealPattynApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MacAyealPattynApproximationEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MacAyealPattynApproximationEnum()
-%MACAYEALPATTYNAPPROXIMATIONENUM - Enum of MacAyealPattynApproximation
-%
-%   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=MacAyealPattynApproximationEnum()
-
-macro=StringToEnum('MacAyealPattynApproximation');
Index: sm/trunk/src/m/enum/MacAyealStokesApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MacAyealStokesApproximationEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MacAyealStokesApproximationEnum()
-%MACAYEALSTOKESAPPROXIMATIONENUM - Enum of MacAyealStokesApproximation
-%
-%   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=MacAyealStokesApproximationEnum()
-
-macro=StringToEnum('MacAyealStokesApproximation');
Index: sm/trunk/src/m/enum/MaskElementonfloatingiceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskElementonfloatingiceEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MaskElementonfloatingiceEnum()
-%MASKELEMENTONFLOATINGICEENUM - Enum of MaskElementonfloatingice
-%
-%   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=MaskElementonfloatingiceEnum()
-
-macro=StringToEnum('MaskElementonfloatingice');
Index: sm/trunk/src/m/enum/MaskElementongroundediceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskElementongroundediceEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MaskElementongroundediceEnum()
-%MASKELEMENTONGROUNDEDICEENUM - Enum of MaskElementongroundedice
-%
-%   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=MaskElementongroundediceEnum()
-
-macro=StringToEnum('MaskElementongroundedice');
Index: sm/trunk/src/m/enum/MaskElementonwaterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskElementonwaterEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MaskElementonwaterEnum()
-%MASKELEMENTONWATERENUM - Enum of MaskElementonwater
-%
-%   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=MaskElementonwaterEnum()
-
-macro=StringToEnum('MaskElementonwater');
Index: /issm/trunk/src/m/enum/MaskGroundediceLevelsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskGroundediceLevelsetEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MaskGroundediceLevelsetEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MaskGroundediceLevelsetEnum()
+%MASKGROUNDEDICELEVELSETENUM - Enum of MaskGroundediceLevelset
+%
+%   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=MaskGroundediceLevelsetEnum()
+
+macro=StringToEnum('MaskGroundediceLevelset');
Index: /issm/trunk/src/m/enum/MaskIceLevelsetEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskIceLevelsetEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MaskIceLevelsetEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MaskIceLevelsetEnum()
+%MASKICELEVELSETENUM - Enum of MaskIceLevelset
+%
+%   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=MaskIceLevelsetEnum()
+
+macro=StringToEnum('MaskIceLevelset');
Index: sm/trunk/src/m/enum/MaskVertexonfloatingiceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskVertexonfloatingiceEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MaskVertexonfloatingiceEnum()
-%MASKVERTEXONFLOATINGICEENUM - Enum of MaskVertexonfloatingice
-%
-%   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=MaskVertexonfloatingiceEnum()
-
-macro=StringToEnum('MaskVertexonfloatingice');
Index: sm/trunk/src/m/enum/MaskVertexongroundediceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskVertexongroundediceEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MaskVertexongroundediceEnum()
-%MASKVERTEXONGROUNDEDICEENUM - Enum of MaskVertexongroundedice
-%
-%   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=MaskVertexongroundediceEnum()
-
-macro=StringToEnum('MaskVertexongroundedice');
Index: sm/trunk/src/m/enum/MaskVertexonwaterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaskVertexonwaterEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MaskVertexonwaterEnum()
-%MASKVERTEXONWATERENUM - Enum of MaskVertexonwater
-%
-%   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=MaskVertexonwaterEnum()
-
-macro=StringToEnum('MaskVertexonwater');
Index: /issm/trunk/src/m/enum/MasstransportAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportAnalysisEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MasstransportAnalysisEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MasstransportAnalysisEnum()
+%MASSTRANSPORTANALYSISENUM - Enum of MasstransportAnalysis
+%
+%   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=MasstransportAnalysisEnum()
+
+macro=StringToEnum('MasstransportAnalysis');
Index: /issm/trunk/src/m/enum/MasstransportHydrostaticAdjustmentEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportHydrostaticAdjustmentEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MasstransportHydrostaticAdjustmentEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MasstransportHydrostaticAdjustmentEnum()
+%MASSTRANSPORTHYDROSTATICADJUSTMENTENUM - Enum of MasstransportHydrostaticAdjustment
+%
+%   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=MasstransportHydrostaticAdjustmentEnum()
+
+macro=StringToEnum('MasstransportHydrostaticAdjustment');
Index: /issm/trunk/src/m/enum/MasstransportIsfreesurfaceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportIsfreesurfaceEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MasstransportIsfreesurfaceEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MasstransportIsfreesurfaceEnum()
+%MASSTRANSPORTISFREESURFACEENUM - Enum of MasstransportIsfreesurface
+%
+%   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=MasstransportIsfreesurfaceEnum()
+
+macro=StringToEnum('MasstransportIsfreesurface');
Index: /issm/trunk/src/m/enum/MasstransportMinThicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportMinThicknessEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MasstransportMinThicknessEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MasstransportMinThicknessEnum()
+%MASSTRANSPORTMINTHICKNESSENUM - Enum of MasstransportMinThickness
+%
+%   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=MasstransportMinThicknessEnum()
+
+macro=StringToEnum('MasstransportMinThickness');
Index: /issm/trunk/src/m/enum/MasstransportNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportNumRequestedOutputsEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MasstransportNumRequestedOutputsEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MasstransportNumRequestedOutputsEnum()
+%MASSTRANSPORTNUMREQUESTEDOUTPUTSENUM - Enum of MasstransportNumRequestedOutputs
+%
+%   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=MasstransportNumRequestedOutputsEnum()
+
+macro=StringToEnum('MasstransportNumRequestedOutputs');
Index: /issm/trunk/src/m/enum/MasstransportPenaltyFactorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportPenaltyFactorEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MasstransportPenaltyFactorEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MasstransportPenaltyFactorEnum()
+%MASSTRANSPORTPENALTYFACTORENUM - Enum of MasstransportPenaltyFactor
+%
+%   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=MasstransportPenaltyFactorEnum()
+
+macro=StringToEnum('MasstransportPenaltyFactor');
Index: /issm/trunk/src/m/enum/MasstransportRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportRequestedOutputsEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MasstransportRequestedOutputsEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MasstransportRequestedOutputsEnum()
+%MASSTRANSPORTREQUESTEDOUTPUTSENUM - Enum of MasstransportRequestedOutputs
+%
+%   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=MasstransportRequestedOutputsEnum()
+
+macro=StringToEnum('MasstransportRequestedOutputs');
Index: /issm/trunk/src/m/enum/MasstransportSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportSolutionEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MasstransportSolutionEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MasstransportSolutionEnum()
+%MASSTRANSPORTSOLUTIONENUM - Enum of MasstransportSolution
+%
+%   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=MasstransportSolutionEnum()
+
+macro=StringToEnum('MasstransportSolution');
Index: /issm/trunk/src/m/enum/MasstransportSpcthicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportSpcthicknessEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MasstransportSpcthicknessEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MasstransportSpcthicknessEnum()
+%MASSTRANSPORTSPCTHICKNESSENUM - Enum of MasstransportSpcthickness
+%
+%   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=MasstransportSpcthicknessEnum()
+
+macro=StringToEnum('MasstransportSpcthickness');
Index: /issm/trunk/src/m/enum/MasstransportStabilizationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportStabilizationEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MasstransportStabilizationEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MasstransportStabilizationEnum()
+%MASSTRANSPORTSTABILIZATIONENUM - Enum of MasstransportStabilization
+%
+%   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=MasstransportStabilizationEnum()
+
+macro=StringToEnum('MasstransportStabilization');
Index: /issm/trunk/src/m/enum/MasstransportVertexPairingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MasstransportVertexPairingEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MasstransportVertexPairingEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MasstransportVertexPairingEnum()
+%MASSTRANSPORTVERTEXPAIRINGENUM - Enum of MasstransportVertexPairing
+%
+%   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=MasstransportVertexPairingEnum()
+
+macro=StringToEnum('MasstransportVertexPairing');
Index: /issm/trunk/src/m/enum/MaximumNumberOfDefinitionsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MaximumNumberOfDefinitionsEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/MaximumNumberOfDefinitionsEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=MaximumNumberOfDefinitionsEnum()
+%MAXIMUMNUMBEROFDEFINITIONSENUM - Enum of MaximumNumberOfDefinitions
+%
+%   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=MaximumNumberOfDefinitionsEnum()
+
+macro=StringToEnum('MaximumNumberOfDefinitions');
Index: sm/trunk/src/m/enum/MaximumNumberOfEnums.m
===================================================================
--- /issm/trunk/src/m/enum/MaximumNumberOfEnums.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MaximumNumberOfEnums()
-%MAXIMUMNUMBEROFENUMS - Enum of MaximumNumberOfEnums
-%
-%   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=MaximumNumberOfEnums()
-
-macro=560;
Index: sm/trunk/src/m/enum/MeshEdgesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshEdgesEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MeshEdgesEnum()
-%MESHEDGESENUM - Enum of MeshEdges
-%
-%   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=MeshEdgesEnum()
-
-macro=StringToEnum('MeshEdges');
Index: sm/trunk/src/m/enum/MeshElementconnectivityEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshElementconnectivityEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MeshElementconnectivityEnum()
-%MESHELEMENTCONNECTIVITYENUM - Enum of MeshElementconnectivity
-%
-%   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=MeshElementconnectivityEnum()
-
-macro=StringToEnum('MeshElementconnectivity');
Index: sm/trunk/src/m/enum/MeshNumberofedgesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MeshNumberofedgesEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=MeshNumberofedgesEnum()
-%MESHNUMBEROFEDGESENUM - Enum of MeshNumberofedges
-%
-%   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=MeshNumberofedgesEnum()
-
-macro=StringToEnum('MeshNumberofedges');
Index: /issm/trunk/src/m/enum/P1P1Enum.m
===================================================================
--- /issm/trunk/src/m/enum/P1P1Enum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/P1P1Enum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=P1P1Enum()
+%P1P1ENUM - Enum of P1P1
+%
+%   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=P1P1Enum()
+
+macro=StringToEnum('P1P1');
Index: /issm/trunk/src/m/enum/P1P1GLSEnum.m
===================================================================
--- /issm/trunk/src/m/enum/P1P1GLSEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/P1P1GLSEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=P1P1GLSEnum()
+%P1P1GLSENUM - Enum of P1P1GLS
+%
+%   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=P1P1GLSEnum()
+
+macro=StringToEnum('P1P1GLS');
Index: /issm/trunk/src/m/enum/P1bubbleEnum.m
===================================================================
--- /issm/trunk/src/m/enum/P1bubbleEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/P1bubbleEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=P1bubbleEnum()
+%P1BUBBLEENUM - Enum of P1bubble
+%
+%   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=P1bubbleEnum()
+
+macro=StringToEnum('P1bubble');
Index: /issm/trunk/src/m/enum/P1bubblecondensedEnum.m
===================================================================
--- /issm/trunk/src/m/enum/P1bubblecondensedEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/P1bubblecondensedEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=P1bubblecondensedEnum()
+%P1BUBBLECONDENSEDENUM - Enum of P1bubblecondensed
+%
+%   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=P1bubblecondensedEnum()
+
+macro=StringToEnum('P1bubblecondensed');
Index: /issm/trunk/src/m/enum/P1xP2Enum.m
===================================================================
--- /issm/trunk/src/m/enum/P1xP2Enum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/P1xP2Enum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=P1xP2Enum()
+%P1XP2ENUM - Enum of P1xP2
+%
+%   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=P1xP2Enum()
+
+macro=StringToEnum('P1xP2');
Index: /issm/trunk/src/m/enum/P2xP1Enum.m
===================================================================
--- /issm/trunk/src/m/enum/P2xP1Enum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/P2xP1Enum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=P2xP1Enum()
+%P2XP1ENUM - Enum of P2xP1
+%
+%   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=P2xP1Enum()
+
+macro=StringToEnum('P2xP1');
Index: sm/trunk/src/m/enum/PattynApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PattynApproximationEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PattynApproximationEnum()
-%PATTYNAPPROXIMATIONENUM - Enum of PattynApproximation
-%
-%   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=PattynApproximationEnum()
-
-macro=StringToEnum('PattynApproximation');
Index: sm/trunk/src/m/enum/PattynIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PattynIceFrontEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PattynIceFrontEnum()
-%PATTYNICEFRONTENUM - Enum of PattynIceFront
-%
-%   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=PattynIceFrontEnum()
-
-macro=StringToEnum('PattynIceFront');
Index: sm/trunk/src/m/enum/PattynStokesApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PattynStokesApproximationEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PattynStokesApproximationEnum()
-%PATTYNSTOKESAPPROXIMATIONENUM - Enum of PattynStokesApproximation
-%
-%   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=PattynStokesApproximationEnum()
-
-macro=StringToEnum('PattynStokesApproximation');
Index: /issm/trunk/src/m/enum/PentaInputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PentaInputEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/PentaInputEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=PentaInputEnum()
+%PENTAINPUTENUM - Enum of PentaInput
+%
+%   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=PentaInputEnum()
+
+macro=StringToEnum('PentaInput');
Index: sm/trunk/src/m/enum/PentaP1InputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PentaP1InputEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PentaP1InputEnum()
-%PENTAP1INPUTENUM - Enum of PentaP1Input
-%
-%   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=PentaP1InputEnum()
-
-macro=StringToEnum('PentaP1Input');
Index: sm/trunk/src/m/enum/PrognosticAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticAnalysisEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PrognosticAnalysisEnum()
-%PROGNOSTICANALYSISENUM - Enum of PrognosticAnalysis
-%
-%   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=PrognosticAnalysisEnum()
-
-macro=StringToEnum('PrognosticAnalysis');
Index: sm/trunk/src/m/enum/PrognosticHydrostaticAdjustmentEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticHydrostaticAdjustmentEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PrognosticHydrostaticAdjustmentEnum()
-%PROGNOSTICHYDROSTATICADJUSTMENTENUM - Enum of PrognosticHydrostaticAdjustment
-%
-%   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=PrognosticHydrostaticAdjustmentEnum()
-
-macro=StringToEnum('PrognosticHydrostaticAdjustment');
Index: sm/trunk/src/m/enum/PrognosticMinThicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticMinThicknessEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PrognosticMinThicknessEnum()
-%PROGNOSTICMINTHICKNESSENUM - Enum of PrognosticMinThickness
-%
-%   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=PrognosticMinThicknessEnum()
-
-macro=StringToEnum('PrognosticMinThickness');
Index: sm/trunk/src/m/enum/PrognosticNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticNumRequestedOutputsEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PrognosticNumRequestedOutputsEnum()
-%PROGNOSTICNUMREQUESTEDOUTPUTSENUM - Enum of PrognosticNumRequestedOutputs
-%
-%   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=PrognosticNumRequestedOutputsEnum()
-
-macro=StringToEnum('PrognosticNumRequestedOutputs');
Index: sm/trunk/src/m/enum/PrognosticPenaltyFactorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticPenaltyFactorEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PrognosticPenaltyFactorEnum()
-%PROGNOSTICPENALTYFACTORENUM - Enum of PrognosticPenaltyFactor
-%
-%   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=PrognosticPenaltyFactorEnum()
-
-macro=StringToEnum('PrognosticPenaltyFactor');
Index: sm/trunk/src/m/enum/PrognosticRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticRequestedOutputsEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PrognosticRequestedOutputsEnum()
-%PROGNOSTICREQUESTEDOUTPUTSENUM - Enum of PrognosticRequestedOutputs
-%
-%   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=PrognosticRequestedOutputsEnum()
-
-macro=StringToEnum('PrognosticRequestedOutputs');
Index: sm/trunk/src/m/enum/PrognosticSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticSolutionEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PrognosticSolutionEnum()
-%PROGNOSTICSOLUTIONENUM - Enum of PrognosticSolution
-%
-%   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=PrognosticSolutionEnum()
-
-macro=StringToEnum('PrognosticSolution');
Index: sm/trunk/src/m/enum/PrognosticSpcthicknessEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticSpcthicknessEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PrognosticSpcthicknessEnum()
-%PROGNOSTICSPCTHICKNESSENUM - Enum of PrognosticSpcthickness
-%
-%   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=PrognosticSpcthicknessEnum()
-
-macro=StringToEnum('PrognosticSpcthickness');
Index: sm/trunk/src/m/enum/PrognosticStabilizationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticStabilizationEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PrognosticStabilizationEnum()
-%PROGNOSTICSTABILIZATIONENUM - Enum of PrognosticStabilization
-%
-%   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=PrognosticStabilizationEnum()
-
-macro=StringToEnum('PrognosticStabilization');
Index: sm/trunk/src/m/enum/PrognosticVertexPairingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticVertexPairingEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=PrognosticVertexPairingEnum()
-%PROGNOSTICVERTEXPAIRINGENUM - Enum of PrognosticVertexPairing
-%
-%   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=PrognosticVertexPairingEnum()
-
-macro=StringToEnum('PrognosticVertexPairing');
Index: /issm/trunk/src/m/enum/QmuMaterialsRheologyBEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuMaterialsRheologyBEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/QmuMaterialsRheologyBEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+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: /issm/trunk/src/m/enum/QmuVxMeshEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVxMeshEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/QmuVxMeshEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+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: /issm/trunk/src/m/enum/QmuVyMeshEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVyMeshEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/QmuVyMeshEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+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: /issm/trunk/src/m/enum/QmuVzMeshEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuVzMeshEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/QmuVzMeshEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+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/SIAApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SIAApproximationEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/SIAApproximationEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=SIAApproximationEnum()
+%SIAAPPROXIMATIONENUM - Enum of SIAApproximation
+%
+%   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=SIAApproximationEnum()
+
+macro=StringToEnum('SIAApproximation');
Index: /issm/trunk/src/m/enum/SSA2dIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SSA2dIceFrontEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/SSA2dIceFrontEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=SSA2dIceFrontEnum()
+%SSA2DICEFRONTENUM - Enum of SSA2dIceFront
+%
+%   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=SSA2dIceFrontEnum()
+
+macro=StringToEnum('SSA2dIceFront');
Index: /issm/trunk/src/m/enum/SSA3dIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SSA3dIceFrontEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/SSA3dIceFrontEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=SSA3dIceFrontEnum()
+%SSA3DICEFRONTENUM - Enum of SSA3dIceFront
+%
+%   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=SSA3dIceFrontEnum()
+
+macro=StringToEnum('SSA3dIceFront');
Index: /issm/trunk/src/m/enum/SSAApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SSAApproximationEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/SSAApproximationEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=SSAApproximationEnum()
+%SSAAPPROXIMATIONENUM - Enum of SSAApproximation
+%
+%   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=SSAApproximationEnum()
+
+macro=StringToEnum('SSAApproximation');
Index: /issm/trunk/src/m/enum/SSAFSApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SSAFSApproximationEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/SSAFSApproximationEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=SSAFSApproximationEnum()
+%SSAFSAPPROXIMATIONENUM - Enum of SSAFSApproximation
+%
+%   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=SSAFSApproximationEnum()
+
+macro=StringToEnum('SSAFSApproximation');
Index: /issm/trunk/src/m/enum/SSAHOApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SSAHOApproximationEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/SSAHOApproximationEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=SSAHOApproximationEnum()
+%SSAHOAPPROXIMATIONENUM - Enum of SSAHOApproximation
+%
+%   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=SSAHOApproximationEnum()
+
+macro=StringToEnum('SSAHOApproximation');
Index: /issm/trunk/src/m/enum/SmoothedSurfaceSlopeXAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SmoothedSurfaceSlopeXAnalysisEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/SmoothedSurfaceSlopeXAnalysisEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+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: /issm/trunk/src/m/enum/SmoothedSurfaceSlopeYAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SmoothedSurfaceSlopeYAnalysisEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/SmoothedSurfaceSlopeYAnalysisEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+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: sm/trunk/src/m/enum/StokesApproximationEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StokesApproximationEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=StokesApproximationEnum()
-%STOKESAPPROXIMATIONENUM - Enum of StokesApproximation
-%
-%   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=StokesApproximationEnum()
-
-macro=StringToEnum('StokesApproximation');
Index: sm/trunk/src/m/enum/StokesIceFrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StokesIceFrontEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=StokesIceFrontEnum()
-%STOKESICEFRONTENUM - Enum of StokesIceFront
-%
-%   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=StokesIceFrontEnum()
-
-macro=StringToEnum('StokesIceFront');
Index: sm/trunk/src/m/enum/StokesSolverEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StokesSolverEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=StokesSolverEnum()
-%STOKESSOLVERENUM - Enum of StokesSolver
-%
-%   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=StokesSolverEnum()
-
-macro=StringToEnum('StokesSolver');
Index: /issm/trunk/src/m/enum/StressbalanceAbstolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceAbstolEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceAbstolEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceAbstolEnum()
+%STRESSBALANCEABSTOLENUM - Enum of StressbalanceAbstol
+%
+%   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=StressbalanceAbstolEnum()
+
+macro=StringToEnum('StressbalanceAbstol');
Index: /issm/trunk/src/m/enum/StressbalanceAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceAnalysisEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceAnalysisEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceAnalysisEnum()
+%STRESSBALANCEANALYSISENUM - Enum of StressbalanceAnalysis
+%
+%   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=StressbalanceAnalysisEnum()
+
+macro=StringToEnum('StressbalanceAnalysis');
Index: /issm/trunk/src/m/enum/StressbalanceFSreconditioningEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceFSreconditioningEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceFSreconditioningEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceFSreconditioningEnum()
+%STRESSBALANCEFSRECONDITIONINGENUM - Enum of StressbalanceFSreconditioning
+%
+%   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=StressbalanceFSreconditioningEnum()
+
+macro=StringToEnum('StressbalanceFSreconditioning');
Index: /issm/trunk/src/m/enum/StressbalanceIcefrontEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceIcefrontEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceIcefrontEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceIcefrontEnum()
+%STRESSBALANCEICEFRONTENUM - Enum of StressbalanceIcefront
+%
+%   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=StressbalanceIcefrontEnum()
+
+macro=StringToEnum('StressbalanceIcefront');
Index: /issm/trunk/src/m/enum/StressbalanceIsnewtonEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceIsnewtonEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceIsnewtonEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceIsnewtonEnum()
+%STRESSBALANCEISNEWTONENUM - Enum of StressbalanceIsnewton
+%
+%   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=StressbalanceIsnewtonEnum()
+
+macro=StringToEnum('StressbalanceIsnewton');
Index: /issm/trunk/src/m/enum/StressbalanceMaxiterEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceMaxiterEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceMaxiterEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceMaxiterEnum()
+%STRESSBALANCEMAXITERENUM - Enum of StressbalanceMaxiter
+%
+%   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=StressbalanceMaxiterEnum()
+
+macro=StringToEnum('StressbalanceMaxiter');
Index: /issm/trunk/src/m/enum/StressbalanceNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceNumRequestedOutputsEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceNumRequestedOutputsEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceNumRequestedOutputsEnum()
+%STRESSBALANCENUMREQUESTEDOUTPUTSENUM - Enum of StressbalanceNumRequestedOutputs
+%
+%   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=StressbalanceNumRequestedOutputsEnum()
+
+macro=StringToEnum('StressbalanceNumRequestedOutputs');
Index: /issm/trunk/src/m/enum/StressbalancePenaltyFactorEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalancePenaltyFactorEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalancePenaltyFactorEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalancePenaltyFactorEnum()
+%STRESSBALANCEPENALTYFACTORENUM - Enum of StressbalancePenaltyFactor
+%
+%   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=StressbalancePenaltyFactorEnum()
+
+macro=StringToEnum('StressbalancePenaltyFactor');
Index: /issm/trunk/src/m/enum/StressbalanceReferentialEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceReferentialEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceReferentialEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceReferentialEnum()
+%STRESSBALANCEREFERENTIALENUM - Enum of StressbalanceReferential
+%
+%   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=StressbalanceReferentialEnum()
+
+macro=StringToEnum('StressbalanceReferential');
Index: /issm/trunk/src/m/enum/StressbalanceReltolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceReltolEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceReltolEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceReltolEnum()
+%STRESSBALANCERELTOLENUM - Enum of StressbalanceReltol
+%
+%   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=StressbalanceReltolEnum()
+
+macro=StringToEnum('StressbalanceReltol');
Index: /issm/trunk/src/m/enum/StressbalanceRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceRequestedOutputsEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceRequestedOutputsEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceRequestedOutputsEnum()
+%STRESSBALANCEREQUESTEDOUTPUTSENUM - Enum of StressbalanceRequestedOutputs
+%
+%   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=StressbalanceRequestedOutputsEnum()
+
+macro=StringToEnum('StressbalanceRequestedOutputs');
Index: /issm/trunk/src/m/enum/StressbalanceRestolEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceRestolEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceRestolEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceRestolEnum()
+%STRESSBALANCERESTOLENUM - Enum of StressbalanceRestol
+%
+%   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=StressbalanceRestolEnum()
+
+macro=StringToEnum('StressbalanceRestol');
Index: /issm/trunk/src/m/enum/StressbalanceRiftPenaltyLockEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceRiftPenaltyLockEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceRiftPenaltyLockEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceRiftPenaltyLockEnum()
+%STRESSBALANCERIFTPENALTYLOCKENUM - Enum of StressbalanceRiftPenaltyLock
+%
+%   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=StressbalanceRiftPenaltyLockEnum()
+
+macro=StringToEnum('StressbalanceRiftPenaltyLock');
Index: /issm/trunk/src/m/enum/StressbalanceRiftPenaltyThresholdEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceRiftPenaltyThresholdEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceRiftPenaltyThresholdEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceRiftPenaltyThresholdEnum()
+%STRESSBALANCERIFTPENALTYTHRESHOLDENUM - Enum of StressbalanceRiftPenaltyThreshold
+%
+%   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=StressbalanceRiftPenaltyThresholdEnum()
+
+macro=StringToEnum('StressbalanceRiftPenaltyThreshold');
Index: /issm/trunk/src/m/enum/StressbalanceSIAAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceSIAAnalysisEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceSIAAnalysisEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceSIAAnalysisEnum()
+%STRESSBALANCESIAANALYSISENUM - Enum of StressbalanceSIAAnalysis
+%
+%   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=StressbalanceSIAAnalysisEnum()
+
+macro=StringToEnum('StressbalanceSIAAnalysis');
Index: /issm/trunk/src/m/enum/StressbalanceShelfDampeningEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceShelfDampeningEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceShelfDampeningEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceShelfDampeningEnum()
+%STRESSBALANCESHELFDAMPENINGENUM - Enum of StressbalanceShelfDampening
+%
+%   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=StressbalanceShelfDampeningEnum()
+
+macro=StringToEnum('StressbalanceShelfDampening');
Index: /issm/trunk/src/m/enum/StressbalanceSolutionEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceSolutionEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceSolutionEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceSolutionEnum()
+%STRESSBALANCESOLUTIONENUM - Enum of StressbalanceSolution
+%
+%   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=StressbalanceSolutionEnum()
+
+macro=StringToEnum('StressbalanceSolution');
Index: /issm/trunk/src/m/enum/StressbalanceSpcvxEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceSpcvxEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceSpcvxEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceSpcvxEnum()
+%STRESSBALANCESPCVXENUM - Enum of StressbalanceSpcvx
+%
+%   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=StressbalanceSpcvxEnum()
+
+macro=StringToEnum('StressbalanceSpcvx');
Index: /issm/trunk/src/m/enum/StressbalanceSpcvyEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceSpcvyEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceSpcvyEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceSpcvyEnum()
+%STRESSBALANCESPCVYENUM - Enum of StressbalanceSpcvy
+%
+%   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=StressbalanceSpcvyEnum()
+
+macro=StringToEnum('StressbalanceSpcvy');
Index: /issm/trunk/src/m/enum/StressbalanceSpcvzEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceSpcvzEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceSpcvzEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceSpcvzEnum()
+%STRESSBALANCESPCVZENUM - Enum of StressbalanceSpcvz
+%
+%   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=StressbalanceSpcvzEnum()
+
+macro=StringToEnum('StressbalanceSpcvz');
Index: /issm/trunk/src/m/enum/StressbalanceVertexPairingEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceVertexPairingEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceVertexPairingEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceVertexPairingEnum()
+%STRESSBALANCEVERTEXPAIRINGENUM - Enum of StressbalanceVertexPairing
+%
+%   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=StressbalanceVertexPairingEnum()
+
+macro=StringToEnum('StressbalanceVertexPairing');
Index: /issm/trunk/src/m/enum/StressbalanceVerticalAnalysisEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceVerticalAnalysisEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceVerticalAnalysisEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceVerticalAnalysisEnum()
+%STRESSBALANCEVERTICALANALYSISENUM - Enum of StressbalanceVerticalAnalysis
+%
+%   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=StressbalanceVerticalAnalysisEnum()
+
+macro=StringToEnum('StressbalanceVerticalAnalysis');
Index: /issm/trunk/src/m/enum/StressbalanceViscosityOvershootEnum.m
===================================================================
--- /issm/trunk/src/m/enum/StressbalanceViscosityOvershootEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/StressbalanceViscosityOvershootEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=StressbalanceViscosityOvershootEnum()
+%STRESSBALANCEVISCOSITYOVERSHOOTENUM - Enum of StressbalanceViscosityOvershoot
+%
+%   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=StressbalanceViscosityOvershootEnum()
+
+macro=StringToEnum('StressbalanceViscosityOvershoot');
Index: /issm/trunk/src/m/enum/TaylorHoodEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TaylorHoodEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/TaylorHoodEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=TaylorHoodEnum()
+%TAYLORHOODENUM - Enum of TaylorHood
+%
+%   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=TaylorHoodEnum()
+
+macro=StringToEnum('TaylorHood');
Index: /issm/trunk/src/m/enum/ThermalIsdynamicbasalspcEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ThermalIsdynamicbasalspcEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/ThermalIsdynamicbasalspcEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=ThermalIsdynamicbasalspcEnum()
+%THERMALISDYNAMICBASALSPCENUM - Enum of ThermalIsdynamicbasalspc
+%
+%   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=ThermalIsdynamicbasalspcEnum()
+
+macro=StringToEnum('ThermalIsdynamicbasalspc');
Index: sm/trunk/src/m/enum/TransientIsdiagnosticEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientIsdiagnosticEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=TransientIsdiagnosticEnum()
-%TRANSIENTISDIAGNOSTICENUM - Enum of TransientIsdiagnostic
-%
-%   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=TransientIsdiagnosticEnum()
-
-macro=StringToEnum('TransientIsdiagnostic');
Index: /issm/trunk/src/m/enum/TransientIsmasstransportEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientIsmasstransportEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/TransientIsmasstransportEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=TransientIsmasstransportEnum()
+%TRANSIENTISMASSTRANSPORTENUM - Enum of TransientIsmasstransport
+%
+%   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=TransientIsmasstransportEnum()
+
+macro=StringToEnum('TransientIsmasstransport');
Index: sm/trunk/src/m/enum/TransientIsprognosticEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientIsprognosticEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=TransientIsprognosticEnum()
-%TRANSIENTISPROGNOSTICENUM - Enum of TransientIsprognostic
-%
-%   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=TransientIsprognosticEnum()
-
-macro=StringToEnum('TransientIsprognostic');
Index: /issm/trunk/src/m/enum/TransientIsstressbalanceEnum.m
===================================================================
--- /issm/trunk/src/m/enum/TransientIsstressbalanceEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/TransientIsstressbalanceEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=TransientIsstressbalanceEnum()
+%TRANSIENTISSTRESSBALANCEENUM - Enum of TransientIsstressbalance
+%
+%   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=TransientIsstressbalanceEnum()
+
+macro=StringToEnum('TransientIsstressbalance');
Index: /issm/trunk/src/m/enum/VzFSEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzFSEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/VzFSEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=VzFSEnum()
+%VZFSENUM - Enum of VzFS
+%
+%   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=VzFSEnum()
+
+macro=StringToEnum('VzFS');
Index: /issm/trunk/src/m/enum/VzHOEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzHOEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/VzHOEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=VzHOEnum()
+%VZHOENUM - Enum of VzHO
+%
+%   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=VzHOEnum()
+
+macro=StringToEnum('VzHO');
Index: sm/trunk/src/m/enum/VzMacAyealEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzMacAyealEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=VzMacAyealEnum()
-%VZMACAYEALENUM - Enum of VzMacAyeal
-%
-%   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=VzMacAyealEnum()
-
-macro=StringToEnum('VzMacAyeal');
Index: sm/trunk/src/m/enum/VzPattynEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzPattynEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=VzPattynEnum()
-%VZPATTYNENUM - Enum of VzPattyn
-%
-%   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=VzPattynEnum()
-
-macro=StringToEnum('VzPattyn');
Index: /issm/trunk/src/m/enum/VzSSAEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzSSAEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/VzSSAEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=VzSSAEnum()
+%VZSSAENUM - Enum of VzSSA
+%
+%   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=VzSSAEnum()
+
+macro=StringToEnum('VzSSA');
Index: sm/trunk/src/m/enum/VzStokesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/VzStokesEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=VzStokesEnum()
-%VZSTOKESENUM - Enum of VzStokes
-%
-%   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=VzStokesEnum()
-
-macro=StringToEnum('VzStokes');
Index: /issm/trunk/src/m/enum/XYZEnum.m
===================================================================
--- /issm/trunk/src/m/enum/XYZEnum.m	(revision 16137)
+++ /issm/trunk/src/m/enum/XYZEnum.m	(revision 16137)
@@ -0,0 +1,11 @@
+function macro=XYZEnum()
+%XYZENUM - Enum of XYZ
+%
+%   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=XYZEnum()
+
+macro=StringToEnum('XYZ');
Index: sm/trunk/src/m/enum/XYZPEnum.m
===================================================================
--- /issm/trunk/src/m/enum/XYZPEnum.m	(revision 16136)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=XYZPEnum()
-%XYZPENUM - Enum of XYZP
-%
-%   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=XYZPEnum()
-
-macro=StringToEnum('XYZP');
Index: /issm/trunk/src/m/exp/Shp2Exp.m
===================================================================
--- /issm/trunk/src/m/exp/Shp2Exp.m	(revision 16137)
+++ /issm/trunk/src/m/exp/Shp2Exp.m	(revision 16137)
@@ -0,0 +1,35 @@
+function Shp2Exp(expfilename,shapefilename)
+%SHP2EXP- transform shape file to Argus .exp file
+%
+%   Usage:
+%      Shp2Exp(expfilename,shapefilename);
+%
+%   Example:
+%      Shp2Exp('Domain.exp','Domain.shp');
+%
+%   See also EXPMASTER, EXPDOC
+
+
+	if ~exist(shapefilename,'file'),
+		error(['Shapefile ' shapefilename ' does not exist']);
+	end
+	shp=shaperead(shapefilename);
+
+	exp=struct([]);
+	for i=1:length(shp),
+		if strcmpi(shp(i).Geometry,'Polygon'),
+			x=shp(i).X; y=shp(i).Y;
+			ids=find(isnan(x));
+			x(ids)=[]; y(ids)=[];
+			
+			exp(end+1).x=x;
+			exp(end).y=y;
+			exp(end).nods=length(x);
+			exp(end).density=1;
+			exp(end).closed=1;
+			exp(end).name=num2str(shp(i).id);
+		end
+	end
+
+	expwrite(exp,expfilename);
+
Index: /issm/trunk/src/m/exp/expcoarsen.py
===================================================================
--- /issm/trunk/src/m/exp/expcoarsen.py	(revision 16137)
+++ /issm/trunk/src/m/exp/expcoarsen.py	(revision 16137)
@@ -0,0 +1,78 @@
+import os.path
+import numpy as npy
+from collections import OrderedDict
+from MatlabFuncs import *
+from expread import expread
+from expwrite import expwrite
+
+def expcoarsen(newfile,oldfile,resolution):
+	""" 
+	EXPCOARSEN - coarsen an exp contour
+
+	This routine read an Argus file and remove points with respect to
+	the resolution (in meters) given in input. 
+
+	Usage:
+	  expcoarsen(newfile,oldfile,resolution)
+
+	Example:
+	   expcoarsen('DomainOutline.exp','Antarctica.exp',4000)
+	""" 
+
+	#Some checks
+	if not os.path.exists(oldfile):
+		raise OSError("expcoarsen error message: file '%s' not found!" % oldfile)
+	if os.path.exists(newfile):
+		choice=raw_input('A file ' + newfile + ' already exists, do you want to modify it? (y/n)')
+		if choice not in 'y': 
+			print('no modification done ... exiting')
+			return 0
+
+	#Get exp oldfile
+	contours=expread(oldfile)
+	newcontours=[]
+
+	for contour in  contours:
+		
+		numpoints=npy.size(contour['x'])
+
+		j=0
+		x=contour['x']
+		y=contour['y']
+
+		#stop if we have reached end of profile (always keep the last point)
+		while j<numpoints-1:
+
+			#see whether we keep this point or not
+			distance=npy.sqrt((x[j]-x[j+1])**2+(y[j]-y[j+1])**2)
+			if distance<resolution and j<numpoints-2:   #do not remove last point
+				x=npy.delete(x,j+1,0)
+				y=npy.delete(y,j+1,0)
+				numpoints=numpoints-1
+			else:
+				division=int(npy.floor(distance/resolution)+1)
+				if division>=2:
+					xi=npy.linspace(x[j],x[j+1],division)
+					yi=npy.linspace(y[j],y[j+1],division)
+					
+					x=npy.hstack((x[0:j+1],xi[1:-1],x[j+1:]))
+					y=npy.hstack((y[0:j+1],yi[1:-1],y[j+1:]))
+
+					#update current point
+					j=j+1+division-2
+					numpoints=numpoints+division-2
+				else:
+					#update current point
+					j=j+1
+		
+		if npy.size(x)>1:
+			#keep the (x,y) contour arond
+			newcontour=OrderedDict()
+			newcontour['nods']=npy.size(x)
+			newcontour['density']=contour['density']
+			newcontour['x']=x
+			newcontour['y']=y
+			newcontours.append(newcontour)
+
+	#write output
+	expwrite(newcontours,newfile)
Index: sm/trunk/src/m/exp/expcreatecontour.m
===================================================================
--- /issm/trunk/src/m/exp/expcreatecontour.m	(revision 16136)
+++ 	(revision )
@@ -1,35 +1,0 @@
-function expcreatecontour(filename)
-%EXPCREATECONTOUR - create a contour from a list of points
-%
-%   expcreatecontour: from a list of (x,y) points (retrieve using ginput on an undetermined
-%   number of points: used RETURN key to end input), create an Argus .exp 
-%   file holding the corresponding closed contour.
-%    
-%   Usage:
-%      expcreatecontour(filename)
-%
-%   See also EXPMASTER, EXPDOC
-
-%Get root of filename
-[path root ext ver]=fileparts(filename);
-
-%Get contour
-disp('Click on contour points you desire. Type RETURN to end input of points');
-[x,y]=ginput();
-
-%close contour
-x=[x;x(1)];
-y=[y;y(1);];
-
-%plot contour
-hold on;
-plot(x,y,'r-');
-
-%create structure for expwrite routine
-a.x=x;
-a.y=y;
-a.name=root;
-a.density=1;
-
-%write contour using expwrite
-expwrite(a,filename);
Index: sm/trunk/src/m/exp/expcreateprofile.m
===================================================================
--- /issm/trunk/src/m/exp/expcreateprofile.m	(revision 16136)
+++ 	(revision )
@@ -1,31 +1,0 @@
-function expcreateprofile(filename)
-%EXPCREATEPROFILE - create an Argus file from a list of points
-%
-%   expcreateprofile: from a list of (x,y) points (retrieve using ginput on an undetermined
-%   number of points: used RETURN key to end input), create an Argus .exp 
-%   file holding the corresponding open profile.
-%    
-%   Usage:
-%      expcreateprofile(filename)
-%
-%   See also EXPMASTER, EXPDOC
-
-%Get root of filename
-[path root ext]=fileparts(filename);
-
-%Get profile
-disp('Click on profile points you desire. Type RETURN to end input of points');
-[x,y]=ginput();
-
-%plot contour
-hold on;
-plot(x,y,'r-');
-
-%create structure for expwrite routine
-a.x=x;
-a.y=y;
-a.name=root;
-a.density=1;
-
-%write profile using expwrite
-expwrite(a,filename);
Index: /issm/trunk/src/m/exp/operation/addcontour.m
===================================================================
--- /issm/trunk/src/m/exp/operation/addcontour.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/addcontour.m	(revision 16137)
@@ -0,0 +1,50 @@
+function [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options)
+%ADDCONTOUR - add a closed contour
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click to add a point to the new profile, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	x=[];
+	y=[];
+
+	while loop
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				x(end+1)=x(1);
+				y(end+1)=y(1);
+				A(end+1).x=x; 
+				A(end).y=y; 
+				A(end).name=root; 
+				A(end).density=1; 
+				numprofiles=numprofiles+1;
+				numpoints=numpoints+length(x);
+				closed(end+1)=1;
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/addendprofile.m
===================================================================
--- /issm/trunk/src/m/exp/operation/addendprofile.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/addendprofile.m	(revision 16137)
@@ -0,0 +1,86 @@
+function [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%ADDENDPROFILE - add point at the end of a n existing profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if ~any(~closed)
+		disp('all profiles are closed')
+		return
+	end	   
+	%select a profile first
+	if numprofiles>1
+		%first step, select a profile
+		isclosed=1;
+		title('click on a profile, RETURN to exit','FontSize',14)
+		while isclosed
+			[xi,yi] = ginput(1);
+			if ~isempty(xi)
+				%get the closest point 
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if closed(profsel)
+					disp('selected profile is closed, make another selection')
+				else
+					isclosed=0;
+				end
+
+			else
+				%RETURN -> out
+				return
+			end
+		end
+	else
+		profsel=1;
+	end
+
+	%initialize x and y
+	x=A(profsel).x;
+	y=A(profsel).y;
+
+	%plot the selected profile
+	hold on
+	plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+		'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+	loop=1;
+	while loop
+
+		%first step, select a profile
+		title('click to add point to the selected profile, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize')+2,'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				A(profsel).x=x; 
+				A(profsel).y=y; 
+				A(profsel).name=root; 
+				A(profsel).density=1; 
+				numpoints=numpoints+length(x);
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/addinsideprofile.m
===================================================================
--- /issm/trunk/src/m/exp/operation/addinsideprofile.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/addinsideprofile.m	(revision 16137)
@@ -0,0 +1,79 @@
+function [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%ADDINSIDEPROFILE - add apoint inside a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<2
+		disp('at least two points are required, exiting...')
+		return
+	end	   
+	hold on
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	loop=1;
+	while loop
+
+		%first step, select a segment
+		title('click on a segment, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		%first click
+		if ~isempty(xi)
+
+			%get the closest segment
+			[profsel indsel]=closestsegment(A,numprofiles,xi,yi);
+
+			%check that at least one segment exists
+			if indsel==0
+				disp('at least two points in one profile are required, exiting...')
+				return
+			end
+
+			%highlight selected segment
+			plot([A(profsel).x(indsel) A(profsel).x(indsel+1)],[A(profsel).y(indsel) A(profsel).y(indsel+1)],...
+				'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+			%next click
+			title('click on the new point''s location, RETURN to exit','FontSize',14)
+			[xi,yi,but] = ginput(1);
+
+			%second click
+			if ~isempty(xi)
+
+				%add point to A
+				A(profsel).x=[A(profsel).x(1:indsel,1); xi; A(profsel).x(indsel+1:end,1)];
+				A(profsel).y=[A(profsel).y(1:indsel,1); yi; A(profsel).y(indsel+1:end,1)];
+				numpoints=numpoints+1;
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+
+			else
+				%RETURN->exit
+				return
+			end
+		else
+			%RETURN-> exit
+			return
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/addprofile.m
===================================================================
--- /issm/trunk/src/m/exp/operation/addprofile.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/addprofile.m	(revision 16137)
@@ -0,0 +1,48 @@
+function [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%ADDPROFILE - add a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click to add a point to the new profile, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	x=[];
+	y=[];
+
+	while loop
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			x(end+1,1)=xi;
+			y(end+1,1)=yi;
+
+			%plot everything
+			undoplots(prevplot);
+			plot(x,y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(x(end),y(end),'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+		else
+
+			%check that the profile is not empty
+			if ~isempty(x)
+				A(end+1).x=x; 
+				A(end).y=y; 
+				A(end).name=root; 
+				A(end).density=1; 
+				numprofiles=numprofiles+1;
+				numpoints=numpoints+length(x);
+				closed(end+1)=0;
+			end
+
+			%get out
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/closeprofile.m
===================================================================
--- /issm/trunk/src/m/exp/operation/closeprofile.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/closeprofile.m	(revision 16137)
@@ -0,0 +1,68 @@
+function [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%CLOSEPROFILE - close one or several profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile to be closed')
+		return
+	end
+
+	title('click on the profiles to be closed, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks,
+		if numprofiles==0    
+			disp('no profile present, exiting...')
+			return            
+		end  
+		if ~any(~closed),
+			disp('All the profiles are closed, exiting...')
+			return
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it from the selection
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			elseif closed(profsel),
+				%profile already closed, do nothing
+				disp('selected profile aready closed, make another selection'),
+			else
+				%add the profile to the list to be closed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%close the profiles
+			for i=1:length(selection),
+				A(selection(i)).x(end+1)=A(selection(i)).x(1);
+				A(selection(i)).y(end+1)=A(selection(i)).y(1);
+				numpoints=numpoints+1;
+				closed(selection(i))=1;
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/closestpoint.m
===================================================================
--- /issm/trunk/src/m/exp/operation/closestpoint.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/closestpoint.m	(revision 16137)
@@ -0,0 +1,21 @@
+function [profsel indsel]=closestpoint(A,numprofiles,xi,yi)
+%CLOSESTPOINT - find the closest point of a profile
+%
+%   This routine find the point of the profile A that is the closest
+%   to (xi,yi) and return the number of the profile and the number of
+%   the point
+%
+%   Usage:
+%     [profsel indsel]=closestpoint(A,numprofiles,xi,yi) 
+
+	%loop over the points of each profile, find the closest to (xi,yi)
+	for i=1:numprofiles,
+		distance=(xi-A(i).x).^2+(yi-A(i).y).^2;
+		[newdistance p]=min(distance);
+		if ((i==1) | (newdistance<olddistance)),
+			indsel=p;
+			profsel=i;
+			olddistance=newdistance;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/closestsegment.m
===================================================================
--- /issm/trunk/src/m/exp/operation/closestsegment.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/closestsegment.m	(revision 16137)
@@ -0,0 +1,28 @@
+function [profsel indsel]=closestsegment(A,numprofiles,xi,yi)
+%CLOSESTSEGMENT - find the closest segment of a profile
+%
+%   This routine find the segment of the profile A that is the closest
+%   to (xi,yi) and return the number of the profile and the number of
+%   the first point belonging to this closest segment
+%
+%   Usage:
+%     [profsel indsel]=closestsegment(A,numprofiles,xi,yi) 
+
+	%loop over the middles of each profile, find the closest to (xi,yi)
+	profsel=0;
+	indsel=0;
+	first=1;
+	for i=1:numprofiles,
+		if length(A(i).x)>1
+			middles=[(A(i).x(1:end-1)+A(i).x(2:end))/2 (A(i).y(1:end-1)+A(i).y(2:end))/2];
+			distance=(xi-middles(:,1)).^2+(yi-middles(:,2)).^2;
+			[newdistance p]=min(distance);
+			if (first | (newdistance<olddistance)),
+				first=0;
+				indsel=p;
+				profsel=i;
+				olddistance=newdistance;
+			end
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/cutarea.m
===================================================================
--- /issm/trunk/src/m/exp/operation/cutarea.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/cutarea.m	(revision 16137)
@@ -0,0 +1,156 @@
+function [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options)
+%CUTAREA - cut several point of a profile
+%
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile. The user must click 3 times to select the
+%   area to be removed. Twice to select the tips and one to select
+%   the part of the profile to be removed
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	points=[];
+
+	%loop (at least 3 clicks needed)
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile present, exiting...')
+			return
+		end	   
+		if numpoints<3
+			disp('at least two points are needed, exiting...')
+			return
+		end	   
+
+		%select a point
+		if isempty(points)
+			title('click on the first tip, RETURN to exit','FontSize',14)
+		elseif length(points)==1
+			title('click on the second tip, RETURN to exit','FontSize',14)
+		else
+			title('click in the middle of the area to be cut, RETURN to exit','FontSize',14)
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			%get the closest point
+			%first time, look at all profiles
+			if isempty(points)
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if ((closed(profsel) & length(A(profsel).x)<4) |  (~closed(profsel) & length(A(profsel).x)<3)),
+					disp('the selected profile has less than 3 points, make another selection');
+				else
+					selection=profsel;
+					points(end+1)=indsel;
+					plot(A(profsel).x,A(profsel).y,...
+						'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+					text(A(selection).x(indsel),A(selection).y(indsel),num2str(1),'FontSize',14,'background',[0.7 0.7 0.9]);
+				end
+			else
+				%get the 2d or 3d point for the given contou
+				[profsel indsel]=closestpoint(A(selection),1,xi,yi);
+				if ismember(indsel,points)
+					disp('the selected points must be distinct')
+				else
+					%second click?
+					if length(points)==1,
+						points(end+1)=indsel;
+						text(A(selection).x(indsel),A(selection).y(indsel),num2str(2),'FontSize',14,'background',[0.7 0.7 0.9]);
+					%third click?
+					else
+						p1=points(1); p2=points(2); p3=indsel;
+						x=A(selection).x; y=A(selection).y;
+						if p1<p2
+							if p3>p1 & p3<p2
+								if closed(selection)
+									%open the profile
+									n=length(A(selection).x);
+									A(selection).x=[A(selection).x(p2:end-1,1);A(selection).x(1:p1,1)];
+									A(selection).y=[A(selection).y(p2:end-1,1);A(selection).y(1:p1,1)];
+									numpoints=numpoints-(n-length(A(selection).x));
+									closed(selection)=0;
+								else
+									%cut in 2 profiles
+									A(selection).x=x(1:p1);
+									A(selection).y=y(1:p1);
+									closed(selection)=0;
+									A(end+1).x=x(p2:end);
+									A(end).y=y(p2:end);
+									A(end).density=A(selection).density;
+									A(end).name=A(selection).name;
+									closed(end+1)=0;
+									numprofiles=numprofiles+1;
+									numpoints=numpoints-(p2-p1-1);
+								end
+							else
+								%only point removal
+								n=length(A(selection).x);
+								A(selection).x=x(p1:p2);
+								A(selection).y=y(p1:p2);
+								numpoints=numpoints-(n-length(A(selection).x));
+								closed(selection)=0;
+							end
+						else
+							if p3>p2 & p3<p1
+								if closed(selection)
+									%open the profile
+									n=length(A(selection).x);
+									A(selection).x=[A(selection).x(p1:end-1,1);A(selection).x(1:p2,1)];
+									A(selection).y=[A(selection).y(p1:end-1,1);A(selection).y(1:p2,1)];
+									numpoints=numpoints-(n-length(A(selection).x));
+									closed(selection)=0;
+								else
+									%cut in 2 profiles
+									closed(selection)=0;
+									A(selection).x=x(1:p2);
+									A(selection).y=y(1:p2);
+									A(end+1).x=x(p1:end);
+									A(end).y=y(p1:end);
+									A(end).density=A(selection).density;
+									A(end).name=A(selection).name;
+									closed(end+1)=0;
+									numprofiles=numprofiles+1;
+									numpoints=numpoints-(p1-p2-1);
+								end
+							else
+								%only point removal
+								n=length(A(selection).x);
+								x(1:p2-1)=[];x(p1-p2+2:end)=[];%it should have been x(p2+1:end)
+								y(1:p2-1)=[];y(p1-p2+2:end)=[];
+								A(selection).x=x;
+								A(selection).y=y;
+								numpoints=numpoints-(n-length(A(selection).x));
+								closed(selection)=0;
+							end
+						end
+
+						%plot new profile
+						undoplots(prevplot);
+						for i=1:numprofiles
+							plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+								'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+						end
+						points=[];
+
+					end
+				end
+			end
+		else
+			%RETRUN-> quit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/cutprofile.m
===================================================================
--- /issm/trunk/src/m/exp/operation/cutprofile.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/cutprofile.m	(revision 16137)
@@ -0,0 +1,79 @@
+function [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%CUTPROFILE - cut a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<2
+		disp('at least two points are needed')
+		return
+	end	   
+	hold on
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	loop=1;
+	while loop
+
+		%select a segment
+		title('click the segment to cut, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest segment
+			[profsel indsel]=closestsegment(A,numprofiles,xi,yi);
+
+			%check that at least one segment exists
+			if indsel==0
+				disp('at least 2 points are required');
+				return,
+			end
+
+			if ((closed(profsel) & length(A(profsel).x)<3) | (~closed(profsel) & length(A(profsel).x)<2))
+				disp('at least 2 points are required, make another selection');
+			else
+				%cut A
+				if closed(profsel)
+					%open the contour
+					A(profsel).x=[A(profsel).x(indsel+1:end-1,1);A(profsel).x(1:indsel,1)];
+					A(profsel).y=[A(profsel).y(indsel+1:end-1,1);A(profsel).y(1:indsel,1)];
+					numpoints=numpoints-1;
+					closed(profsel)=0;
+				else
+					%cut the contour in 2 profiles
+					A(end+1).x=A(profsel).x(indsel+1:end,1);
+					A(end).y=A(profsel).y(indsel+1:end,1);
+					A(end).name=root; 
+					A(end).density=1; 
+					A(profsel).x=A(profsel).x(1:indsel,1);
+					A(profsel).y=A(profsel).y(1:indsel,1);
+					numprofiles=numprofiles+1;
+					closed(end+1)=0;
+				end
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+			end
+		else
+			%RETURN->exit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/mergeprofiles.m
===================================================================
--- /issm/trunk/src/m/exp/operation/mergeprofiles.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/mergeprofiles.m	(revision 16137)
@@ -0,0 +1,152 @@
+function [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options)
+%MERGEPROFILES - merge profiles
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile. The user must select the two tips that
+%   he/she wants to merge
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+hold on
+loop=1;
+
+%Take all the tips coordinates of open profiles
+counter=1; tips=[];
+for i=1:numprofiles
+	if ~closed(i),
+		%x and y coord, profile number, 1 if beginning, 2 and if end
+		if length(A(i).x)==1,
+			tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+			counter=counter+1;
+		else
+			tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+			tips(counter+1,:) = [A(i).x(end) A(i).y(end) i  2];
+			counter=counter+2;
+		end
+	end
+end
+
+if size(tips,1)<2
+	disp('at least one unclosed profile is required')
+	return
+end
+
+%plot the tips only
+plot(tips(:,1),tips(:,2),...
+	'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+firsttip=1;
+
+%loop (at least 2 clicks needed)
+while loop
+
+	%some checks
+	if size(tips,1)<2
+		disp('at least one unclosed profiles are required')
+		return
+	end
+
+	%select a point
+	if firsttip
+		title('click on the first tip, RETURN to exit','FontSize',14)
+	else
+		title('click on the second tip, RETURN to exit','FontSize',14)
+	end
+
+	[xi,yi] = ginput(1);
+
+	if ~isempty(xi)
+
+		if firsttip
+			%find the selected tip
+			distance=(xi-tips(:,1)).^2+(yi-tips(:,2)).^2;
+			[dmin tip1]=min(distance);
+			numprofile1=tips(tip1,3);
+			firsttip=0;
+
+			%remove tip1 from tips list
+			newtips=tips;
+			newtips(tip1,:)=[];
+
+			%plot selected tip
+			plot(tips(tip1,1),tips(tip1,2),...
+				'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			plot(A(numprofile1).x,A(numprofile1).y,...
+				'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+
+		%second selection
+		else
+			distance=(xi-newtips(:,1)).^2+(yi-newtips(:,2)).^2;
+			[dmin tip2]=min(distance);
+			numprofile2=newtips(tip2,3);
+
+			if numprofile1==numprofile2
+				%close the profile
+				A(numprofile1).x(end+1)=A(numprofile1).x(1);
+				A(numprofile1).y(end+1)=A(numprofile1).y(1);
+				numpoints=numpoints+1;
+				closed(numprofile1)=1;
+
+			else
+
+				if tips(tip1,4)==1 & newtips(tip2,4)==1,
+					A(numprofile1).x=[flipud(A(numprofile2).x); A(numprofile1).x];
+					A(numprofile1).y=[flipud(A(numprofile2).y); A(numprofile1).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==1 & newtips(tip2,4)==2,
+					A(numprofile1).x=[A(numprofile2).x; A(numprofile1).x];
+					A(numprofile1).y=[A(numprofile2).y; A(numprofile1).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==2 & newtips(tip2,4)==1,
+					A(numprofile1).x=[A(numprofile1).x; A(numprofile2).x];
+					A(numprofile1).y=[A(numprofile1).y; A(numprofile2).y];
+					numprofiles=numprofiles-1;
+
+				elseif tips(tip1,4)==2 & newtips(tip2,4)==2,
+					A(numprofile1).x=[A(numprofile1).x; flipud(A(numprofile2).x)];
+					A(numprofile1).y=[A(numprofile1).y; flipud(A(numprofile2).y)];
+					numprofiles=numprofiles-1;
+				end
+
+				%delete profile2
+				A(numprofile2)=[];
+				closed(numprofile2)=[];
+
+			end
+
+			%update tips
+			counter=1; tips=[];
+			for i=1:numprofiles
+				if ~closed(i),
+					%x and y coord, profile number, 1 if beginning, 2 and if end
+					if length(A(i).x)==1,
+						tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+						counter=counter+1;
+					else
+						tips(counter,:)=[A(i).x(1)   A(i).y(1)   i  1];
+						tips(counter+1,:) = [A(i).x(end) A(i).y(end) i  2];
+						counter=counter+2;
+					end
+				end
+			end
+
+			%plot new profile
+			undoplots(prevplot);
+			for i=1:numprofiles
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+			if ~isempty(tips)
+				plot(tips(:,1),tips(:,2),...
+					'LineStyle','none','MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+			end
+
+			%back to beginning
+			firsttip=1;
+		end
+	else
+		%RETRUN-> quit
+		loop=0;
+	end
+end
Index: /issm/trunk/src/m/exp/operation/modifyposition.m
===================================================================
--- /issm/trunk/src/m/exp/operation/modifyposition.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/modifyposition.m	(revision 16137)
@@ -0,0 +1,77 @@
+function [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options)
+%MODIFYPOSITION - modify the prosition of a point of a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting..')
+		return
+	end
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	while loop
+
+		%select a point to be modified 
+		title('click on the point to be modified, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest point
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			%plot the point in blue
+			plot(A(profsel).x(indsel),A(profsel).y(indsel),...
+				'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+				'MarkerEdgeColor',getfieldvalue(options,'selectioncolor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+			%select new location
+			title('click on the new location, RETURN to exit','FontSize',14)
+			[xi,yi] = ginput(1);
+
+			if ~isempty(xi)
+
+				%modification of its coordinates
+				A(profsel).x(indsel)=xi;
+				A(profsel).y(indsel)=yi;
+
+				%modify the last point if the profile is closed and indsel=end or 1
+				if closed(profsel)
+					if indsel==1 
+						A(profsel).x(end)=xi;
+						A(profsel).y(end)=yi;
+					elseif indsel==length(A(profsel).x)
+						A(profsel).x(1)=xi;
+						A(profsel).y(1)=yi;
+					end
+				end
+
+				%plot new profile
+				undoplots(prevplot);
+				for i=1:numprofiles
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				end
+			else
+				%RETURN-> exit
+				loop=0;
+			end
+		else
+			%RETURN-> exit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/orientprofile.m
===================================================================
--- /issm/trunk/src/m/exp/operation/orientprofile.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/orientprofile.m	(revision 16137)
@@ -0,0 +1,54 @@
+function [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%ORIENTPROFILE - cahnge profile orientation
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click on the profiles to be reoriented, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile to be reoriented, exiting...')
+			return
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it from list
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			else
+				%add the profile to the list to be removed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%reorient profiles
+			selection=sort(selection);
+			for i=1:length(selection),
+				A(selection(i)).x=flipud(A(selection(i)).x);
+				A(selection(i)).y=flipud(A(selection(i)).y);
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/removepoints.m
===================================================================
--- /issm/trunk/src/m/exp/operation/removepoints.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/removepoints.m	(revision 16137)
@@ -0,0 +1,85 @@
+function [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+%REMOVEPOINTS - remove a point from a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end
+
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+
+	end
+
+	while loop
+
+		%check that at least one point is present
+		if numpoints==0
+			disp('at least one point are needed')
+			return
+		end	   
+
+		%select a point to be deleted
+		title('click on the point to be removed, RETURN to exit','FontSize',14)
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get the closest point
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			%remove point of A
+			A(profsel).x(indsel)=[];
+			A(profsel).y(indsel)=[];
+
+			%unclose the domain if only 2 points remaining
+			if closed(profsel)
+				if length(A(profsel).x)==3
+					A(profsel).x(end)=[];
+					A(profsel).y(end)=[];
+					numpoints=numpoints-1;
+					closed(profsel)=0;
+				end
+			end
+
+			%remove the last point if the profile is closed and indsel=end or 1
+			if closed(profsel)
+				if indsel==1 
+					A(profsel).x(end)=A(profsel).x(1);
+					A(profsel).y(end)=A(profsel).y(1);
+				elseif indsel==length(A(profsel).x)
+					A(profsel).x(1)=A(profsel).x(end);
+					A(profsel).y(1)=A(profsel).y(end);
+				end
+			end
+			numpoints=numpoints-1;
+
+			%plot new profile
+			undoplots(prevplot);
+			for i=1:numprofiles
+				plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+					'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+				if length(A(i).x)==1
+					plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+						'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker','o');
+				end
+			end
+
+		else
+			%RETURN-> exit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/removeprofile.m
===================================================================
--- /issm/trunk/src/m/exp/operation/removeprofile.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/removeprofile.m	(revision 16137)
@@ -0,0 +1,56 @@
+function [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+%REMOVEPROFILE - delete a profile
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	title('click on the profiles to be removed, RETURN to exit','FontSize',14)
+	hold on
+
+	loop=1;
+	selection=[];
+
+	while loop
+
+		%some checks
+		if numprofiles==0
+			disp('no profile to be removed, exiting...')
+			return
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+
+			%get closest profile
+			[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+
+			if ismember(profsel,selection)
+				%profile was in selection, remove it
+				selection(find(selection==profsel))=[];
+				%back to regular color
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			else
+				%add the profile to the list to be removed
+				selection(end+1)=profsel;
+				%in selectioncolor
+				plot(A(profsel).x,A(profsel).y,...
+					'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+			end
+		else
+			%remove the profiles
+			selection=sort(selection);
+			for i=1:length(selection),
+				numprofiles=numprofiles-1;
+				numpoints=numpoints-length(A(selection(i)-(i-1)).x);
+				A(selection(i)-(i-1))=[];
+				closed(selection(i)-(i-1))=[];
+			end
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/removeseveralpoints.m
===================================================================
--- /issm/trunk/src/m/exp/operation/removeseveralpoints.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/removeseveralpoints.m	(revision 16137)
@@ -0,0 +1,130 @@
+function [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+%REMOVESEVERALPOINTS - remove several point
+%
+%   this script is used by exptool as an elementary operation
+%   on an ARGUS profile
+%
+%   Usage:
+%      [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options)
+
+	%some checks
+	if numprofiles==0
+		disp('no profile present, exiting...')
+		return
+	end	   
+	if numpoints<3
+		disp('at least 3 points are required, exiting...')
+		return
+	end	   
+	hold on
+	loop=1;
+
+	%plot squares
+	for i=1:numprofiles
+		plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+			'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+	end
+
+	points=[];
+
+	%loop (at least 3 clicks needed)
+	while loop
+
+		%some checks
+		if numpoints<3
+			disp('at least 3 points are required, exiting...')
+			return
+		end
+
+		%select a point
+		if isempty(points)
+			title('click on the first tip, RETURN to exit','FontSize',14)
+		elseif length(points)==1
+			title('click on the second tip, RETURN to exit','FontSize',14)
+		else
+			title('click in the middle of the area to be removed, RETURN to exit','FontSize',14)
+		end
+
+		[xi,yi] = ginput(1);
+
+		if ~isempty(xi)
+			%get the closest point
+			%first time, look at all profiles
+			if isempty(points)
+				[profsel indsel]=closestpoint(A,numprofiles,xi,yi);
+				if ((closed(profsel) & length(A(profsel).x)<4) |  (~closed(profsel) & length(A(profsel).x)<3)),
+					disp('the selected profile has less than 3 points, make another selection');
+				else
+					selection=profsel;
+					points(end+1)=indsel;
+					plot(A(profsel).x,A(profsel).y,...
+						'color',getfieldvalue(options,'selectioncolor'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'));
+					text(A(selection).x(indsel),A(selection).y(indsel),num2str(1),'FontSize',14,'background',[0.7 0.7 0.9]);
+				end
+				%disp(['p1= ' num2str(indsel)]),
+			else
+				%get the 2d or 3d point for the given contou
+				[profsel indsel]=closestpoint(A(selection),1,xi,yi);
+				if ismember(indsel,points)
+					disp('the selected points must be distinct')
+				else
+					%second click?
+					if length(points)==1,
+						points(end+1)=indsel;
+						text(A(selection).x(indsel),A(selection).y(indsel),num2str(2),'FontSize',14,'background',[0.7 0.7 0.9]);
+						%disp(['p2= ' num2str(indsel)]),
+					%third click?
+					else
+						p1=points(1); p2=points(2); p3=indsel;
+						%disp(['p3= ' num2str(indsel)]),
+						if p1<p2
+							if p3>p1 & p3<p2
+								A(selection).x(p1+1:p2-1)=[];
+								A(selection).y(p1+1:p2-1)=[];
+								numpoints=numpoints-(p2-p1-1);
+							else
+								A(selection).x=A(selection).x(p1:p2);
+								A(selection).y=A(selection).y(p1:p2);
+								numpoints=numpoints-(numpoints-1-p2)-(p1-1);
+								if closed(selection)
+									%reattach the tips
+									A(selection).x(end+1)=A(selection).x(1);
+									A(selection).y(end+1)=A(selection).y(1);
+									numpoints=numpoints+1;
+								end
+							end
+						else
+							if p3>p2 & p3<p1
+								A(selection).x(p2+1:p1-1)=[];
+								A(selection).y(p2+1:p1-1)=[];
+								numpoints=numpoints-(p1-p2-1);
+							else
+								A(selection).x=A(selection).x(p2:p1);
+								A(selection).y=A(selection).y(p2:p1);
+								numpoints=numpoints-(numpoints-1-p1)-(p2-1);
+								if closed(selection)
+									%reattach the tips
+									A(selection).x(end+1)=A(selection).x(1);
+									A(selection).y(end+1)=A(selection).y(1);
+									numpoints=numpoints+1;
+								end
+							end
+						end
+
+						%plot new profiles
+						undoplots(prevplot);
+						for i=1:numprofiles
+							plot(A(i).x,A(i).y,'color',getfieldvalue(options,'color'),'LineStyle',getfieldvalue(options,'LineStyle'),'LineWidth',getfieldvalue(options,'LineWidth'),...
+								'MarkerEdgeColor',getfieldvalue(options,'MarkerEdgeColor'),'MarkerSize',getfieldvalue(options,'MarkerSize'),'Marker',getfieldvalue(options,'Marker'));
+						end
+						points=[];
+
+					end
+				end
+			end
+		else
+			%RETRUN-> quit
+			loop=0;
+		end
+	end
+end
Index: /issm/trunk/src/m/exp/operation/undoplots.m
===================================================================
--- /issm/trunk/src/m/exp/operation/undoplots.m	(revision 16137)
+++ /issm/trunk/src/m/exp/operation/undoplots.m	(revision 16137)
@@ -0,0 +1,12 @@
+function  undoplots(prevplot)
+%UNDOPLOTS - undo plots
+%
+%   Usage:undoplots(prevplot)
+
+	%erase all previous plots
+	g=get(gca,'children');
+	L=length(g);
+	for i=1:L-prevplot
+		delete(g(i));
+	end
+end
Index: /issm/trunk/src/m/geometry/FlagElements.m
===================================================================
--- /issm/trunk/src/m/geometry/FlagElements.m	(revision 16136)
+++ /issm/trunk/src/m/geometry/FlagElements.m	(revision 16137)
@@ -2,5 +2,5 @@
 %FLAGELEMENTS - flag the elements in an region
 %
-%   The region can be given with an exp file, a list of elements.
+%   The region can be given with an exp file, a list of elements or vertices
 %
 %   Usage: 
@@ -12,5 +12,4 @@
 %      flag=FlagElements(md,'Domain.exp');
 %      flag=FlagElements(md,'~Domain.exp');
-%      flag=FlagElements(md,md.mask.elementongroundedice);
 
 	if ischar(region),
@@ -47,9 +46,12 @@
 		end
 	elseif isfloat(region) | islogical(region),
-		if size(region,1)~=md.mesh.numberofelements,
+		if size(region,1)==md.mesh.numberofelements,
+			flag=region;
+		elseif size(region,1)==md.mesh.numberofvertices,
+			flag=logical(sum(region(md.mesh.elements)>0,2)==size(md.mesh.elements,2));
+		else
 			help FlagElements
 			error('Flaglist for region must be of same size as number of elements in model');
 		end
-		flag=region;
 	else
 		error('Invalid region option');
Index: /issm/trunk/src/m/geometry/FlagElements.py
===================================================================
--- /issm/trunk/src/m/geometry/FlagElements.py	(revision 16136)
+++ /issm/trunk/src/m/geometry/FlagElements.py	(revision 16137)
@@ -10,5 +10,5 @@
 	FLAGELEMENTS - flag the elements in an region
 
-	   The region can be given with an exp file, a list of elements.
+	   The region can be given with an exp file, a list of elements or vertices
 
 	   Usage: 
@@ -20,5 +20,4 @@
 	      flag=FlagElements(md,'Domain.exp');
 	      flag=FlagElements(md,'~Domain.exp');
-	      flag=FlagElements(md,md.mask.elementongroundedice);
 	"""
 
@@ -55,7 +54,10 @@
 
 	elif isinstance(region,numpy.ndarray) or isinstance(region,bool):
-		if not numpy.size(region,0)==md.mesh.numberofelements:
+		if numpy.size(region,0)==md.mesh.numberofelements:
+			flag=region
+		elif numpy.size(region,0)==md.mesh.numberofvertices:
+			flag=(numpy.sum(region[md.mesh.elements-1]>0,axis=1)==numpy.size(md.mesh.elements,1))
+		else:
 			raise TypeError("Flaglist for region must be of same size as number of elements in model.")
-		flag=region
 
 	else:
Index: /issm/trunk/src/m/geometry/ThicknessCorrection.m
===================================================================
--- /issm/trunk/src/m/geometry/ThicknessCorrection.m	(revision 16136)
+++ /issm/trunk/src/m/geometry/ThicknessCorrection.m	(revision 16137)
@@ -23,5 +23,5 @@
 
 %get nodes on ice sheet and on ice shelf
-pos_shelf=find(~md.mask.vertexongroundedice);
+pos_shelf=find(md.mask.groundedice_levelset<0.);
 pos_GL=intersect(unique(md.mesh.elements(find(md.mask.elementongroundedice),:)),unique(md.mesh.elements(find(md.mask.elementonfloatingice),:)));
 debug=(length(pos_shelf)>50000);
Index: /issm/trunk/src/m/geometry/slope.py
===================================================================
--- /issm/trunk/src/m/geometry/slope.py	(revision 16137)
+++ /issm/trunk/src/m/geometry/slope.py	(revision 16137)
@@ -0,0 +1,46 @@
+import numpy as npy
+from GetNodalFunctionsCoeff import  GetNodalFunctionsCoeff
+
+def slope(md,*args):
+	"""
+	SLOPE - compute the surface slope
+
+	Usage:
+		sx,sy,s=slope(md)
+		sx,sy,s=slope(md,md.results.TransientSolution(1).Surface)
+	"""
+
+	#load some variables (it is much faster if the variables are loaded from md once for all) 
+	if md.mesh.dimension==2:
+		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
+
+	if len(args)==0:
+		surf=md.geometry.surface
+	elif len(args)==1:
+		surf=args[0]
+	else:
+		raise RuntimeError("slope.py usage error")
+
+	#%compute nodal functions coefficients N(x,y)=alpha x + beta y + gamma
+	alpha,beta=GetNodalFunctionsCoeff(index,x,y)[0:2]
+
+	summation=npy.array([[1],[1],[1]])
+	sx=npy.dot(surf[index-1]*alpha,summation).reshape(-1,)
+	sy=npy.dot(surf[index-1]*beta,summation).reshape(-1,)
+
+	s=npy.sqrt(sx**2+sy**2)
+
+	if md.mesh.dimension==3:
+		sx=project3d(md,'vector',sx,'type','element')
+		sy=project3d(md,'vector',sy,'type','element')
+		s=npy.sqrt(sx**2+sy**2)
+
+	return (sx,sy,s)
Index: /issm/trunk/src/m/interp/InterpFromFile.m
===================================================================
--- /issm/trunk/src/m/interp/InterpFromFile.m	(revision 16136)
+++ /issm/trunk/src/m/interp/InterpFromFile.m	(revision 16137)
@@ -38,7 +38,10 @@
 Names=FieldFindVarNames(filename);
 Data=load(filename);
+disp('WARNING: function deprecated, replace InterpFromFile by the following command:');
 if strcmpi(Names.interp,'node'),
+	disp(['   data=InterpFromGridToMesh(' Names.xname ',' Names.yname ',' Names.dataname ',x,y,default_value);']);
 	data_out=InterpFromGridToMesh(Data.(Names.xname),Data.(Names.yname),Data.(Names.dataname),x,y,default_value);
 else
+	disp(['   data=InterpFromMeshToMesh2d(' Names.indexname ',' Names.xname ',' Names.yname ',' Names.dataname ',x,y);']);
 	data_out=InterpFromMeshToMesh2d(Data.(Names.indexname),Data.(Names.xname),Data.(Names.yname),Data.(Names.dataname),x,y);
 end
Index: /issm/trunk/src/m/interp/averaging.m
===================================================================
--- /issm/trunk/src/m/interp/averaging.m	(revision 16136)
+++ /issm/trunk/src/m/interp/averaging.m	(revision 16137)
@@ -20,5 +20,5 @@
 
 if ((nargin~=4) & (nargin~=3)),
-	error('averaging error message');
+	error('averaging error message: wrong number of arguments');
 end
 if (length(data)~=md.mesh.numberofelements & length(data)~=md.mesh.numberofvertices),
Index: /issm/trunk/src/m/interp/averaging.py
===================================================================
--- /issm/trunk/src/m/interp/averaging.py	(revision 16137)
+++ /issm/trunk/src/m/interp/averaging.py	(revision 16137)
@@ -0,0 +1,89 @@
+import numpy as npy
+from GetAreas import GetAreas
+from scipy.sparse import csc_matrix
+
+def averaging(md,data,iterations,layer=0):
+	'''
+	AVERAGING - smooths the input over the mesh
+	
+	   This routine takes a list over the elements or the nodes in input
+	   and return a list over the nodes.
+	   For each iterations it computes the average over each element (average 
+	   of the vertices values) and then computes the average over each node
+	   by taking the average of the element around a node weighted by the
+	   elements volume
+	   For 3d mesh, a last argument can be added to specify the layer to be averaged on.
+	
+	   Usage:
+	      smoothdata=averaging(md,data,iterations)
+	      smoothdata=averaging(md,data,iterations,layer)
+	
+	   Examples:
+	      velsmoothed=averaging(md,md.initialization.vel,4)
+	      pressure=averaging(md,md.initialization.pressure,0)
+	      temperature=averaging(md,md.initialization.temperature,1,1)
+	'''
+
+	if (len(data)!=md.mesh.numberofelements & len(data)!=md.mesh.numberofvertices):
+		raise StandardError('averaging error message: data not supported yet')
+	if md.mesh.dimension==3 and layer!=0:
+		if layer<=0 or layer>md.mesh.numberoflayers:
+			raise ValueError('layer should be between 1 and md.mesh.numberoflayers')
+	else:
+		layer=0
+	
+	#initialization
+	if layer==0:
+		weights=npy.zeros(md.mesh.numberofvertices,)
+		data=data.flatten(1)
+	else:
+		weights=npy.zeros(md.mesh.numberofvertices2d,)
+		data=data[(layer-1)*md.mesh.numberofvertices2d+1:layer*md.mesh.numberofvertices2d,:]
+	
+	#load some variables (it is much faster if the variabes are loaded from md once for all)
+	if layer==0:
+		index=md.mesh.elements
+		numberofnodes=md.mesh.numberofvertices
+		numberofelements=md.mesh.numberofelements
+	else:
+		index=md.mesh.elements2d
+		numberofnodes=md.mesh.numberofvertices2d
+		numberofelements=md.mesh.numberofelements2d
+	
+	#build some variables
+	if md.mesh.dimension==3 and layer==0:
+		rep=6
+		areas=GetAreas(index,md.mesh.x,md.mesh.y,md.mesh.z)
+	elif md.mesh.dimension==2:
+		rep=3
+		areas=GetAreas(index,md.mesh.x,md.mesh.y)
+	else:
+		rep=3
+		areas=GetAreas(index,md.mesh.x2d,md.mesh.y2d)
+
+	index=index-1 # since python indexes starting from zero
+	line=index.flatten(1)
+	areas=npy.vstack(areas).reshape(-1,)
+	summation=1./rep*npy.ones(rep,)
+	linesize=rep*numberofelements
+	
+	#update weights that holds the volume of all the element holding the node i
+	weights=csc_matrix( (npy.tile(areas,(rep,1)).reshape(-1,),(line,npy.zeros(linesize,))), shape=(numberofnodes,1))
+	
+	#initialization
+	if len(data)==numberofelements:
+		average_node=csc_matrix( (npy.tile(areas*data,(rep,1)).reshape(-1,),(line,npy.zeros(linesize,))), shape=(numberofnodes,1))
+		average_node=average_node/weights
+	else:
+		average_node=data
+	
+	#loop over iteration
+	for i in npy.arange(1,iterations+1):
+		average_el=npy.asarray(npy.dot(average_node.todense()[index].reshape(numberofelements,rep),npy.vstack(summation))).reshape(-1,)
+		average_node=csc_matrix( (npy.tile(areas*average_el.reshape(-1),(rep,1)).reshape(-1,),(line,npy.zeros(linesize,))), shape=(numberofnodes,1))
+		average_node=average_node/weights
+	
+	#return output as a full matrix (C code do not like sparse matrices)
+	average=npy.asarray(average_node.todense()).reshape(-1,)
+
+	return average
Index: /issm/trunk/src/m/inversions/MisfitDeinterlace.m
===================================================================
--- /issm/trunk/src/m/inversions/MisfitDeinterlace.m	(revision 16136)
+++ /issm/trunk/src/m/inversions/MisfitDeinterlace.m	(revision 16137)
@@ -6,5 +6,5 @@
 %
 %   Example:
-%      Jstruct=MisfitDeinterlace(md.results.diagnostic.J,md.fit)
+%      Jstruct=MisfitDeinterlace(md.results.stressbalance.J,md.fit)
 %
 %
Index: /issm/trunk/src/m/inversions/misfit.m
===================================================================
--- /issm/trunk/src/m/inversions/misfit.m	(revision 16136)
+++ /issm/trunk/src/m/inversions/misfit.m	(revision 16137)
@@ -13,6 +13,8 @@
 	x=md.mesh.x;
 	y=md.mesh.y;
-	vx=md.initialization.vx;
-	vy=md.initialization.vy;
+	%vx=md.initialization.vx;
+	%vy=md.initialization.vy;
+	vx=md.results.StressbalanceSolution.Vx;
+	vy=md.results.StressbalanceSolution.Vy;
 	vx_obs=md.inversion.vx_obs;
 	vy_obs=md.inversion.vy_obs;
Index: /issm/trunk/src/m/inversions/parametercontroldrag.py
===================================================================
--- /issm/trunk/src/m/inversions/parametercontroldrag.py	(revision 16137)
+++ /issm/trunk/src/m/inversions/parametercontroldrag.py	(revision 16137)
@@ -0,0 +1,118 @@
+def parametercontroldrag(md,*args):
+	"""
+	PARAMETERCONTROLDRAG - parameterization for control method on drag
+
+	It is possible to specify the number of steps, values for the
+	minimum and maximum values of the drag, the 
+	kind of cm_responses to use or the the optscal.
+
+	Usage:
+	   md=parametercontroldrag(md,varargin)
+
+	Example:
+	  md=parametercontroldrag(md)
+	  md=parametercontroldrag(md,'nsteps',20,'cm_responses',0)
+	  md=parametercontroldrag(md,'cm_min',1,'cm_max',150,'cm_jump',0.99,'maxiter',20)
+	  md=parametercontroldrag(md,eps_cm',10^-4,'optscal',[10^7 10^8])
+
+	See also PARAMETERCONTROLB
+	"""
+
+	#process options
+	options=pairoptions(*args)
+
+	#control type
+	md.inversion.control_parameters='FrictionCoefficient'
+
+	#weights
+	weights=options.getfieldvalue('weights',npy.ones(md.mesh.numberofvertices))
+	if npy.size(weights)!=md.mesh.numberofvertices:
+		md.inversion.cost_functions_coefficients=ones(md.mesh.numberofvertices)
+	else:
+		md.inversion.cost_functions_coefficients=weights
+
+	#nsteps
+	nsteps=options.getfieldvalue('nsteps',100);
+	if (npy.size(nsteps)!=1) | (nsteps<=0) | (floor(nsteps)!=nsteps):
+		md.inversion.nsteps=100
+	else:
+		md.inversion.nsteps=nsteps
+
+	#cm_min
+	cm_min=options.getfieldvalue('cm_min',ones(md.mesh.numberofvertices))
+	if (npy.size(cm_min)==1):
+		md.inversion.min_parameters=cm_min*ones(md.mesh.numberofvertices)
+	elif (npy.size(cm_min)==md.mesh.numberofvertices):
+		md.inversion.min_parameters=cm_min
+	else:
+		md.inversion.min_parameters=cm_min;
+
+	#cm_max
+	cm_max=options.getfieldvalue('cm_max',250*ones(md.mesh.numberofvertices))
+	if (npy.size(cm_max)==1):
+		md.inversion.max_parameters=cm_max*ones(md.mesh.numberofvertices)
+	elif (npy.size(cm_max)==md.mesh.numberofvertices):
+		md.inversion.max_parameters=cm_max
+	else:
+		md.inversion.max_parameters=cm_max
+
+	#eps_cm
+	eps_cm=optoins.getfieldvalue('eps_cm',float('nan'))
+	if (npy.size(eps_cm)~=1 | eps_cm<0 ):
+		md.inversion.cost_function_threshold=float('nan')
+	else:
+		md.inversion.cost_function_threshold=eps_cm
+
+	#maxiter
+	maxiter=options.getfieldvalue('maxiter',10*ones(md.inversion.nsteps))
+	if (npy.any(maxiter<0) | npy.any(floor(maxiter)~=maxiter)):
+		md.inversion.maxiter_per_step=10*ones(md.inversion.nsteps)
+	else:
+		raise RuntimeError("not implemented yet, see below matlab lines")
+		#md.inversion.maxiter_per_step=repmat(maxiter(:),md.inversion.nsteps,1);
+		#md.inversion.maxiter_per_step(md.inversion.nsteps+1:end)=[];
+
+	#cm_jump
+	cm_jump=options.getfieldvalue('cm_jump',0.8*ones(md.inversion.nsteps))
+	if !npy.isreal(cm_jump):
+		md.inversion.step_threshold=0.8*ones(md.inversion.nsteps)
+	else:
+		raise RuntimeError("not implemented yet, see below matlab lines")
+		#md.inversion.step_threshold=repmat(cm_jump(:),md.inversion.nsteps,1);
+		#md.inversion.step_threshold(md.inversion.nsteps+1:end)=[];
+
+	#cm_responses
+	found=0;
+	if options.exist('cm_responses'):
+		cm_responses=options.getfieldvalue('cm_responses')
+		if ~any(~ismember(cm_responses,[101 105])):
+			md.inversion.cost_functions=repmat(cm_responses(:),md.inversion.nsteps,1);
+			md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+			found=1;
+	if ~found
+		third=ceil(md.inversion.nsteps/3);
+		md.inversion.cost_functions=[...
+			103*ones(third,1);...
+			101*ones(third,1);...
+			repmat([101;101;103;101],third,1)...
+			];
+		md.inversion.cost_functions(md.inversion.nsteps+1:end)=[];
+	end
+
+	%optscal
+	found=0;
+	if exist(options,'optscal'),
+		optscal=getfieldvalue(options,'optscal');
+		if ~any(optscal<0),
+			md.inversion.gradient_scaling=repmat(optscal(:),md.inversion.nsteps,1);
+			md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+			found=1;
+		end
+	end
+	if ~found
+		third=ceil(md.inversion.nsteps/3);
+		md.inversion.gradient_scaling=[50*ones(3,1);15*ones(third-3,1);10*ones(third,1);repmat([10;10;20;10],third,1)];
+		md.inversion.gradient_scaling(md.inversion.nsteps+1:end)=[];
+	end
+
+	return md
Index: /issm/trunk/src/m/io/loadmodel.py
===================================================================
--- /issm/trunk/src/m/io/loadmodel.py	(revision 16136)
+++ /issm/trunk/src/m/io/loadmodel.py	(revision 16137)
@@ -1,4 +1,5 @@
 import os.path
 from loadvars import *
+from whichdb import whichdb
 
 def loadmodel(path):
@@ -12,6 +13,6 @@
 	"""
 
-	#check existence
-	if os.path.exists(path):
+	#check existence of database (independent of file extension!)
+	if whichdb(path):
 		#do nothing
 		pass
Index: /issm/trunk/src/m/io/loadvars.py
===================================================================
--- /issm/trunk/src/m/io/loadvars.py	(revision 16136)
+++ /issm/trunk/src/m/io/loadvars.py	(revision 16137)
@@ -1,4 +1,5 @@
 import shelve
 import os.path
+from whichdb import whichdb
 
 def loadvars(*args):
@@ -48,5 +49,5 @@
 		raise TypeError("Unrecognized input arguments.")
 
-	if os.path.exists(filename):
+	if whichdb(filename):
 		print "Loading variables from file '%s'." % filename
 	else:
Index: /issm/trunk/src/m/materials/paterson.py
===================================================================
--- /issm/trunk/src/m/materials/paterson.py	(revision 16136)
+++ /issm/trunk/src/m/materials/paterson.py	(revision 16137)
@@ -15,5 +15,5 @@
 		raise RuntimeError("input temperature should be in Kelvin (positive)")
 	
-	T = temperature-273.15
+	T = temperature.reshape(-1,)-273.15
 
 	#The routine below is equivalent to:
@@ -30,5 +30,5 @@
 	# rigidity=fittedmodel(temperature);
 
-	rigidity=numpy.zeros((numpy.size(T,axis=0),1))
+	rigidity=numpy.zeros_like(T)
 	pos1=numpy.nonzero(T<=-45)
 	rigidity[pos1]=10**8*(-0.000292866376675*(T[pos1]+50)**3+ 0.011672640664130*(T[pos1]+50)**2  -0.325004442485481*(T[pos1]+50)+  6.524779401948101)
Index: /issm/trunk/src/m/mech/analyticaldamage.m
===================================================================
--- /issm/trunk/src/m/mech/analyticaldamage.m	(revision 16137)
+++ /issm/trunk/src/m/mech/analyticaldamage.m	(revision 16137)
@@ -0,0 +1,159 @@
+function [damage,B,backstress]=analyticaldamage(md,varargin)
+%ANALYTICALDAMAGE - compute damage for an ice shelf 
+%
+%	 This routine computes damage as a function of water/ice
+%	 material properties, ice thickness, strain rate, and ice 
+%	 rigidity.  The model must contain computed strain rates,
+%	 either from observed or modeled ice velocities.
+%
+%   Available options:
+%		- 'eq'			: analytical equation to use in the calculation.  Must be one of:
+%								'Weertman1D' for a confined ice shelf free to flow in one direction
+%								'Weertman2D' for an unconfined ice shelf free to spread in any direction
+%								'Thomas' for a 2D ice shelf, taking into account full strain rate tensor (default)
+%		- 'smoothing'	: the amount of smoothing to be applied to the strain rate data.
+%								Type 'help averaging' for more information on its usage.
+%		- 'sigmab'		: a compressive backstress term to be subtracted from the driving stress 
+%								in the damage calculation
+%
+%   Return values:
+%		'damage' which is truncated in the range [0,1-1e-9]
+%
+%	   'B' is the rigidity, which is equal to md.materials.rheology_B in areas outside
+%		those defined by 'mask.'  Within areas defined by 'mask,' where negative damage 
+%		is inferred, 'B' is updated to make damage equal to zero.  
+%
+%		'backstress' is the inferred backstress necessary to balance the analytical solution
+%		(keeping damage within its appropriate limits, e.g. D in [0,1]).
+%
+%   Usage:
+%      [damage,B,backstress]=analyticaldamage(md,options)
+%
+%   Example:
+%      [damage,B,backstress]=analyticaldamage(md,'eq','Weertman2D','smoothing',2,'backstress',10e3);
+
+% check inputs
+if (nargin<1),
+	help analyticaldamage
+	error('bad usage');
+end
+if isempty(fieldnames(md.results)),
+	error(['md.results.strainrate is not present.  Calculate using md=mechanicalproperties(md,vx,vy)']);
+end
+if ~(md.mesh.dimension==2),
+	error('only 2d model supported currently');
+end
+if any(md.flowequation.element_equation~=2),
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA elements');
+end
+
+% process options
+options = pairoptions(varargin{:});
+eq = getfieldvalue(options,'eq','Thomas');
+smoothing = getfieldvalue(options,'smoothing',0);
+sigmab = getfieldvalue(options,'sigmab',0);
+if length(sigmab)==1,
+	sigmab=sigmab*ones(md.mesh.numberofelements,1);
+end
+
+% average element strain rates onto vertices
+e1=averaging(md,md.results.strainrate.principalvalue1,smoothing)/md.constants.yts; % convert to s^-1
+e2=averaging(md,md.results.strainrate.principalvalue2,smoothing)/md.constants.yts;
+exx=averaging(md,md.results.strainrate.xx,smoothing)/md.constants.yts;
+eyy=averaging(md,md.results.strainrate.yy,smoothing)/md.constants.yts;
+exy=averaging(md,md.results.strainrate.xy,smoothing)/md.constants.yts;
+
+% checks: any of e1 or e2 equal to zero?
+pos=find(e1==0);
+if any(pos==1)
+	disp('WARNING: first principal strain rate equal to zero.  Value set to 1e-13 s^-1');
+	e1(pos)=1e-13;
+end
+pos=find(e2==0);
+if any(pos==1)
+	disp('WARNING: second principal strain rate equal to zero.  Value set to 1e-13 s^-1');
+	e2(pos)=1e-13;
+end
+
+%% old method using principal strain rates {{{
+%% ex=maximum principal tensile strain rate
+%ex=e1;
+%a=e2./e1;
+%pos=find(e1<0 & e2>0); % longitudinal compression and lateral tension
+%a(pos)=e1(pos)./e2(pos);
+%ex(pos)=e2(pos);
+%pos2=find(e1<0 & e2<0 & abs(e1)<abs(e2)); % lateral and longitudinal compression
+%a(pos2)=e1(pos2)./e2(pos2);
+%ex(pos2)=e2(pos2);
+%pos3=find(e1>0 & e2>0 & abs(e1)<abs(e2)); % lateral and longitudinal tension 
+%a(pos3)=e1(pos3)./e2(pos3);
+%ex(pos3)=e2(pos3);
+%id=find(e1<0 & e2<0);
+%a(id)=-a(id); % where both strain rates are compressive, enforce negative alpha
+%
+%% }}}
+
+% new method using longitudinal strain rates defined by observed velocity vector
+velangle=atan(md.initialization.vy./md.initialization.vx);
+ex=0.5*(exx+eyy)+0.5*(exx-eyy).*cos(2*velangle)+exy.*sin(2*velangle);
+ey=exx+eyy-ex; % trace of strain rate tensor is invariant
+exy=-0.5*(exx-eyy).*sin(2*velangle)+exy.*cos(2*velangle);
+a=ey./ex;
+b=exy./ex;
+pos=find(ex<0 & ey<0);
+%length(pos)
+a(pos)=-a(pos);
+
+% a < -1 in areas of strong lateral compression or longitudinal compression
+% and theta is undefined at a = -2
+pos=find(abs((abs(a)-2))<1e-3);
+a(pos)=-2+1e-3;
+
+% spreading stress
+rhoi=md.materials.rho_ice;
+rhow=md.materials.rho_water;
+C=0.5*rhoi*md.constants.g*(1-rhoi/rhow);
+T=C*md.geometry.thickness;
+
+% rheology
+B=md.materials.rheology_B;
+n=averaging(md,md.materials.rheology_n,0);
+
+switch eq
+	case 'Weertman1D'
+		theta=1./8*ones(md.mesh.numberofvertices,1);
+		a=zeros(md.mesh.numberofvertices,1);
+	case 'Weertman2D'
+		theta=1./9*ones(md.mesh.numberofvertices,1);
+		a=ones(md.mesh.numberofvertices,1);
+	case 'Thomas'
+		theta=((1+a+a.^2+b.^2).^((n-1)/2))./(abs(2+a).^n);
+	otherwise
+		error('argument passed to "eq" not valid.  Type "help analyticaldamage" for usage');
+end
+
+D=1-(1+a+a.^2+b.^2).^((n-1)./(2*n))./abs(ex).^(1./n).*(T-sigmab)./B./(2+a)./sign(ex);
+
+backstress=zeros(md.mesh.numberofvertices,1);
+
+% D>1 where (2+a).*sign(ex)<0, compressive regions where high backstress needed
+pos=find(D>1);
+D(pos)=0;
+
+% backstress to bring damage to zero
+backstress(pos)=T(pos)-(1-D(pos)).*B(pos).*sign(ex(pos)).*(2+a(pos)).*abs(ex(pos)).^(1./n(pos))./(1+a(pos)+a(pos).^2).^((n(pos)-1)/2./n(pos));
+
+pos=find(D<0);
+mask=ismember(1:md.mesh.numberofvertices,pos);
+D(pos)=0;
+
+% backstress to bring negative damage to zero
+backstress(pos)=T(pos)-(1-D(pos)).*B(pos).*sign(ex(pos)).*(2+a(pos)).*abs(ex(pos)).^(1./n(pos))./(1+a(pos)+a(pos).^2).^((n(pos)-1)/2./n(pos));
+
+pos=find(backstress<0);
+backstress(pos)=0;
+
+% increased rigidity to bring negative damage to zero
+B(pos)=sign(ex(pos))./(2+a(pos)).*(1+a(pos)+a(pos).^2).^((n(pos)-1)/2./n(pos)).*T(pos)./abs(ex(pos)).^(1./n(pos));
+
+damage=D;
Index: /issm/trunk/src/m/mech/analyticaldamage.py
===================================================================
--- /issm/trunk/src/m/mech/analyticaldamage.py	(revision 16137)
+++ /issm/trunk/src/m/mech/analyticaldamage.py	(revision 16137)
@@ -0,0 +1,155 @@
+import numpy as npy
+from pairoptions import pairoptions
+from averaging import averaging
+from plotmodel import plotmodel
+
+def analyticaldamage(md,*args):
+	'''
+	ANALYTICALDAMAGE - compute damage for an ice shelf 
+	
+		 This routine computes damage as a function of water/ice
+		 material properties, ice thickness, strain rate, and ice 
+		 rigidity.  The model must contain computed strain rates,
+		 either from observed or modeled ice velocities.
+	
+	   Available options:
+			- 'eq'			: analytical equation to use in the calculation.  Must be one of:
+									'Weertman1D' for a confined ice shelf free to flow in one direction
+									'Weertman2D' for an unconfined ice shelf free to spread in any direction
+									'Thomas' for a 2D ice shelf, taking into account full strain rate tensor (default)
+			- 'smoothing'	: the amount of smoothing to be applied to the strain rate data.
+									Type 'help averaging' for more information on its usage.
+			- 'sigmab'		: a compressive backstress term to be subtracted from the driving stress 
+									in the damage calculation
+	
+	   Return values:
+			'damage' which is truncated in the range [0,1-1e-9]
+	
+		   'B' is the rigidity, which is equal to md.materials.rheology_B in areas outside
+			those defined by 'mask.'  Within areas defined by 'mask,' where negative damage 
+			is inferred, 'B' is updated to make damage equal to zero.  
+	
+			'backstress' is the inferred backstress necessary to balance the analytical solution
+			(keeping damage within its appropriate limits, e.g. D in [0,1]).
+	
+	   Usage:
+	      [damage,B,backstress]=analyticaldamage(md,options)
+	
+	   Example:
+	      [damage,B,backstress]=analyticaldamage(md,'eq','Weertman2D','smoothing',2,'backstress',10e3)
+	'''
+
+	# check inputs
+	if 'strainrate' not in md.results.__dict__:
+		raise StandardError('md.results.strainrate not present.  Calculate using md=mechanicalproperties(md,vx,vy)')
+	if md.mesh.dimension!=2:
+		raise StandardError('only 2D model supported currently')
+	if npy.any(md.flowequation.element_equation!=2):
+		print 'Warning: the model has some non SSA elements. These will be treated like SSA elements'
+
+	# process options
+	options = pairoptions(*args)
+	eq = options.getfieldvalue('eq','Thomas')
+	smoothing = options.getfieldvalue('smoothing',0)
+	sigmab = options.getfieldvalue('sigmab',0)
+	if len(sigmab==1):
+		sigmab=sigmab*npy.ones(md.mesh.numberofvertices,)
+	
+	# average element strain rates onto vertices
+	e1=averaging(md,md.results.strainrate.principalvalue1,smoothing)/md.constants.yts # convert to s^-1
+	e2=averaging(md,md.results.strainrate.principalvalue2,smoothing)/md.constants.yts
+	exx=averaging(md,md.results.strainrate.xx,smoothing)/md.constants.yts
+	eyy=averaging(md,md.results.strainrate.yy,smoothing)/md.constants.yts
+	exy=averaging(md,md.results.strainrate.xy,smoothing)/md.constants.yts
+	
+	# checks: any of e1 or e2 equal to zero?
+	pos=npy.nonzero(e1==0)
+	if npy.any(pos==1):
+		print 'WARNING: first principal strain rate equal to zero.  Value set to 1e-13 s^-1'
+		e1[pos]=1e-13
+	pos=npy.nonzero(e2==0)
+	if npy.any(pos==1):
+		disp('WARNING: second principal strain rate equal to zero.  Value set to 1e-13 s^-1');
+		e2[pos]=1e-13
+	
+	## old method using principal strain rates {{{
+	## ex=maximum principal tensile strain rate
+	#ex=e1;
+	#a=e2./e1;
+	#pos=find(e1<0 & e2>0); # longitudinal compression and lateral tension
+	#a(pos)=e1(pos)./e2(pos);
+	#ex(pos)=e2(pos);
+	#pos2=find(e1<0 & e2<0 & abs(e1)<abs(e2)); # lateral and longitudinal compression
+	#a(pos2)=e1(pos2)./e2(pos2);
+	#ex(pos2)=e2(pos2);
+	#pos3=find(e1>0 & e2>0 & abs(e1)<abs(e2)); # lateral and longitudinal tension 
+	#a(pos3)=e1(pos3)./e2(pos3);
+	#ex(pos3)=e2(pos3);
+	#id=find(e1<0 & e2<0);
+	#a(id)=-a(id); # where both strain rates are compressive, enforce negative alpha
+	#
+	## }}}
+	
+	# new method using longitudinal strain rates defined by observed velocity vector
+	velangle=npy.arctan(md.initialization.vy/md.initialization.vx)
+	ex=0.5*(exx+eyy)+0.5*(exx-eyy)*npy.cos(2.*velangle)+exy*npy.sin(2.*velangle)
+	ey=exx+eyy-ex # trace of strain rate tensor is invariant
+	exy=-0.5*(exx-eyy)*npy.sin(2.*velangle)+exy*npy.cos(2.*velangle)
+	a=ey/ex
+	b=exy/ex
+	pos=npy.nonzero(npy.logical_and(ex<0,ey<0))
+	#length(pos)
+	a[pos]=-a[pos]
+	
+	# a < -1 in areas of strong lateral compression or longitudinal compression
+	# and theta is undefined at a = -2
+	pos=npy.nonzero(abs((abs(a)-2))<1e-3)
+	a[pos]=-2+1e-3
+	
+	# spreading stress
+	rhoi=md.materials.rho_ice
+	rhow=md.materials.rho_water
+	C=0.5*rhoi*md.constants.g*(1.-rhoi/rhow)
+	T=C*md.geometry.thickness
+	
+	# rheology
+	B=md.materials.rheology_B
+	n=averaging(md,md.materials.rheology_n,0)
+	
+	if eq=='Weertman1D':
+		theta=1./8*npy.ones(md.mesh.numberofvertices,)
+		a=npy.zeros(md.mesh.numberofvertices,)
+	elif eq=='Weertman2D':
+		theta=1./9*npy.ones(md.mesh.numberofvertices,1)
+		a=npy.ones(md.mesh.numberofvertices,)
+	elif eq=='Thomas':
+		theta=((1+a+a**2+b**2)**((n-1)/2))/(abs(2+a)**n)
+	else:
+		raise StandardError('argument passed to "eq" not valid.  Type "help analyticaldamage" for usage')
+	
+	D=1-(1+a+a**2+b**2)**((n-1)/(2*n))/abs(ex)**(1./n)*(T-sigmab)/B/(2+a)/npy.sign(ex)
+	
+	backstress=npy.zeros(md.mesh.numberofvertices,)
+	
+	# D>1 where (2+a).*sign(ex)<0, compressive regions where high backstress needed
+	pos=npy.nonzero(D>1)
+	D[pos]=0
+	
+	# backstress to bring damage to zero
+	backstress[pos]=T[pos]-(1-D[pos])*B[pos]*npy.sign(ex[pos])*(2+a[pos])*abs(ex[pos])**(1./n[pos])/(1+a[pos]+a[pos]**2)**((n[pos]-1)/2./n[pos])
+	
+	pos=npy.nonzero(D<0)
+	D[pos]=0
+
+	# backstress to bring negative damage to zero
+	backstress[pos]=T[pos]-(1-D[pos])*B[pos]*npy.sign(ex[pos])*(2+a[pos])*abs(ex[pos])**(1./n[pos])/(1+a[pos]+a[pos]**2)**((n[pos]-1)/2./n[pos])
+	
+	pos=npy.nonzero(backstress<0)
+	backstress[pos]=0
+	
+	# increased rigidity to bring negative damage to zero
+	B[pos]=npy.sign(ex[pos])/(2+a[pos])*(1+a[pos]+a[pos]**2)**((n[pos]-1)/2./n[pos])*T[pos]/abs(ex[pos])**(1./n[pos]);
+	
+	damage=D
+	
+	return damage, B, backstress
Index: /issm/trunk/src/m/mech/cfl_step.m
===================================================================
--- /issm/trunk/src/m/mech/cfl_step.m	(revision 16136)
+++ /issm/trunk/src/m/mech/cfl_step.m	(revision 16137)
@@ -8,5 +8,5 @@
 %
 %   Example:
-%      dt=cfl_step(md,md.results.DiagnosticSolution.Vx,md.results.DiagnosticSolution.Vy)
+%      dt=cfl_step(md,md.results.StressbalanceSolution.Vx,md.results.StressbalanceSolution.Vy)
 
 %Check length of velocities 
Index: /issm/trunk/src/m/mech/mechanicalproperties.m
===================================================================
--- /issm/trunk/src/m/mech/mechanicalproperties.m	(revision 16136)
+++ /issm/trunk/src/m/mech/mechanicalproperties.m	(revision 16137)
@@ -21,5 +21,5 @@
 end
 if any(md.flowequation.element_equation~=2),
-	disp('Warning: the model has some non macayeal elements. These will be treated like MacAyeal''s elements');
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA''s elements');
 end
 
Index: /issm/trunk/src/m/mech/mechanicalproperties.py
===================================================================
--- /issm/trunk/src/m/mech/mechanicalproperties.py	(revision 16137)
+++ /issm/trunk/src/m/mech/mechanicalproperties.py	(revision 16137)
@@ -0,0 +1,141 @@
+import numpy as npy
+from GetNodalFunctionsCoeff import GetNodalFunctionsCoeff
+from results import results
+
+def mechanicalproperties(md,vx,vy):
+	"""
+	MECHANICALPROPERTIES - compute stress and strain rate for a goven velocity
+	
+   this routine computes the components of the stress tensor
+   strain rate tensor and their respective principal directions.
+   the results are in the model md: md.results
+	
+   Usage:
+      md=mechanicalproperties(md,vx,vy)
+	
+   Example:
+      md=mechanicalproperties(md,md.initialization.vx,md.initialization.vy)
+      md=mechanicalproperties(md,md.inversion.vx_obs,md.inversion.vy_obs)
+	"""
+
+	#some checks
+	if len(vx)!=md.mesh.numberofvertices or len(vy)!=md.mesh.numberofvertices:
+		raise ValueError('the input velocity should be of size ' + md.mesh.numberofvertices)
+
+	if md.mesh.dimension!=2:
+		raise StandardError('only 2D model supported currently')
+
+	if npy.any(md.flowequation.element_equation!=2):
+		print 'Warning: the model has some non SSA elements. These will be treated like SSA elements'
+	
+	#initialization
+	numberofelements=md.mesh.numberofelements
+	index=md.mesh.elements
+	summation=npy.array([[1],[1],[1]])
+	directionsstress=npy.zeros((numberofelements,4))
+	directionsstrain=npy.zeros((numberofelements,4))
+	valuesstress=npy.zeros((numberofelements,2))
+	valuesstrain=npy.zeros((numberofelements,2))
+	
+	#compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+	alpha,beta=GetNodalFunctionsCoeff(index,md.mesh.x,md.mesh.y)[0:2]
+	
+	#compute shear
+	vxlist=vx[index-1]/md.constants.yts
+	vylist=vy[index-1]/md.constants.yts
+	ux=npy.dot((vxlist*alpha),summation).reshape(-1,)
+	uy=npy.dot((vxlist*beta),summation).reshape(-1,)
+	vx=npy.dot((vylist*alpha),summation).reshape(-1,)
+	vy=npy.dot((vylist*beta),summation).reshape(-1,)
+	uyvx=(vx+uy)/2.
+	#clear vxlist vylist
+	
+	#compute viscosity
+	nu=npy.zeros((numberofelements,))
+	B_bar=npy.dot(md.materials.rheology_B[index-1],summation/3.).reshape(-1,)
+	power=(md.materials.rheology_n-1.)/(2.*md.materials.rheology_n)
+	second_inv=(ux**2.+vy**2.+((uy+vx)**2.)/4.+ux*vy).reshape(-1,)
+	
+	#some corrections
+	location=npy.nonzero(npy.logical_and(second_inv==0,power!=0))
+	nu[location]=10^18 	#arbitrary maximum viscosity to apply where there is no effective shear
+	
+	if 'matice' in md.materials.__module__:
+		location=npy.nonzero(second_inv)
+		nu[location]=B_bar[location]/(second_inv[location]**power[location])
+		location=npy.nonzero(npy.logical_and(second_inv==0,power==0))
+		nu[location]=B_bar[location]
+	elif 'matdamageice' in md.materials.__module__:
+		Zinv=npy.dot(md.materials.rheology_Z[index-1],summation/3.).reshape(-1,)
+		location=npy.nonzero(second_inv)
+		nu[location]=Zinv[location]*B_bar[location]/npy.power(second_inv[location],power[location])
+		location=npy.nonzero(npy.logical_and(second_inv==0,power==0))
+		nu[location]=Zinv[location]*B_bar[location]
+		#clear Zinv
+	else:
+		raise StandardError('class of md.materials (' + md.materials.__module__ + ') not recognized or not supported')
+	
+	#compute stress
+	tau_xx=nu*ux
+	tau_yy=nu*vy
+	tau_xy=nu*uyvx
+	
+	#compute principal properties of stress
+	for i in npy.arange(numberofelements):
+	
+		#compute stress and strainrate matrices
+		stress=npy.array([ [tau_xx[i], tau_xy[i]], [tau_xy[i], tau_yy[i]] ])
+		strain=npy.array([ [ux[i], uyvx[i]], [uyvx[i], vy[i]] ])
+	
+		#eigenvalues and vectors for stress
+		value,directions=npy.linalg.eig(stress);
+		idx=abs(value).argsort()[::-1] # sort in descending order
+		value=value[idx]
+		directions=directions[:,idx]
+		valuesstress[i,:]=[value[0],value[1]]
+		directionsstress[i,:]=directions.transpose().flatten()
+
+		#eigenvalues and vectors for strain
+		value,directions=npy.linalg.eig(strain);
+		idx=abs(value).argsort()[::-1] # sort in descending order
+		value=value[idx]
+		directions=directions[:,idx]
+		valuesstrain[i,:]=[value[0],value[1]]
+		directionsstrain[i,:]=directions.transpose().flatten()
+
+	##plug onto the model
+	##NB: Matlab sorts the eigen value in increasing order, we want the reverse
+	stress=results()
+	stress.xx=tau_xx
+	stress.yy=tau_yy
+	stress.xy=tau_xy
+	stress.principalvalue1=valuesstress[:,0]
+	stress.principalaxis1=directionsstress[:,0:2]
+	stress.principalvalue2=valuesstress[:,1]
+	stress.principalaxis2=directionsstress[:,2:4]
+	stress.effectivevalue=1./npy.sqrt(2.)*npy.sqrt(stress.xx**2+stress.yy**2+2.*stress.xy**2)
+	md.results.stress=stress
+	
+	strainrate=results()
+	strainrate.xx=ux*md.constants.yts #strain rate in 1/a instead of 1/s
+	strainrate.yy=vy*md.constants.yts 
+	strainrate.xy=uyvx*md.constants.yts 
+	strainrate.principalvalue1=valuesstrain[:,0]*md.constants.yts 
+	strainrate.principalaxis1=directionsstrain[:,0:2]
+	strainrate.principalvalue2=valuesstrain[:,1]*md.constants.yts 
+	strainrate.principalaxis2=directionsstrain[:,2:4]
+	strainrate.effectivevalue=1./npy.sqrt(2.)*npy.sqrt(strainrate.xx**2+strainrate.yy**2+2.*strainrate.xy**2)
+	md.results.strainrate=strainrate
+	
+	deviatoricstress=results()
+	deviatoricstress.xx=tau_xx
+	deviatoricstress.yy=tau_yy
+	deviatoricstress.xy=tau_xy
+	deviatoricstress.principalvalue1=valuesstress[:,0]
+	deviatoricstress.principalaxis1=directionsstress[:,1:2]
+	deviatoricstress.principalvalue2=valuesstress[:,1]
+	deviatoricstress.principalaxis2=directionsstress[:,2:4]
+	deviatoricstress.effectivevalue=1./npy.sqrt(2.)*npy.sqrt(stress.xx**2+stress.yy**2+2.*stress.xy**2)
+	md.results.deviatoricstress=deviatoricstress
+
+	return md
Index: /issm/trunk/src/m/mech/steadystateiceshelftemp.m
===================================================================
--- /issm/trunk/src/m/mech/steadystateiceshelftemp.m	(revision 16137)
+++ /issm/trunk/src/m/mech/steadystateiceshelftemp.m	(revision 16137)
@@ -0,0 +1,60 @@
+function temperature=steadystateiceshelftemp(md,surfacetemp,basaltemp)
+%STEADYSTATEICESHELFTEMP - compute depth-averaged steady-state temperature of an ice shelf 
+%
+%   This routine computes the depth-averaged temperature accounting for vertical advection 
+%   and diffusion of heat into the base of the ice shelf as a function of surface and 
+%   basal temperature and the basal melting rate.  Horizontal advection is ignored.
+%   The solution is a depth-averaged version of Equation 25 in Holland and Jenkins (1999).
+%
+%	 In addition to supplying md, the surface and basal temperatures of the ice shelf must
+%	 be supplied in degrees Kelvin.
+%
+%	 The model md must also contain the fields: 
+%	 md.geometry.thickness
+%	 md.basalforcings.melting_rate (positive for melting, negative for freezing)
+
+%   Usage:
+%      temperature=steadystateiceshelftemp(md,surfacetemp,basaltemp)
+
+if (length(md.geometry.thickness)~=md.mesh.numberofvertices)
+	error(['steadystateiceshelftemp error message: thickness should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+
+%surface and basal temperatures in degrees C
+if (length(surfacetemp)~=md.mesh.numberofvertices)
+	error(['steadystateiceshelftemp error message: surfacetemp should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+
+if (length(basaltemp)~=md.mesh.numberofvertices)
+	error(['steadystateiceshelftemp error message: basaltemp should have a length of ' num2str(md.mesh.numberofvertices)])
+end
+
+% Convert temps to Celsius for Holland and Jenkins (1999) equation
+Ts=-273.15+surfacetemp;
+Tb=-273.15+basaltemp;
+
+Hi=md.geometry.thickness;
+ki=1.14e-6*md.constants.yts; % ice shelf thermal diffusivity from Holland and Jenkins (1999) converted to m^2/yr 
+
+%vertical velocity of ice shelf, calculated from melting rate 
+wi=md.materials.rho_water/md.materials.rho_ice.*md.basalforcings.melting_rate; 
+
+%temperature profile is linear if melting rate is zero, depth-averaged temp is simple average in this case
+temperature=(Ts+Tb)/2;  % where wi~=0
+
+pos=find(abs(wi)>=1e-4); % to avoid division by zero
+
+%calculate depth-averaged temperature (in Celsius)
+%temperature(pos)=-( (Tb(pos)-Ts(pos))*ki./wi(pos) + Hi(pos).*Tb(pos) - (Hi(pos).*Ts(pos) + (Tb(pos)-Ts(pos))*ki./wi(pos)).*exp(Hi(pos).*wi(pos)/ki) )./( Hi(pos).*(exp(Hi(pos).*wi(pos)/ki)-1));
+temperature(pos)=-( ((Tb(pos)-Ts(pos))*ki./wi(pos) + Hi(pos).*Tb(pos))./exp(Hi(pos).*wi(pos)/ki) - Hi(pos).*Ts(pos) + (Tb(pos)-Ts(pos))*ki./wi(pos))./( Hi(pos).*(1-exp(-Hi(pos).*wi(pos)/ki)));
+
+%temperature should not be less than surface temp
+pos=find(temperature<Ts);
+temperature(pos)=Ts(pos);
+
+% NaN where melt rates are too high (infinity/infinity in exponential)
+pos=find(isnan(temperature));
+temperature(pos)=Ts(pos);
+
+%convert to Kelvin
+temperature=temperature+273.15;
Index: /issm/trunk/src/m/mech/steadystateiceshelftemp.py
===================================================================
--- /issm/trunk/src/m/mech/steadystateiceshelftemp.py	(revision 16137)
+++ /issm/trunk/src/m/mech/steadystateiceshelftemp.py	(revision 16137)
@@ -0,0 +1,65 @@
+import numpy as npy
+
+def steadystateiceshelftemp(md,surfacetemp,basaltemp):
+	"""
+	Compute the depth-averaged steady-state temperature of an ice shelf 
+	This routine computes the depth-averaged temperature accounting for vertical advection 
+	and diffusion of heat into the base of the ice shelf as a function of surface and basal 
+	temperature and the basal melting rate.  Horizontal advection is ignored.
+   The solution is a depth-averaged version of Equation 25 in Holland and Jenkins (1999).
+
+	In addition to supplying md, the surface and basal temperatures of the ice shelf must be supplied in degrees Kelvin.
+
+	The model md must also contain the fields: 
+	md.geometry.thickness
+	md.basalforcings.melting_rate (positive for melting, negative for freezing)
+
+   Usage:
+      temperature=steadystateiceshelftemp(md,surfacetemp,basaltemp)
+	"""
+
+	if len(md.geometry.thickness)!=md.mesh.numberofvertices:
+		raise ValueError('steadystateiceshelftemp error message: thickness should have a length of ' + md.mesh.numberofvertices)
+	
+	#surface and basal temperatures in degrees C
+	if len(surfacetemp)!=md.mesh.numberofvertices:
+		raise ValueError('steadystateiceshelftemp error message: surfacetemp should have a length of ' + md.mesh.numberofvertices)
+	
+	if len(basaltemp)!=md.mesh.numberofvertices:
+		raise ValueError('steadystateiceshelftemp error message: basaltemp should have a length of ' +md.mesh.numberofvertices)
+	
+	# Convert temps to Celsius for Holland and Jenkins (1999) equation
+	Ts=-273.15+surfacetemp
+	Tb=-273.15+basaltemp
+	
+	Hi=md.geometry.thickness
+	ki=1.14e-6*md.constants.yts # ice shelf thermal diffusivity from Holland and Jenkins (1999) converted to m^2/yr 
+	
+	#vertical velocity of ice shelf, calculated from melting rate 
+	wi=md.materials.rho_water/md.materials.rho_ice*md.basalforcings.melting_rate 
+	
+	#temperature profile is linear if melting rate is zero, depth-averaged temp is simple average in this case
+	temperature=(Ts+Tb)/2  # where wi~=0
+	
+	pos=npy.nonzero(abs(wi)>=1e-4) # to avoid division by zero
+
+	npy.seterr(over='raise',divide='raise') # raise errors if floating point exceptions are encountered in following calculation
+	#calculate depth-averaged temperature (in Celsius)
+	try:
+		temperature[pos]=-( (Tb[pos]-Ts[pos])*ki/wi[pos] + Hi[pos]*Tb[pos] - (Hi[pos]*Ts[pos] + (Tb[pos]-Ts[pos])*ki/wi[pos])*npy.exp(Hi[pos]*wi[pos]/ki) )/( Hi[pos]*(npy.exp(Hi[pos]*wi[pos]/ki)-1))
+	except FloatingPointError:
+		print 'steadystateiceshelf warning: overflow encountered in multipy/divide/exp, trying another formulation.' 
+		temperature[pos]=-( ((Tb[pos]-Ts[pos])*ki/wi[pos] + Hi[pos]*Tb[pos])/npy.exp(Hi[pos]*wi[pos]/ki) - Hi[pos]*Ts[pos] + (Tb[pos]-Ts[pos])*ki/wi[pos])/( Hi[pos]*(1-npy.exp(-Hi[pos]*wi[pos]/ki)))
+	
+	#temperature should not be less than surface temp
+	pos=npy.nonzero(temperature<Ts)
+	temperature[pos]=Ts[pos]
+	
+	# NaN where melt rates are too high (infinity/infinity in exponential)
+	pos=npy.nonzero(npy.isnan(temperature))
+	temperature[pos]=Ts[pos]
+	
+	#convert to Kelvin
+	temperature=temperature+273.15
+
+	return temperature
Index: /issm/trunk/src/m/mech/strainrateuncert.m
===================================================================
--- /issm/trunk/src/m/mech/strainrateuncert.m	(revision 16136)
+++ /issm/trunk/src/m/mech/strainrateuncert.m	(revision 16137)
@@ -6,6 +6,6 @@
 %   The results are stored in md.results
 %
-%	 'dvx' and 'dvy' are velocity errors in x and y components.  These 
-%	 can either be scalars or arrays of length md.mesh.numberofvertices
+%	 'dvx' and 'dvy' are velocity errors in x and y components in m/yr.  
+%   These can either be scalars or arrays of length md.mesh.numberofvertices
 %
 %   Usage:
@@ -36,5 +36,5 @@
 end
 if any(md.flowequation.element_equation~=2),
-	disp('Warning: the model has some non macayeal elements. These will be treated like MacAyeal''s elements');
+	disp('Warning: the model has some non SSA elements. These will be treated like SSA''s elements');
 end
 
@@ -42,4 +42,6 @@
 index=md.mesh.elements;
 summation=[1;1;1];
+dvxlist=dvx(index);
+dvylist=dvy(index);
 
 %compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
@@ -48,17 +50,17 @@
 strainrateuncert=struct('xx',[],'yy',[],'xy',[],'principalvalue1',[],'principalvalue2',[],'effectivevalue',[]);
 
-strainrateuncert.xx=dvx.*sqrt(alpha.^2*summation);
-strainrateuncert.yy=dvy.*sqrt(beta.^2*summation);
-strainrateuncert.xy=0.5*sqrt(dvx.^2.*(beta.^2*summation)+dvy.^2.*(alpha.^2*summation));
+strainrateuncert.xx=sqrt((dvxlist.*alpha).^2*summation);
+strainrateuncert.yy=sqrt((dvylist.*beta).^2*summation);
+strainrateuncert.xy=0.5*sqrt((dvxlist.*beta).^2*summation+(dvylist.*alpha).^2*summation);
 
-exx=md.results.strainrate.xx;
+exx=md.results.strainrate.xx; 
 eyy=md.results.strainrate.yy;
 exy=md.results.strainrate.xy;
-p1a=strainrateuncert.xx.*(0.5+0.25*(0.5*((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
-p2a=strainrateuncert.yy.*(0.5-0.25*(0.5*((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
-p3a=strainrateuncert.xy.*(((exx-eyy)/2).^(2)+exy.^2).^(-1./2).*exy;
-p1b=strainrateuncert.xx.*(0.5-0.25*(0.5*((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
-p2b=strainrateuncert.yy.*(0.5+0.25*(0.5*((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
-p3b=strainrateuncert.xy.*(-(((exx-eyy)/2).^(2)+exy.^2).^(-1./2).*exy);
+p1a=strainrateuncert.xx.*(0.5+0.25*(((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
+p2a=strainrateuncert.yy.*(0.5-0.25*(((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
+p3a=strainrateuncert.xy.*((((exx-eyy)/2).^2+exy.^2).^(-1./2).*exy);
+p1b=strainrateuncert.xx.*(0.5-0.25*(((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
+p2b=strainrateuncert.yy.*(0.5+0.25*(((exx-eyy)/2).^2+exy.^2).^(-1./2).*(exx-eyy));
+p3b=strainrateuncert.xy.*(-(((exx-eyy)/2).^2+exy.^2).^(-1./2).*exy);
 strainrateuncert.principalvalue1=sqrt(p1a.^2+p2a.^2+p3a.^2);
 strainrateuncert.principalvalue2=sqrt(p1b.^2+p2b.^2+p3b.^2);
Index: /issm/trunk/src/m/mesh/ComputeMetric.m
===================================================================
--- /issm/trunk/src/m/mesh/ComputeMetric.m	(revision 16136)
+++ /issm/trunk/src/m/mesh/ComputeMetric.m	(revision 16137)
@@ -7,5 +7,5 @@
 %
 %   Example:
-%      metric=ComputeMetric(hessian,2/9,10^-1,100,10^5,find(md.nodeonwater)
+%      metric=ComputeMetric(hessian,2/9,10^-1,100,10^5,[])
 
 %first, find the eigen values of each line of H=[hessian(i,1) hessian(i,2); hessian(i,2) hessian(i,3)]
Index: /issm/trunk/src/m/mesh/ComputeMetric.py
===================================================================
--- /issm/trunk/src/m/mesh/ComputeMetric.py	(revision 16136)
+++ /issm/trunk/src/m/mesh/ComputeMetric.py	(revision 16137)
@@ -10,5 +10,5 @@
 
 	   Example:
-	      metric=ComputeMetric(hessian,2/9,10^-1,100,10^5,find(md.nodeonwater)
+	      metric=ComputeMetric(hessian,2/9,10^-1,100,10^5,[])
 	"""
 
Index: /issm/trunk/src/m/mesh/MeshQuality.m
===================================================================
--- /issm/trunk/src/m/mesh/MeshQuality.m	(revision 16136)
+++ /issm/trunk/src/m/mesh/MeshQuality.m	(revision 16137)
@@ -17,10 +17,5 @@
 
 %Compute metric
-if length(md.nodeonwater)==md.mesh.numberofvertices,
-	pos=find(md.nodeonwater);
-else
-	pos=[];
-end
-metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos);
+metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,[]);
 
 %Get Areas
Index: /issm/trunk/src/m/mesh/bamg.m
===================================================================
--- /issm/trunk/src/m/mesh/bamg.m	(revision 16136)
+++ /issm/trunk/src/m/mesh/bamg.m	(revision 16137)
@@ -325,5 +325,4 @@
 md.mesh.z=zeros(md.mesh.numberofvertices,1);
 md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
-md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
 md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
 md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
Index: /issm/trunk/src/m/mesh/bamg.py
===================================================================
--- /issm/trunk/src/m/mesh/bamg.py	(revision 16136)
+++ /issm/trunk/src/m/mesh/bamg.py	(revision 16137)
@@ -332,5 +332,4 @@
 	md.mesh.z=numpy.zeros(md.mesh.numberofvertices)
 	md.mesh.vertexonbed=numpy.ones(md.mesh.numberofvertices,bool)
-	md.mask.vertexonwater=numpy.zeros(md.mesh.numberofvertices,bool)
 	md.mesh.vertexonsurface=numpy.ones(md.mesh.numberofvertices,bool)
 	md.mesh.elementonbed=numpy.ones(md.mesh.numberofelements,bool)
Index: /issm/trunk/src/m/mesh/meshconvert.m
===================================================================
--- /issm/trunk/src/m/mesh/meshconvert.m	(revision 16136)
+++ /issm/trunk/src/m/mesh/meshconvert.m	(revision 16137)
@@ -42,5 +42,4 @@
 md.mesh.z=zeros(md.mesh.numberofvertices,1);
 md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
-md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
 md.mesh.vertexonsurface=ones(md.mesh.numberofvertices,1);
 md.mesh.elementonbed=ones(md.mesh.numberofelements,1);
Index: /issm/trunk/src/m/miscellaneous/issmdoc.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/issmdoc.m	(revision 16136)
+++ /issm/trunk/src/m/miscellaneous/issmdoc.m	(revision 16137)
@@ -11,5 +11,5 @@
 disp(sprintf('%-63s %s','       md=setmask(md,''all'','''');','%defines the glacier system as an ice shelf (no island)'));
 disp(sprintf('%-63s %s','       md=parameterize(md,''Square.par'');','%fills all the other fields of the model'));
-disp(sprintf('%-63s %s','       md=setflowequation(md,''macayeal'',''all'');','%defines all elements as MacAyeal''s SSA'));
-disp(sprintf('%-63s %s','       md=solve(md,DiagnosticSolutionEnum());','%solve for stress balance'));
-disp(sprintf('%-63s %s','       plotmodel(md,''data'',md.results.DiagnosticSolution.Vel);','%displays the velocity (type plotdoc for plotmodel help)'));
+disp(sprintf('%-63s %s','       md=setflowequation(md,''SSA'',''all'');','%defines all elements as SSA''s SSA'));
+disp(sprintf('%-63s %s','       md=solve(md,StressbalanceSolutionEnum());','%solve for stress balance'));
+disp(sprintf('%-63s %s','       plotmodel(md,''data'',md.results.StressbalanceSolution.Vel);','%displays the velocity (type plotdoc for plotmodel help)'));
Index: sm/trunk/src/m/os/dakotaversion.m
===================================================================
--- /issm/trunk/src/m/os/dakotaversion.m	(revision 16136)
+++ 	(revision )
@@ -1,26 +1,0 @@
-function DAKOTA_VERSION=dakotaversion()
-%DAKOTAVERSION - recover dakota version number, inside config.h file
-%
-%   Usage:
-%       DAKOTA_VERSION=dakotaversion();
-
-%default
-DAKOTA_VERSION='';
-
-configfile=[issmdir() '/config.h'];
-if ~exist(configfile,'file'),
-	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
-end
-
-%go through the file, and recover the line we want
-fid=fopen(configfile,'r');
-if(fid==-1), error(['could not open file: ' configfile]); end
-
-while(true),
-	tline=fgets(fid);
-	if ~ischar(tline), break, end
-	if  strncmp(tline,'#define _DAKOTA_VERSION_',24),
-		DAKOTA_VERSION=strtrim(strrep(tline(26:end),'"',''));
-	end
-end
-fclose(fid);
Index: sm/trunk/src/m/os/dakotaversion.py
===================================================================
--- /issm/trunk/src/m/os/dakotaversion.py	(revision 16136)
+++ 	(revision )
@@ -1,34 +1,0 @@
-import os
-from issmdir import *
-from MatlabFuncs import *
-
-def dakotaversion():
-	"""
-	DAKOTAVERSION - recover dakota version number, inside config.h file
- 
-	   Usage:
-	      DAKOTA_VERSION=dakotaversion();
-	"""
-
-	#default
-	DAKOTA_VERSION=''
-
-	configfile=os.path.join(issmdir(),'config.h')
-	if not os.path.exists(configfile):
-		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
-
-	#go through the file, and recover the line we want
-	try:
-		fid=open(configfile,'r')
-	except IOError as e:
-		raise IOerror("could not open file: '%s'" % configfile)
-
-	for tline in fid:
-		if strncmp(tline,'#define _DAKOTA_VERSION_',24):
-			DAKOTA_VERSION=tline[25:].replace('"','').strip()
-			break
-
-	fid.close()
-
-	return DAKOTA_VERSION
-
Index: sm/trunk/src/m/os/ismpi.m
===================================================================
--- /issm/trunk/src/m/os/ismpi.m	(revision 16136)
+++ 	(revision )
@@ -1,32 +1,0 @@
-function flag=ismpi()
-%ISMPI - figure out if MPI package was compiled with ISSM
-%
-%   Usage:
-%       flag=ismpi();
-
-configfile=[issmdir() '/bin/config.h']; %should find it in the install target
-if ~exist(configfile,'file'),
-	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
-end
-
-%go through the file, and recover the line we want
-flag=2;
-fid=fopen(configfile,'r');
-if(fid==-1), error(['could not open file: ' configfile]); end
-
-while(true),
-	tline=fgets(fid);
-	if ~ischar(tline), break, end
-	if strncmp(tline,'/* #undef _HAVE_MPI_ */',23),
-		flag=0;
-		break;
-	end
-	if  strncmp(tline,'#define _HAVE_MPI_',18),
-		flag=1;
-		break;
-	end
-end
-fclose(fid);
-if flag==2,
-	error('could not determine whether MPI was or was not compiled');
-end
Index: sm/trunk/src/m/os/ismpi.py
===================================================================
--- /issm/trunk/src/m/os/ismpi.py	(revision 16136)
+++ 	(revision )
@@ -1,37 +1,0 @@
-import os
-from issmdir import *
-from MatlabFuncs import *
-
-def ismpi():
-	"""
-	ISMPI - figure out if MPI package was compiled with ISSM
- 
-	   Usage:
-	      flag=ismpi();
-	"""
-
-	configfile=os.path.join(issmdir(),'bin','config.h')    #should find it in the install target
-	if not os.path.exists(configfile):
-		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
-
-	#go through the file, and recover the line we want
-	flag=2
-	try:
-		fid=open(configfile,'r')
-	except IOError as e:
-		raise IOError("could not open file: '%s'" % configfile)
-
-	for tline in fid:
-		if strncmp(tline,'/* #undef _HAVE_MPI_ */',23):
-			flag=0
-			break
-		if  strncmp(tline,'#define _HAVE_MPI_',18):
-			flag=1
-			break
-
-	fid.close()
-	if flag==2:
-		raise RuntimeError("could not determine whether MPI was or was not compiled.")
-
-	return flag
-
Index: sm/trunk/src/m/os/ismumps.m
===================================================================
--- /issm/trunk/src/m/os/ismumps.m	(revision 16136)
+++ 	(revision )
@@ -1,32 +1,0 @@
-function flag=ismumps()
-%ISMUMPS - figure out if MUMPS package was compiled with ISSM
-%
-%   Usage:
-%       flag=ismumps();
-
-configfile=[issmdir() '/bin/config.h']; %should find it in the install target
-if ~exist(configfile,'file'),
-	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
-end
-
-%go through the file, and recover the line we want
-flag=2;
-fid=fopen(configfile,'r');
-if(fid==-1), error(['could not open file: ' configfile]); end
-
-while(true),
-	tline=fgets(fid);
-	if ~ischar(tline), break, end
-	if strncmp(tline,'/* #undef _HAVE_MUMPS_ */',25),
-		flag=0;
-		break;
-	end
-	if  strncmp(tline,'#define _HAVE_MUMPS_',20),
-		flag=1;
-		break;
-	end
-end
-fclose(fid);
-if flag==2,
-	error('could not determine whether MUMPS was or was not compiled');
-end
Index: sm/trunk/src/m/os/ismumps.py
===================================================================
--- /issm/trunk/src/m/os/ismumps.py	(revision 16136)
+++ 	(revision )
@@ -1,37 +1,0 @@
-import os
-from issmdir import *
-from MatlabFuncs import *
-
-def ismumps():
-	"""
-	ISMUMPS - figure out if MUMPS package was compiled with ISSM
- 
-	   Usage:
-	      flag=ismumps();
-	"""
-
-	configfile=os.path.join(issmdir(),'bin','config.h')    #should find it in the install target
-	if not os.path.exists(configfile):
-		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
-
-	#go through the file, and recover the line we want
-	flag=2
-	try:
-		fid=open(configfile,'r')
-	except IOError as e:
-		raise IOError("could not open file: '%s'" % configfile)
-
-	for tline in fid:
-		if strncmp(tline,'/* #undef _HAVE_MUMPS_ */',25):
-			flag=0
-			break
-		if  strncmp(tline,'#define _HAVE_MUMPS_',20):
-			flag=1
-			break
-
-	fid.close()
-	if flag==2:
-		raise RuntimeError("could not determine whether MUMPS was or was not compiled.")
-
-	return flag
-
Index: sm/trunk/src/m/os/ispetsc.m
===================================================================
--- /issm/trunk/src/m/os/ispetsc.m	(revision 16136)
+++ 	(revision )
@@ -1,32 +1,0 @@
-function flag=ispetsc()
-%ISPETSC - figure out if PETSC package was compiled with ISSM
-%
-%   Usage:
-%       flag=ispetsc();
-
-configfile=[issmdir() '/bin/config.h']; %should find it in the install target
-if ~exist(configfile,'file'),
-	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
-end
-
-%go through the file, and recover the line we want
-flag=2;
-fid=fopen(configfile,'r');
-if(fid==-1), error(['could not open file: ' configfile]); end
-
-while(true),
-	tline=fgets(fid);
-	if ~ischar(tline), break, end
-	if strncmp(tline,'/* #undef _HAVE_PETSC_ */',25),
-		flag=0;
-		break;
-	end
-	if  strncmp(tline,'#define _HAVE_PETSC_',20),
-		flag=1;
-		break;
-	end
-end
-fclose(fid);
-if flag==2,
-	error('could not determine whether PETSC was or was not compiled');
-end
Index: sm/trunk/src/m/os/ispetsc.py
===================================================================
--- /issm/trunk/src/m/os/ispetsc.py	(revision 16136)
+++ 	(revision )
@@ -1,37 +1,0 @@
-import os
-from issmdir import *
-from MatlabFuncs import *
-
-def ispetsc():
-	"""
-	ISPETSC - figure out if PETSC package was compiled with ISSM
- 
-	   Usage:
-	      flag=ispetsc();
-	"""
-
-	configfile=os.path.join(issmdir(),'bin','config.h')    #should find it in the install target
-	if not os.path.exists(configfile):
-		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
-
-	#go through the file, and recover the line we want
-	flag=2
-	try:
-		fid=open(configfile,'r')
-	except IOError as e:
-		raise IOError("could not open file: '%s'" % configfile)
-
-	for tline in fid:
-		if strncmp(tline,'/* #undef _HAVE_PETSC_ */',25):
-			flag=0
-			break
-		if  strncmp(tline,'#define _HAVE_PETSC_',20):
-			flag=1
-			break
-
-	fid.close()
-	if flag==2:
-		raise RuntimeError("could not determine whether PETSC was or was not compiled.")
-
-	return flag
-
Index: sm/trunk/src/m/os/petscversion.m
===================================================================
--- /issm/trunk/src/m/os/petscversion.m	(revision 16136)
+++ 	(revision )
@@ -1,26 +1,0 @@
-function PETSC_VERSION=petscversion()
-%PETSCVERSION - recover petsc version number, inside config.h file
-%
-%   Usage:
-%       PETSC_VERSION=petscversion();
-
-%default
-PETSC_VERSION=3;
-
-configfile=[issmdir() '/config.h'];
-if ~exist(configfile,'file'),
-	error(['File ' configfile ' not found. ISSM has not been configured yet!']);
-end
-
-%go through the file, and recover the line we want
-fid=fopen(configfile,'r');
-if(fid==-1), error(['could not open file: ' configfile]); end
-
-while(true),
-	tline=fgets(fid);
-	if ~ischar(tline), break, end
-	if  strncmp(tline,'#define _PETSC_MAJOR_',21),
-		PETSC_VERSION=str2num(tline(23));
-	end
-end
-fclose(fid);
Index: sm/trunk/src/m/os/petscversion.py
===================================================================
--- /issm/trunk/src/m/os/petscversion.py	(revision 16136)
+++ 	(revision )
@@ -1,34 +1,0 @@
-import os
-from issmdir import *
-from MatlabFuncs import *
-
-def petscversion():
-	"""
-	PETSCVERSION - recover petsc version number, inside config.h file
- 
-	   Usage:
-	      PETSC_VERSION=petscversion();
-	"""
-
-	#default
-	PETSC_VERSION=3
-
-	configfile=os.path.join(issmdir(),'config.h')
-	if not os.path.exists(configfile):
-		raise RuntimeError("File '%s' not found. ISSM has not been configured yet!" % configfile)
-
-	#go through the file, and recover the line we want
-	try:
-		fid=open(configfile,'r')
-	except IOError as e:
-		raise IOerror("could not open file: '%s'" % configfile)
-
-	for tline in fid:
-		if strncmp(tline,'#define _PETSC_MAJOR_',21):
-			PETSC_VERSION=int(tline[22])
-			break
-
-	fid.close()
-
-	return PETSC_VERSION
-
Index: /issm/trunk/src/m/parameterization/contourenvelope.m
===================================================================
--- /issm/trunk/src/m/parameterization/contourenvelope.m	(revision 16136)
+++ /issm/trunk/src/m/parameterization/contourenvelope.m	(revision 16137)
@@ -7,5 +7,4 @@
 %   Example:
 %      segments=contourenvelope(md,'Stream.exp');
-%      segments=contourenvelope(md,md.mask.elementonfloatingice)
 %      segments=contourenvelope(md);
 
Index: /issm/trunk/src/m/parameterization/contourenvelope.py
===================================================================
--- /issm/trunk/src/m/parameterization/contourenvelope.py	(revision 16136)
+++ /issm/trunk/src/m/parameterization/contourenvelope.py	(revision 16137)
@@ -15,5 +15,4 @@
 	   Example:
 	      segments=contourenvelope(md,'Stream.exp');
-	      segments=contourenvelope(md,md.mask.elementonfloatingice)
 	      segments=contourenvelope(md);
 	"""
Index: /issm/trunk/src/m/parameterization/setflowequation.m
===================================================================
--- /issm/trunk/src/m/parameterization/setflowequation.m	(revision 16136)
+++ /issm/trunk/src/m/parameterization/setflowequation.m	(revision 16137)
@@ -3,13 +3,13 @@
 %
 %   This routine works like plotmodel: it works with an even number of inputs
-%   'hutter','macayeal','l1l2','pattyn','stokes' and 'fill' are the possible options
+%   'SIA','SSA','L1L2','HO','FS' and 'fill' are the possible options
 %   that must be followed by the corresponding exp file or flags list
 %   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
 %   If user wants every element outside the domain to be 
-%   setflowequationd, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+%   setflowequationd, add '~' to the name of the domain file (ex: '~HO.exp');
 %   an empty string '' will be considered as an empty domain
 %   a string 'all' will be considered as the entire domain
 %   You can specify the type of coupling, 'penalties' or 'tiling', to use with the input 'coupling'
-%   NB: l1l2 cannot currently be coupled to any other ice flow model
+%   NB: L1L2 cannot currently be coupled to any other ice flow model
 %
 %   Usage:
@@ -17,6 +17,5 @@
 %
 %   Example:
-%      md=setflowequation(md,'pattyn','Pattyn.exp','macayeal',md.mask.elementonfloatingice,'fill','hutter');
-%      md=setflowequation(md,'pattyn','Pattyn.exp',fill','hutter','coupling','tiling');
+%      md=setflowequation(md,'HO','HO.exp',fill','SIA','coupling','tiling');
 
 %some checks on list of arguments
@@ -36,96 +35,97 @@
 
 %recover elements distribution
-hutterflag   = FlagElements(md,getfieldvalue(options,'hutter',''));
-macayealflag = FlagElements(md,getfieldvalue(options,'macayeal',''));
-pattynflag   = FlagElements(md,getfieldvalue(options,'pattyn',''));
-l1l2flag     = FlagElements(md,getfieldvalue(options,'l1l2',''));
-stokesflag   = FlagElements(md,getfieldvalue(options,'stokes',''));
-filltype     = getfieldvalue(options,'fill','none');
+SIAflag  = FlagElements(md,getfieldvalue(options,'SIA',''));
+SSAflag  = FlagElements(md,getfieldvalue(options,'SSA',''));
+HOflag   = FlagElements(md,getfieldvalue(options,'HO',''));
+L1L2flag = FlagElements(md,getfieldvalue(options,'L1L2',''));
+FSflag   = FlagElements(md,getfieldvalue(options,'FS',''));
+filltype = getfieldvalue(options,'fill','none');
+displayunused(options);
 
 %Flag the elements that have not been flagged as filltype
-if strcmpi(filltype,'hutter'),
-	hutterflag(find(~(macayealflag | pattynflag)))=1;
-elseif strcmpi(filltype,'macayeal'),
-	macayealflag(find(~(hutterflag | pattynflag | stokesflag)))=1;
-elseif strcmpi(filltype,'pattyn'),
-	pattynflag(find(~(hutterflag | macayealflag | stokesflag)))=1;
+if strcmpi(filltype,'SIA'),
+	SIAflag(find(~(SSAflag | HOflag)))=1;
+elseif strcmpi(filltype,'SSA'),
+	SSAflag(find(~(SIAflag | HOflag | FSflag)))=1;
+elseif strcmpi(filltype,'HO'),
+	HOflag(find(~(SIAflag | SSAflag | FSflag)))=1;
 end
 
 %check that each element has at least one flag
-if any(hutterflag+macayealflag+pattynflag+l1l2flag+stokesflag==0),
-	error('elements type not assigned, must be specified')
+if any(SIAflag+SSAflag+HOflag+L1L2flag+FSflag==0),
+	error('elements type not assigned, supported models are ''SIA'',''SSA'',''HO'' and ''FS''')
 end
 
 %check that each element has only one flag
-if any(hutterflag+macayealflag+pattynflag+l1l2flag+stokesflag>1),
+if any(SIAflag+SSAflag+HOflag+L1L2flag+FSflag>1),
 	disp('setflowequation warning message: some elements have several types, higher order type is used for them')
-	hutterflag(find(hutterflag & macayealflag))=0;
-	hutterflag(find(hutterflag & pattynflag))=0;
-	macayealflag(find(macayealflag & pattynflag))=0;
-end
-
-%check that l1l2 is not coupled to any other model for now
-if any(l1l2flag) & any(hutterflag | macayealflag | pattynflag | stokesflag)
-	error('l1l2 cannot be coupled to any other model');
-end
-
-%Check that no l1l2 or pattyn or stokes for 2d mesh
+	SIAflag(find(SIAflag & SSAflag))=0;
+	SIAflag(find(SIAflag & HOflag))=0;
+	SSAflag(find(SSAflag & HOflag))=0;
+end
+
+%check that L1L2 is not coupled to any other model for now
+if any(L1L2flag) & any(SIAflag | SSAflag | HOflag | FSflag)
+	error('L1L2 cannot be coupled to any other model');
+end
+
+%Check that no L1L2 or HO or FS for 2d mesh
 if (md.mesh.dimension==2),
-	if any(l1l2flag | stokesflag | pattynflag)
-		error('stokes and pattyn elements not allowed in 2d mesh, extrude it first')
-	end
-end
-
-%Stokes can only be used alone for now:
-if any(stokesflag) &any(hutterflag),
-	error('stokes cannot be used with any other model for now, put stokes everywhere')
+	if any(L1L2flag | FSflag | HOflag)
+		error('FS and HO elements not allowed in 2d mesh, extrude it first')
+	end
+end
+
+%FS can only be used alone for now:
+if any(FSflag) &any(SIAflag),
+	error('FS cannot be used with any other model for now, put FS everywhere')
 end
 
 %Initialize node fields
-nodeonhutter=zeros(md.mesh.numberofvertices,1);
-nodeonhutter(md.mesh.elements(find(hutterflag),:))=1;
-nodeonmacayeal=zeros(md.mesh.numberofvertices,1);
-nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
-nodeonpattyn=zeros(md.mesh.numberofvertices,1);
-nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
-nodeonl1l2=zeros(md.mesh.numberofvertices,1);
-nodeonl1l2(md.mesh.elements(find(l1l2flag),:))=1;
-nodeonstokes=zeros(md.mesh.numberofvertices,1);
+nodeonSIA=zeros(md.mesh.numberofvertices,1);
+nodeonSIA(md.mesh.elements(find(SIAflag),:))=1;
+nodeonSSA=zeros(md.mesh.numberofvertices,1);
+nodeonSSA(md.mesh.elements(find(SSAflag),:))=1;
+nodeonHO=zeros(md.mesh.numberofvertices,1);
+nodeonHO(md.mesh.elements(find(HOflag),:))=1;
+nodeonL1L2=zeros(md.mesh.numberofvertices,1);
+nodeonL1L2(md.mesh.elements(find(L1L2flag),:))=1;
+nodeonFS=zeros(md.mesh.numberofvertices,1);
 noneflag=zeros(md.mesh.numberofelements,1);
 
-%First modify stokesflag to get rid of elements contrained everywhere (spc + border with pattyn or macayeal)
-if any(stokesflag),
-	fullspcnodes=double((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy)+~isnan(md.diagnostic.spcvz))==3 | (nodeonpattyn & nodeonstokes));         %find all the nodes on the boundary of the domain without icefront
+%First modify FSflag to get rid of elements contrained everywhere (spc + border with HO or SSA)
+if any(FSflag),
+	fullspcnodes=double((~isnan(md.stressbalance.spcvx)+~isnan(md.stressbalance.spcvy)+~isnan(md.stressbalance.spcvz))==3 | (nodeonHO & nodeonFS));         %find all the nodes on the boundary of the domain without icefront
 	fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
-	stokesflag(find(fullspcelems))=0;
-	nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
-end
-
-%Then complete with NoneApproximation or the other model used if there is no stokes
-if any(stokesflag), 
-	if any(pattynflag), %fill with pattyn
-		pattynflag(~stokesflag)=1;
-		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
-	elseif any(macayealflag), %fill with macayeal
-		macayealflag(~stokesflag)=1;
-		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+	FSflag(find(fullspcelems))=0;
+	nodeonFS(md.mesh.elements(find(FSflag),:))=1;
+end
+
+%Then complete with NoneApproximation or the other model used if there is no FS
+if any(FSflag), 
+	if any(HOflag), %fill with HO
+		HOflag(~FSflag)=1;
+		nodeonHO(md.mesh.elements(find(HOflag),:))=1;
+	elseif any(SSAflag), %fill with SSA
+		SSAflag(~FSflag)=1;
+		nodeonSSA(md.mesh.elements(find(SSAflag),:))=1;
 	else %fill with none 
-		noneflag(find(~stokesflag))=1;
-	end
-end
-
-%Now take care of the coupling between MacAyeal and Pattyn
-md.diagnostic.vertex_pairing=[];
-nodeonmacayealpattyn=zeros(md.mesh.numberofvertices,1);
-nodeonpattynstokes=zeros(md.mesh.numberofvertices,1);
-nodeonmacayealstokes=zeros(md.mesh.numberofvertices,1);
-macayealpattynflag=zeros(md.mesh.numberofelements,1);
-macayealstokesflag=zeros(md.mesh.numberofelements,1);
-pattynstokesflag=zeros(md.mesh.numberofelements,1);
+		noneflag(find(~FSflag))=1;
+	end
+end
+
+%Now take care of the coupling between SSA and HO
+md.stressbalance.vertex_pairing=[];
+nodeonSSAHO=zeros(md.mesh.numberofvertices,1);
+nodeonHOFS=zeros(md.mesh.numberofvertices,1);
+nodeonSSAFS=zeros(md.mesh.numberofvertices,1);
+SSAHOflag=zeros(md.mesh.numberofelements,1);
+SSAFSflag=zeros(md.mesh.numberofelements,1);
+HOFSflag=zeros(md.mesh.numberofelements,1);
 if strcmpi(coupling_method,'penalties'),
-	%Create the border nodes between Pattyn and MacAyeal and extrude them
+	%Create the border nodes between HO and SSA and extrude them
 	numnodes2d=md.mesh.numberofvertices2d;
 	numlayers=md.mesh.numberoflayers;
-	bordernodes2d=find(nodeonpattyn(1:numnodes2d) & nodeonmacayeal(1:numnodes2d)); %Nodes connected to two different types of elements
+	bordernodes2d=find(nodeonHO(1:numnodes2d) & nodeonSSA(1:numnodes2d)); %Nodes connected to two different types of elements
 
 	%initialize and fill in penalties structure
@@ -135,166 +135,167 @@
 			penalties=[penalties; [bordernodes2d bordernodes2d+md.mesh.numberofvertices2d*(i)]];
 		end
-		md.diagnostic.vertex_pairing=penalties;
+		md.stressbalance.vertex_pairing=penalties;
 	end
 elseif strcmpi(coupling_method,'tiling'),
-	if any(macayealflag) & any(pattynflag), %coupling macayeal pattyn
+	if any(SSAflag) & any(HOflag), %coupling SSA HO
 		%Find node at the border
-		nodeonmacayealpattyn(find(nodeonmacayeal & nodeonpattyn))=1;
-		%Macayeal elements in contact with this layer become MacAyealPattyn elements
-		matrixelements=ismember(md.mesh.elements,find(nodeonmacayealpattyn));
+		nodeonSSAHO(find(nodeonSSA & nodeonHO))=1;
+		%SSA elements in contact with this layer become SSAHO elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonSSAHO));
 		commonelements=sum(matrixelements,2)~=0;
-		commonelements(find(pattynflag))=0; %only one layer: the elements previously in macayeal
-		macayealflag(find(commonelements))=0; %these elements are now macayealpattynelements
-		macayealpattynflag(find(commonelements))=1;
-		nodeonmacayeal(:)=0;
-		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
+		commonelements(find(HOflag))=0; %only one layer: the elements previously in SSA
+		SSAflag(find(commonelements))=0; %these elements are now SSAHOelements
+		SSAHOflag(find(commonelements))=1;
+		nodeonSSA(:)=0;
+		nodeonSSA(md.mesh.elements(find(SSAflag),:))=1;
 
 		%rule out elements that don't touch the 2 boundaries
-		pos=find(macayealpattynflag);
+		pos=find(SSAHOflag);
 		elist=zeros(length(pos),1);
-		elist = elist + any(sum(nodeonmacayeal(md.mesh.elements(pos,:)),2),2);
-		elist = elist - any(sum(nodeonpattyn(md.mesh.elements(pos,:))  ,2),2);
+		elist = elist + any(sum(nodeonSSA(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonHO(md.mesh.elements(pos,:))  ,2),2);
 		pos1=find(elist==1);
-		macayealflag(pos(pos1))=1;
-		macayealpattynflag(pos(pos1))=0;
+		SSAflag(pos(pos1))=1;
+		SSAHOflag(pos(pos1))=0;
 		pos2=find(elist==-1);
-		pattynflag(pos(pos2))=1;
-		macayealpattynflag(pos(pos2))=0;
+		HOflag(pos(pos2))=1;
+		SSAHOflag(pos(pos2))=0;
 
 		%Recompute nodes associated to these elements
-		nodeonmacayeal(:)=0;
-		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
-		nodeonpattyn(:)=0;
-		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
-		nodeonmacayealpattyn(:)=0;
-		nodeonmacayealpattyn(md.mesh.elements(find(macayealpattynflag),:))=1;
-
-	elseif any(pattynflag) & any(stokesflag), %coupling pattyn stokes
+		nodeonSSA(:)=0;
+		nodeonSSA(md.mesh.elements(find(SSAflag),:))=1;
+		nodeonHO(:)=0;
+		nodeonHO(md.mesh.elements(find(HOflag),:))=1;
+		nodeonSSAHO(:)=0;
+		nodeonSSAHO(md.mesh.elements(find(SSAHOflag),:))=1;
+
+	elseif any(HOflag) & any(FSflag), %coupling HO FS
 		%Find node at the border
-		nodeonpattynstokes(find(nodeonpattyn & nodeonstokes))=1;
-		%Stokes elements in contact with this layer become PattynStokes elements
-		matrixelements=ismember(md.mesh.elements,find(nodeonpattynstokes));
+		nodeonHOFS(find(nodeonHO & nodeonFS))=1;
+		%FS elements in contact with this layer become HOFS elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonHOFS));
 		commonelements=sum(matrixelements,2)~=0;
-		commonelements(find(pattynflag))=0; %only one layer: the elements previously in macayeal
-		stokesflag(find(commonelements))=0; %these elements are now macayealpattynelements
-		pattynstokesflag(find(commonelements))=1;
-		nodeonstokes=zeros(md.mesh.numberofvertices,1);
-		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+		commonelements(find(HOflag))=0; %only one layer: the elements previously in SSA
+		FSflag(find(commonelements))=0; %these elements are now SSAHOelements
+		HOFSflag(find(commonelements))=1;
+		nodeonFS=zeros(md.mesh.numberofvertices,1);
+		nodeonFS(md.mesh.elements(find(FSflag),:))=1;
 
 		%rule out elements that don't touch the 2 boundaries
-		pos=find(pattynstokesflag);
+		pos=find(HOFSflag);
 		elist=zeros(length(pos),1);
-		elist = elist + any(sum(nodeonstokes(md.mesh.elements(pos,:)),2),2);
-		elist = elist - any(sum(nodeonpattyn(md.mesh.elements(pos,:)),2),2);
+		elist = elist + any(sum(nodeonFS(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonHO(md.mesh.elements(pos,:)),2),2);
 		pos1=find(elist==1);
-		stokesflag(pos(pos1))=1;
-		pattynstokesflag(pos(pos1))=0;
+		FSflag(pos(pos1))=1;
+		HOFSflag(pos(pos1))=0;
 		pos2=find(elist==-1);
-		pattynflag(pos(pos2))=1;
-		pattynstokesflag(pos(pos2))=0;
+		HOflag(pos(pos2))=1;
+		HOFSflag(pos(pos2))=0;
 
 		%Recompute nodes associated to these elements
-		nodeonstokes(:)=0;
-		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
-		nodeonpattyn(:)=0;
-		nodeonpattyn(md.mesh.elements(find(pattynflag),:))=1;
-		nodeonpattynstokes(:)=0;
-		nodeonpattynstokes(md.mesh.elements(find(pattynstokesflag),:))=1;
-
-	elseif any(stokesflag) & any(macayealflag),
+		nodeonFS(:)=0;
+		nodeonFS(md.mesh.elements(find(FSflag),:))=1;
+		nodeonHO(:)=0;
+		nodeonHO(md.mesh.elements(find(HOflag),:))=1;
+		nodeonHOFS(:)=0;
+		nodeonHOFS(md.mesh.elements(find(HOFSflag),:))=1;
+
+	elseif any(FSflag) & any(SSAflag),
 		%Find node at the border
-		nodeonmacayealstokes(find(nodeonmacayeal & nodeonstokes))=1;
-		%Stokes elements in contact with this layer become MacAyealStokes elements
-		matrixelements=ismember(md.mesh.elements,find(nodeonmacayealstokes));
+		nodeonSSAFS(find(nodeonSSA & nodeonFS))=1;
+		%FS elements in contact with this layer become SSAFS elements
+		matrixelements=ismember(md.mesh.elements,find(nodeonSSAFS));
 		commonelements=sum(matrixelements,2)~=0;
-		commonelements(find(macayealflag))=0; %only one layer: the elements previously in macayeal
-		stokesflag(find(commonelements))=0; %these elements are now macayealmacayealelements
-		macayealstokesflag(find(commonelements))=1;
-		nodeonstokes=zeros(md.mesh.numberofvertices,1);
-		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
+		commonelements(find(SSAflag))=0; %only one layer: the elements previously in SSA
+		FSflag(find(commonelements))=0; %these elements are now SSASSAelements
+		SSAFSflag(find(commonelements))=1;
+		nodeonFS=zeros(md.mesh.numberofvertices,1);
+		nodeonFS(md.mesh.elements(find(FSflag),:))=1;
 
 		%rule out elements that don't touch the 2 boundaries
-		pos=find(macayealstokesflag);
+		pos=find(SSAFSflag);
 		elist=zeros(length(pos),1);
-		elist = elist + any(sum(nodeonmacayeal(md.mesh.elements(pos,:)),2),2);
-		elist = elist - any(sum(nodeonstokes(md.mesh.elements(pos,:))  ,2),2);
+		elist = elist + any(sum(nodeonSSA(md.mesh.elements(pos,:)),2),2);
+		elist = elist - any(sum(nodeonFS(md.mesh.elements(pos,:))  ,2),2);
 		pos1=find(elist==1);
-		macayealflag(pos(pos1))=1;
-		macayealstokesflag(pos(pos1))=0;
+		SSAflag(pos(pos1))=1;
+		SSAFSflag(pos(pos1))=0;
 		pos2=find(elist==-1);
-		stokesflag(pos(pos2))=1;
-		macayealstokesflag(pos(pos2))=0;
+		FSflag(pos(pos2))=1;
+		SSAFSflag(pos(pos2))=0;
 
 		%Recompute nodes associated to these elements
-		nodeonmacayeal(:)=0;
-		nodeonmacayeal(md.mesh.elements(find(macayealflag),:))=1;
-		nodeonstokes(:)=0;
-		nodeonstokes(md.mesh.elements(find(stokesflag),:))=1;
-		nodeonmacayealstokes(:)=0;
-		nodeonmacayealstokes(md.mesh.elements(find(macayealstokesflag),:))=1;
-
-	elseif any(stokesflag) & any(hutterflag),
+		nodeonSSA(:)=0;
+		nodeonSSA(md.mesh.elements(find(SSAflag),:))=1;
+		nodeonFS(:)=0;
+		nodeonFS(md.mesh.elements(find(FSflag),:))=1;
+		nodeonSSAFS(:)=0;
+		nodeonSSAFS(md.mesh.elements(find(SSAFSflag),:))=1;
+
+	elseif any(FSflag) & any(SIAflag),
 		error('type of coupling not supported yet');
 	end
 end
 
-%Create MacaAyealPattynApproximation where needed
+%Create MacaAyealHOApproximation where needed
 md.flowequation.element_equation=zeros(md.mesh.numberofelements,1);
 md.flowequation.element_equation(find(noneflag))=0;
-md.flowequation.element_equation(find(hutterflag))=1;
-md.flowequation.element_equation(find(macayealflag))=2;
-md.flowequation.element_equation(find(l1l2flag))=8;
-md.flowequation.element_equation(find(pattynflag))=3;
-md.flowequation.element_equation(find(stokesflag))=4;
-md.flowequation.element_equation(find(macayealpattynflag))=5;
-md.flowequation.element_equation(find(macayealstokesflag))=6;
-md.flowequation.element_equation(find(pattynstokesflag))=7;
+md.flowequation.element_equation(find(SIAflag))=1;
+md.flowequation.element_equation(find(SSAflag))=2;
+md.flowequation.element_equation(find(L1L2flag))=8;
+md.flowequation.element_equation(find(HOflag))=3;
+md.flowequation.element_equation(find(FSflag))=4;
+md.flowequation.element_equation(find(SSAHOflag))=5;
+md.flowequation.element_equation(find(SSAFSflag))=6;
+md.flowequation.element_equation(find(HOFSflag))=7;
 
 %border
-md.flowequation.borderpattyn=nodeonpattyn;
-md.flowequation.bordermacayeal=nodeonmacayeal;
-md.flowequation.borderstokes=nodeonstokes;
+md.flowequation.borderHO=nodeonHO;
+md.flowequation.borderSSA=nodeonSSA;
+md.flowequation.borderFS=nodeonFS;
 
 %Create vertices_type
 md.flowequation.vertex_equation=zeros(md.mesh.numberofvertices,1);
-pos=find(nodeonmacayeal);
+pos=find(nodeonSSA);
 md.flowequation.vertex_equation(pos)=2;
-pos=find(nodeonl1l2);
+pos=find(nodeonL1L2);
 md.flowequation.vertex_equation(pos)=8;
-pos=find(nodeonpattyn);
+pos=find(nodeonHO);
 md.flowequation.vertex_equation(pos)=3;
-pos=find(nodeonhutter);
+pos=find(nodeonSIA);
 md.flowequation.vertex_equation(pos)=1;
-pos=find(nodeonmacayealpattyn);
+pos=find(nodeonSSAHO);
 md.flowequation.vertex_equation(pos)=5;
-pos=find(nodeonstokes);
+pos=find(nodeonFS);
 md.flowequation.vertex_equation(pos)=4;
-if any(stokesflag),
-	pos=find(~nodeonstokes);
-	if(~any(pattynflag) & ~any(macayealflag)),
+if any(FSflag),
+	pos=find(~nodeonFS);
+	if(~any(HOflag) & ~any(SSAflag)),
 		md.flowequation.vertex_equation(pos)=0;
 	end
 end
-pos=find(nodeonpattynstokes);
+pos=find(nodeonHOFS);
 md.flowequation.vertex_equation(pos)=7;
-pos=find(nodeonmacayealstokes);
+pos=find(nodeonSSAFS);
 md.flowequation.vertex_equation(pos)=6;
 
 %figure out solution types
-md.flowequation.ishutter=double(any(md.flowequation.element_equation==1));
-md.flowequation.ismacayealpattyn=double(any(md.flowequation.element_equation==2 | md.flowequation.element_equation==3));
-md.flowequation.isstokes=double(any(md.flowequation.element_equation==4));
-md.flowequation.isl1l2=double(any(md.flowequation.element_equation==8));
+md.flowequation.isSIA  = double(any(md.flowequation.element_equation == 1));
+md.flowequation.isSSA  = double(any(md.flowequation.element_equation == 2));
+md.flowequation.isHO   = double(any(md.flowequation.element_equation == 3));
+md.flowequation.isL1L2 = double(any(md.flowequation.element_equation == 8));
+md.flowequation.isFS   = double(any(md.flowequation.element_equation == 4));
 
 return
 
 %Check that tiling can work:
-if any(md.flowequation.bordermacayeal) & any(md.flowequation.borderpattyn) & any(md.flowequation.borderpattyn + md.flowequation.bordermacayeal ~=1),
+if any(md.flowequation.borderSSA) & any(md.flowequation.borderHO) & any(md.flowequation.borderHO + md.flowequation.borderSSA ~=1),
 	error('error coupling domain too irregular');
 end
-if any(md.flowequation.bordermacayeal) & any(md.flowequation.borderstokes) & any(md.flowequation.borderstokes + md.flowequation.bordermacayeal ~=1),
+if any(md.flowequation.borderSSA) & any(md.flowequation.borderFS) & any(md.flowequation.borderFS + md.flowequation.borderSSA ~=1),
 	error('error coupling domain too irregular');
 end
-if any(md.flowequation.borderstokes) & any(md.flowequation.borderpattyn) & any(md.flowequation.borderpattyn + md.flowequation.borderstokes~=1),
+if any(md.flowequation.borderFS) & any(md.flowequation.borderHO) & any(md.flowequation.borderHO + md.flowequation.borderFS~=1),
 	error('error coupling domain too irregular');
 end
Index: /issm/trunk/src/m/parameterization/setflowequation.py
===================================================================
--- /issm/trunk/src/m/parameterization/setflowequation.py	(revision 16136)
+++ /issm/trunk/src/m/parameterization/setflowequation.py	(revision 16137)
@@ -11,9 +11,9 @@
 
 	   This routine works like plotmodel: it works with an even number of inputs
-	   'hutter','macayeal','pattyn','l1l2','stokes' and 'fill' are the possible options
+	   'SIA','SSA','HO','L1L2','FS' and 'fill' are the possible options
 	   that must be followed by the corresponding exp file or flags list
 	   It can either be a domain file (argus type, .exp extension), or an array of element flags. 
 	   If user wants every element outside the domain to be 
-	   setflowequationd, add '~' to the name of the domain file (ex: '~Pattyn.exp');
+	   setflowequationd, add '~' to the name of the domain file (ex: '~HO.exp');
 	   an empty string '' will be considered as an empty domain
 	   a string 'all' will be considered as the entire domain
@@ -24,6 +24,5 @@
 
 	   Example:
-	      md=setflowequation(md,'pattyn','Pattyn.exp','macayeal',md.mask.elementonfloatingice,'fill','hutter');
-	      md=setflowequation(md,'pattyn','Pattyn.exp',fill','hutter','coupling','tiling');
+	      md=setflowequation(md,'HO','HO.exp',fill','SIA','coupling','tiling');
 	"""
 
@@ -42,87 +41,87 @@
 
 	#recover elements distribution
-	hutterflag   = FlagElements(md,options.getfieldvalue('hutter',''))
-	macayealflag = FlagElements(md,options.getfieldvalue('macayeal',''))
-	pattynflag   = FlagElements(md,options.getfieldvalue('pattyn',''))
-	l1l2flag     = FlagElements(md,options.getfieldvalue('l1l2',''))
-	stokesflag   = FlagElements(md,options.getfieldvalue('stokes',''))
+	SIAflag   = FlagElements(md,options.getfieldvalue('SIA',''))
+	SSAflag = FlagElements(md,options.getfieldvalue('SSA',''))
+	HOflag   = FlagElements(md,options.getfieldvalue('HO',''))
+	L1L2flag     = FlagElements(md,options.getfieldvalue('L1L2',''))
+	FSflag   = FlagElements(md,options.getfieldvalue('FS',''))
 	filltype     = options.getfieldvalue('fill','none')
 
 	#Flag the elements that have not been flagged as filltype
-	if   strcmpi(filltype,'hutter'):
-		hutterflag[numpy.nonzero(numpy.logical_not(logical_or_n(macayealflag,pattynflag)))]=True
-	elif strcmpi(filltype,'macayeal'):
-		macayealflag[numpy.nonzero(numpy.logical_not(logical_or_n(hutterflag,pattynflag,stokesflag)))]=True
-	elif strcmpi(filltype,'pattyn'):
-		pattynflag[numpy.nonzero(numpy.logical_not(logical_or_n(hutterflag,macayealflag,stokesflag)))]=True
+	if   strcmpi(filltype,'SIA'):
+		SIAflag[numpy.nonzero(numpy.logical_not(logical_or_n(SSAflag,HOflag)))]=True
+	elif strcmpi(filltype,'SSA'):
+		SSAflag[numpy.nonzero(numpy.logical_not(logical_or_n(SIAflag,HOflag,FSflag)))]=True
+	elif strcmpi(filltype,'HO'):
+		HOflag[numpy.nonzero(numpy.logical_not(logical_or_n(SIAflag,SSAflag,FSflag)))]=True
 
 	#check that each element has at least one flag
-	if not any(hutterflag+macayealflag+l1l2flag+pattynflag+stokesflag):
-		raise TypeError("elements type not assigned, must be specified")
+	if not any(SIAflag+SSAflag+L1L2flag+HOflag+FSflag):
+		raise TypeError("elements type not assigned, supported models are 'SIA','SSA','HO' and 'FS'")
 
 	#check that each element has only one flag
-	if any(hutterflag+macayealflag+l1l2flag+pattynflag+stokesflag>1):
+	if any(SIAflag+SSAflag+L1L2flag+HOflag+FSflag>1):
 		print "setflowequation warning message: some elements have several types, higher order type is used for them"
-		hutterflag[numpy.nonzero(numpy.logical_and(hutterflag,macayealflag))]=False
-		hutterflag[numpy.nonzero(numpy.logical_and(hutterflag,pattynflag))]=False
-		macayealflag[numpy.nonzero(numpy.logical_and(macayealflag,pattynflag))]=False
-
-	#Check that no pattyn or stokes for 2d mesh
+		SIAflag[numpy.nonzero(numpy.logical_and(SIAflag,SSAflag))]=False
+		SIAflag[numpy.nonzero(numpy.logical_and(SIAflag,HOflag))]=False
+		SSAflag[numpy.nonzero(numpy.logical_and(SSAflag,HOflag))]=False
+
+	#Check that no HO or FS for 2d mesh
 	if md.mesh.dimension==2:
-		if numpy.any(logical_or_n(l1l2flag,stokesflag,pattynflag)):
-			raise TypeError("stokes and pattyn elements not allowed in 2d mesh, extrude it first")
-
-	#Stokes can only be used alone for now:
-	if any(stokesflag) and any(hutterflag):
-		raise TypeError("stokes cannot be used with any other model for now, put stokes everywhere")
+		if numpy.any(logical_or_n(L1L2flag,FSflag,HOflag)):
+			raise TypeError("FS and HO elements not allowed in 2d mesh, extrude it first")
+
+	#FS can only be used alone for now:
+	if any(FSflag) and any(SIAflag):
+		raise TypeError("FS cannot be used with any other model for now, put FS everywhere")
 
 	#Initialize node fields
-	nodeonhutter=numpy.zeros(md.mesh.numberofvertices,bool)
-	nodeonhutter[md.mesh.elements[numpy.nonzero(hutterflag),:]-1]=True
-	nodeonmacayeal=numpy.zeros(md.mesh.numberofvertices,bool)
-	nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:]-1]=True
-	nodeonl1l2=numpy.zeros(md.mesh.numberofvertices,bool)
-	nodeonl1l2[md.mesh.elements[numpy.nonzero(l1l2flag),:]-1]=True
-	nodeonpattyn=numpy.zeros(md.mesh.numberofvertices,bool)
-	nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:]-1]=True
-	nodeonstokes=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonSIA=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonSIA[md.mesh.elements[numpy.nonzero(SIAflag),:]-1]=True
+	nodeonSSA=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
+	nodeonL1L2=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonL1L2[md.mesh.elements[numpy.nonzero(L1L2flag),:]-1]=True
+	nodeonHO=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
+	nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
 	noneflag=numpy.zeros(md.mesh.numberofelements,bool)
 
-	#First modify stokesflag to get rid of elements contrained everywhere (spc + border with pattyn or macayeal)
-	if any(stokesflag):
-#		fullspcnodes=double((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy)+~isnan(md.diagnostic.spcvz))==3 | (nodeonpattyn & nodeonstokes));         %find all the nodes on the boundary of the domain without icefront
-		fullspcnodes=numpy.logical_or(numpy.logical_not(numpy.isnan(md.diagnostic.spcvx)).astype(int)+ \
-		                              numpy.logical_not(numpy.isnan(md.diagnostic.spcvy)).astype(int)+ \
-		                              numpy.logical_not(numpy.isnan(md.diagnostic.spcvz)).astype(int)==3, \
-		                              numpy.logical_and(nodeonpattyn,nodeonstokes).reshape(-1,1)).astype(int)    #find all the nodes on the boundary of the domain without icefront
+	#First modify FSflag to get rid of elements contrained everywhere (spc + border with HO or SSA)
+	if any(FSflag):
+#		fullspcnodes=double((~isnan(md.stressbalance.spcvx)+~isnan(md.stressbalance.spcvy)+~isnan(md.stressbalance.spcvz))==3 | (nodeonHO & nodeonFS));         %find all the nodes on the boundary of the domain without icefront
+		fullspcnodes=numpy.logical_or(numpy.logical_not(numpy.isnan(md.stressbalance.spcvx)).astype(int)+ \
+		                              numpy.logical_not(numpy.isnan(md.stressbalance.spcvy)).astype(int)+ \
+		                              numpy.logical_not(numpy.isnan(md.stressbalance.spcvz)).astype(int)==3, \
+		                              numpy.logical_and(nodeonHO,nodeonFS).reshape(-1,1)).astype(int)    #find all the nodes on the boundary of the domain without icefront
 #		fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
 		fullspcelems=(numpy.sum(fullspcnodes[md.mesh.elements-1],axis=1)==6).astype(int)    #find all the nodes on the boundary of the domain without icefront
-		stokesflag[numpy.nonzero(fullspcelems.reshape(-1))]=False
-		nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:]-1]=True
-
-	#Then complete with NoneApproximation or the other model used if there is no stokes
-	if any(stokesflag): 
-		if   any(pattynflag):    #fill with pattyn
-			pattynflag[numpy.logical_not(stokesflag)]=True
-			nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:]-1]=True
-		elif any(macayealflag):    #fill with macayeal
-			macayealflag[numpy.logical_not(stokesflag)]=True
-			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:]-1]=True
+		FSflag[numpy.nonzero(fullspcelems.reshape(-1))]=False
+		nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
+
+	#Then complete with NoneApproximation or the other model used if there is no FS
+	if any(FSflag): 
+		if   any(HOflag):    #fill with HO
+			HOflag[numpy.logical_not(FSflag)]=True
+			nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
+		elif any(SSAflag):    #fill with SSA
+			SSAflag[numpy.logical_not(FSflag)]=True
+			nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
 		else:    #fill with none 
-			noneflag[numpy.nonzero(numpy.logical_not(stokesflag))]=True
-
-	#Now take care of the coupling between MacAyeal and Pattyn
-	md.diagnostic.vertex_pairing=numpy.array([])
-	nodeonmacayealpattyn=numpy.zeros(md.mesh.numberofvertices,bool)
-	nodeonpattynstokes=numpy.zeros(md.mesh.numberofvertices,bool)
-	nodeonmacayealstokes=numpy.zeros(md.mesh.numberofvertices,bool)
-	macayealpattynflag=numpy.zeros(md.mesh.numberofelements,bool)
-	macayealstokesflag=numpy.zeros(md.mesh.numberofelements,bool)
-	pattynstokesflag=numpy.zeros(md.mesh.numberofelements,bool)
+			noneflag[numpy.nonzero(numpy.logical_not(FSflag))]=True
+
+	#Now take care of the coupling between SSA and HO
+	md.stressbalance.vertex_pairing=numpy.array([])
+	nodeonSSAHO=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonHOFS=numpy.zeros(md.mesh.numberofvertices,bool)
+	nodeonSSAFS=numpy.zeros(md.mesh.numberofvertices,bool)
+	SSAHOflag=numpy.zeros(md.mesh.numberofelements,bool)
+	SSAFSflag=numpy.zeros(md.mesh.numberofelements,bool)
+	HOFSflag=numpy.zeros(md.mesh.numberofelements,bool)
 	if   strcmpi(coupling_method,'penalties'):
-		#Create the border nodes between Pattyn and MacAyeal and extrude them
+		#Create the border nodes between HO and SSA and extrude them
 		numnodes2d=md.mesh.numberofvertices2d
 		numlayers=md.mesh.numberoflayers
-		bordernodes2d=numpy.nonzero(numpy.logical_and(nodeonpattyn[0:numnodes2d],nodeonmacayeal[0:numnodes2d]))[0]+1    #Nodes connected to two different types of elements
+		bordernodes2d=numpy.nonzero(numpy.logical_and(nodeonHO[0:numnodes2d],nodeonSSA[0:numnodes2d]))[0]+1    #Nodes connected to two different types of elements
 
 		#initialize and fill in penalties structure
@@ -131,160 +130,161 @@
 			for	i in xrange(1,numlayers):
 				penalties=numpy.vstack((penalties,numpy.hstack((bordernodes2d.reshape(-1,1),bordernodes2d.reshape(-1,1)+md.mesh.numberofvertices2d*(i)))))
-			md.diagnostic.vertex_pairing=penalties
+			md.stressbalance.vertex_pairing=penalties
 
 	elif strcmpi(coupling_method,'tiling'):
-		if   any(macayealflag) and any(pattynflag):    #coupling macayeal pattyn
+		if   any(SSAflag) and any(HOflag):    #coupling SSA HO
 			#Find node at the border
-			nodeonmacayealpattyn[numpy.nonzero(numpy.logical_and(nodeonmacayeal,nodeonpattyn))]=True
-			#Macayeal elements in contact with this layer become MacAyealPattyn elements
-			matrixelements=ismember(md.mesh.elements-1,numpy.nonzero(nodeonmacayealpattyn)[0])
+			nodeonSSAHO[numpy.nonzero(numpy.logical_and(nodeonSSA,nodeonHO))]=True
+			#SSA elements in contact with this layer become SSAHO elements
+			matrixelements=ismember(md.mesh.elements-1,numpy.nonzero(nodeonSSAHO)[0])
 			commonelements=numpy.sum(matrixelements,axis=1)!=0
-			commonelements[numpy.nonzero(pattynflag)]=False    #only one layer: the elements previously in macayeal
-			macayealflag[numpy.nonzero(commonelements)]=False    #these elements are now macayealpattynelements
-			macayealpattynflag[numpy.nonzero(commonelements)]=True
-			nodeonmacayeal[:]=False
-			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:]-1]=True
+			commonelements[numpy.nonzero(HOflag)]=False    #only one layer: the elements previously in SSA
+			SSAflag[numpy.nonzero(commonelements)]=False    #these elements are now SSAHOelements
+			SSAHOflag[numpy.nonzero(commonelements)]=True
+			nodeonSSA[:]=False
+			nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
 
 			#rule out elements that don't touch the 2 boundaries
-			pos=numpy.nonzero(macayealpattynflag)[0]
+			pos=numpy.nonzero(SSAHOflag)[0]
 			elist=numpy.zeros(numpy.size(pos),dtype=int)
-			elist = elist + numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
-			elist = elist - numpy.sum(nodeonpattyn[md.mesh.elements[pos,:]-1]  ,axis=1).astype(bool)
+			elist = elist + numpy.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
+			elist = elist - numpy.sum(nodeonHO[md.mesh.elements[pos,:]-1]  ,axis=1).astype(bool)
 			pos1=numpy.nonzero(elist==1)[0]
-			macayealflag[pos[pos1]]=True
-			macayealpattynflag[pos[pos1]]=False
+			SSAflag[pos[pos1]]=True
+			SSAHOflag[pos[pos1]]=False
 			pos2=numpy.nonzero(elist==-1)[0]
-			pattynflag[pos[pos2]]=True
-			macayealpattynflag[pos[pos2]]=False
+			HOflag[pos[pos2]]=True
+			SSAHOflag[pos[pos2]]=False
 
 			#Recompute nodes associated to these elements
-			nodeonmacayeal[:]=False
-			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:]-1]=True
-			nodeonpattyn[:]=False
-			nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:]-1]=True
-			nodeonmacayealpattyn[:]=False
-			nodeonmacayealpattyn[md.mesh.elements[numpy.nonzero(macayealpattynflag),:]-1]=True
-
-		elif any(pattynflag) and any(stokesflag):    #coupling pattyn stokes
+			nodeonSSA[:]=False
+			nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
+			nodeonHO[:]=False
+			nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
+			nodeonSSAHO[:]=False
+			nodeonSSAHO[md.mesh.elements[numpy.nonzero(SSAHOflag),:]-1]=True
+
+		elif any(HOflag) and any(FSflag):    #coupling HO FS
 			#Find node at the border
-			nodeonpattynstokes[numpy.nonzero(numpy.logical_and(nodeonpattyn,nodeonstokes))]=True
-			#Stokes elements in contact with this layer become PattynStokes elements
-			matrixelements=ismember(md.mesh.elements-1,numpy.nonzero(nodeonpattynstokes)[0])
+			nodeonHOFS[numpy.nonzero(numpy.logical_and(nodeonHO,nodeonFS))]=True
+			#FS elements in contact with this layer become HOFS elements
+			matrixelements=ismember(md.mesh.elements-1,numpy.nonzero(nodeonHOFS)[0])
 			commonelements=numpy.sum(matrixelements,axis=1)!=0
-			commonelements[numpy.nonzero(pattynflag)]=False    #only one layer: the elements previously in macayeal
-			stokesflag[numpy.nonzero(commonelements)]=False    #these elements are now macayealpattynelements
-			pattynstokesflag[numpy.nonzero(commonelements)]=True
-			nodeonstokes=numpy.zeros(md.mesh.numberofvertices,bool)
-			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:]-1]=True
+			commonelements[numpy.nonzero(HOflag)]=False    #only one layer: the elements previously in SSA
+			FSflag[numpy.nonzero(commonelements)]=False    #these elements are now SSAHOelements
+			HOFSflag[numpy.nonzero(commonelements)]=True
+			nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
+			nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
 
 			#rule out elements that don't touch the 2 boundaries
-			pos=numpy.nonzero(pattynstokesflag)[0]
+			pos=numpy.nonzero(HOFSflag)[0]
 			elist=numpy.zeros(numpy.size(pos),dtype=int)
-			elist = elist + numpy.sum(nodeonstokes[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
-			elist = elist - numpy.sum(nodeonpattyn[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
+			elist = elist + numpy.sum(nodeonFS[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
+			elist = elist - numpy.sum(nodeonHO[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
 			pos1=numpy.nonzero(elist==1)[0]
-			stokesflag[pos[pos1]]=True
-			pattynstokesflag[pos[pos1]]=False
+			FSflag[pos[pos1]]=True
+			HOFSflag[pos[pos1]]=False
 			pos2=numpy.nonzero(elist==-1)[0]
-			pattynflag[pos[pos2]]=True
-			pattynstokesflag[pos[pos2]]=False
+			HOflag[pos[pos2]]=True
+			HOFSflag[pos[pos2]]=False
 
 			#Recompute nodes associated to these elements
-			nodeonstokes[:]=False
-			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:]-1]=True
-			nodeonpattyn[:]=False
-			nodeonpattyn[md.mesh.elements[numpy.nonzero(pattynflag),:]-1]=True
-			nodeonpattynstokes[:]=False
-			nodeonpattynstokes[md.mesh.elements[numpy.nonzero(pattynstokesflag),:]-1]=True
-
-		elif any(stokesflag) and any(macayealflag):
+			nodeonFS[:]=False
+			nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
+			nodeonHO[:]=False
+			nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
+			nodeonHOFS[:]=False
+			nodeonHOFS[md.mesh.elements[numpy.nonzero(HOFSflag),:]-1]=True
+
+		elif any(FSflag) and any(SSAflag):
 			#Find node at the border
-			nodeonmacayealstokes[numpy.nonzero(numpy.logical_and(nodeonmacayeal,nodeonstokes))]=True
-			#Stokes elements in contact with this layer become MacAyealStokes elements
-			matrixelements=ismember(md.mesh.elements-1,numpy.nonzero(nodeonmacayealstokes)[0])
+			nodeonSSAFS[numpy.nonzero(numpy.logical_and(nodeonSSA,nodeonFS))]=True
+			#FS elements in contact with this layer become SSAFS elements
+			matrixelements=ismember(md.mesh.elements-1,numpy.nonzero(nodeonSSAFS)[0])
 			commonelements=numpy.sum(matrixelements,axis=1)!=0
-			commonelements[numpy.nonzero(macayealflag)]=False    #only one layer: the elements previously in macayeal
-			stokesflag[numpy.nonzero(commonelements)]=False    #these elements are now macayealmacayealelements
-			macayealstokesflag[numpy.nonzero(commonelements)]=True
-			nodeonstokes=numpy.zeros(md.mesh.numberofvertices,bool)
-			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:]-1]=True
+			commonelements[numpy.nonzero(SSAflag)]=False    #only one layer: the elements previously in SSA
+			FSflag[numpy.nonzero(commonelements)]=False    #these elements are now SSASSAelements
+			SSAFSflag[numpy.nonzero(commonelements)]=True
+			nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
+			nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
 
 			#rule out elements that don't touch the 2 boundaries
-			pos=numpy.nonzero(macayealstokesflag)[0]
+			pos=numpy.nonzero(SSAFSflag)[0]
 			elist=numpy.zeros(numpy.size(pos),dtype=int)
-			elist = elist + numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
-			elist = elist - numpy.sum(nodeonstokes[md.mesh.elements[pos,:]-1]  ,axis=1).astype(bool)
+			elist = elist + numpy.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
+			elist = elist - numpy.sum(nodeonFS[md.mesh.elements[pos,:]-1]  ,axis=1).astype(bool)
 			pos1=numpy.nonzero(elist==1)[0]
-			macayealflag[pos[pos1]]=True
-			macayealstokesflag[pos[pos1]]=False
+			SSAflag[pos[pos1]]=True
+			SSAFSflag[pos[pos1]]=False
 			pos2=numpy.nonzero(elist==-1)[0]
-			stokesflag[pos[pos2]]=True
-			macayealstokesflag[pos[pos2]]=False
+			FSflag[pos[pos2]]=True
+			SSAFSflag[pos[pos2]]=False
 
 			#Recompute nodes associated to these elements
-			nodeonmacayeal[:]=False
-			nodeonmacayeal[md.mesh.elements[numpy.nonzero(macayealflag),:]-1]=True
-			nodeonstokes[:]=False
-			nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:]-1]=True
-			nodeonmacayealstokes[:]=False
-			nodeonmacayealstokes[md.mesh.elements[numpy.nonzero(macayealstokesflag),:]-1]=True
-
-		elif any(stokesflag) and any(hutterflag):
+			nodeonSSA[:]=False
+			nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
+			nodeonFS[:]=False
+			nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
+			nodeonSSAFS[:]=False
+			nodeonSSAFS[md.mesh.elements[numpy.nonzero(SSAFSflag),:]-1]=True
+
+		elif any(FSflag) and any(SIAflag):
 			raise TypeError("type of coupling not supported yet")
 
-	#Create MacAyealPattynApproximation where needed
+	#Create SSAHOApproximation where needed
 	md.flowequation.element_equation=numpy.zeros(md.mesh.numberofelements,int)
 	md.flowequation.element_equation[numpy.nonzero(noneflag)]=0
-	md.flowequation.element_equation[numpy.nonzero(hutterflag)]=1
-	md.flowequation.element_equation[numpy.nonzero(macayealflag)]=2
-	md.flowequation.element_equation[numpy.nonzero(l1l2flag)]=8
-	md.flowequation.element_equation[numpy.nonzero(pattynflag)]=3
-	md.flowequation.element_equation[numpy.nonzero(stokesflag)]=4
-	md.flowequation.element_equation[numpy.nonzero(macayealpattynflag)]=5
-	md.flowequation.element_equation[numpy.nonzero(macayealstokesflag)]=6
-	md.flowequation.element_equation[numpy.nonzero(pattynstokesflag)]=7
+	md.flowequation.element_equation[numpy.nonzero(SIAflag)]=1
+	md.flowequation.element_equation[numpy.nonzero(SSAflag)]=2
+	md.flowequation.element_equation[numpy.nonzero(L1L2flag)]=8
+	md.flowequation.element_equation[numpy.nonzero(HOflag)]=3
+	md.flowequation.element_equation[numpy.nonzero(FSflag)]=4
+	md.flowequation.element_equation[numpy.nonzero(SSAHOflag)]=5
+	md.flowequation.element_equation[numpy.nonzero(SSAFSflag)]=6
+	md.flowequation.element_equation[numpy.nonzero(HOFSflag)]=7
 
 	#border
-	md.flowequation.borderpattyn=nodeonpattyn
-	md.flowequation.bordermacayeal=nodeonmacayeal
-	md.flowequation.borderstokes=nodeonstokes
+	md.flowequation.borderHO=nodeonHO
+	md.flowequation.borderSSA=nodeonSSA
+	md.flowequation.borderFS=nodeonFS
 
 	#Create vertices_type
 	md.flowequation.vertex_equation=numpy.zeros(md.mesh.numberofvertices,int)
-	pos=numpy.nonzero(nodeonmacayeal)
+	pos=numpy.nonzero(nodeonSSA)
 	md.flowequation.vertex_equation[pos]=2
-	pos=numpy.nonzero(nodeonl1l2)
+	pos=numpy.nonzero(nodeonL1L2)
 	md.flowequation.vertex_equation[pos]=8
-	pos=numpy.nonzero(nodeonpattyn)
+	pos=numpy.nonzero(nodeonHO)
 	md.flowequation.vertex_equation[pos]=3
-	pos=numpy.nonzero(nodeonhutter)
+	pos=numpy.nonzero(nodeonSIA)
 	md.flowequation.vertex_equation[pos]=1
-	pos=numpy.nonzero(nodeonmacayealpattyn)
+	pos=numpy.nonzero(nodeonSSAHO)
 	md.flowequation.vertex_equation[pos]=5
-	pos=numpy.nonzero(nodeonstokes)
+	pos=numpy.nonzero(nodeonFS)
 	md.flowequation.vertex_equation[pos]=4
-	if any(stokesflag):
-		pos=numpy.nonzero(numpy.logical_not(nodeonstokes))
-		if not (any(pattynflag) or any(macayealflag)):
+	if any(FSflag):
+		pos=numpy.nonzero(numpy.logical_not(nodeonFS))
+		if not (any(HOflag) or any(SSAflag)):
 			md.flowequation.vertex_equation[pos]=0
-	pos=numpy.nonzero(nodeonpattynstokes)
+	pos=numpy.nonzero(nodeonHOFS)
 	md.flowequation.vertex_equation[pos]=7
-	pos=numpy.nonzero(nodeonmacayealstokes)
+	pos=numpy.nonzero(nodeonSSAFS)
 	md.flowequation.vertex_equation[pos]=6
 
 	#figure out solution types
-	md.flowequation.ishutter=any(md.flowequation.element_equation==1)
-	md.flowequation.ismacayealpattyn=bool(numpy.any(numpy.logical_or(md.flowequation.element_equation==2,md.flowequation.element_equation==3)))
-	md.flowequation.isl1l2=any(md.flowequation.element_equation==8)
-	md.flowequation.isstokes=any(md.flowequation.element_equation==4)
+	md.flowequation.isSIA=any(md.flowequation.element_equation==1)
+	md.flowequation.isSSA=any(md.flowequation.element_equation==2)
+	md.flowequation.isL1L2=any(md.flowequation.element_equation==8)
+	md.flowequation.isHO=any(md.flowequation.element_equation==3)
+	md.flowequation.isFS=any(md.flowequation.element_equation==4)
 
 	return md
 
 	#Check that tiling can work:
-	if any(md.flowequation.bordermacayeal) and any(md.flowequation.borderpattyn) and any(md.flowequation.borderpattyn + md.flowequation.bordermacayeal !=1):
+	if any(md.flowequation.borderSSA) and any(md.flowequation.borderHO) and any(md.flowequation.borderHO + md.flowequation.borderSSA !=1):
 		raise TypeError("error coupling domain too irregular")
-	if any(md.flowequation.bordermacayeal) and any(md.flowequation.borderstokes) and any(md.flowequation.borderstokes + md.flowequation.bordermacayeal !=1):
+	if any(md.flowequation.borderSSA) and any(md.flowequation.borderFS) and any(md.flowequation.borderFS + md.flowequation.borderSSA !=1):
 		raise TypeError("error coupling domain too irregular")
-	if any(md.flowequation.borderstokes) and any(md.flowequation.borderpattyn) and any(md.flowequation.borderpattyn + md.flowequation.borderstokes !=1):
+	if any(md.flowequation.borderFS) and any(md.flowequation.borderHO) and any(md.flowequation.borderHO + md.flowequation.borderFS !=1):
 		raise TypeError("error coupling domain too irregular")
 
Index: /issm/trunk/src/m/parameterization/setmask.m
===================================================================
--- /issm/trunk/src/m/parameterization/setmask.m	(revision 16136)
+++ /issm/trunk/src/m/parameterization/setmask.m	(revision 16137)
@@ -41,9 +41,6 @@
 %}}}
 
-%Return: 
-md.mask.elementonfloatingice=elementonfloatingice;
-md.mask.vertexonfloatingice=vertexonfloatingice;
-md.mask.elementongroundedice=elementongroundedice;
-md.mask.vertexongroundedice=vertexongroundedice;
-md.mask.vertexonwater=zeros(md.mesh.numberofvertices,1);
-md.mask.elementonwater=zeros(md.mesh.numberofelements,1);
+%level sets
+md.mask.ice_levelset=ones(md.mesh.numberofvertices,1);
+md.mask.groundedice_levelset=vertexongroundedice;
+md.mask.groundedice_levelset(find(vertexongroundedice==0.))=-1.;
Index: /issm/trunk/src/m/parameterization/setmask.py
===================================================================
--- /issm/trunk/src/m/parameterization/setmask.py	(revision 16136)
+++ /issm/trunk/src/m/parameterization/setmask.py	(revision 16137)
@@ -41,11 +41,8 @@
 	#}}}
 
-	#Return: 
-	md.mask.elementonfloatingice = elementonfloatingice
-	md.mask.vertexonfloatingice = vertexonfloatingice
-	md.mask.elementongroundedice = elementongroundedice
-	md.mask.vertexongroundedice = vertexongroundedice
-	md.mask.vertexonwater = numpy.zeros(md.mesh.numberofvertices,bool)
-	md.mask.elementonwater = numpy.zeros(md.mesh.numberofelements,bool)
+	#level sets
+	md.mask.ice_levelset         = numpy.ones(md.mesh.numberofvertices,bool)
+	md.mask.groundedice_levelset = -1.*numpy.ones((md.mesh.numberofvertices,1))
+	md.mask.groundedice_levelset[md.mesh.elements[numpy.nonzero(elementongroundedice),:]-1]=1.
 
 	return md
Index: /issm/trunk/src/m/parameterization/setmask2.m
===================================================================
--- /issm/trunk/src/m/parameterization/setmask2.m	(revision 16136)
+++ /issm/trunk/src/m/parameterization/setmask2.m	(revision 16137)
@@ -139,10 +139,3 @@
 
 %Return: 
-md.mask.vertexonfloatingice=vertexonfloatingice;
-md.mask.elementonfloatingice=elementonfloatingice;
-md.mask.vertexonwater=vertexonwater;
-md.mask.elementonwater=elementonwater;
-md.mask.vertexongroundedice=vertexongroundedice;
-md.mask.elementongroundedice=elementongroundedice;
-
 md.mesh.segmentmarkers(:)=1;
Index: /issm/trunk/src/m/plot/applyoptions.m
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.m	(revision 16136)
+++ /issm/trunk/src/m/plot/applyoptions.m	(revision 16137)
@@ -241,16 +241,18 @@
 
 %expdisp
-filename=(getfieldvalue(options,'expdisp'));
-style=(getfieldvalue(options,'expstyle'));
-linewidth=(getfieldvalue(options,'linewidth',1));
-for i=1:length(getfieldvalue(options,'expdisp')),
-	filenamei=filename{i};
-	stylei=style{i};
-	if length(linewidth)==1,
-		linewidthi=linewidth;
-	else
-		linewidthi=linewidth{i};
-	end
-	expdisp(filenamei,gcf,stylei,linewidthi,getfieldvalue(options,'unit',1));
+if exist(options,'expdisp'),
+	filename=(getfieldvalue(options,'expdisp'));
+	style=(getfieldvalue(options,'expstyle'));
+	linewidth=(getfieldvalue(options,'linewidth',1));
+	for i=1:length(getfieldvalue(options,'expdisp')),
+		filenamei=filename{i};
+		stylei=style{i};
+		if length(linewidth)==1,
+			linewidthi=linewidth;
+		else
+			linewidthi=linewidth{i};
+		end
+		expdisp(filenamei,gcf,stylei,getfieldvalue(options,'linewidth',1),getfieldvalue(options,'unit',1));
+	end
 end
 
@@ -356,10 +358,10 @@
 	%box off
 	if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
-		A=expread([ jplsvn() '/projects/ModelData/Exp/GreenlandBoxFront.exp']);
+		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'),
-		A=expread([ jplsvn() '/projects/ModelData/Exp/Antarctica.exp']);
+		A=expread('/u/astrid-r1b/ModelData/Exp/Antarctica.exp');
 	else
 		error('applyoptions error message: hemisphere not defined');
Index: /issm/trunk/src/m/plot/applyoptions.py
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.py	(revision 16136)
+++ /issm/trunk/src/m/plot/applyoptions.py	(revision 16137)
@@ -1,5 +1,4 @@
-from matplotlib.ticker import MaxNLocator
-
 try:
+	from matplotlib.ticker import MaxNLocator
 	import pylab as p
 except ImportError:
Index: /issm/trunk/src/m/plot/manualcb.m
===================================================================
--- /issm/trunk/src/m/plot/manualcb.m	(revision 16136)
+++ /issm/trunk/src/m/plot/manualcb.m	(revision 16137)
@@ -13,4 +13,5 @@
 %      - 'tick'        : specified values of tick labels
 %      - 'ticksep'     : spacing between ticks
+%      - 'inverttickposition' : put ticks on the left hand side for vertical cb
 
 %check inputs
@@ -53,10 +54,15 @@
 
 %Prepare ticks
-deltaz = getfieldvalue(options,'ticksep',dtick(zmax-zmin));
-ztick  = getfieldvalue(options,'tick',(deltaz*ceil(zmin/deltaz)):deltaz:zmax);
-if (any(ztick>zmax) | any(ztick<zmin)),
-	error('one or more specified tick values falls outside of [zmin,zmax]');
+if ~exist(options,'log'),
+	deltaz = getfieldvalue(options,'ticksep',dtick(zmax-zmin));
+	ztick  = getfieldvalue(options,'tick',(deltaz*ceil(zmin/deltaz)):deltaz:zmax);
+	if (any(ztick>zmax) | any(ztick<zmin)),
+		error('one or more specified tick values falls outside of [zmin,zmax]');
+	end
+	ytick  = (ztick-zmin)/(zmax-zmin);
+else
+	ztick = getfieldvalue(options,'tick',round(logspace(log(zmin)/log(10),log(zmax)/log(10),8)));
+	ytick = linspace(0,1,numel(ztick));
 end
-ytick  = (ztick-zmin)/(zmax-zmin);
 
 %Display colorbar
@@ -73,5 +79,9 @@
 if strcmpi(getfieldvalue(options,'orientation','vertical'),'vertical'),
 	%Use FOR LOOP otherwise numbers are not correcly centered
-	for i=1:length(ytick), text(1.5,ytick(i),num2str(ztick(i)),'HorizontalAlignment','left','VerticalAlignment','middle','FontSize',fontsize); end
+	if getfieldvalue(options,'inverttickposition',0)==1,
+		for i=1:length(ytick), text(-0.5,ytick(i),num2str(ztick(i)),'HorizontalAlignment','right','VerticalAlignment','middle','FontSize',fontsize); end
+	else
+		for i=1:length(ytick), text(1.5,ytick(i),num2str(ztick(i)),'HorizontalAlignment','left','VerticalAlignment','middle','FontSize',fontsize); end
+	end
 	if smallbars,
 		for i=1:numel(ztick)
@@ -92,17 +102,17 @@
 
 if exist(options,'title'),
+	title(getfieldvalue(options,'title'),'FontSize',fontsize);
+end
+if exist(options,'ylabel'),
 	if strcmpi(getfieldvalue(options,'orientation','vertical'),'horizontal'),
 		th=title(getfieldvalue(options,'title'),'FontSize',fontsize);
 		set(th,'Position',[ytick(end)+0.075,-0.3]);
 	else
-		title(getfieldvalue(options,'title'),'FontSize',fontsize);
+		ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize);
 	end
-end
-if exist(options,'ylabel'),
-	ylabel(getfieldvalue(options,'ylabel'),'FontSize',fontsize);
 end
 	
 %Back to original axes
-if strcmpi(getfieldvalue(options,'showregion',0),0)
+if getfieldvalue(options,'showregion',0)==0,
 	axes(mainaxes);
 end
Index: /issm/trunk/src/m/plot/plot_BC.m
===================================================================
--- /issm/trunk/src/m/plot/plot_BC.m	(revision 16136)
+++ /issm/trunk/src/m/plot/plot_BC.m	(revision 16137)
@@ -10,17 +10,17 @@
 if strcmpi(dirichleton,'on'),
 	h1=plot3(...
-		md.mesh.x(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.y(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.z(find(~isnan(md.diagnostic.spcvx(1:md.mesh.numberofvertices,1)))),...
+		md.mesh.x(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
+		md.mesh.y(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
+		md.mesh.z(find(~isnan(md.stressbalance.spcvx(1:md.mesh.numberofvertices,1)))),...
 		'ro','MarkerSize',14,'MarkerFaceColor','r');
 	h2=plot3(...
-		md.mesh.x(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.y(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.z(find(~isnan(md.diagnostic.spcvy(1:md.mesh.numberofvertices,1)))),...
+		md.mesh.x(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
+		md.mesh.y(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
+		md.mesh.z(find(~isnan(md.stressbalance.spcvy(1:md.mesh.numberofvertices,1)))),...
 		'bo','MarkerSize',10,'MarkerFaceColor','b');
 	h3=plot3(...
-		md.mesh.x(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.y(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
-		md.mesh.z(find(~isnan(md.diagnostic.spcvz(1:md.mesh.numberofvertices,1)))),...
+		md.mesh.x(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
+		md.mesh.y(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
+		md.mesh.z(find(~isnan(md.stressbalance.spcvz(1:md.mesh.numberofvertices,1)))),...
 		'yo','MarkerSize',6 ,'MarkerFaceColor','y');
 end
Index: /issm/trunk/src/m/plot/plot_elementnumbering.m
===================================================================
--- /issm/trunk/src/m/plot/plot_elementnumbering.m	(revision 16136)
+++ /issm/trunk/src/m/plot/plot_elementnumbering.m	(revision 16137)
@@ -26,5 +26,5 @@
 	%numbering
 	text(sum(x(elements(:,1:3)),2)/3,sum(y(elements(:,1:3)),2)/3,sum(z(elements(:,1:3)),2)/3,...
-		num2str(transpose(1:size(elements,1))),...
+		num2str(elementnumbers),...
 		'HorizontalAlignment','center','VerticalAlignment','middle');
 else
@@ -48,5 +48,5 @@
 	%numbering
 	text(sum(x(elements(:,1:6)),2)/6,sum(y(elements(:,1:6)),2)/6,sum(z(elements(:,1:6)),2)/6,...
-		num2str(transpose(1:size(elements,1))),...
+		num2str(elementnumbers),...
 		'HorizontalAlignment','center','VerticalAlignment','middle');
 end
Index: /issm/trunk/src/m/plot/plot_elementstype.m
===================================================================
--- /issm/trunk/src/m/plot/plot_elementstype.m	(revision 16136)
+++ /issm/trunk/src/m/plot/plot_elementstype.m	(revision 16137)
@@ -18,29 +18,29 @@
 
 if is2d
-	%Hutter elements
+	%SIA elements
 	posH=find(data==1);
 	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); 
 	p1=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',1,'FaceColor','flat','EdgeColor',edgecolor);
-	%MacAyeal element
+	%SSA element
 	posM=find(data==2);
 	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); 
 	p2=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',2,'FaceColor','flat','EdgeColor',edgecolor);
-	%Pattyn element
+	%HO element
 	posP=find(data==3);
 	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); 
 	p3=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',3,'FaceColor','flat','EdgeColor',edgecolor);
-	%MacAyealPattyn element
+	%SSAHO element
 	posMP=find(data==5);
 	A=elements(posMP,1); B=elements(posMP,2); C=elements(posMP,3); 
 	p5=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',5,'FaceColor','flat','EdgeColor',edgecolor);
-	%Stokes elements
+	%FS elements
 	posS=find(data==4);
 	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); 
 	p6=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',4,'FaceColor','flat','EdgeColor',edgecolor);
-	%MacAyealStokes elements
+	%SSAFS elements
 	posMS=find(data==6);
 	A=elements(posMS,1); B=elements(posMS,2); C=elements(posMS,3); 
 	p7=patch( 'Faces', [A B C], 'Vertices', [x y z],'CData',6,'FaceColor','flat','EdgeColor',edgecolor);
-	%PattynStokes elements
+	%HOFS elements
 	posPS=find(data==7);
 	A=elements(posPS,1); B=elements(posPS,2); C=elements(posPS,3); 
@@ -52,9 +52,9 @@
 
 	legend([p1 p2 p3 p5 p6 p7 p8 p9],...
-		'Hutter''s elements','MacAyeal''s elements','Pattyn''s elements',...
-		'MacAyealPattyn''s elements','Stokes''s elements','MacAyealStokes''s elements','PattynStokes''s elements','None element');
+		'SIA''s elements','SSA''s elements','HO''s elements',...
+		'SSAHO''s elements','FS''s elements','SSAFS''s elements','HOFS''s elements','None element');
 
 else
-	%Hutter elements
+	%SIA elements
 	posH=find(data==1);
 	A=elements(posH,1); B=elements(posH,2); C=elements(posH,3); D=elements(posH,4); E=elements(posH,5); F=elements(posH,6);
@@ -64,5 +64,5 @@
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 1,'FaceColor','flat','EdgeColor',edgecolor);
-	%MacAyeal elements
+	%SSA elements
 	posM=find(data==2);
 	A=elements(posM,1); B=elements(posM,2); C=elements(posM,3); D=elements(posM,4); E=elements(posM,5); F=elements(posM,6);
@@ -72,5 +72,5 @@
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 2,'FaceColor','flat','EdgeColor',edgecolor);
-	%Pattyn elements
+	%HO elements
 	posP=find(data==3);
 	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
@@ -80,5 +80,5 @@
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 3,'FaceColor','flat','EdgeColor',edgecolor);
-	%Stokes elements
+	%FS elements
 	posS=find(data==4);
 	A=elements(posS,1); B=elements(posS,2); C=elements(posS,3); D=elements(posS,4); E=elements(posS,5); F=elements(posS,6);
@@ -88,5 +88,5 @@
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 4,'FaceColor','flat','EdgeColor',edgecolor);
-	%MacAyealPattyn elements
+	%SSAHO elements
 	posP=find(data==5);
 	A=elements(posP,1); B=elements(posP,2); C=elements(posP,3); D=elements(posP,4); E=elements(posP,5); F=elements(posP,6);
@@ -96,5 +96,5 @@
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 5,'FaceColor','flat','EdgeColor',edgecolor);
-	%PattynStokes elements
+	%HOFS elements
 	PosPS=find(data==7);
 	A=elements(PosPS,1); B=elements(PosPS,2); C=elements(PosPS,3); D=elements(PosPS,4); E=elements(PosPS,5); F=elements(PosPS,6);
@@ -104,5 +104,5 @@
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'CData', 7,'FaceColor','flat','EdgeColor',edgecolor);
-	%MacAyealStokes elements
+	%SSAFS elements
 	PosMS=find(data==6);
 	A=elements(PosMS,1); B=elements(PosMS,2); C=elements(PosMS,3); D=elements(PosMS,4); E=elements(PosMS,5); F=elements(PosMS,6);
@@ -122,6 +122,6 @@
 
 	legend([p1 p2 p3 p4 p5 p6 p7 p8],...
-		'Hutter''s elements','MacAyeal''s elements','Pattyn''s elements','Stokes''s elements',...
-		'MacAyealPattyn''s elements','PattynStokes''s elements','MacAyealStokes''s elements','None elements');
+		'SIA''s elements','SSA''s elements','HO''s elements','FS''s elements',...
+		'SSAHO''s elements','HOFS''s elements','SSAFS''s elements','None elements');
 end
 
Index: /issm/trunk/src/m/plot/plot_gridded.m
===================================================================
--- /issm/trunk/src/m/plot/plot_gridded.m	(revision 16136)
+++ /issm/trunk/src/m/plot/plot_gridded.m	(revision 16137)
@@ -23,15 +23,11 @@
 %Interpolating data on grid
 [x_m y_m data_grid]=InterpFromMeshToGrid(elements,x,y,data,xlim(1),ylim(2),post,post,round(diff(ylim)/post),round(diff(xlim)/post),NaN);
+data_grid_save = data_grid;
 if size(data_grid,1)<3 | size(data_grid,2)<3,
 	error('data_grid size too small in plot_gridded, check posting and units');
 end
 
-%Get and change colormap
-map    = getcolormap(options);
-lenmap = size(map,1);
-map    = [1 1 1; map];
-options=changefieldvalue(options,'colormap',map);
-
 %Process data_grid: add white in NaN and correct caxis accordingly
+[data_nani data_nanj]=find(isnan(data_grid) | data_grid==-9999);
 if exist(options,'caxis'),
 	caxis_opt=getfieldvalue(options,'caxis');
@@ -44,8 +40,4 @@
 	data_max=max(data_grid(:));
 end
-options = changefieldvalue(options,'cbYLim',[data_min data_max]);
-white   = data_min - (data_max-data_min)/(lenmap);
-options = changefieldvalue(options,'caxis',[white data_max]);
-data_grid(isnan(data_grid))=white;
 
 %Select plot area 
@@ -53,10 +45,36 @@
 
 %shading interp;
-if exist(options,'forcecolormap'),
-	image_rgb = ind2rgb(uint16((data_grid - data_min)*(length(map)/(data_max-data_min))),map);
-	h=imagesc(xlim,ylim,image_rgb);
-else
-	h=imagesc(xlim,ylim,data_grid);
+map    = getcolormap(options);
+image_rgb = ind2rgb(uint16((data_grid - data_min)*(length(map)/(data_max-data_min))),map);
+if exist(options,'shaded'),
+	a    = -45;
+	scut = 0.2;
+	c    = 1;
+	% computes lighting from elevation gradient
+	[fx,fy] = gradient(data_grid_save,x_m,y_m);
+	fxy = -fx*sind(a) - fy*cosd(a);
+	clear fx fy % free some memory...
+	fxy(isnan(fxy)) = 0;
+
+	% computes maximum absolute gradient (median-style), normalizes, saturates and duplicates in 3-D matrix
+	r = repmat(max(min(fxy/nmedian(abs(fxy),1 - scut/100),1),-1),[1,1,3]);
+
+	% applies contrast using exponent
+	rp = (1 - abs(r)).^c;
+	image_rgb = image_rgb.*rp;
+
+	% lighter for positive gradient
+	k = find(r > 0);
+	image_rgb(k) = image_rgb(k) + (1 - rp(k));
 end
+
+% set novalues / NaN to black color
+if ~isempty(data_nani)
+	nancolor=getfieldvalue(options,'nancolor',[1 1 1]);
+	image_rgb(sub2ind(size(image_rgb),repmat(data_nani,1,3),repmat(data_nanj,1,3),repmat(1:3,size(data_nani,1),1))) = repmat(nancolor,size(data_nani,1),1);
+end
+
+%plot grid
+h=imagesc(xlim,ylim,image_rgb);
 axis xy
 
@@ -68,3 +86,7 @@
 
 %Apply options
+if ~isnan(data_min),
+	options=changefieldvalue(options,'caxis',[data_min data_max]); % force caxis so that the colorbar is ready
+end
+options=addfielddefault(options,'axis','xy equal'); % default axis
 applyoptions(md,data,options);
Index: /issm/trunk/src/m/plot/plot_icefront.m
===================================================================
--- /issm/trunk/src/m/plot/plot_icefront.m	(revision 16136)
+++ /issm/trunk/src/m/plot/plot_icefront.m	(revision 16137)
@@ -12,7 +12,13 @@
 %process mesh and data
 [x y z elements is2d isplanet]=processmesh(md,[],options);
-icefront=md.diagnostic.icefront;
+ice=(md.mask.ice_levelset>0);
+noice=(md.mask.ice_levelset<=0);
+zeroice=(md.mask.ice_levelset==0);
+elementice=sum(ice(md.mesh.elements),2);
+elementnoice=sum(noice(md.mesh.elements),2);
+elementzeroice=sum(zeroice(md.mesh.elements),2);
 
 if (md.mesh.dimension==2),
+	icefront=(elementice & elementnoice) & ~(elementice==2 & elementzeroice);
 
 	%plot mesh
@@ -22,29 +28,13 @@
 
 	%highlight elements on neumann
-	pos=find(icefront(:,end)==1);
-	pos=icefront(pos,end-1);
+	pos=find(icefront);
 	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
 	h2=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
-	pos=find(icefront(:,end)==0);
-	pos=icefront(pos,end-1);
-	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
-	h3=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
+	hold on;
 
-	pos=find(icefront(:,end)==2);
-	pos=icefront(pos,end-1);
-	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); 
-	h3bis=patch( 'Faces', [A B C], 'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
+	%Plot zero ice_levelset line
 
-	%display arrows pointing outward
-	xstart=mean(x(icefront(:,1:end-2)),2);
-	ystart=mean(y(icefront(:,1:end-2)),2);
-	length=sqrt((x(icefront(:,1))-x(icefront(:,2))).^2 + (y(icefront(:,1))-y(icefront(:,2))).^2 );
-	normal(:,1)=cos(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
-	normal(:,2)=sin(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
-	xend=xstart+length.*normal(:,1);
-	yend=ystart+length.*normal(:,2);
-	q=quiver(xstart,ystart,xend-xstart,yend-ystart); hold on;
-	h4=plot(xstart,ystart,'r*');
 else
+	icefront=(elementice & elementnoice) & ~(elementice==4 & elementzeroice);
 
 	%plot mesh
@@ -58,6 +48,5 @@
 
 	%highlight elements on neumann
-	pos=find(icefront(:,end)==1);
-	pos=icefront(pos,end-1);
+	pos=find(icefront);
 	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
 	h2=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
@@ -66,37 +55,9 @@
 	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
 	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','blue','EdgeColor','black');
-	pos=find(icefront(:,end)==0);
-	pos=icefront(pos,end-1);
-	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
-	h3=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
-	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
-	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
-	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
-	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','green','EdgeColor','black');
-	pos=find(icefront(:,end)==2);
-	pos=icefront(pos,end-1);
-	A=elements(pos,1); B=elements(pos,2); C=elements(pos,3); D=elements(pos,4); E=elements(pos,5); F=elements(pos,6);
-	h3bis=patch( 'Faces', [A B C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
-	patch( 'Faces', [D E F],  'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
-	patch( 'Faces', [A B E D],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
-	patch( 'Faces', [B E F C],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
-	patch( 'Faces', [C A D F],'Vertices', [x y z],'FaceVertexCData', [1 1 1],'FaceColor','cyan','EdgeColor','black');
-
-	%display arrows pointing outward
-	xstart=mean(x(icefront(:,1:end-2)),2);
-	ystart=mean(y(icefront(:,1:end-2)),2);
-	zstart=mean(z(icefront(:,1:end-2)),2);
-	length=sqrt((x(icefront(:,1))-x(icefront(:,2))).^2 + (y(icefront(:,1))-y(icefront(:,2))).^2 );
-	normal(:,1)=cos(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
-	normal(:,2)=sin(atan2((x(icefront(:,1))-x(icefront(:,2))) , (y(icefront(:,2))-y(icefront(:,1)))));
-	xend=xstart+length.*normal(:,1);
-	yend=ystart+length.*normal(:,2);
-	q=quiver3(xstart,ystart,zstart,xend-xstart,yend-ystart,zeros(numel(xstart),1)); hold on;
-	h4=plot3(xstart,ystart,zstart,'r*');
 end
 
 %legend (disable warnings)
 warning off
-legend([h2,h3,h3bis,q],'element on ice front (Water)','element on ice front (Air)','element on ice front (Ice)','normal vectors')
+legend([h2],'element on ice front')
 warning on
 
Index: /issm/trunk/src/m/plot/plot_mesh.py
===================================================================
--- /issm/trunk/src/m/plot/plot_mesh.py	(revision 16136)
+++ /issm/trunk/src/m/plot/plot_mesh.py	(revision 16137)
@@ -28,3 +28,4 @@
 	#apply options
 	options.addfielddefault('title','Mesh')
+	options.addfielddefault('colorbar','off')
 	applyoptions(md,[],options)
Index: /issm/trunk/src/m/plot/plot_penalties.m
===================================================================
--- /issm/trunk/src/m/plot/plot_penalties.m	(revision 16136)
+++ /issm/trunk/src/m/plot/plot_penalties.m	(revision 16137)
@@ -40,5 +40,5 @@
 		P2=plot3(x(md.penalties(i,:)),y(md.penalties(i,:)),z(md.penalties(i,:)),'bo-','LineWidth',2,'MarkerSize',8,'MarkerFaceColor','b');
 	end
-	legend([P1 P2],'MacAyeal''s penalized nodes','Pattyn''s penalized nodes');
+	legend([P1 P2],'SSA''s penalized nodes','HO''s penalized nodes');
 end
 
Index: /issm/trunk/src/m/plot/plot_referential.m
===================================================================
--- /issm/trunk/src/m/plot/plot_referential.m	(revision 16136)
+++ /issm/trunk/src/m/plot/plot_referential.m	(revision 16137)
@@ -12,7 +12,7 @@
 %process mesh and data
 [x y z elements is2d isplanet]=processmesh(md,[],options);
-referential=md.diagnostic.referential;
+referential=md.stressbalance.referential;
 
-Xhat=md.diagnostic.referential(:,1:3);
+Xhat=md.stressbalance.referential(:,1:3);
 pos=find(sum(isnan(Xhat),2));
 Xhat(pos,:)=repmat([1 0 0],size(pos,1),1);
@@ -20,5 +20,5 @@
 Xhat=Xhat./[Xhatnorm Xhatnorm Xhatnorm];
 
-Zhat=md.diagnostic.referential(:,4:6);
+Zhat=md.stressbalance.referential(:,4:6);
 pos=find(sum(isnan(Zhat),2));
 Zhat(pos,:)=repmat([0 0 1],size(pos,1),1);
@@ -87,5 +87,5 @@
 
 %apply options
-options=addfielddefault(options,'title','Diagnostic referential');
+options=addfielddefault(options,'title','Stressbalance referential');
 options=addfielddefault(options,'colorbar',0);
 applyoptions(md,[],options);
Index: /issm/trunk/src/m/plot/plot_scatter.m
===================================================================
--- /issm/trunk/src/m/plot/plot_scatter.m	(revision 16136)
+++ /issm/trunk/src/m/plot/plot_scatter.m	(revision 16137)
@@ -1,5 +1,19 @@
 function plot_scatter(x,y,level,varargin),
+%PLOT_SCATTER - scatter plot
+%
+%   Usage:
+%      plot_scatter(x,y,level,options);
+%
+%   Available options:
+%      'MarkerSize' : default is 3
+%      'Line'       : use line instead of circles
+%      'Cutoff'     : cut the line if the distance between 2 points is
+%                     greater than Cutoff (default is 1000)
 
-options=pairoptions(varargin{:}); 
+if nargin == 4,
+	options = varargin{1};
+else
+	options=pairoptions(varargin{:}); 
+end
 
 %check input
@@ -47,10 +61,26 @@
 hold on
 hp=[];
-for i=1:numcolors
-	pos=find(colorind==i);
-	hprime=plot3(x(pos),y(pos),ones(size(x(pos))),...
-		'o','MarkerSize',getfieldvalue(options,'MarkerSize',3),'MarkerEdgeColor',palette(i,:),...
-		'MarkerFaceColor',palette(i,:));
-	hp=[hp;hprime];
+if ~exist(options,'line'),
+	for i=1:numcolors
+		pos=find(colorind==i);
+		hprime=plot3(x(pos),y(pos),ones(size(x(pos))),...
+			'o','MarkerSize',getfieldvalue(options,'MarkerSize',3),'MarkerEdgeColor',palette(i,:),...
+			'MarkerFaceColor',palette(i,:));
+		hp=[hp;hprime];
+	end
+else
+	distances = sqrt( (x(1:end-1)-x(2:end)).^2 + (y(1:end-1)-y(2:end)).^2);
+	pos=find(distances>getfieldvalue(options,'Cutoff',1000));
+	x(pos,:)=NaN;
+	y(pos,:)=NaN;
+	for j=1:numcolors;
+		pos=find(colorind==j);
+		if(~isempty(pos) & pos(1)==1), pos(1)=[]; end
+		if ~isempty(pos),
+			tempx = [x(pos-1) x(pos) NaN(size(pos))]';
+			tempy = [y(pos-1) y(pos) NaN(size(pos))]';
+			line(tempx(1:end-1),tempy(1:end-1),'color',palette(j,:),'linewidth',getfieldvalue(options,'LineWidth',2));
+		end
+	end
 end
 
Index: /issm/trunk/src/m/plot/plot_vertexnumbering.m
===================================================================
--- /issm/trunk/src/m/plot/plot_vertexnumbering.m	(revision 16136)
+++ /issm/trunk/src/m/plot/plot_vertexnumbering.m	(revision 16137)
@@ -20,5 +20,5 @@
 
 	%numbering
-	text(x,y,z,num2str(transpose(1:size(x,1))),...
+	text(x,y,z,num2str(vertexnumbers),...
 		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
 
@@ -37,5 +37,5 @@
 
 	%numbering
-	text(x,y,z,num2str(transpose(1:size(x,1))),...
+	text(x,y,z,num2str(vertexnumbers),...
 		'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
 
Index: /issm/trunk/src/m/plot/plotdoc.m
===================================================================
--- /issm/trunk/src/m/plot/plotdoc.m	(revision 16136)
+++ /issm/trunk/src/m/plot/plotdoc.m	(revision 16137)
@@ -27,5 +27,5 @@
 disp('                  - ''highlightvertices'': to highlight vertices (use highlight option to enter the vertex list');
 disp('                  - ''mesh'': draw mesh using trisurf');
-disp('                  - ''referential'': diagnostic referential');
+disp('                  - ''referential'': stressbalance referential');
 disp('                  - ''riftvel'': velocities along rifts');
 disp('                  - ''riftrelvel'': relative velocities along rifts');
Index: /issm/trunk/src/m/plot/plotmodel.py
===================================================================
--- /issm/trunk/src/m/plot/plotmodel.py	(revision 16136)
+++ /issm/trunk/src/m/plot/plotmodel.py	(revision 16137)
@@ -51,4 +51,5 @@
 		#Create figure
 		#plots will be visible by default if ipython is run in interactive mode (invoked by ipython --pylab)
+		#UNLESS plotmodel is called within a script (e.g. a runme.py file) 
 		#handling the 'visible' option will need some check on whether ipython is currently in interactive or non-interactive mode
 
@@ -65,4 +66,5 @@
 		#except StandardError:
 		#	print 'error in plot_manager'
+		p.show()
 	else:
 		raise StandardError('plotmodel error message: no output data found.')
Index: /issm/trunk/src/m/plot/processmesh.py
===================================================================
--- /issm/trunk/src/m/plot/processmesh.py	(revision 16136)
+++ /issm/trunk/src/m/plot/processmesh.py	(revision 16137)
@@ -6,5 +6,5 @@
 
 	Usage:
-		[x y z elements is2d]=processmech(md,data,options)
+		x,y,z,elements,is2d=processmech(md,data,options)
 
 	See also: PLOTMODEL, PROCESSDATA
Index: /issm/trunk/src/m/plot/scaleruler.m
===================================================================
--- /issm/trunk/src/m/plot/scaleruler.m	(revision 16136)
+++ /issm/trunk/src/m/plot/scaleruler.m	(revision 16137)
@@ -10,4 +10,5 @@
 fontweight = getfieldvalue(options,'fontweight','n');
 fontsize   = getfieldvalue(options,'scaleruler_fontsize',16);
+unitscale  = getfieldvalue(options,'unit',1.);
 
 %Go through structure and fill missing arguments
@@ -17,13 +18,13 @@
 
 %retrieve scale parameters
-x0            = structure(1);
-y0            = structure(2);
-lengthscale   = structure(3);
-widthscale    = structure(4);
-numberofticks = structure(5);
+x0            = double(structure(1))/unitscale;
+y0            = double(structure(2))/unitscale;
+lengthscale   = double(structure(3))/unitscale;
+widthscale    = double(structure(4))/unitscale;
+numberofticks = double(structure(5));
 
 %If only one tick, just draw a rectangle
 if numberofticks==1,
-	text(x0+lengthscale/2,y0+2*widthscale,2,[num2str(lengthscale/1000) 'km'],...
+	text(x0+lengthscale/2,y0+2*widthscale,2,[num2str(lengthscale*unitscale/1000) ' km'],...
 		'FontSize',fontsize,'FontWeight',fontweight,'Color',fontcolor,'HorizontalAlignment','center','VerticalAlignment','baseline');
 	patch([x0 x0+lengthscale x0+lengthscale x0],[y0 y0 y0+widthscale y0+widthscale],2*ones(1,4),fontcolor,'Edgecolor',fontcolor);
@@ -48,5 +49,5 @@
 		Bu=[Au(1)+unitlength Ad(2)+widthscale];
 		Bd=[Ad(1)+unitlength Ad(2)];
-		Tick=Tick+unitlength;
+		Tick=(Tick+unitlength)*unitscale;
 
 		%pathes
Index: /issm/trunk/src/m/plot/showregion.m
===================================================================
--- /issm/trunk/src/m/plot/showregion.m	(revision 16136)
+++ /issm/trunk/src/m/plot/showregion.m	(revision 16137)
@@ -16,7 +16,7 @@
 %box off
 if strcmpi(md.mesh.hemisphere,'n') | strcmpi(md.mesh.hemisphere,'north'),
-	A=expread([issmdir() 'projects/Exp/Greenland.exp']);
+	A=expread(['/u/astrid-r1b/ModelData/Exp/Greenland.exp']);
 elseif strcmpi(md.mesh.hemisphere,'s') | strcmpi(md.mesh.hemisphere,'south'),
-	A=expread([issmdir() '/projects/Exp/Antarctica.exp']);
+	A=expread(['/u/astrid-r1b/ModelData/Exp/Antarctica.exp']);
 else
 	error('applyoptions error message: hemisphere not defined');
Index: /issm/trunk/src/m/qmu/dakota_m_write.m
===================================================================
--- /issm/trunk/src/m/qmu/dakota_m_write.m	(revision 16136)
+++ /issm/trunk/src/m/qmu/dakota_m_write.m	(revision 16137)
@@ -207,5 +207,5 @@
 fprintf(fidm,'%%  Run the solution.\n\n');
 
-fprintf(fidm,['\tmd=solve(md,''diagnostic'',''' package ''');\n\n']);
+fprintf(fidm,['\tmd=solve(md,''stressbalance'',''' package ''');\n\n']);
 
 end
Index: /issm/trunk/src/m/qmu/examples/direct.m
===================================================================
--- /issm/trunk/src/m/qmu/examples/direct.m	(revision 16136)
+++ /issm/trunk/src/m/qmu/examples/direct.m	(revision 16137)
@@ -1,5 +1,5 @@
 %using library mode of Dakota, only for parallel runs.
 md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.analysis_driver='stressbalance';
 md.qmu.params.evaluation_concurrency=1;
 
Index: /issm/trunk/src/m/qmu/examples/lrel_mmf.m
===================================================================
--- /issm/trunk/src/m/qmu/examples/lrel_mmf.m	(revision 16136)
+++ /issm/trunk/src/m/qmu/examples/lrel_mmf.m	(revision 16137)
@@ -86,5 +86,5 @@
 %%  sample analysis
 
-%md=solve(md,'analysis_type','diagnostic');
+%md=solve(md,'analysis_type','stressbalance');
 
 %plotmodel(md,'data','mesh')
Index: /issm/trunk/src/m/qmu/examples/samp_direct.m
===================================================================
--- /issm/trunk/src/m/qmu/examples/samp_direct.m	(revision 16136)
+++ /issm/trunk/src/m/qmu/examples/samp_direct.m	(revision 16137)
@@ -50,5 +50,5 @@
 
 md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.analysis_driver='stressbalance';
 md.qmu.params.evaluation_concurrency=1;
 
Index: /issm/trunk/src/m/qmu/preqmu.m
===================================================================
--- /issm/trunk/src/m/qmu/preqmu.m	(revision 16136)
+++ /issm/trunk/src/m/qmu/preqmu.m	(revision 16137)
@@ -1,5 +1,5 @@
 function md=preqmu(md,options)
 %QMU - apply Quantification of Margins and Uncertainties techniques 
-%      to a solution sequence (like diagnostic.m, progonstic.m, etc ...), 
+%      to a solution sequence (like stressbalance.m, progonstic.m, etc ...), 
 %      using the Dakota software from Sandia.
 %
Index: /issm/trunk/src/m/qmu/process_qmu_options.m
===================================================================
--- /issm/trunk/src/m/qmu/process_qmu_options.m	(revision 16136)
+++ /issm/trunk/src/m/qmu/process_qmu_options.m	(revision 16137)
@@ -39,6 +39,6 @@
 %check solution type is supported
 if ~(strcmpi(analysis_type,'control') |  ...
-		strcmpi(analysis_type,'diagnostic') |  ...
-		strcmpi(analysis_type,'prognostic') |  ...
+		strcmpi(analysis_type,'stressbalance') |  ...
+		strcmpi(analysis_type,'masstransport') |  ...
 		strcmpi(analysis_type,'thermal') |  ...
 		strcmpi(analysis_type,'parameters') |  ...
Index: /issm/trunk/src/m/qmu/qmuresponse.m
===================================================================
--- /issm/trunk/src/m/qmu/qmuresponse.m	(revision 16136)
+++ /issm/trunk/src/m/qmu/qmuresponse.m	(revision 16137)
@@ -28,8 +28,9 @@
 	m_dhu=models.dhu;
 	m_ds=models.ds;
-	ishutter=m_dhu.parameters.ishutter;
-	ismacayealpattyn=m_dh.parameters.ismacayealpattyn;
-	isstokes=m_ds.parameters.isstokes;
-	if ishutter,
+	isSIA=m_dhu.parameters.isSIA;
+	isSSA=m_dh.parameters.isSSA;
+	isHO=m_dh.parameters.isHO;
+	isFS=m_ds.parameters.isFS;
+	if isSIA,
 
 % for now, separate all segments from double array for parallel to make cells
@@ -57,5 +58,5 @@
 		end
 
-	elseif ismacayealpattyn,
+	elseif isSSA || isHO,
 
 % for now, separate all segments from double array for parallel to make cells
@@ -83,5 +84,5 @@
 		end
 
-	elseif isstokes,
+	elseif isFS,
 
 % for now, separate all segments from double array for parallel to make cells
Index: /issm/trunk/src/m/regional/BasinConstrain.m
===================================================================
--- /issm/trunk/src/m/regional/BasinConstrain.m	(revision 16136)
+++ /issm/trunk/src/m/regional/BasinConstrain.m	(revision 16137)
@@ -48,6 +48,6 @@
 
 %all elements outside the constraint domain are equivalent to water. all nodes outside are spc'd.
-md.diagnostic.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
-md.diagnostic.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
+md.stressbalance.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
+md.stressbalance.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
 md.mask.elementonwater(elementnotondomain)=1;
 
@@ -56,8 +56,8 @@
 numpos=unique(md.mesh.elements(pos,:));
 nodes=setdiff(1:1:md.mesh.numberofvertices,numpos);
-md.diagnostic.spcvx(nodes)=md.inversion.vx_obs(nodes);
-md.diagnostic.spcvy(nodes)=md.inversion.vy_obs(nodes);
+md.stressbalance.spcvx(nodes)=md.inversion.vx_obs(nodes);
+md.stressbalance.spcvy(nodes)=md.inversion.vy_obs(nodes);
 
 %make sure icefronts that are completely spc'd are taken out:
-free_segments=find((~isnan(md.diagnostic.spcvx(md.diagnostic.icefront(:,1:2))) + ~isnan(md.diagnostic.spcvy(md.diagnostic.icefront(:,1:2))))~=2);
-md.diagnostic.icefront=md.diagnostic.icefront(free_segments,:);
+free_segments=find((~isnan(md.stressbalance.spcvx(md.stressbalance.icefront(:,1:2))) + ~isnan(md.stressbalance.spcvy(md.stressbalance.icefront(:,1:2))))~=2);
+md.stressbalance.icefront=md.stressbalance.icefront(free_segments,:);
Index: /issm/trunk/src/m/regional/BasinConstrainShelf.m
===================================================================
--- /issm/trunk/src/m/regional/BasinConstrainShelf.m	(revision 16136)
+++ /issm/trunk/src/m/regional/BasinConstrainShelf.m	(revision 16137)
@@ -48,6 +48,6 @@
 
 %all elements outside the constraint domain are equivalent to water. all nodes outside are spc'd.
-md.diagnostic.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
-md.diagnostic.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
+md.stressbalance.spcvx(vertexnotondomain)=md.inversion.vx_obs(vertexnotondomain);
+md.stressbalance.spcvy(vertexnotondomain)=md.inversion.vy_obs(vertexnotondomain);
 md.mask.elementonwater(elementnotondomain)=1;
 
@@ -56,19 +56,19 @@
 numpos=unique(md.mesh.elements(pos,:));
 nodes=setdiff(1:1:md.mesh.numberofvertices,numpos);
-md.diagnostic.spcvx(nodes)=md.inversion.vx_obs(nodes);
-md.diagnostic.spcvy(nodes)=md.inversion.vy_obs(nodes);
+md.stressbalance.spcvx(nodes)=md.inversion.vx_obs(nodes);
+md.stressbalance.spcvy(nodes)=md.inversion.vy_obs(nodes);
 
 %make sure any node with NaN velocity is spc'd:
 %we spc to the smoothed value, so that control methods don't go berserk trying to figure out what reaction force to apply for the spc to stand.
 pos=find(isnan(md.inversion.vel_obs_raw));
-md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos); 
-md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos); 
+md.stressbalance.spcvx(pos)=md.inversion.vx_obs(pos); 
+md.stressbalance.spcvy(pos)=md.inversion.vy_obs(pos); 
 
 %iceshelves: any vertex on floating ice is spc'd
-pos=find(md.mask.vertexongroundedice);
-md.diagnostic.spcvx(pos)=md.inversion.vx_obs(pos); 
-md.diagnostic.spcvy(pos)=md.inversion.vy_obs(pos); 
+pos=find(md.mask.groundedice_levelset<0.);
+md.stressbalance.spcvx(pos)=md.inversion.vx_obs(pos); 
+md.stressbalance.spcvy(pos)=md.inversion.vy_obs(pos); 
 
 %make sure icefronts that are completely spc'd are taken out:
-free_segments=find((~isnan(md.diagnostic.spcvx(md.diagnostic.icefront(:,1:2))) + ~isnan(md.diagnostic.spcvy(md.diagnostic.icefront(:,1:2))) )~=2);
-md.diagnostic.icefront=md.diagnostic.icefront(free_segments,:);
+free_segments=find((~isnan(md.stressbalance.spcvx(md.stressbalance.icefront(:,1:2))) + ~isnan(md.stressbalance.spcvy(md.stressbalance.icefront(:,1:2))) )~=2);
+md.stressbalance.icefront=md.stressbalance.icefront(free_segments,:);
Index: /issm/trunk/src/m/regional/regionaltransient2d.m
===================================================================
--- /issm/trunk/src/m/regional/regionaltransient2d.m	(revision 16136)
+++ /issm/trunk/src/m/regional/regionaltransient2d.m	(revision 16137)
@@ -115,27 +115,27 @@
 	%As long as there are recorded time steps, spc the boundaries with velocities
 	if nsteps > 0
-		md2.diagnostic.spcvx=md2.diagnostic.spcvx*ones(1,size(spcx,2));
-		md2.diagnostic.spcvy=md2.diagnostic.spcvy*ones(1,size(spcy,2));
-		md2.diagnostic.spcvz=md2.diagnostic.spcvz*ones(1,size(spcx,2));
-		md2.prognostic.spcthickness=md2.prognostic.spcthickness*ones(1,size(spct,2));
-		md2.diagnostic.spcvx(find(md2.mesh.vertexonboundary),:)=spcx(find(md2.mesh.vertexonboundary),:);
-		md2.diagnostic.spcvy(find(md2.mesh.vertexonboundary),:)=spcy(find(md2.mesh.vertexonboundary),:);
-		md2.diagnostic.spcvz(find(md2.mesh.vertexonboundary),:)=0;
-		md2.prognostic.spcthickness(find(md2.mesh.vertexonboundary),:)=spct(find(md2.mesh.vertexonboundary),:);
-		md2.diagnostic.spcvx=[md2.diagnostic.spcvx; steps];
-		md2.diagnostic.spcvy=[md2.diagnostic.spcvy; steps];
-		md2.diagnostic.spcvz=[md2.diagnostic.spcvz; steps];
-		md2.prognostic.spcthickness=[md2.prognostic.spcthickness; steps];
+		md2.stressbalance.spcvx=md2.stressbalance.spcvx*ones(1,size(spcx,2));
+		md2.stressbalance.spcvy=md2.stressbalance.spcvy*ones(1,size(spcy,2));
+		md2.stressbalance.spcvz=md2.stressbalance.spcvz*ones(1,size(spcx,2));
+		md2.masstransport.spcthickness=md2.masstransport.spcthickness*ones(1,size(spct,2));
+		md2.stressbalance.spcvx(find(md2.mesh.vertexonboundary),:)=spcx(find(md2.mesh.vertexonboundary),:);
+		md2.stressbalance.spcvy(find(md2.mesh.vertexonboundary),:)=spcy(find(md2.mesh.vertexonboundary),:);
+		md2.stressbalance.spcvz(find(md2.mesh.vertexonboundary),:)=0;
+		md2.masstransport.spcthickness(find(md2.mesh.vertexonboundary),:)=spct(find(md2.mesh.vertexonboundary),:);
+		md2.stressbalance.spcvx=[md2.stressbalance.spcvx; steps];
+		md2.stressbalance.spcvy=[md2.stressbalance.spcvy; steps];
+		md2.stressbalance.spcvz=[md2.stressbalance.spcvz; steps];
+		md2.masstransport.spcthickness=[md2.masstransport.spcthickness; steps];
 	end
 
-	%Diagnostic.  Don't spc the icefront vertices.
-	if ~isnan(md2.diagnostic.icefront)
+	%Stressbalance.  Don't spc the icefront vertices.
+	if ~isnan(md2.stressbalance.icefront)
 		md1s=md1.extract(area);
-		%md2.diagnostic.icefront=[md2.mesh.segments 2];
+		%md2.stressbalance.icefront=[md2.mesh.segments 2];
 		e2=md2.mesh.segments(:,end);
 		e1=md1s.mesh.segments(:,end);
 
 		pload = nan*ones(size(md1s.mesh.elements,1),1);
-		pload(md1s.diagnostic.icefront(:,end-1))=md1s.diagnostic.icefront(:,end);
+		pload(md1s.stressbalance.icefront(:,end-1))=md1s.stressbalance.icefront(:,end);
 
 		x2=mean(md2.mesh.x(md2.mesh.elements(e2,:)),2);
@@ -145,9 +145,9 @@
 
 		pload2=griddata(x1,y1,pload,x2,y2,'nearest');
-		md2.diagnostic.icefront=[md2.mesh.segments(~isnan(pload2),:) pload2(~isnan(pload2))];
-		md2.diagnostic.spcvx(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
-		md2.diagnostic.spcvy(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
-		md2.diagnostic.spcvz(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
-		md2.prognostic.spcthickness(unique(md2.diagnostic.icefront(:,1:2)),:)=nan;
+		md2.stressbalance.icefront=[md2.mesh.segments(~isnan(pload2),:) pload2(~isnan(pload2))];
+		md2.stressbalance.spcvx(unique(md2.stressbalance.icefront(:,1:2)),:)=nan;
+		md2.stressbalance.spcvy(unique(md2.stressbalance.icefront(:,1:2)),:)=nan;
+		md2.stressbalance.spcvz(unique(md2.stressbalance.icefront(:,1:2)),:)=nan;
+		md2.masstransport.spcthickness(unique(md2.stressbalance.icefront(:,1:2)),:)=nan;
 	end
 
Index: /issm/trunk/src/m/solve/WriteData.m
===================================================================
--- /issm/trunk/src/m/solve/WriteData.m	(revision 16136)
+++ /issm/trunk/src/m/solve/WriteData.m	(revision 16137)
@@ -39,4 +39,8 @@
 		data  = scale.*data;
 	end
+end
+if(size(data,1)==forcinglength),
+	yts=365.0*24.0*3600.0;
+	data(end,:) = data(end,:)*yts;
 end
 
Index: /issm/trunk/src/m/solve/WriteData.py
===================================================================
--- /issm/trunk/src/m/solve/WriteData.py	(revision 16136)
+++ /issm/trunk/src/m/solve/WriteData.py	(revision 16137)
@@ -53,4 +53,8 @@
 		else:
 			data  = scale*data
+	if numpy.size(data) > 1 :
+		if numpy.size(data,0)==forcinglength:
+			yts=365.0*24.0*3600.0
+			data[-1,:] = yts*data[-1,:]
 
 	#Step 1: write the enum to identify this record uniquely
Index: /issm/trunk/src/m/solve/marshall.m
===================================================================
--- /issm/trunk/src/m/solve/marshall.m	(revision 16136)
+++ /issm/trunk/src/m/solve/marshall.m	(revision 16137)
@@ -17,5 +17,5 @@
 
 %First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
-WriteData(fid,'enum',MaximumNumberOfEnums(),'data',true,'format','Boolean');
+WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum(),'data',true,'format','Boolean');
 
 %Go through all model fields: check that it is a class and call checkconsistency
Index: /issm/trunk/src/m/solve/marshall.py
===================================================================
--- /issm/trunk/src/m/solve/marshall.py	(revision 16136)
+++ /issm/trunk/src/m/solve/marshall.py	(revision 16137)
@@ -22,5 +22,5 @@
 
 	#First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
-	WriteData(fid,'enum',MaximumNumberOfEnums(),'data',True,'format','Boolean')
+	WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum(),'data',True,'format','Boolean')
 
 	#Go through all model fields: check that it is a class and call checkconsistency
Index: /issm/trunk/src/m/solve/process_solve_options.m
===================================================================
--- /issm/trunk/src/m/solve/process_solve_options.m	(revision 16136)
+++ /issm/trunk/src/m/solve/process_solve_options.m	(revision 16137)
@@ -9,7 +9,8 @@
 %solution_type: check on this option, error out otherwise
 solution_type=getfieldvalue(options,'solution_type');
-if ~ismember(solution_type,[DiagnosticSolutionEnum(),PrognosticSolutionEnum(),ThermalSolutionEnum(),...
+if ~ismember(solution_type,[StressbalanceSolutionEnum(),MasstransportSolutionEnum(),ThermalSolutionEnum(),...
 		SteadystateSolutionEnum(),TransientSolutionEnum(),EnthalpySolutionEnum(),...
-		BalancethicknessSolutionEnum(),BalancethicknessSoftSolutionEnum(),BedSlopeSolutionEnum(),...
+		BalancethicknessSolutionEnum(),BalancethicknessSoftSolutionEnum(),...
+		BalancevelocitySolutionEnum(),BedSlopeSolutionEnum(),...
 		SurfaceSlopeSolutionEnum(),HydrologySolutionEnum(),FlaimSolutionEnum(),GiaSolutionEnum()]),
 	error(['process_solve_options error message: solution_type ' EnumToString(solution_type) ' not supported yet!']);
Index: /issm/trunk/src/m/solve/process_solve_options.py
===================================================================
--- /issm/trunk/src/m/solve/process_solve_options.py	(revision 16136)
+++ /issm/trunk/src/m/solve/process_solve_options.py	(revision 16137)
@@ -18,7 +18,8 @@
 	#solution_type: check on this option, error out otherwise
 	solution_type=options.getfieldvalue('solution_type')
-	if solution_type not in (DiagnosticSolutionEnum(),PrognosticSolutionEnum(),ThermalSolutionEnum(),\
+	if solution_type not in (StressbalanceSolutionEnum(),MasstransportSolutionEnum(),ThermalSolutionEnum(),\
 			SteadystateSolutionEnum(),TransientSolutionEnum(),EnthalpySolutionEnum(),\
-			BalancethicknessSolutionEnum(),BedSlopeSolutionEnum(),SurfaceSlopeSolutionEnum(),\
+			BalancethicknessSolutionEnum(),BalancevelocitySolutionEnum(),\
+			BedSlopeSolutionEnum(),SurfaceSlopeSolutionEnum(),\
 			HydrologySolutionEnum(),FlaimSolutionEnum(),GiaSolutionEnum()):
 		raise ValueError("process_solve_options error message: solution_type '%s' not supported yet!" % EnumToString(solution_type)[0])
Index: /issm/trunk/src/m/solve/solve.m
===================================================================
--- /issm/trunk/src/m/solve/solve.m	(revision 16136)
+++ /issm/trunk/src/m/solve/solve.m	(revision 16137)
@@ -7,6 +7,6 @@
 %
 %   solution types available comprise:
-%		 - DiagnosticSolutionEnum
-%		 - PrognosticSolutionEnum
+%		 - StressbalanceSolutionEnum
+%		 - MasstransportSolutionEnum
 %		 - ThermalSolutionEnum
 %		 - SteadystateSolutionEnum
@@ -22,5 +22,5 @@
 %
 %   Examples:
-%      md=solve(md,DiagnosticSolutionEnum);
+%      md=solve(md,StressbalanceSolutionEnum);
 
 %recover and process solve options
Index: /issm/trunk/src/m/solve/solve.py
===================================================================
--- /issm/trunk/src/m/solve/solve.py	(revision 16136)
+++ /issm/trunk/src/m/solve/solve.py	(revision 16137)
@@ -8,5 +8,4 @@
 from ismodelselfconsistent import *
 from marshall import *
-from ispetsc import *
 from waitonlock import *
 from loadresultsfromcluster import *
@@ -21,6 +20,6 @@
  
 	   solution types available comprise:
-	      - DiagnosticSolutionEnum
-	      - PrognosticSolutionEnum
+	      - StressbalanceSolutionEnum
+	      - MasstransportSolutionEnum
 	      - ThermalSolutionEnum
 	      - SteadystateSolutionEnum
@@ -36,5 +35,5 @@
  
 	   Examples:
-	      md=solve(md,DiagnosticSolutionEnum);
+	      md=solve(md,StressbalanceSolutionEnum);
 	"""
 
Index: /issm/trunk/src/m/solve/waitonlock.m
===================================================================
--- /issm/trunk/src/m/solve/waitonlock.m	(revision 16136)
+++ /issm/trunk/src/m/solve/waitonlock.m	(revision 16137)
@@ -39,4 +39,7 @@
 	if port,
 		command = ['ssh -l ' login ' -p ' num2str(port) ' localhost "[ -f ' lockfilename ' ] && [ -f ' logfilename ' ]" 2>/dev/null'];
+	elseif isa(cluster,'cloud')
+		command = [' [ -f ' lockfilename ' ] && [ -f ' logfilename ' ] 2>/dev/null'];
+		command = [starcluster() ' sshmaster ' cluster.name ' --user ' cluster.login ' ''' command ''''];
 	else
 		command = ['ssh -l ' login ' ' cluster.name ' "[ -f ' lockfilename ' ] && [ -f ' logfilename ' ]" 2>/dev/null'];
Index: /issm/trunk/src/m/solvers/asmoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/asmoptions.py	(revision 16136)
+++ /issm/trunk/src/m/solvers/asmoptions.py	(revision 16137)
@@ -1,6 +1,3 @@
-#module imports {{{
 from pairoptions import *
-from petscversion  import *
-#}}}
 def asmoptions(*args):
 	#ASMOPTIONS - return ASM petsc options
Index: /issm/trunk/src/m/solvers/issmsolver.py
===================================================================
--- /issm/trunk/src/m/solvers/issmsolver.py	(revision 16136)
+++ /issm/trunk/src/m/solvers/issmsolver.py	(revision 16137)
@@ -1,6 +1,3 @@
-#module imports {{{
 from pairoptions import *
-from petscversion  import *
-#}}}
 def asmoptions(*args):
 	#ISSMSOLVE - return issm solver options
Index: /issm/trunk/src/m/solvers/jacobiasmoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/jacobiasmoptions.py	(revision 16136)
+++ /issm/trunk/src/m/solvers/jacobiasmoptions.py	(revision 16137)
@@ -1,6 +1,3 @@
-#module imports {{{
 from pairoptions import *
-from petscversion  import *
-#}}}
 def jacobiasmoptions(*args):
 	#ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
Index: /issm/trunk/src/m/solvers/jacobicgoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/jacobicgoptions.py	(revision 16136)
+++ /issm/trunk/src/m/solvers/jacobicgoptions.py	(revision 16137)
@@ -1,6 +1,3 @@
-#module imports {{{
 from pairoptions import *
-from petscversion  import *
-#}}}
 def jacobicgoptions(*args):
 	#ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
Index: /issm/trunk/src/m/solvers/matlaboptions.py
===================================================================
--- /issm/trunk/src/m/solvers/matlaboptions.py	(revision 16136)
+++ /issm/trunk/src/m/solvers/matlaboptions.py	(revision 16137)
@@ -1,6 +1,3 @@
-#module imports {{{
 from pairoptions import *
-from petscversion  import *
-#}}}
 def matlaboptions(*args):
 	#MATLABOPTIONS - return Matlab petsc options
Index: /issm/trunk/src/m/solvers/mumpsoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/mumpsoptions.m	(revision 16136)
+++ /issm/trunk/src/m/solvers/mumpsoptions.m	(revision 16137)
@@ -10,6 +10,6 @@
 
 %default mumps options
-PETSC_VERSION=petscversion();
-if PETSC_VERSION==2,
+PETSC_VERSION=IssmConfig('_PETSC_MAJOR_');
+if PETSC_VERSION==2.,
 	mumps.toolkit='petsc';
 	mumps.mat_type=getfieldvalue(options,'mat_type','aijmumps');
@@ -19,5 +19,5 @@
 	mumps.pc_factor_shift_positive_definite=getfieldvalue(options,'pc_factor_shift_positive_definite','true');
 end
-if PETSC_VERSION==3,
+if PETSC_VERSION==3.,
 	mumps.toolkit='petsc';
 	mumps.mat_type=getfieldvalue(options,'mat_type','mpiaij');
Index: /issm/trunk/src/m/solvers/mumpsoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/mumpsoptions.py	(revision 16136)
+++ /issm/trunk/src/m/solvers/mumpsoptions.py	(revision 16137)
@@ -1,5 +1,5 @@
 from collections import OrderedDict
 from pairoptions import *
-from petscversion import *
+from IssmConfig  import *
 
 def mumpsoptions(*args):
@@ -16,6 +16,6 @@
 
 	#default mumps options
-	PETSC_VERSION=petscversion()
-	if PETSC_VERSION==2:
+	PETSC_VERSION=IssmConfig('_PETSC_MAJOR_')[0]
+	if PETSC_VERSION==2.:
 		mumps['toolkit']='petsc'
 		mumps['mat_type']=options.getfieldvalue('mat_type','aijmumps')
@@ -24,5 +24,5 @@
 		mumps['mat_mumps_icntl_14']=options.getfieldvalue('mat_mumps_icntl_14',120)
 		mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true')
-	if PETSC_VERSION==3:
+	if PETSC_VERSION==3.:
 		mumps['toolkit']='petsc'
 		mumps['mat_type']=options.getfieldvalue('mat_type','mpiaij')
Index: /issm/trunk/src/m/solvers/soroptions.py
===================================================================
--- /issm/trunk/src/m/solvers/soroptions.py	(revision 16136)
+++ /issm/trunk/src/m/solvers/soroptions.py	(revision 16137)
@@ -1,6 +1,3 @@
-#module imports {{{
 from pairoptions import *
-from petscversion  import *
-#}}}
 def soroptions(*args):
 	#SOROPTIONS - return Relaxation Solver petsc options
Index: /issm/trunk/src/m/solvers/stokesoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/stokesoptions.m	(revision 16136)
+++ /issm/trunk/src/m/solvers/stokesoptions.m	(revision 16137)
@@ -10,9 +10,9 @@
 
 %default stokes options
-PETSC_VERSION=petscversion();
-if PETSC_VERSION==2,
+PETSC_VERSION=IssmConfig('_PETSC_MAJOR_')[0];
+if PETSC_VERSION==2.,
 	error('stokesoptions error message: multi-physics options not supported in Petsc 2');
 end
-if PETSC_VERSION==3,
+if PETSC_VERSION==3.,
 	stokes.toolkit='petsc';
 	stokes.mat_type=getfieldvalue(options,'mat_type','mpiaij');
Index: /issm/trunk/src/m/solvers/stokesoptions.py
===================================================================
--- /issm/trunk/src/m/solvers/stokesoptions.py	(revision 16136)
+++ /issm/trunk/src/m/solvers/stokesoptions.py	(revision 16137)
@@ -1,6 +1,4 @@
-#module imports {{{
 from pairoptions import *
-from petscversion  import *
-#}}}
+from IssmConfig  import *
 def stokesoptions(*args):
 	#STOKESOPTIONS - return STOKES multi-physics solver petsc options
@@ -14,9 +12,9 @@
 
 	#default stokes options
-	PETSC_VERSION=petscversion()
+	PETSC_VERSION=IssmConfig('_PETSC_MAJOR_')[0]
 
-	if PETSC_VERSION==2:
+	if PETSC_VERSION==2.:
 		raise RuntimeError('stokesoptions error message: multi-physics options not supported in Petsc 2')
-	if PETSC_VERSION==3:
+	if PETSC_VERSION==3.:
 		options=[['toolkit','petsc'],['mat_type','mpiaij'],['ksp_max_it',1000],['ksp_type','gmres'],['pc_type','fieldsplit'],['pc_field_split_type','schur'],\
 	['fieldsplit_0_pc_type','hypre'],['fieldsplit_0_ksp_type','gmres'],['fieldsplit_0_pc_hypre_type','boomerang'],\
Index: /issm/trunk/src/mobile/native/Main.cpp
===================================================================
--- /issm/trunk/src/mobile/native/Main.cpp	(revision 16136)
+++ /issm/trunk/src/mobile/native/Main.cpp	(revision 16137)
@@ -1,3 +1,3 @@
-#include "../../c/issm.h"
+#include "../../c/main/issm.h"
 #include <cstddef>
 #include <stdio.h>
@@ -22,9 +22,9 @@
 		int argc; //arguments to constructor.
 		char** argv = NULL;
-		COMM    communicator = 1; //fake communicator for constructor
 		const char* issmname = "issm.exe";
 		char *solution_type = NULL;
 		char *absfile = NULL;
 		char *relfile = NULL;
+		ISSM_MPI_Comm    comm=1;
 
 		/*log:*/
@@ -45,5 +45,5 @@
 		
 		/*call Model constructor passing in infile as File Descriptor parameter.*/
-		fm  = new FemModel(argc,argv,communicator);
+		fm  = new FemModel(argc,argv,comm);
 
 		/*we'll need the toolkits activated right away to use matrices: */
@@ -70,5 +70,5 @@
 	}
 	/*}}}*/
-	void Solve(JNIEnv *env, jclass clazz , jdouble alpha, jdouble temperature, jobject buf){ /*{{{*/
+	void Solve(JNIEnv *env, jclass clazz , jdouble alpha, jobject buf){ /*{{{*/
 
 		int i,count;
@@ -87,18 +87,21 @@
 		/*reset basal friction to what it was before: */
 		__android_log_print(ANDROID_LOG_INFO, "Native","alpha %g ",alpha);
-		/*reset basal temperature to what it was before: */
-		__android_log_print(ANDROID_LOG_INFO, "Native","temperature %g ",temperature);
+		
+		__android_log_print(ANDROID_LOG_INFO, "Native","ok-1");
 
 		InputDuplicatex(fm->elements,fm->nodes,fm->vertices,fm->loads,fm->materials,fm->parameters,AndroidFrictionCoefficientEnum,FrictionCoefficientEnum);
+		__android_log_print(ANDROID_LOG_INFO, "Native","ok0");
 
 		/*now scale friction by alpha: */
 		InputScalex(fm->elements,fm->nodes,fm->vertices,fm->loads,fm->materials,fm->parameters,FrictionCoefficientEnum,alpha/100);
+		__android_log_print(ANDROID_LOG_INFO, "Native","ok1");
 
 		/*solve: */
 		fm -> Solve();
+		__android_log_print(ANDROID_LOG_INFO, "Native","ok2");
 
 		/*retrieve results: */
 		__android_log_print(ANDROID_LOG_INFO, "Native","Retrieving results ");
-		fm->elements->ProcessResultsUnits();
+		//fm->elements->ProcessResultsUnits(); we are now in SI units
 		patch=fm->elements->ResultsToPatch();
 
@@ -168,5 +171,5 @@
 	{
 			{"createISSMModel"   ,"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I"  , (void *) Initialize},
-			{"solveISSMModel", "(DDLjava/nio/DoubleBuffer;)V", (void *) Solve}
+			{"solveISSMModel", "(DLjava/nio/DoubleBuffer;)V", (void *) Solve}
 	};
 	/*}}}*/
Index: /issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp
===================================================================
--- /issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp	(revision 16137)
+++ /issm/trunk/src/wrappers/IssmConfig/IssmConfig.cpp	(revision 16137)
@@ -0,0 +1,101 @@
+/*\file IssmConfig.c
+ *\brief: get configuration names
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./IssmConfig.h"
+
+void IssmConfigUsage(void){/*{{{*/
+	_printf0_("\n");
+	_printf0_("   usage: " << __FUNCT__ << "value = IssmConfig('string');\n");
+	_printf0_("\n");
+}/*}}}*/
+WRAPPER(IssmConfig){
+
+	/*input/output*/
+	char       *name     = NULL;
+	bool        isstring = false;
+	IssmDouble  value   = 0.;
+	char       *svalue   = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&IssmConfigUsage);
+
+	/*Fetch inputs: */
+	FetchData(&name,NAME);
+
+	/*Core*/
+	if(strcmp(name,"_HAVE_MPI_")==0){
+		#ifdef _HAVE_MPI_
+		value = 1.;
+		#else
+		value = 0.;
+		#endif
+	}
+	else if(strcmp(name,"_HAVE_DAKOTA_")==0){
+		#ifdef _HAVE_DAKOTA_
+		value = 1.;
+		#else
+		value = 0.;
+		#endif
+	}
+	else if(strcmp(name,"_HAVE_MUMPS_")==0){
+		#ifdef _HAVE_MUMPS_
+		value = 1.;
+		#else
+		value = 0.;
+		#endif
+	}
+	else if(strcmp(name,"_HAVE_PETSC_")==0){
+		#ifdef _HAVE_PETSC_
+		value = 1.;
+		#else
+		value = 0.;
+		#endif
+	}
+	else if(strcmp(name,"_PETSC_MAJOR_")==0){
+		#ifdef _PETSC_MAJOR_
+		value = IssmDouble(_PETSC_MAJOR_);
+		#else
+		_error_("_PETSC_MAJOR_ not found in config.h");
+		#endif
+	}
+	else if(strcmp(name,"_DAKOTA_VERSION_")==0){
+		#ifdef _DAKOTA_VERSION_
+		isstring = true;
+		svalue =xNew<char>(strlen(_DAKOTA_VERSION_)+1);
+		xMemCpy<char>(svalue,_DAKOTA_VERSION_,(strlen(_DAKOTA_VERSION_)+1));
+		#else
+		_error_("_DAKOTA_VERSION_ not found in config.h");
+		#endif
+	}
+	else if(strcmp(name,"ISSM_PREFIX")==0){
+		isstring = true;
+		svalue =xNew<char>(strlen(ISSM_PREFIX)+1);
+		xMemCpy<char>(svalue,ISSM_PREFIX,(strlen(ISSM_PREFIX)+1));
+	}
+	else{
+		_error_("variable " << name << " not supported yet");
+	}
+
+	/* output: */
+	if(isstring)
+	 WriteData(VALUE,svalue);
+	else
+	 WriteData(VALUE,value);
+
+	/*Clean up*/
+	xDelete<char>(name);
+	xDelete<char>(svalue);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/IssmConfig/IssmConfig.h
===================================================================
--- /issm/trunk/src/wrappers/IssmConfig/IssmConfig.h	(revision 16137)
+++ /issm/trunk/src/wrappers/IssmConfig/IssmConfig.h	(revision 16137)
@@ -0,0 +1,48 @@
+/*!\file:  IssmConfig.h
+ * \brief header file for IssmConfig module.
+ */ 
+
+#ifndef _ISSMCONFIG_H
+#define _ISSMCONFIG_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/shared/Enum/Enum.h"
+#include "../../c/shared/shared.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "IssmConfig"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define NAME (mxArray*)prhs[0]
+/* serial output macros: */
+#define VALUE (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define NAME PyTuple_GetItem(args,0)
+/* serial output macros: */
+#define VALUE output,0
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  1
+
+#endif  /* _TEST_H */
Index: /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp
===================================================================
--- /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 16136)
+++ /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 16137)
@@ -22,10 +22,10 @@
 	int     numberofelements;
 	int     numberofvertices;
-	double *elements         = NULL;
+	int    *elements         = NULL;
 	int     elements_width;
 
 	int numberofelements2d;
 	int numberofvertices2d;
-	double* elements2d=NULL;
+	int* elements2d=NULL;
 
 	int numberoflayers;
Index: /issm/trunk/src/wrappers/matlab/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 16136)
+++ /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 16137)
@@ -1,5 +1,9 @@
-AM_CPPFLAGS = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@
+AM_CPPFLAGS = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @AMPIINCL@
+#AUTOMAKE_OPTIONS = subdir-objects
 
 EXEEXT=$(MATLABWRAPPEREXT)
+
+#define prefix (from http://www.gnu.org/software/autoconf/manual/autoconf-2.67/html_node/Defining-Directories.html)
+AM_CPPFLAGS+=  -DISSM_PREFIX='"$(prefix)"'
 
 #matlab io{{{
@@ -13,24 +17,10 @@
 io_sources= ./include/matlabincludes.h\
 				./io/matlabio.h\
-				./io/MatlabNArrayToNArray.cpp\
 				./io/CheckNumMatlabArguments.cpp\
-				./io/mxGetAssignedField.cpp\
 				./io/WriteMatlabData.cpp\
-				./io/FetchMatlabData.cpp\
-				./io/OptionParse.cpp\
-				./io/MatlabMatrixToMatrix.cpp\
-				./io/MatlabVectorToVector.cpp\
-				./io/MatlabVectorToDoubleVector.cpp\
-				./io/MatlabMatrixToDoubleMatrix.cpp\
-				./io/MatlabMatrixToIssmMat.cpp\
-				./io/MatlabVectorToIssmVec.cpp
-
-				
-if PETSC
-io_sources += ./io/MatlabMatrixToPetscMat.cpp\
-				./io/MatlabVectorToPetscVec.cpp
-endif
+				./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)
@@ -74,4 +64,5 @@
 						 InterpFromMeshToGrid.la\
 						 InterpFromMesh2d.la\
+						 IssmConfig.la\
 						 Ll2xy.la\
 						 NodeConnectivity.la\
@@ -120,5 +111,6 @@
 
 if SHAREDLIBS
-deps += ../../c/libISSMModules.la ../../c/libISSMCore.la ./libISSMApi.la ./libISSMMatlab.a
+deps += ./libISSMMatlab.la ../../c/libISSMModules.la ../../c/libISSMCore.la ./libISSMApi.la
+
 else
 deps += ./libISSMMatlab.a ../../c/libISSMModules.a ../../c/libISSMCore.a ./libISSMApi.a
@@ -135,9 +127,9 @@
 #}}}
 # Module sources and dependencies {{{
-libISSMMatlab_la_LIBADD = $(MPILIB) $(PETSCLIB) $(GSLLIB) $(MATHLIB) $(MEXLIB) ./../../c/libISSMCore.la
-libISSMMatlab_la_LDFLAGS = -module
+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
+libISSMApi_la_LDFLAGS = -module -export-dynamic
 
 AverageFilter_la_SOURCES = ../AverageFilter/AverageFilter.cpp\
@@ -159,5 +151,5 @@
 Chaco_la_SOURCES = ../Chaco/Chaco.cpp\
 						 ../Chaco/Chaco.h
-Chaco_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(CHACOLIB) $(GSLLIB)
+Chaco_la_LIBADD = ${deps} $(MPILIB) $(CHACOLIB) $(GSLLIB) $(PETSCLIB)
 
 ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
@@ -209,4 +201,8 @@
 InterpFromMesh2d_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
 
+IssmConfig_la_SOURCES = ../IssmConfig/IssmConfig.cpp\
+										../IssmConfig/IssmConfig.h
+IssmConfig_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
 KMLFileRead_la_SOURCES = ../KMLFileRead/KMLFileRead.cpp\
 								 ../KMLFileRead/KMLFileRead.h
Index: /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp	(revision 16136)
+++ /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp	(revision 16137)
@@ -10,4 +10,5 @@
 
 #include "./matlabio.h"
+#include <cstring> 
 
 /*Primitive data types*/
@@ -269,7 +270,10 @@
 
 	/*Check that it is a vector*/
-	if(M>0){
-		if(N!=1) _error_("input vector of size " << M << "x" << N << " should have only one column");
-	}
+	if(M*N>0 && (M!=1 && N!=1)){
+		_error_("input vector of size " << M << "x" << N << " should have only one column");
+	}
+
+	/*Transpose Row vectors*/
+	if(M==1 && N>1) M=N;
 
 	/*Assign output pointers:*/
@@ -294,5 +298,5 @@
 
 		/*Convert matlab vector to double*  vector: */
-		MatlabVectorToDoubleVector(&doublevector,&outvector_rows,dataref);
+		FetchData(&doublevector,&outvector_rows,dataref);
 
 		/*Convert double vector into integer vector: */
@@ -326,5 +330,5 @@
 
 		/*Convert matlab vector to double*  vector: */
-		MatlabVectorToDoubleVector(&doublevector,&outvector_rows,dataref);
+		FetchData(&doublevector,&outvector_rows,dataref);
 
 		/*Convert double vector into integer vector: */
@@ -358,5 +362,5 @@
 
 		/*Convert matlab vector to double*  vector: */
-		MatlabVectorToDoubleVector(&doublevector,&outvector_rows,dataref);
+		FetchData(&doublevector,&outvector_rows,dataref);
 
 		/*Convert double vector into float vector: */
@@ -481,49 +485,4 @@
 
 /*ISSM objects*/
-/*FUNCTION FetchData(Matrix<double>** pmatrix,const mxArray* dataref){{{*/
-void FetchData(Matrix<double>** pmatrix,const mxArray* dataref){
-
-	Matrix<double>* outmatrix=NULL;
-	int dummy=0;
-
-	if (mxIsClass(dataref,"double") ){
-
-		/*Convert matlab matrix to matrix: */
-		outmatrix=MatlabMatrixToMatrix(dataref);
-
-	}
-	else{
-		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
-	}
-
-	/*Assign output pointers:*/
-	*pmatrix=outmatrix;
-}
-/*}}}*/
-/*FUNCTION FetchData(Vector<double>** pvector,const mxArray* dataref){{{*/
-void FetchData(Vector<double>** pvector,const mxArray* dataref){
-
-	Vector<double>* vector=NULL;
-	int dummy;
-
-	if(mxIsEmpty(dataref)){
-		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
-		vector=new Vector<double>(0);
-	}
-	else if (mxIsClass(dataref,"double") ){
-
-		/*Convert matlab vector to petsc vector: */
-		vector=MatlabVectorToVector(dataref);
-	}
-	else{
-		/*This is an error: we don't have the correct input!: */
-		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
-	}
-
-	/*Assign output pointers:*/
-	*pvector=vector;
-}
-/*}}}*/
 /*FUNCTION FetchData(BamgGeom** pbamggeom,const mxArray* dataref){{{*/
 void FetchData(BamgGeom** pbamggeom,const mxArray* dataref){
@@ -681,2 +640,574 @@
 }
 /*}}}*/
+
+/*Toolkit*/
+/*FUNCTION MatlabMatrixToDoubleMatrix {{{*/
+int MatlabMatrixToDoubleMatrix(double** pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
+
+	int        i,j,count,rows,cols;
+
+	/*output: */
+	double* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex*    ir=NULL;
+	mwIndex*    jc=NULL;
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		double* pmxmatrix=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			/*Now, get ir,jc and pr: */
+			ir=mxGetIr(mxmatrix);
+			jc=mxGetJc(mxmatrix);
+
+			/*Now, start inserting data into double* matrix: */
+			count=0;
+			for(i=0;i<cols;i++){
+				for(j=0;j<(jc[i+1]-jc[i]);j++){
+					matrix[rows*ir[count]+i]=pmxmatrix[count];
+					count++;
+				}
+			}
+		}
+
+	}
+	else if(mxIsClass(mxmatrix,"double")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		double* pmxmatrix=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else if(mxIsClass(mxmatrix,"single")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		float *pmxmatrix=(float*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else if(mxIsClass(mxmatrix,"int16")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		short int *pmxmatrix=(short*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else if(mxIsClass(mxmatrix,"uint8")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		char *pmxmatrix=(char*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else{
+		_error_("Matlab matrix type Not implemented yet");
+	}
+
+	/*Assign output pointer: */
+	*pmatrix=matrix;
+	*pmatrix_rows=rows;
+	*pmatrix_cols=cols;
+
+	return 1;
+}/*}}}*/
+/*FUNCTION MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
+int MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
+
+	int  i,j,rows,cols;
+	int  numel,ndims;
+	int *size,*dims;
+	double* mxmatrix_ptr=NULL;
+	const mwSize* ipt=NULL;
+
+	/*output: */
+	double* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	double  *pr    = NULL;
+	int      count;
+
+	/*get Matlab matrix information: */
+	numel=mxGetNumberOfElements(mxmatrix);
+	ndims=mxGetNumberOfDimensions(mxmatrix);
+	ipt  =mxGetDimensions(mxmatrix);
+	size =xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		rows = mxGetM(mxmatrix);
+		cols = mxGetN(mxmatrix);
+
+		matrix=xNewZeroInit<double>(rows*cols);
+
+		/*Now, get ir,jc and pr: */
+		ir = mxGetIr(mxmatrix);
+		jc = mxGetJc(mxmatrix);
+		pr = mxGetPr(mxmatrix);
+
+		/*Now, start inserting data into double* matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				*(matrix+rows*ir[count]+i)=pr[count];
+				count++;
+			}
+		}
+
+	}
+	else{
+
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
+
+		/*Create serial matrix: */
+		matrix=xNewZeroInit<double>(numel);
+
+		dims=xNew<int>(ndims);
+		for(i=0;i<numel;i++){
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			j = IndexFromRowWiseDims(dims,size,ndims);
+			matrix[j]=(double)mxmatrix_ptr[i];
+		}
+		xDelete<int>(dims);
+	}
+
+	/*Assign output pointer: */
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
+int MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
+
+	int  i,j,rows,cols;
+	int  numel,ndims;
+	int *size,*dims;
+	bool* mxmatrix_ptr=NULL;
+	const mwSize* ipt=NULL;
+
+	/*output: */
+	bool* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	bool    *pm    = NULL;
+	int      count;
+
+	/*get Matlab matrix information: */
+	numel = mxGetNumberOfElements(mxmatrix);
+	ndims = mxGetNumberOfDimensions(mxmatrix);
+	ipt   = mxGetDimensions(mxmatrix);
+	size  = xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+		matrix=xNewZeroInit<bool>(rows*cols);
+
+		/*Now, get ir,jc and pm: */
+		ir=mxGetIr(mxmatrix);
+		jc=mxGetJc(mxmatrix);
+		pm=(bool*)mxGetData(mxmatrix);
+
+		/*Now, start inserting data into bool* matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				matrix[rows*ir[count]+i]=pm[count];
+				count++;
+			}
+		}
+	}
+	else{
+
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=(bool*)mxGetData(mxmatrix);
+
+		/*Create serial matrix: */
+		matrix=xNew<bool>(numel);
+		dims=xNew<int>(ndims);
+		for(i=0;i<numel;i++){
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			j=IndexFromRowWiseDims(dims,size,ndims);
+			matrix[j]=(bool)mxmatrix_ptr[i];
+		}
+		xDelete<int>(dims);
+	}
+
+	/*Assign output pointer: */
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
+int MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
+
+	int           i,j,rows,cols;
+	int           numel,ndims;
+	int          *size , *dims;
+	mxChar       *mxmatrix_ptr = NULL;
+	const mwSize *ipt          = NULL;
+
+	/*output: */
+	char* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	char    *pm    = NULL;
+	int      count;
+
+	/*get Matlab matrix information: */
+	numel = mxGetNumberOfElements(mxmatrix);
+	ndims = mxGetNumberOfDimensions(mxmatrix);
+	ipt   = mxGetDimensions(mxmatrix);
+	size  = xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		rows = mxGetM(mxmatrix);
+		cols = mxGetN(mxmatrix);
+		matrix=xNew<char>(rows*cols);
+
+		/*Now, get ir,jc and pm: */
+		ir = mxGetIr(mxmatrix);
+		jc = mxGetJc(mxmatrix);
+		pm = (char*)mxGetData(mxmatrix);
+
+		/*Now, start inserting data into char* matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				matrix[rows*ir[count]+i]=(char)pm[count];
+				count++;
+			}
+		}
+	}
+	else{
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=mxGetChars(mxmatrix);
+
+		/*Create serial matrix: */
+		matrix=xNew<char>(numel+1);
+		matrix[numel]='\0';
+
+		/*looping code adapted from Matlab example explore.c: */
+		int elements_per_page = size[0] * size[1];
+		/* total_number_of_pages = size[2] x size[3] x ... x size[N-1] */
+		int total_number_of_pages = 1;
+		for (i=2; i<ndims; i++) {
+			total_number_of_pages *= size[i];
+		}
+
+		i=0;
+		for (int page=0; page < total_number_of_pages; page++) {
+			int row;
+			/* On each page, walk through each row. */
+			for (row=0; row<size[0]; row++)  {
+				int column;
+				j = (page * elements_per_page) + row;
+
+				/* Walk along each column in the current row. */
+				for (column=0; column<size[1]; column++) {
+					*(matrix+i++)=(char)*(mxmatrix_ptr+j);
+					j += size[0];
+				}
+			}
+		}
+	}
+
+	/*Assign output pointer: */
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION mxGetAssignedField{{{*/
+mxArray* mxGetAssignedField(const mxArray* pmxa_array,int number,const char* field){
+
+	//output
+	mxArray* mxfield=NULL;
+
+	//input
+	mxArray    *inputs[2];
+	mxArray    *pindex      = NULL;
+	const char *fnames[2];
+	mwSize      ndim        = 2;
+	mwSize      onebyone[2] = {1,1};
+
+	//We want to call the subsasgn method, and get the returned array.This ensures that if we are running 
+	//large sized problems, the data is truly loaded from disk by the model subsasgn class method.
+	inputs[0]=(mxArray*)pmxa_array; //this is the model
+
+	//create index structure used in the assignment (index.type='.' and index.subs='x' for field x for ex)
+	fnames[0] = "type";
+	fnames[1] = "subs";
+	pindex=mxCreateStructArray( ndim,onebyone,2,fnames);
+	mxSetField( pindex, 0, "type",mxCreateString("."));
+	mxSetField( pindex, 0, "subs",mxCreateString(field));
+	inputs[1]=pindex;
+
+	mexCallMATLAB( 1, &mxfield, 2, (mxArray**)inputs, "subsref");
+
+	return mxfield;
+}/*}}}*/
+
+GenericOption<double>* OptionDoubleParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<double> *odouble = NULL;
+
+	/*check and parse the name  */
+	odouble=new GenericOption<double>();
+	odouble->name =xNew<char>(strlen(name)+1);
+	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
+	FetchData(&odouble->value,prhs[0]);
+	odouble->numel=1;
+	odouble->ndims=1;
+	odouble->size=NULL;
+
+	return(odouble);
+}/*}}}*/
+GenericOption<double*>* OptionDoubleArrayParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<double*> *odouble = NULL;
+
+	/*check and parse the name  */
+	odouble=new GenericOption<double*>();
+	odouble->name =xNew<char>(strlen(name)+1);
+	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"double")){
+		_error_("Value of option \"" << odouble->name  << "\" must be class \"double\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&odouble->value,&odouble->numel,&odouble->ndims,&odouble->size,prhs[0]);
+
+	return(odouble);
+}/*}}}*/
+GenericOption<bool*>* OptionLogicalParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<bool*> *ological = NULL;
+
+	/*check and parse the name  */
+	ological=new GenericOption<bool*>();
+	ological->name =xNew<char>(strlen(name)+1);
+	memcpy(ological->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"logical")){
+		_error_("Value of option \"" << ological->name  << "\" must be class \"logical\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&ological->value,&ological->numel,&ological->ndims,&ological->size,prhs[0]);
+
+	return(ological);
+}/*}}}*/
+GenericOption<char*>* OptionCharParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<char*>  *ochar = NULL;
+
+	/*check and parse the name  */
+	ochar=new GenericOption<char*>();
+	ochar->name =xNew<char>(strlen(name)+1);
+	memcpy(ochar->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"char")){
+		_error_("Value of option \"" << ochar->name  << "\" must be class \"char\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&ochar->value,&ochar->numel,&ochar->ndims,&ochar->size,prhs[0]);
+
+	return(ochar);
+}/*}}}*/
+GenericOption<Options**>* OptionStructParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	int            i;
+	char           namei[161];
+	Option*                   option      = NULL;
+	GenericOption<Options**>  *ostruct    = NULL;
+	const mwSize  *ipt        = NULL;
+	const mxArray *structi;
+	mwIndex        sindex;
+
+	/*check and parse the name  */
+	ostruct=new GenericOption<Options**>();
+	ostruct->name =xNew<char>(strlen(name)+1);
+	memcpy(ostruct->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"struct")){
+		_error_("Value of option \"" << ostruct->name  << "\" must be class \"struct\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	ostruct->numel=mxGetNumberOfElements(prhs[0]);
+	ostruct->ndims=mxGetNumberOfDimensions(prhs[0]);
+	ipt           =mxGetDimensions(prhs[0]);
+	ostruct->size =xNew<int>(ostruct->ndims);
+	for (i=0; i<ostruct->ndims; i++) ostruct->size[i]=(int)ipt[i];
+	if (ostruct->numel) ostruct->value=xNew<Options*>(ostruct->numel);
+
+	/*loop through and process each element of the struct array  */
+	for (sindex=0; sindex<ostruct->numel; sindex++) {
+		ostruct->value[sindex]=new Options;
+
+		/*loop through and process each field for the element  */
+		for (i=0; i<mxGetNumberOfFields(prhs[0]); i++) {
+			sprintf(namei,"%s.%s",name,mxGetFieldNameByNumber(prhs[0],i));
+			structi=mxGetFieldByNumber(prhs[0],sindex,i);
+
+			option=(Option*)OptionParse(namei,&structi);
+			ostruct->value[sindex]->AddObject((Object*)option);
+			option=NULL;
+		}
+	}
+
+	return(ostruct);
+}/*}}}*/
+GenericOption<Options*>* OptionCellParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	int            i;
+	int           *dims;
+	char           namei[161];
+	char           cstr[81];
+	GenericOption<Options*> *ocell      = NULL;
+	Option        *option     = NULL;
+	const mwSize  *ipt        = NULL;
+	const mxArray *celli;
+	mwIndex        cindex;
+
+	/*check and parse the name  */
+	ocell=new GenericOption<Options*>();
+	ocell->name =xNew<char>(strlen(name)+1);
+	memcpy(ocell->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"cell")){
+		_error_("Value of option \"" << ocell->name  << "\" must be class \"cell\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+
+	ocell->numel=mxGetNumberOfElements(prhs[0]);
+	ocell->ndims=mxGetNumberOfDimensions(prhs[0]);
+	ipt         =mxGetDimensions(prhs[0]);
+	ocell->size =xNew<int>(ocell->ndims);
+	for (i=0; i<ocell->ndims; i++) ocell->size[i]=(int)ipt[i];
+	ocell->value=new Options;
+
+	/*loop through and process each element of the cell array  */
+	dims=xNew<int>(ocell->ndims);
+	for (cindex=0; cindex<ocell->numel; cindex++) {
+		ColumnWiseDimsFromIndex(dims,(int)cindex,ocell->size,ocell->ndims);
+		StringFromDims(cstr,dims,ocell->ndims);
+		#ifdef _INTEL_WIN_
+			_snprintf(namei,161,"%s%s",name,cstr);
+		#else
+			snprintf(namei,161,"%s%s",name,cstr);
+		#endif
+		celli=mxGetCell(prhs[0],cindex);
+
+		option=(Option*)OptionParse(namei,&celli);
+		ocell->value->AddObject((Object*)option);
+		option=NULL;
+	}
+	xDelete<int>(dims);
+
+	return(ocell);
+}/*}}}*/
+Option* OptionParse(char* name, const mxArray* prhs[]){ /*{{{*/
+
+	Option  *option = NULL;
+	mxArray *lhs[1];
+
+	/*parse the value according to the matlab data type  */
+	if     (mxIsClass(prhs[0],"double")  && (mxGetNumberOfElements(prhs[0])==1))
+	 option=(Option*)OptionDoubleParse(name,prhs);
+	else if(mxIsClass(prhs[0],"double")  && (mxGetNumberOfElements(prhs[0])!=1))
+	 option=(Option*)OptionDoubleArrayParse(name,prhs);
+	else if(mxIsClass(prhs[0],"logical"))
+	 option=(Option*)OptionLogicalParse(name,prhs);
+	else if(mxIsClass(prhs[0],"char"))
+	 option=(Option*)OptionCharParse(name,prhs);
+	else if(mxIsClass(prhs[0],"struct"))
+	 option=(Option*)OptionStructParse(name,prhs);
+	else if(mxIsClass(prhs[0],"cell"))
+	 option=(Option*)OptionCellParse(name,prhs);
+	else {
+		_printf0_("  Converting value of option \"" << name << "\" from unrecognized class \"" << mxGetClassName(prhs[0]) << "\" to class \"" << "struct" << "\".\n");
+		if (!mexCallMATLAB(1,lhs,1,(mxArray**)prhs,"struct")) {
+			option=(Option*)OptionStructParse(name,(const mxArray**)lhs);
+			mxDestroyArray(lhs[0]);
+		}
+		else _error_("Second argument value of option \""<< name <<"\" is of unrecognized class \""<< mxGetClassName(prhs[0]) <<"\".");
+	}
+
+	return(option);
+}/*}}}*/
Index: sm/trunk/src/wrappers/matlab/io/MatlabMatrixToDoubleMatrix.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToDoubleMatrix.cpp	(revision 16136)
+++ 	(revision )
@@ -1,129 +1,0 @@
-/* \file MatlabMatrixToDoubleMatrix.cpp
- * \brief: convert a sparse or dense matlab matrix to a double* pointer
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-/*Matlab includes: */
-#include "./matlabio.h"
-
-int MatlabMatrixToDoubleMatrix(double** pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
-
-	int        i,j,count,rows,cols;
-
-	/*output: */
-	double* matrix=NULL;
-
-	/*matlab indices: */
-	mwIndex*    ir=NULL;
-	mwIndex*    jc=NULL;
-
-	/*Ok, first check if we are dealing with a sparse or full matrix: */
-	if (mxIsSparse(mxmatrix)){
-
-		/*Dealing with sparse matrix: recover size first: */
-		double* pmxmatrix=(double*)mxGetPr(mxmatrix);
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-
-		if(rows*cols){
-			matrix=xNewZeroInit<double>(rows*cols);
-
-			/*Now, get ir,jc and pr: */
-			ir=mxGetIr(mxmatrix);
-			jc=mxGetJc(mxmatrix);
-
-			/*Now, start inserting data into double* matrix: */
-			count=0;
-			for(i=0;i<cols;i++){
-				for(j=0;j<(jc[i+1]-jc[i]);j++){
-					matrix[rows*ir[count]+i]=pmxmatrix[count];
-					count++;
-				}
-			}
-		}
-
-	}
-	else if(mxIsClass(mxmatrix,"double")){
-		/*Dealing with dense matrix: recover pointer and size: */
-		double* pmxmatrix=(double*)mxGetPr(mxmatrix);
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-
-		/*Create serial matrix: */
-		if(rows*cols){
-			matrix=xNewZeroInit<double>(rows*cols);
-
-			for(i=0;i<rows;i++){
-				for(j=0;j<cols;j++){
-					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
-				}
-			}
-		}
-	}
-	else if(mxIsClass(mxmatrix,"single")){
-		/*Dealing with dense matrix: recover pointer and size: */
-		float *pmxmatrix=(float*)mxGetPr(mxmatrix);
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-
-		/*Create serial matrix: */
-		if(rows*cols){
-			matrix=xNewZeroInit<double>(rows*cols);
-
-			for(i=0;i<rows;i++){
-				for(j=0;j<cols;j++){
-					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
-				}
-			}
-		}
-	}
-	else if(mxIsClass(mxmatrix,"int16")){
-		/*Dealing with dense matrix: recover pointer and size: */
-		short int *pmxmatrix=(short*)mxGetPr(mxmatrix);
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-
-		/*Create serial matrix: */
-		if(rows*cols){
-			matrix=xNewZeroInit<double>(rows*cols);
-
-			for(i=0;i<rows;i++){
-				for(j=0;j<cols;j++){
-					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
-				}
-			}
-		}
-	}
-	else if(mxIsClass(mxmatrix,"uint8")){
-		/*Dealing with dense matrix: recover pointer and size: */
-		char *pmxmatrix=(char*)mxGetPr(mxmatrix);
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-
-		/*Create serial matrix: */
-		if(rows*cols){
-			matrix=xNewZeroInit<double>(rows*cols);
-
-			for(i=0;i<rows;i++){
-				for(j=0;j<cols;j++){
-					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
-				}
-			}
-		}
-	}
-	else{
-		_error_("Matlab matrix type Not implemented yet");
-	}
-
-	/*Assign output pointer: */
-	*pmatrix=matrix;
-	*pmatrix_rows=rows;
-	*pmatrix_cols=cols;
-
-	return 1;
-}
Index: sm/trunk/src/wrappers/matlab/io/MatlabMatrixToIssmMat.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToIssmMat.cpp	(revision 16136)
+++ 	(revision )
@@ -1,21 +1,0 @@
-/*!\file MatlabMatrixToIssmDenseMat.cpp
- */
-
-/*Headers:*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "./matlabio.h"
-
-IssmMat<double>* MatlabMatrixToIssmMat(const mxArray* dataref){
-
-	IssmDenseMat<double>* output=NULL;
-
-	output=new IssmDenseMat<double>();
-	MatlabMatrixToDoubleMatrix(&output->matrix,&output->M,&output->N,dataref);
-	return (IssmMat<double>*)output;
-
-}
Index: sm/trunk/src/wrappers/matlab/io/MatlabMatrixToMatrix.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToMatrix.cpp	(revision 16136)
+++ 	(revision )
@@ -1,27 +1,0 @@
-/*!\file MatlabMatrixToMatrix.cpp
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "./matlabio.h"
-
-Matrix<double>* MatlabMatrixToMatrix(const mxArray* mxmatrix){
-
-	int dummy;
-	Matrix<double>* matrix=NULL;
-
-	/*allocate matrix object: */
-	matrix=new Matrix<double>();
-
-	#ifdef _HAVE_PETSC_
-	matrix->pmatrix=MatlabMatrixToPetscMat(mxmatrix);
-	#else
-	matrix->imatrix=MatlabMatrixToIssmMat(mxmatrix);
-	#endif
-
-	return matrix;
-}
Index: sm/trunk/src/wrappers/matlab/io/MatlabMatrixToPetscMat.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToPetscMat.cpp	(revision 16136)
+++ 	(revision )
@@ -1,124 +1,0 @@
-/* \file MatlabMatrixToPetscMatrix.cpp
- * \brief: convert a sparse or dense matlab matrix to a serial Petsc matrix:
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-#include "../../c/shared/shared.h"
-
-/*Petsc includes: */
-#ifdef _HAVE_PETSC_
-#include <petscmat.h>
-#include <petscvec.h>
-#include <petscksp.h>
-#endif
-
-/*Matlab includes: */
-#include "./matlabio.h"
-
-PetscMat* MatlabMatrixToPetscMat(const mxArray* mxmatrix){
-
-	int dummy;
-	PetscMat* matrix=new PetscMat();
-
-	MatlabMatrixToPetscMat(&matrix->matrix, &dummy, &dummy, mxmatrix);
-
-	return matrix;
-}
-int MatlabMatrixToPetscMat(Mat* pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
-
-	int rows, cols;
-	double *mxmatrix_ptr = NULL;
-	double *tmatrix      = NULL;
-	int ierr;
-	int i,j;
-
-	/*output: */
-	Mat matrix = NULL;
-
-	/*matlab indices: */
-	mwIndex *ir = NULL;
-	mwIndex *jc = NULL;
-	double  *pr = NULL;
-	int     count;
-	int     nnz;
-	int     nz;
-
-	/*petsc indices: */
-	int *idxm = NULL;
-	int *idxn = NULL;
-
-	/*Ok, first check if we are dealing with a sparse or full matrix: */
-	if (mxIsSparse(mxmatrix)){
-
-		/*Dealing with sparse matrix: recover size first: */
-		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-		nnz=mxGetNzmax(mxmatrix);
-		if(rows){
-			nz=(int)((double)nnz/(double)rows);
-		}
-		else{
-			nz=0;
-		}
-
-		ierr=MatCreateSeqAIJ(PETSC_COMM_SELF,rows,cols,nz,PETSC_NULL,&matrix);CHKERRQ(ierr);
-
-		/*Now, get ir,jc and pr: */
-		pr=mxGetPr(mxmatrix);
-		ir=mxGetIr(mxmatrix);
-		jc=mxGetJc(mxmatrix);
-
-		/*Now, start inserting data into sparse matrix: */
-		count=0;
-		for(i=0;i<cols;i++){
-			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				MatSetValue(matrix,ir[count],i,pr[count],INSERT_VALUES);
-				count++;
-			}
-		}
-	}
-	else{
-		/*Dealing with dense matrix: recover pointer and size: */
-		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-
-		/*transpose, as Petsc now does not allows MAT_COLUMN_ORIENTED matrices in MatSetValues: */
-		tmatrix=xNew<double>(rows*cols);
-		for(i=0;i<cols;i++){
-			for(j=0;j<rows;j++){
-				*(tmatrix+rows*i+j)=*(mxmatrix_ptr+cols*j+i);
-			}
-		}
-
-		/*Create serial matrix: */
-		ierr=MatCreateSeqDense(PETSC_COMM_SELF,rows,cols,NULL,&matrix);CHKERRQ(ierr);
-
-		/*Insert mxmatrix_ptr values into petsc matrix: */
-		idxm=xNew<int>(rows);
-		idxn=xNew<int>(cols);
-
-		for(i=0;i<rows;i++)idxm[i]=i;
-		for(i=0;i<cols;i++)idxn[i]=i;
-
-		ierr=MatSetValues(matrix,rows,idxm,cols,idxn,tmatrix,INSERT_VALUES); CHKERRQ(ierr);
-
-		xDelete<double>(tmatrix);
-	}
-
-	/*Assemble matrix: */
-	MatAssemblyBegin(matrix,MAT_FINAL_ASSEMBLY); 
-	MatAssemblyEnd(matrix,MAT_FINAL_ASSEMBLY);
-
-	/*Assign output pointer: */
-	*pmatrix=matrix;
-	if(pmatrix_rows) *pmatrix_rows=rows;
-	if(pmatrix_cols) *pmatrix_cols=cols;
-
-	return 1;
-}
Index: sm/trunk/src/wrappers/matlab/io/MatlabNArrayToNArray.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabNArrayToNArray.cpp	(revision 16136)
+++ 	(revision )
@@ -1,248 +1,0 @@
-/* \file MatlabNArrayToNArray.cpp
- * \brief: convert a sparse or dense matlab n-dimensional array to cpp n-dimensional array
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include "./matlabio.h"
-
-/*FUNCTION MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
-int MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
-
-	int  i,j,rows,cols;
-	int  numel,ndims;
-	int *size,*dims;
-	double* mxmatrix_ptr=NULL;
-	const mwSize* ipt=NULL;
-
-	/*output: */
-	double* matrix=NULL;
-
-	/*matlab indices: */
-	mwIndex *ir    = NULL;
-	mwIndex *jc    = NULL;
-	double  *pr    = NULL;
-	int      count;
-
-	/*get Matlab matrix information: */
-	numel=mxGetNumberOfElements(mxmatrix);
-	ndims=mxGetNumberOfDimensions(mxmatrix);
-	ipt  =mxGetDimensions(mxmatrix);
-	size =xNew<int>(ndims);
-	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
-
-	/*Ok, first check if we are dealing with a sparse or full matrix: */
-	if (mxIsSparse(mxmatrix)){
-
-		/*Dealing with sparse matrix: recover size first: */
-		rows = mxGetM(mxmatrix);
-		cols = mxGetN(mxmatrix);
-
-		matrix=xNewZeroInit<double>(rows*cols);
-
-		/*Now, get ir,jc and pr: */
-		ir = mxGetIr(mxmatrix);
-		jc = mxGetJc(mxmatrix);
-		pr = mxGetPr(mxmatrix);
-
-		/*Now, start inserting data into double* matrix: */
-		count=0;
-		for(i=0;i<cols;i++){
-			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				*(matrix+rows*ir[count]+i)=pr[count];
-				count++;
-			}
-		}
-
-	}
-	else{
-
-		/*Dealing with dense matrix: recover pointer and size: */
-		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
-
-		/*Create serial matrix: */
-		matrix=xNewZeroInit<double>(numel);
-
-		dims=xNew<int>(ndims);
-		for(i=0;i<numel;i++){
-			ColumnWiseDimsFromIndex(dims,i,size,ndims);
-			j = IndexFromRowWiseDims(dims,size,ndims);
-			matrix[j]=(double)mxmatrix_ptr[i];
-		}
-		xDelete<int>(dims);
-	}
-
-	/*Assign output pointer: */
-	*pmatrix       = matrix;
-	*pmatrix_numel = numel;
-	*pmatrix_ndims = ndims;
-	*pmatrix_size  = size;
-
-	return 1;
-}
-/*}}}*/
-/*FUNCTION MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
-int MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
-
-	int  i,j,rows,cols;
-	int  numel,ndims;
-	int *size,*dims;
-	bool* mxmatrix_ptr=NULL;
-	const mwSize* ipt=NULL;
-
-	/*output: */
-	bool* matrix=NULL;
-
-	/*matlab indices: */
-	mwIndex *ir    = NULL;
-	mwIndex *jc    = NULL;
-	bool    *pm    = NULL;
-	int      count;
-
-	/*get Matlab matrix information: */
-	numel = mxGetNumberOfElements(mxmatrix);
-	ndims = mxGetNumberOfDimensions(mxmatrix);
-	ipt   = mxGetDimensions(mxmatrix);
-	size  = xNew<int>(ndims);
-	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
-
-	/*Ok, first check if we are dealing with a sparse or full matrix: */
-	if (mxIsSparse(mxmatrix)){
-
-		/*Dealing with sparse matrix: recover size first: */
-		rows=mxGetM(mxmatrix);
-		cols=mxGetN(mxmatrix);
-		matrix=xNewZeroInit<bool>(rows*cols);
-
-		/*Now, get ir,jc and pm: */
-		ir=mxGetIr(mxmatrix);
-		jc=mxGetJc(mxmatrix);
-		pm=(bool*)mxGetData(mxmatrix);
-
-		/*Now, start inserting data into bool* matrix: */
-		count=0;
-		for(i=0;i<cols;i++){
-			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				matrix[rows*ir[count]+i]=pm[count];
-				count++;
-			}
-		}
-	}
-	else{
-
-		/*Dealing with dense matrix: recover pointer and size: */
-		mxmatrix_ptr=(bool*)mxGetData(mxmatrix);
-
-		/*Create serial matrix: */
-		matrix=xNew<bool>(numel);
-		dims=xNew<int>(ndims);
-		for(i=0;i<numel;i++){
-			ColumnWiseDimsFromIndex(dims,i,size,ndims);
-			j=IndexFromRowWiseDims(dims,size,ndims);
-			matrix[j]=(bool)mxmatrix_ptr[i];
-		}
-		xDelete<int>(dims);
-	}
-
-	/*Assign output pointer: */
-	*pmatrix       = matrix;
-	*pmatrix_numel = numel;
-	*pmatrix_ndims = ndims;
-	*pmatrix_size  = size;
-
-	return 1;
-}
-/*}}}*/
-/*FUNCTION MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
-int MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
-
-	int           i,j,rows,cols;
-	int           numel,ndims;
-	int          *size , *dims;
-	mxChar       *mxmatrix_ptr = NULL;
-	const mwSize *ipt          = NULL;
-
-	/*output: */
-	char* matrix=NULL;
-
-	/*matlab indices: */
-	mwIndex *ir    = NULL;
-	mwIndex *jc    = NULL;
-	char    *pm    = NULL;
-	int      count;
-
-	/*get Matlab matrix information: */
-	numel = mxGetNumberOfElements(mxmatrix);
-	ndims = mxGetNumberOfDimensions(mxmatrix);
-	ipt   = mxGetDimensions(mxmatrix);
-	size  = xNew<int>(ndims);
-	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
-
-	/*Ok, first check if we are dealing with a sparse or full matrix: */
-	if (mxIsSparse(mxmatrix)){
-
-		/*Dealing with sparse matrix: recover size first: */
-		rows = mxGetM(mxmatrix);
-		cols = mxGetN(mxmatrix);
-		matrix=xNew<char>(rows*cols);
-
-		/*Now, get ir,jc and pm: */
-		ir = mxGetIr(mxmatrix);
-		jc = mxGetJc(mxmatrix);
-		pm = (char*)mxGetData(mxmatrix);
-
-		/*Now, start inserting data into char* matrix: */
-		count=0;
-		for(i=0;i<cols;i++){
-			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				matrix[rows*ir[count]+i]=(char)pm[count];
-				count++;
-			}
-		}
-	}
-	else{
-		/*Dealing with dense matrix: recover pointer and size: */
-		mxmatrix_ptr=mxGetChars(mxmatrix);
-
-		/*Create serial matrix: */
-		matrix=xNew<char>(numel+1);
-		matrix[numel]='\0';
-
-		/*looping code adapted from Matlab example explore.c: */
-		int elements_per_page = size[0] * size[1];
-		/* total_number_of_pages = size[2] x size[3] x ... x size[N-1] */
-		int total_number_of_pages = 1;
-		for (i=2; i<ndims; i++) {
-			total_number_of_pages *= size[i];
-		}
-
-		i=0;
-		for (int page=0; page < total_number_of_pages; page++) {
-			int row;
-			/* On each page, walk through each row. */
-			for (row=0; row<size[0]; row++)  {
-				int column;
-				j = (page * elements_per_page) + row;
-
-				/* Walk along each column in the current row. */
-				for (column=0; column<size[1]; column++) {
-					*(matrix+i++)=(char)*(mxmatrix_ptr+j);
-					j += size[0];
-				}
-			}
-		}
-	}
-
-	/*Assign output pointer: */
-	*pmatrix       = matrix;
-	*pmatrix_numel = numel;
-	*pmatrix_ndims = ndims;
-	*pmatrix_size  = size;
-
-	return 1;
-}
-/*}}}*/
Index: sm/trunk/src/wrappers/matlab/io/MatlabVectorToDoubleVector.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToDoubleVector.cpp	(revision 16136)
+++ 	(revision )
@@ -1,90 +1,0 @@
-/* \file MatlabVectorToDoubleVector.cpp
- * \brief: convert a sparse or dense matlab vector to a serial vector:
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-/*Matlab includes: */
-#include "./matlabio.h"
-
-int MatlabVectorToDoubleVector(double** pvector,int* pvector_rows,const mxArray* mxvector){
-
-	int rows,cols;
-	double* mxvector_ptr=NULL;
-	int ierr;
-	int i,j;
-
-	/*output: */
-	double* vector=NULL;
-
-	/*matlab indices: */
-	mwIndex*    ir=NULL;
-	mwIndex*    jc=NULL;
-	double* pr=NULL;
-	int     count;
-	int     nnz;
-	int     nz;
-
-	/*Ok, first check if we are dealing with a sparse or full vector: */
-	if (mxIsSparse(mxvector)){
-
-		/*Dealing with sparse vector: recover size first: */
-		mxvector_ptr=(double*)mxGetPr(mxvector);
-		rows=mxGetM(mxvector);
-		cols=mxGetN(mxvector);
-		nnz=mxGetNzmax(mxvector);
-
-		/*Check that input is actualy a vector*/
-		if (cols!=1) _error_("input vector of size " << rows << "x" << cols << " should have only one column");
-
-		nz=(int)((double)nnz/(double)rows);
-
-		if(rows){
-			vector=xNewZeroInit<double>(rows);
-
-			/*Now, get ir,jc and pr: */
-			pr=mxGetPr(mxvector);
-			ir=mxGetIr(mxvector);
-			jc=mxGetJc(mxvector);
-
-			/*Now, start inserting data into sparse vector: */
-			count=0;
-			for(i=0;i<cols;i++){
-				for(j=0;j<(jc[i+1]-jc[i]);j++){
-					vector[ir[count]]=pr[count];
-					count++;
-				}
-			}
-		}
-
-	}
-	else{
-
-		/*Dealing with dense vector: recover pointer and size: */
-		mxvector_ptr=(double*)mxGetPr(mxvector);
-		rows=mxGetM(mxvector);
-		cols=mxGetN(mxvector);
-
-		/*Check that input is actualy a vector*/
-		if (cols!=1) _error_("input vector of size " << rows << "x" << cols << " should have only one column");
-
-		/*allocate and memcpy*/
-		if(rows){
-			vector=xNew<double>(rows);
-			memcpy(vector,mxvector_ptr,rows*sizeof(double));
-		}
-		else{
-			vector=NULL;
-		}
-	}
-
-	/*Assign output pointer: */
-	*pvector=vector;
-	*pvector_rows=rows;
-
-	return 1;
-}
Index: sm/trunk/src/wrappers/matlab/io/MatlabVectorToIssmSeqVec.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToIssmSeqVec.cpp	(revision 16136)
+++ 	(revision )
@@ -1,15 +1,0 @@
-/*!\file MatlabVectorToIssmSeqVec.cpp
- */
-
-/*Headers:*/
-#include "./matlabio.h"
-
-IssmSeqVec<double>* MatlabVectorToIssmSeqVec(const mxArray* dataref){
-
-	IssmSeqVec<double>* output=NULL;
-
-	output=new IssmSeqVec<double>();
-	MatlabVectorToDoubleVector(&output->vector,&output->M,dataref);
-	return output;
-
-}
Index: sm/trunk/src/wrappers/matlab/io/MatlabVectorToIssmVec.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToIssmVec.cpp	(revision 16136)
+++ 	(revision )
@@ -1,21 +1,0 @@
-/*!\file MatlabVectorToIssmVec.cpp
- */
-
-/*Headers:*/
-#include "./matlabio.h"
-
-IssmVec<double>* MatlabVectorToIssmVec(const mxArray* dataref){
-
-	IssmVec<double>* output=NULL;
-	IssmSeqVec<double>* seqvec=NULL;
-
-	output=new IssmVec<double>();
-
-	seqvec=new IssmSeqVec<double>();
-
-	MatlabVectorToDoubleVector(&seqvec->vector,&seqvec->M,dataref);
-
-	output->vector=(IssmAbsVec<double>*)seqvec;
-	return output;
-
-}
Index: sm/trunk/src/wrappers/matlab/io/MatlabVectorToPetscVec.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToPetscVec.cpp	(revision 16136)
+++ 	(revision )
@@ -1,100 +1,0 @@
-/* \file MatlabVectorToPetscVector.cpp
- * \brief: convert a sparse or dense matlab vector to a serial Petsc vector:
- */
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-/*Matlab includes: */
-#include "./matlabio.h"
-
-PetscVec* MatlabVectorToPetscVec(const mxArray* mxvector){
-
-	int dummy;
-	PetscVec* vector=new PetscVec();
-
-	MatlabVectorToPetscVec(&vector->vector,&dummy, mxvector);
-
-	return vector;
-}
-
-int MatlabVectorToPetscVec(Vec* pvector,int* pvector_rows,const mxArray* mxvector){
-
-	int rows, cols;
-	double* mxvector_ptr=NULL;
-	int ierr;
-	int i,j;
-
-	/*output: */
-	Vec vector=NULL;
-
-	/*matlab indices: */
-	mwIndex*    ir=NULL;
-	mwIndex*    jc=NULL;
-	double* pr=NULL;
-	int     count;
-	int     nnz;
-	int     nz;
-
-	/*petsc indices: */
-	int* idxm=NULL;
-
-	/*Ok, first check if we are dealing with a sparse or full vector: */
-	if (mxIsSparse(mxvector)){
-
-		/*Dealing with sparse vector: recover size first: */
-		mxvector_ptr=(double*)mxGetPr(mxvector);
-		rows=mxGetM(mxvector);
-		cols=mxGetN(mxvector);
-		nnz=mxGetNzmax(mxvector);
-		nz=(int)((double)nnz/(double)rows);
-
-		ierr=VecCreateSeq(PETSC_COMM_SELF,rows,&vector);CHKERRQ(ierr);
-
-		/*Now, get ir,jc and pr: */
-		pr=mxGetPr(mxvector);
-		ir=mxGetIr(mxvector);
-		jc=mxGetJc(mxvector);
-
-		/*Now, start inserting data into sparse vector: */
-		count=0;
-		for(i=0;i<cols;i++){
-			for(j=0;j<(jc[i+1]-jc[i]);j++){
-				VecSetValue(vector,ir[count],pr[count],INSERT_VALUES);
-				count++;
-			}
-		}
-
-	}
-	else{
-
-		/*Dealing with dense vector: recover pointer and size: */
-		mxvector_ptr=(double*)mxGetPr(mxvector);
-		rows=mxGetM(mxvector);
-		cols=mxGetN(mxvector);
-
-		/*Create serial vector: */
-		ierr=VecCreateSeq(PETSC_COMM_SELF,rows,&vector);CHKERRQ(ierr);
-
-		/*Insert mxvector_ptr values into petsc vector: */
-		idxm=xNew<int>(rows);
-
-		for(i=0;i<rows;i++)idxm[i]=i;
-
-		ierr=VecSetValues(vector,rows,idxm,mxvector_ptr,INSERT_VALUES);CHKERRQ(ierr);
-
-	}
-
-	/*Assemble vector: */
-	VecAssemblyBegin(vector);
-	VecAssemblyEnd(vector);
-
-	/*Assign output pointer: */
-	*pvector=vector;
-	*pvector_rows=rows;
-
-	return 1;
-}
Index: sm/trunk/src/wrappers/matlab/io/MatlabVectorToVector.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToVector.cpp	(revision 16136)
+++ 	(revision )
@@ -1,27 +1,0 @@
-/*!\file MatlabVectorToVector.cpp
- */
-
-/*Headers:*/
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-#include "./matlabio.h"
-
-Vector<double>* MatlabVectorToVector(const mxArray* mxvector){
-
-	int dummy;
-	Vector<double>* vector=NULL;
-
-	/*allocate vector object: */
-	vector=new Vector<double>();
-
-	#ifdef _HAVE_PETSC_
-	vector->pvector=MatlabVectorToPetscVec(mxvector);
-	#else
-	vector->ivector=MatlabVectorToIssmVec(mxvector);
-	#endif
-
-	return vector;
-}
Index: sm/trunk/src/wrappers/matlab/io/OptionParse.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/OptionParse.cpp	(revision 16136)
+++ 	(revision )
@@ -1,199 +1,0 @@
-/*\file OptionParse.c
- *\brief: functions to parse the mex options.
- */
-#ifdef HAVE_CONFIG_H
-    #include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#include <cstring> 
-#include "./matlabio.h"
-
-GenericOption<double>* OptionDoubleParse( char* name, const mxArray* prhs[]){ /*{{{*/
-
-	GenericOption<double> *odouble = NULL;
-
-	/*check and parse the name  */
-	odouble=new GenericOption<double>();
-	odouble->name =xNew<char>(strlen(name)+1);
-	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
-	FetchData(&odouble->value,prhs[0]);
-	odouble->numel=1;
-	odouble->ndims=1;
-	odouble->size=NULL;
-
-	return(odouble);
-}/*}}}*/
-GenericOption<double*>* OptionDoubleArrayParse( char* name, const mxArray* prhs[]){ /*{{{*/
-
-	GenericOption<double*> *odouble = NULL;
-
-	/*check and parse the name  */
-	odouble=new GenericOption<double*>();
-	odouble->name =xNew<char>(strlen(name)+1);
-	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
-
-	/*check and parse the value  */
-	if (!mxIsClass(prhs[0],"double")){
-		_error_("Value of option \"" << odouble->name  << "\" must be class \"double\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
-	}
-	FetchData(&odouble->value,&odouble->numel,&odouble->ndims,&odouble->size,prhs[0]);
-
-	return(odouble);
-}/*}}}*/
-GenericOption<bool*>* OptionLogicalParse( char* name, const mxArray* prhs[]){ /*{{{*/
-
-	GenericOption<bool*> *ological = NULL;
-
-	/*check and parse the name  */
-	ological=new GenericOption<bool*>();
-	ological->name =xNew<char>(strlen(name)+1);
-	memcpy(ological->name,name,(strlen(name)+1)*sizeof(char));
-
-	/*check and parse the value  */
-	if (!mxIsClass(prhs[0],"logical")){
-		_error_("Value of option \"" << ological->name  << "\" must be class \"logical\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
-	}
-	FetchData(&ological->value,&ological->numel,&ological->ndims,&ological->size,prhs[0]);
-
-	return(ological);
-}/*}}}*/
-GenericOption<char*>* OptionCharParse( char* name, const mxArray* prhs[]){ /*{{{*/
-
-	GenericOption<char*>  *ochar = NULL;
-
-	/*check and parse the name  */
-	ochar=new GenericOption<char*>();
-	ochar->name =xNew<char>(strlen(name)+1);
-	memcpy(ochar->name,name,(strlen(name)+1)*sizeof(char));
-
-	/*check and parse the value  */
-	if (!mxIsClass(prhs[0],"char")){
-		_error_("Value of option \"" << ochar->name  << "\" must be class \"char\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
-	}
-	FetchData(&ochar->value,&ochar->numel,&ochar->ndims,&ochar->size,prhs[0]);
-
-	return(ochar);
-}/*}}}*/
-GenericOption<Options**>* OptionStructParse( char* name, const mxArray* prhs[]){ /*{{{*/
-
-	int            i;
-	char           namei[161];
-	Option*                   option      = NULL;
-	GenericOption<Options**>  *ostruct    = NULL;
-	const mwSize  *ipt        = NULL;
-	const mxArray *structi;
-	mwIndex        sindex;
-
-	/*check and parse the name  */
-	ostruct=new GenericOption<Options**>();
-	ostruct->name =xNew<char>(strlen(name)+1);
-	memcpy(ostruct->name,name,(strlen(name)+1)*sizeof(char));
-
-	/*check and parse the value  */
-	if (!mxIsClass(prhs[0],"struct")){
-		_error_("Value of option \"" << ostruct->name  << "\" must be class \"struct\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
-	}
-	ostruct->numel=mxGetNumberOfElements(prhs[0]);
-	ostruct->ndims=mxGetNumberOfDimensions(prhs[0]);
-	ipt           =mxGetDimensions(prhs[0]);
-	ostruct->size =xNew<int>(ostruct->ndims);
-	for (i=0; i<ostruct->ndims; i++) ostruct->size[i]=(int)ipt[i];
-	if (ostruct->numel) ostruct->value=xNew<Options*>(ostruct->numel);
-
-	/*loop through and process each element of the struct array  */
-	for (sindex=0; sindex<ostruct->numel; sindex++) {
-		ostruct->value[sindex]=new Options;
-
-		/*loop through and process each field for the element  */
-		for (i=0; i<mxGetNumberOfFields(prhs[0]); i++) {
-			sprintf(namei,"%s.%s",name,mxGetFieldNameByNumber(prhs[0],i));
-			structi=mxGetFieldByNumber(prhs[0],sindex,i);
-
-			option=(Option*)OptionParse(namei,&structi);
-			ostruct->value[sindex]->AddObject((Object*)option);
-			option=NULL;
-		}
-	}
-
-	return(ostruct);
-}/*}}}*/
-GenericOption<Options*>* OptionCellParse( char* name, const mxArray* prhs[]){ /*{{{*/
-
-	int            i;
-	int           *dims;
-	char           namei[161];
-	char           cstr[81];
-	GenericOption<Options*> *ocell      = NULL;
-	Option        *option     = NULL;
-	const mwSize  *ipt        = NULL;
-	const mxArray *celli;
-	mwIndex        cindex;
-
-	/*check and parse the name  */
-	ocell=new GenericOption<Options*>();
-	ocell->name =xNew<char>(strlen(name)+1);
-	memcpy(ocell->name,name,(strlen(name)+1)*sizeof(char));
-
-	/*check and parse the value  */
-	if (!mxIsClass(prhs[0],"cell")){
-		_error_("Value of option \"" << ocell->name  << "\" must be class \"cell\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
-	}
-
-	ocell->numel=mxGetNumberOfElements(prhs[0]);
-	ocell->ndims=mxGetNumberOfDimensions(prhs[0]);
-	ipt         =mxGetDimensions(prhs[0]);
-	ocell->size =xNew<int>(ocell->ndims);
-	for (i=0; i<ocell->ndims; i++) ocell->size[i]=(int)ipt[i];
-	ocell->value=new Options;
-
-	/*loop through and process each element of the cell array  */
-	dims=xNew<int>(ocell->ndims);
-	for (cindex=0; cindex<ocell->numel; cindex++) {
-		ColumnWiseDimsFromIndex(dims,(int)cindex,ocell->size,ocell->ndims);
-		StringFromDims(cstr,dims,ocell->ndims);
-		#ifdef _INTEL_WIN_
-			_snprintf(namei,161,"%s%s",name,cstr);
-		#else
-			snprintf(namei,161,"%s%s",name,cstr);
-		#endif
-		celli=mxGetCell(prhs[0],cindex);
-
-		option=(Option*)OptionParse(namei,&celli);
-		ocell->value->AddObject((Object*)option);
-		option=NULL;
-	}
-	xDelete<int>(dims);
-
-	return(ocell);
-}/*}}}*/
-Option* OptionParse(char* name, const mxArray* prhs[]){ /*{{{*/
-
-	Option  *option = NULL;
-	mxArray *lhs[1];
-
-	/*parse the value according to the matlab data type  */
-	if     (mxIsClass(prhs[0],"double")  && (mxGetNumberOfElements(prhs[0])==1))
-	 option=(Option*)OptionDoubleParse(name,prhs);
-	else if(mxIsClass(prhs[0],"double")  && (mxGetNumberOfElements(prhs[0])!=1))
-	 option=(Option*)OptionDoubleArrayParse(name,prhs);
-	else if(mxIsClass(prhs[0],"logical"))
-	 option=(Option*)OptionLogicalParse(name,prhs);
-	else if(mxIsClass(prhs[0],"char"))
-	 option=(Option*)OptionCharParse(name,prhs);
-	else if(mxIsClass(prhs[0],"struct"))
-	 option=(Option*)OptionStructParse(name,prhs);
-	else if(mxIsClass(prhs[0],"cell"))
-	 option=(Option*)OptionCellParse(name,prhs);
-	else {
-		_printf0_("  Converting value of option \"" << name << "\" from unrecognized class \"" << mxGetClassName(prhs[0]) << "\" to class \"" << "struct" << "\".\n");
-		if (!mexCallMATLAB(1,lhs,1,(mxArray**)prhs,"struct")) {
-			option=(Option*)OptionStructParse(name,(const mxArray**)lhs);
-			mxDestroyArray(lhs[0]);
-		}
-		else _error_("Second argument value of option \""<< name <<"\" is of unrecognized class \""<< mxGetClassName(prhs[0]) <<"\".");
-	}
-
-	return(option);
-}/*}}}*/
Index: /issm/trunk/src/wrappers/matlab/io/matlabio.h
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/matlabio.h	(revision 16136)
+++ /issm/trunk/src/wrappers/matlab/io/matlabio.h	(revision 16137)
@@ -39,10 +39,8 @@
 void FetchData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref);
 void FetchData(bool** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref);
-void FetchData(Matrix<double>** pmatrix,const mxArray* dataref);
 void FetchData(int** pvector,int* pM,const mxArray* dataref);
 void FetchData(float** pvector,int* pM,const mxArray* dataref);
 void FetchData(double** pvector,int* pM,const mxArray* dataref);
 void FetchData(bool** pvector,int* pM,const mxArray* dataref);
-void FetchData(Vector<double>** pvector,const mxArray* dataref);
 void FetchData(char** pstring,const mxArray* dataref);
 void FetchData(char** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref);
@@ -73,10 +71,5 @@
 int CheckNumMatlabArguments(int nlhs,int NLHS, int nrhs,int NRHS, const char* THISFUNCTION, void (*function)( void ));
 
-/*Matlab to Matrix routines: */
-Matrix<double>* MatlabMatrixToMatrix(const mxArray* mxmatrix);
-Vector<double>* MatlabVectorToVector(const mxArray* mxvector);
-
 /*Matlab to double* routines: */
-int MatlabVectorToDoubleVector(double** pvector,int* pvector_rows,const mxArray* mxvector);
 int MatlabMatrixToDoubleMatrix(double** pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix);
 int MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix);
@@ -84,16 +77,4 @@
 int MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix);
 
-/*Matlab to IssmDenseMat routines: */
-IssmMat<double>* MatlabMatrixToIssmMat(const mxArray* dataref);
-IssmVec<double>* MatlabVectorToIssmVec(const mxArray* dataref);
-
-/*Matlab to Petsc routines: */
-#ifdef _HAVE_PETSC_
-int MatlabMatrixToPetscMat(Mat* matrix,int* prows,int* pcols, const mxArray* mxmatrix);
-PetscMat* MatlabMatrixToPetscMat(const mxArray* mxmatrix);
-int MatlabVectorToPetscVec(Vec* pvector,int* pvector_rows,const mxArray* mxvector);
-PetscVec* MatlabVectorToPetscVec(const mxArray* mxvector);
-#endif
-
 /*Print*/
 void ApiPrintf(const char* string);
Index: sm/trunk/src/wrappers/matlab/io/mxGetAssignedField.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/mxGetAssignedField.cpp	(revision 16136)
+++ 	(revision )
@@ -1,39 +1,0 @@
-/*!\file: mxGetAssignedField.c: 
- * \brief: abstract interface on parallel side for i/o, so it ressembles the serial i/o.
- *
- * In serial mode, this routine takes care of returning the field coming 
- * from the model. If largesize is 1, we are running out of core models in 
- * matlab, and we need to call the subsref private method from the model object
- * in order to correctly load the data from disk.
- */
-
-#include "./matlabio.h"
-
-mxArray* mxGetAssignedField(const mxArray* pmxa_array,int number,const char* field){
-
-	//output
-	mxArray* mxfield=NULL;
-
-	//input
-	mxArray    *inputs[2];
-	mxArray    *pindex      = NULL;
-	const char *fnames[2];
-	mwSize      ndim        = 2;
-	mwSize      onebyone[2] = {1,1};
-
-	//We want to call the subsasgn method, and get the returned array.This ensures that if we are running 
-	//large sized problems, the data is truly loaded from disk by the model subsasgn class method.
-	inputs[0]=(mxArray*)pmxa_array; //this is the model
-
-	//create index structure used in the assignment (index.type='.' and index.subs='x' for field x for ex)
-	fnames[0] = "type";
-	fnames[1] = "subs";
-	pindex=mxCreateStructArray( ndim,onebyone,2,fnames);
-	mxSetField( pindex, 0, "type",mxCreateString("."));
-	mxSetField( pindex, 0, "subs",mxCreateString(field));
-	inputs[1]=pindex;
-
-	mexCallMATLAB( 1, &mxfield, 2, (mxArray**)inputs, "subsref");
-
-	return mxfield;
-}
Index: /issm/trunk/src/wrappers/python/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/python/Makefile.am	(revision 16136)
+++ /issm/trunk/src/wrappers/python/Makefile.am	(revision 16137)
@@ -1,5 +1,9 @@
-AM_CPPFLAGS = @DAKOTAINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+AM_CPPFLAGS = @DAKOTAINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@ @AMPIINCL@
+#AUTOMAKE_OPTIONS = subdir-objects
 
 EXEEXT=$(PYTHONWRAPPEREXT)
+
+#define prefix (from http://www.gnu.org/software/autoconf/manual/autoconf-2.67/html_node/Defining-Directories.html)
+AM_CPPFLAGS+=  -DISSM_PREFIX='"$(prefix)"'
 
 #python io{{{
@@ -50,4 +54,5 @@
 						InterpFromMeshToMesh2d.la\
 						InterpFromGridToMesh.la\
+						IssmConfig.la\
 						MeshProfileIntersection.la\
 						NodeConnectivity.la\
@@ -142,4 +147,8 @@
 InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB) $(GSLLIB)
 
+IssmConfig_la_SOURCES = ../IssmConfig/IssmConfig.cpp\
+											 ../IssmConfig/IssmConfig.h
+IssmConfig_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
 MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
 										../MeshProfileIntersection/MeshProfileIntersection.h
Index: sm/trunk/startup.m
===================================================================
--- /issm/trunk/startup.m	(revision 16136)
+++ 	(revision )
@@ -1,72 +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_DIR , or if on a Windows machine, ISSM_DIR_WIN
-if ~ispc,
-	ISSM_DIR=getenv('ISSM_DIR');
-else
-	ISSM_DIR=getenv('ISSM_DIR_WIN');
-	%ISSM_DIR='';
-end
-if (isempty(ISSM_DIR)),
-	error('''ISSM_DIR'' environment variable is empty! You should define ISSM_DIR 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_DIR in this file, in case it is not correctly setup. 
-
-%ISSM path
-addpath([ISSM_DIR '/src/m/os/']); %loads recursivepath
-addpath([ISSM_DIR '/bin']);
-addpath([ISSM_DIR '/lib']);
-addpath(recursivepath([ISSM_DIR '/src/m']));
-addpath(recursivepath([ISSM_DIR '/externalpackages/scotch']));
-addpath(recursivepath([ISSM_DIR '/externalpackages/canos']));
-addpath(recursivepath([ISSM_DIR '/externalpackages/kml']));
-addpath(recursivepath([ISSM_DIR '/externalpackages/export_fig']));
-addpath(recursivepath([ISSM_DIR '/externalpackages/googleearthtoolbox']));
-addpath(recursivepath([ISSM_DIR '/externalpackages/howatmask']));
-addpath(recursivepath([ISSM_DIR '/externalpackages/cm_and_cb_utilities']));
-addpath(recursivepath([ISSM_DIR '/externalpackages/dem']));
-
-clear ISSM_DIR;
-
-%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_DIR 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
-
-%  deal with Matlab bug (on Linux, not WinXP) -- unless
-%  the class has been called, "empty" method can not be found
-if ~ispc,
-	normal_uncertain;
-	continuous_design;
-	continuous_state;
-	linear_inequality_constraint;
-	linear_equality_constraint;
-	response_function;
-	objective_function;
-	least_squares_term;
-	nonlinear_inequality_constraint;
-	nonlinear_equality_constraint;
-	clear ans;
-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: sm/trunk/startup.py
===================================================================
--- /issm/trunk/startup.py	(revision 16136)
+++ 	(revision )
@@ -1,30 +1,0 @@
-#!/usr/bin/env python
-# STARTUP - Python startup script
-#
-#  startup.py is a script run by python at the beginning of a session, just
-#  before handing over the prompt to the user if the environment variable
-#  PYTHONSTARTUP is defined:
-#  export PYTHONSTARTUP=$ISSM_DIR/startup.py
-#  This startup script should be run by users before trying to use ISSM.
-
-import os,sys
-
-#Recover ISSM_DIR and USERNAME
-ISSM_DIR=os.getenv('ISSM_DIR')
-USERNAME =os.getenv('USER')
-if(ISSM_DIR==None):
-	raise NameError('"ISSM_DIR" environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!')
-
-#Go through src/m and append any directory that contains a *.py file to PATH 
-for root,dirs,files in os.walk(ISSM_DIR+ '/src/m'):
-	if '.svn' in dirs:
-		dirs.remove('.svn')
-	for file in files:
-		if file.find(".py") != -1:
-			if file.find(".pyc") == -1:
-				if root not in sys.path:
-					sys.path.append(root)
-				
-sys.path.append(ISSM_DIR + '/lib')
-
-print("\n  To get started with ISSM, type issmdoc at the command prompt.\n\n")
Index: /issm/trunk/test/Exp/79North.exp
===================================================================
--- /issm/trunk/test/Exp/79North.exp	(revision 16136)
+++ /issm/trunk/test/Exp/79North.exp	(revision 16137)
@@ -2,5 +2,5 @@
 ## Icon:0
 # Points Count Value
-16 1.000000
+18 1.000000
 # X pos Y pos
 464009.1397656691 -1027407.4008438819
@@ -16,6 +16,8 @@
 474328.7574005903 -1040333.8187579215
 490074.1533796453 -1041072.4712101523
+491111.0844876733 -1038645.7820016426
 489754.9899476374 -1026299.4221655356
 477094.8404779918 -1020390.2025476890
+471001.4291198556 -1014587.7884811594
 468158.2643817714 -1015096.5266400346
 464009.1397656691 -1027407.4008438819
Index: /issm/trunk/test/Exp/SquareFront2.exp
===================================================================
--- /issm/trunk/test/Exp/SquareFront2.exp	(revision 16137)
+++ /issm/trunk/test/Exp/SquareFront2.exp	(revision 16137)
@@ -0,0 +1,10 @@
+## Name:icefront
+## Icon:0
+# Points Count  Value
+5 1.
+# X pos Y pos
+1000 999000
+1000 1100000
+999000 1100000
+999000 999000
+-1000 999000
Index: /issm/trunk/test/NightlyRun/IdToName.m
===================================================================
--- /issm/trunk/test/NightlyRun/IdToName.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/IdToName.m	(revision 16137)
@@ -6,15 +6,15 @@
 
 switch id,
-	case 101, name='SquareShelfConstrainedDiagM2d';
-	case 102, name='SquareShelfConstrainedDiagM3d';
-	case 103, name='SquareShelfConstrainedDiagP3d';
-	case 104, name='SquareShelfConstrainedDiagS3d';
-	case 105, name='SquareShelfConstrainedProg2d';
-	case 106, name='SquareShelfConstrainedProg2dDG';
-	case 107, name='SquareShelfConstrainedProg3d';
+	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='SquareShelfConstrainedTranM2d';
-	case 111, name='SquareShelfConstrainedTranP3d';
+	case 110, name='SquareShelfConstrainedTranSSA2d';
+	case 111, name='SquareShelfConstrainedTranHO';
 	case 112, name='SquareShelfConstrainedSurfSlop2d';
 	case 113, name='SquareShelfConstrainedSurfSlope3d';
@@ -27,32 +27,32 @@
 	case 120, name='SquareShelfConstrainedEnthalpyStea';
 	case 121, name='SquareShelfConstrainedEnthalpyTran';
-	case 122, name='SquareShelfConstrainedTransP3dEnth';
-	case 201, name='SquareShelfDiagM2d';
-	case 202, name='SquareShelfDiagM3d';
-	case 203, name='SquareShelfDiagP3d';
-	case 204, name='SquareShelfDiagS3d';
-	case 205, name='SquareShelfDiagMP3dPenalties';
+	case 122, name='SquareShelfConstrainedTransHOEnth';
+	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='SquareShelfTranM2d';
-	case 209, name='SquareShelfTranM3d';
-	case 210, name='SquareShelfTranP3d';
-	case 211, name='SquareShelfTranS3d';
-	case 212, name='SquareShelfCMBM2d';
-	case 213, name='SquareShelfCMBM3d';
-	case 214, name='SquareShelfCMBP3d';
-	case 215, name='SquareShelfCMBS3d';
-	case 216, name='SquareShelfDiagM2dRift';
+	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='SquareShelfDiagMP3dTiling';
-	case 220, name='SquareShelfDiagPS3dTiling';
-	case 221, name='SquareShelfDiagMS3dTiling';
-	case 222, name='SquareShelfDiagM2dTransientIncrHydro';
-	case 223, name='SquareShelfDiagM2dTransientIncrNonHydro';
-	case 224, name='SquareShelfDiagP3dTransientIncrHydro';
-	case 225, name='SquareShelfDiagP3dTransientIncrNonHydro';
-	case 226, name='SquareShelfTranCflM2d';
-	case 227, name='SquareShelfTranCflP3d';
+	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';
@@ -60,39 +60,42 @@
 	case 231, name='SquareShelfTranForcePos3d';
 	case 232, name='SquareShelfTherTranForcTemp';
-	case 233, name='SquareShelfTranP3dForcTemp';
+	case 233, name='SquareShelfTranHOForcTemp';
 	case 234, name='SquareShelfTranForceNeg2dDakotaSamp';
 	case 235, name='SquareShelfTranForceNeg2dDakotaLocal';
-	case 236, name='SquareShelfTranIspddIsdeltaM2d';
-	case 237, name='SquareShelfTranIspddIsdeltaM3d';
-	case 270, name='SquareShelfDiagM2dDamage';
-	case 272, name='SquareShelfCMZM2dDamage';
-	case 274, name='SquareShelfDiagM2dDamageRift';
-	case 301, name='SquareSheetConstrainedDiagM2d';
-	case 302, name='SquareSheetConstrainedDiagH2d';
-	case 303, name='SquareSheetConstrainedDiagHM2d';
-	case 304, name='SquareSheetConstrainedDiagM3d';
-	case 305, name='SquareSheetConstrainedDiagH3d';
-	case 306, name='SquareSheetConstrainedDiagHM3d';
-	case 307, name='SquareSheetConstrainedDiagP3d';
-	case 308, name='SquareSheetConstrainedDiagS3d';
-	case 309, name='SquareSheetConstrainedProg2d';
-	case 320, name='SquareSheetConstrainedProg2dDG';
-	case 311, name='SquareSheetConstrainedProg3d';
+	case 236, name='SquareShelfTranIspddIsdeltaSSA2d';
+	case 237, name='SquareShelfTranIspddIsdeltaSSA3d';
+	case 270, name='SquareShelfStressSSA2dDamage';
+	case 272, name='SquareShelfCMZSSA2dDamage';
+	case 274, name='SquareShelfStressSSA2dDamageRift';
+	case 280, name='SquareShelfStressSSA2dHigherOrder';
+	case 285, name='SquareShelfStressHOHigherOrder';
+	case 290, name='SquareShelfStressFSP2P1';
+	case 301, name='SquareSheetConstrainedStressSSA2d';
+	case 302, name='SquareSheetConstrainedStressSIA2d';
+	case 303, name='SquareSheetConstrainedStressHSSA2d';
+	case 304, name='SquareSheetConstrainedStressSSA3d';
+	case 305, name='SquareSheetConstrainedStressSIA3d';
+	case 306, name='SquareSheetConstrainedStressHSSA3d';
+	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='SquareSheetConstrainedTranH2d';
-	case 315, name='SquareSheetConstrainedTranH3d';
-	case 316, name='SquareSheetConstrainedTranM2d';
-	case 317, name='SquareSheetConstrainedTranP3d';
-	case 318, name='SquareSheetConstrainedSteaH3d';
-	case 319, name='SquareSheetConstrainedCMDragM2d';
-	case 320, name='SquareSheetConstrainedCMDragM3d';
-	case 321, name='SquareSheetConstrainedCMDragP3d';
-	case 322, name='SquareSheetConstrainedCMDragS3d';
-	case 323, name='SquareSheetConstrainedTranCflM2d';
-	case 324, name='SquareSheetConstrainedTranCflH3d';
+	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='SquareSheetConstrainedTransP3dEnth';
+	case 327, name='SquareSheetConstrainedTransHOEnth';
 	case 328, name='SquareSheetConstrainedSmbGradients2d';
 	case 329, name='SquareSheetConstrainedSmbGradients3d';
@@ -100,56 +103,60 @@
 	case 332, name='SquareSheetConstrainedHydrologyDC';
 	case 333, name='SquareSheetHydrologyDCTwoLayers';
-	case 401, name='SquareSheetShelfDiagM2d';
-	case 402, name='SquareSheetShelfDiagM3d';
-	case 403, name='SquareSheetShelfDiagP3d';
-	case 404, name='SquareSheetShelfDiagS3d';
-	case 405, name='SquareSheetShelfDiagMP3dPenalties';
+	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='SquareSheetShelfTranM2d';
-	case 409, name='SquareSheetShelfTranMP3dPenalties';
-	case 410, name='SquareSheetShelfSteaM3d';
-	case 411, name='SquareSheetShelfSteaP3d';
-	case 412, name='SquareSheetShelfDiadM3dDakota';
-	case 413, name='SquareSheetShelfDiadM3dDakotaPart';
-	case 414, name='SquareSheetShelfDiadM3dDakotaMassFlux';
-	case 415, name='SquareSheetShelfCMDragSteaM3d';
-	case 416, name='SquareSheetShelfCMDragSteaP3d';
-	case 417, name='SquareSheetShelfDiadM3dDakotaSamp';
-	case 418, name='SquareSheetShelfDiadM3dDakotaAreaAverage';
-	case 419, name='SquareSheetShelfDiagMP3dTiling';
+	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='SquareSheetShelfDiagPS3dTiling';
-	case 422, name='SquareSheetShelfDiagMS3dTiling';
-	case 423, name='RoundSheetShelfGLMigrationM2d';
-	case 424, name='SquareSheetShelfGroundingLine2dAgressice';
+	case 421, name='SquareSheetShelfStressHOFS3dTiling';
+	case 422, name='SquareSheetShelfStressSSAFS3dTiling';
+	case 423, name='RoundSheetShelfGLMigrationSSA2d';
+	case 424, name='SquareSheetShelfGroundingLine2dAgressive';
 	case 425, name='SquareSheetShelfGroundingLine2dSoft';
-	case 426, name='SquareSheetShelfGroundingLine3dAgressice';
+	case 426, name='SquareSheetShelfGroundingLine3dAgressive';
 	case 427, name='SquareSheetShelfGroundingLine3dSoft';
-	case 428, name='SquareSheetShelfDiagM2dNewton';
-	case 429, name='SquareSheetShelfDiagP3dNewton';
-	case 430, name='SquareSheetShelfDiagS3dNewton';
-	case 431, name='SquareSheetShelfSteaEnthalpyM3d';
-	case 432, name='SquareSheetShelfSteaEnthalpyP3d';
-	case 433, name='RoundSheetShelfGLMigrationM3d';
-	case 501, name='PigDiagM2d';
-	case 502, name='PigDiagP3d';
-	case 503, name='PigDiagS3d';
-	case 504, name='PigTranM2d';
-	case 505, name='PigTranM3d';
-	case 506, name='PigTranP3d';
-	case 507, name='PigTranS3d';
-	case 508, name='PigSteaM3d';
-	case 509, name='PigSteaP3d';
-	case 510, name='PigSteaS3d';
-	case 511, name='PigCMBS3d';
-	case 512, name='PigCMDragP3d';
-	case 513, name='PigCMDragSteaM3d';
+	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 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='79NorthProg2d';
-	case 602, name='79NorthProg2dDG';
-	case 603, name='79NorthProg3d';
+	case 601, name='79NorthMasstransp2d';
+	case 602, name='79NorthMasstransp2dDG';
+	case 603, name='79NorthMasstransp3d';
 	case 604, name='79NorthSurfSlop2d';
 	case 605, name='79NorthSurfSlop3d';
@@ -161,22 +168,22 @@
 	case 611, name='79NorthCMBalThic2dCG';
 	case 612, name='79NorthCMBalThic2dDG';
-	case 613, name='79NorthCMBalThicVxVyParalle';
-	case 1101, name='ISMIPAPattyn';
-	case 1102, name='ISMIPAStokes';
-	case 1103, name='ISMIPBPattyn';
-	case 1104, name='ISMIPBStokes';
-	case 1105, name='ISMIPCPattyn';
-	case 1106, name='ISMIPCStokes';
-	case 1107, name='ISMIPDPattyn';
-	case 1108, name='ISMIPDStokes';
+	case 613, name='79NorthCMBalThicVxVy';
+	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='EISMINTDiag1';
-	case 1203, name='EISMINTDiag2';
+	case 1202, name='EISMINTStress1';
+	case 1203, name='EISMINTStress2';
 	case 1204, name='EISMINTTran2';
-	case 1205, name='EISMINTRoundIceSheetStaticHutter';
-	case 1206, name='EISMINTRoundIceSheetStaticPattyn';
-	case 1207, name='EISMINTRoundIceSheetStaticStokes';
+	case 1205, name='EISMINTRoundIceSheetStaticSIA';
+	case 1206, name='EISMINTRoundIceSheetStaticHO';
+	case 1207, name='EISMINTRoundIceSheetStaticFS';
 	case 1208, name='EISMINTA';
 	case 1301, name='ThermalMelting';
@@ -188,6 +195,6 @@
 	case 1501, name='SquareShelfTranSawTooth2d';
 	case 1502, name='SquareShelfTranSawTooth3d';
-	case 1601, name='SquareShelfM2dRotation';
-	case 1602, name='SquareSheetShelfP3dRotation';
+	case 1601, name='SquareShelfSSA2dRotation';
+	case 1602, name='SquareSheetShelfHORotation';
 	case 2001, name='SquareSheetConstrainedGia2d';
 	case 2051, name='GiaBenchmarksAB2dA1';
@@ -203,15 +210,15 @@
 	case 2082, name='GiaBenchmarksAB2dD2';
 	case 2083, name='GiaBenchmarksAB2dD3';
-	case 3001, name='SquareShelfConstrainedDiagM2dAdolc';
-	case 3002, name='SquareShelfConstrainedDiagM3dAdolc';
-	case 3003, name='SquareShelfConstrainedDiagP3dAdolc';
-	case 3004, name='SquareShelfConstrainedDiagS3dAdolc';
-	case 3005, name='SquareShelfConstrainedProg2dAdolc';
-	case 3006, name='SquareShelfConstrainedProg2dDGAdolc';
-	case 3007, name='SquareShelfConstrainedProg3dAdolc';
+	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='SquareShelfConstrainedTranM2dAdolc';
-	case 3015, name='SquareShelfConstrainedProg2dAdolcForwardDifference';
+	case 3010, name='SquareShelfConstrainedTranSSA2dAdolc';
+	case 3015, name='SquareShelfConstrainedMasstransp2dAdolcForwardDifference';
 	case 3019, name='SquareShelfConstrainedTherTranAdolcReverseVsForward';
 
Index: /issm/trunk/test/NightlyRun/IdToName.py
===================================================================
--- /issm/trunk/test/NightlyRun/IdToName.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/IdToName.py	(revision 16137)
@@ -10,197 +10,220 @@
 
 	idname={
-		101 : 'SquareShelfConstrainedDiagM2d',
-		102 : 'SquareShelfConstrainedDiagM3d',
-		103 : 'SquareShelfConstrainedDiagP3d',
-		104 : 'SquareShelfConstrainedDiagS3d',
-		105 : 'SquareShelfConstrainedProg2d',
-		106 : 'SquareShelfConstrainedProg2dDG',
-		107 : 'SquareShelfConstrainedProg3d',
-		108 : 'SquareShelfConstrainedTherStea',
-		109 : 'SquareShelfConstrainedTherTran',
-		110 : 'SquareShelfConstrainedTranM2d',
-		111 : 'SquareShelfConstrainedTranP3d',
-		112 : 'SquareShelfConstrainedSurfSlop2d',
-		113 : 'SquareShelfConstrainedSurfSlope3d',
-		114 : 'SquareShelfConstrainedBedSlop2d',
-		115 : 'SquareShelfConstrainedBedSlop3d',
-		116 : 'SquareShelfConstrainedBalThic2d',
-		117 : 'SquareShelfConstrainedBalThic3d',
-		118 : 'SquareShelfConstrainedBalThic2dDG',
-		119 : 'SquareBamgMesh',
-		120 : 'SquareShelfConstrainedEnthalpyStea',
-		121 : 'SquareShelfConstrainedEnthalpyTran',
-		122 : 'SquareShelfConstrainedTransP3dEnth',
-		201 : 'SquareShelfDiagM2d',
-		202 : 'SquareShelfDiagM3d',
-		203 : 'SquareShelfDiagP3d',
-		204 : 'SquareShelfDiagS3d',
-		205 : 'SquareShelfDiagMP3dPenalties',
-		206 : 'SquareShelfTherStea',
-		207 : 'SquareShelfTherTran',
-		208 : 'SquareShelfTranM2d',
-		209 : 'SquareShelfTranM3d',
-		210 : 'SquareShelfTranP3d',
-		211 : 'SquareShelfTranS3d',
-		212 : 'SquareShelfCMBM2d',
-		213 : 'SquareShelfCMBM3d',
-		214 : 'SquareShelfCMBP3d',
-		215 : 'SquareShelfCMBS3d',
-		216 : 'SquareShelfDiagM2dRift',
-		217 : 'SquareShelfConstrained',
-		218 : 'SquareShelfConstrainedDakotaB',
-		219 : 'SquareShelfDiagMP3dTiling',
-		220 : 'SquareShelfDiagPS3dTiling',
-		221 : 'SquareShelfDiagMS3dTiling',
-		222 : 'SquareShelfDiagM2dTransientIncrHydro',
-		223 : 'SquareShelfDiagM2dTransientIncrNonHydro',
-		224 : 'SquareShelfDiagP3dTransientIncrHydro',
-		225 : 'SquareShelfDiagP3dTransientIncrNonHydro',
-		226 : 'SquareShelfTranCflM2d',
-		227 : 'SquareShelfTranCflP3d',
-		228 : 'SquareShelfTranForceNeg2d',
-		229 : 'SquareShelfTranForcePos2d',
-		230 : 'SquareShelfTranForceNeg3d',
-		231 : 'SquareShelfTranForcePos3d',
-		232 : 'SquareShelfTherTranForcTemp',
-		233 : 'SquareShelfTranP3dForcTemp',
-		234 : 'SquareShelfTranForceNeg2dDakotaSamp',
-		235 : 'SquareShelfTranForceNeg2dDakotaLocal',
-		236 : 'SquareShelfTranIspddIsdeltaM2d',
-		237 : 'SquareShelfTranIspddIsdeltaM3d',
-		301 : 'SquareSheetConstrainedDiagM2d',
-		302 : 'SquareSheetConstrainedDiagH2d',
-		303 : 'SquareSheetConstrainedDiagHM2d',
-		304 : 'SquareSheetConstrainedDiagM3d',
-		305 : 'SquareSheetConstrainedDiagH3d',
-		306 : 'SquareSheetConstrainedDiagHM3d',
-		307 : 'SquareSheetConstrainedDiagP3d',
-		308 : 'SquareSheetConstrainedDiagS3d',
-		309 : 'SquareSheetConstrainedProg2d',
-		310 : 'SquareSheetConstrainedProg2dDG',
-		311 : 'SquareSheetConstrainedProg3d',
-		312 : 'SquareSheetConstrainedTherStea',
-		313 : 'SquareSheetConstrainedTherTran',
-		314 : 'SquareSheetConstrainedTranH2d',
-		315 : 'SquareSheetConstrainedTranH3d',
-		316 : 'SquareSheetConstrainedTranM2d',
-		317 : 'SquareSheetConstrainedTranP3d',
-		318 : 'SquareSheetConstrainedSteaH3d',
-		319 : 'SquareSheetConstrainedCMDragM2d',
-		320 : 'SquareSheetConstrainedCMDragM3d',
-		321 : 'SquareSheetConstrainedCMDragP3d',
-		322 : 'SquareSheetConstrainedCMDragS3d',
-		323 : 'SquareSheetConstrainedTranCflM2d',
-		324 : 'SquareSheetConstrainedTranCflH3d',
-		325 : 'SquareSheetConstrainedEnthalpyStea',
-		326 : 'SquareSheetConstrainedEnthalpyTran',
-		327 : 'SquareSheetConstrainedTransP3dEnth',
-		328 : 'SquareSheetConstrainedSmbGradients2d',
-		329 : 'SquareSheetConstrainedSmbGradients3d',
-		331 : 'SquareSheetConstrainedHydrology',
-		333 : 'SquareSheetConstrainedTranCflM3d',
-		401 : 'SquareSheetShelfDiagM2d',
-		402 : 'SquareSheetShelfDiagM3d',
-		403 : 'SquareSheetShelfDiagP3d',
-		404 : 'SquareSheetShelfDiagS3d',
-		405 : 'SquareSheetShelfDiagMP3dPenalties',
-		406 : 'SquareSheetShelfTherStea',
-		407 : 'SquareSheetShelfTherTran',
-		408 : 'SquareSheetShelfTranM2d',
-		409 : 'SquareSheetShelfTranMP3dPenalties',
-		410 : 'SquareSheetShelfSteaM3d',
-		411 : 'SquareSheetShelfSteaP3d',
-		412 : 'SquareSheetShelfDiadM3dDakota',
-		413 : 'SquareSheetShelfDiadM3dDakotaPart',
-		414 : 'SquareSheetShelfDiadM3dDakotaMassFlux',
-		415 : 'SquareSheetShelfCMDragSteaM3d',
-		416 : 'SquareSheetShelfCMDragSteaP3d',
-		417 : 'SquareSheetShelfDiadM3dDakotaSamp',
-		418 : 'SquareSheetShelfDiadM3dDakotaAreaAverage',
-		419 : 'SquareSheetShelfDiagMP3dTiling',
-		420 : 'SquareSheetShelfDakotaScaledResponse',
-		421 : 'SquareSheetShelfDiagPS3dTiling',
-		422 : 'SquareSheetShelfDiagMS3dTiling',
-		423 : 'RoundSheetShelfGLMigrationM2d',
-		424 : 'SquareSheetShelfGroundingLine2dAgressice',
-		425 : 'SquareSheetShelfGroundingLine2dSoft',
-		426 : 'SquareSheetShelfGroundingLine3dAgressice',
-		427 : 'SquareSheetShelfGroundingLine3dSoft',
-		428 : 'SquareSheetShelfDiagM2dNewton',
-		429 : 'SquareSheetShelfDiagP3dNewton',
-		430 : 'SquareSheetShelfDiagS3dNewton',
-		431 : 'SquareSheetShelfSteaEnthalpyM3d',
-		432 : 'SquareSheetShelfSteaEnthalpyP3d',
-		433 : 'RoundSheetShelfGLMigrationM3d',
-		501 : 'PigDiagM2d',
-		502 : 'PigDiagP3d',
-		503 : 'PigDiagS3d',
-		504 : 'PigTranM2d',
-		505 : 'PigTranM3d',
-		506 : 'PigTranP3d',
-		507 : 'PigTranS3d',
-		508 : 'PigSteaM3d',
-		509 : 'PigSteaP3d',
-		510 : 'PigSteaS3d',
-		511 : 'PigCMBS3d',
-		512 : 'PigCMDragP3d',
-		513 : 'PigCMDragSteaM3d',
-		514 : 'PigBamgMesh',
-		515 : 'PigTherTranSUPG',
-		516 : 'PigTherSteaSUPG',
-		601 : '79NorthProg2d',
-		602 : '79NorthProg2dDG',
-		603 : '79NorthProg3d',
-		604 : '79NorthSurfSlop2d',
-		605 : '79NorthSurfSlop3d',
-		606 : '79NorthBedSlop2d',
-		607 : '79NorthBedSlop3d',
-		608 : '79NorthBalThic2d',
-		609 : '79NorthBalThic2dDG',
-		610 : '79NorthBalThic3d',
-		611 : '79NorthCMBalThic2dCG',
-		612 : '79NorthCMBalThic2dDG',
-		613 : '79NorthCMBalThicVxVy',
-		1101 : 'ISMIPAPattyn',
-		1102 : 'ISMIPAStokes',
-		1103 : 'ISMIPBPattyn',
-		1104 : 'ISMIPBStokes',
-		1105 : 'ISMIPCPattyn',
-		1106 : 'ISMIPCStokes',
-		1107 : 'ISMIPDPattyn',
-		1108 : 'ISMIPDStokes',
-		1109 : 'ISMIPE',
-		1110 : 'ISMIPF',
-		1201 : 'EISMINTMassConservation',
-		1202 : 'EISMINTDiag1',
-		1203 : 'EISMINTDiag2',
-		1204 : 'EISMINTTran2',
-		1205 : 'EISMINTRoundIceSheetStaticHutter',
-		1206 : 'EISMINTRoundIceSheetStaticPattyn',
-		1207 : 'EISMINTRoundIceSheetStaticStokes',
-		1208 : 'EISMINTA',
-		1301 : 'ThermalMelting',
-		1302 : 'ThermalAdvection',
-		1303 : 'ThermalConduction',
-		1304 : 'ThermalGeothermalFlux',
-		1401 : 'AdaptiveMeshRefinement1',
-		1402 : 'AdaptiveMeshRefinement2',
-		1501 : 'SquareShelfTranSawTooth2d',
-		1502 : 'SquareShelfTranSawTooth3d',
-		1601 : 'SquareShelfM2dRotation',
-		1602 : 'SquareSheetShelfP3dRotation', 
-		2001 : 'SquareSheetConstrainedGia2d',
-		3001 : 'SquareShelfConstrainedDiagM2dAdolc',
-		3002 : 'SquareShelfConstrainedDiagM3dAdolc',
-		3003 : 'SquareShelfConstrainedDiagP3dAdolc',
-		3004 : 'SquareShelfConstrainedDiagS3dAdolc',
-		3005 : 'SquareShelfConstrainedProg2dAdolc',
-		3006 : 'SquareShelfConstrainedProg2dDGAdolc',
-		3007 : 'SquareShelfConstrainedProg3dAdolc',
-		3008 : 'SquareShelfConstrainedTherSteaAdolc',
-		3009 : 'SquareShelfConstrainedTherTranAdolc',
-		3010 : 'SquareShelfConstrainedTranM2dAdolc',
-		3015 : 'SquareShelfConstrainedProg2dAdolcForwardDifference',
-		3019 : 'SquareShelfConstrainedTherTranAdolcReverseVsForward',
+	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',
+	280  : 'SquareShelfStressSSA2dHigherOrder',
+	285  : 'SquareShelfStressHOHigherOrder',
+	290  : 'SquareShelfStressFSP2P1',
+	301  : 'SquareSheetConstrainedStressSSA2d',
+	302  : 'SquareSheetConstrainedStressSIA2d',
+	303  : 'SquareSheetConstrainedStressHSSA2d',
+	304  : 'SquareSheetConstrainedStressSSA3d',
+	305  : 'SquareSheetConstrainedStressSIA3d',
+	306  : 'SquareSheetConstrainedStressHSSA3d',
+	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',
+	331  : 'SquareSheetConstrainedHydrologyShreve',
+	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  : 'SquareSheetShelfGroundingLine2dAgressive',
+	425  : 'SquareSheetShelfGroundingLine2dSoft',
+	426  : 'SquareSheetShelfGroundingLine3dAgressive',
+	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',
+	612  : '79NorthCMBalThic2dDG',
+	613  : '79NorthCMBalThicVxVy',
+	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',
 	}
 
@@ -209,3 +232,2 @@
 	else:
 		return idname
-
Index: /issm/trunk/test/NightlyRun/ad.m
===================================================================
--- /issm/trunk/test/NightlyRun/ad.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/ad.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
Index: /issm/trunk/test/NightlyRun/ad_maxalloc.m
===================================================================
--- /issm/trunk/test/NightlyRun/ad_maxalloc.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/ad_maxalloc.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
Index: /issm/trunk/test/NightlyRun/android.m
===================================================================
--- /issm/trunk/test/NightlyRun/android.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/android.m	(revision 16137)
@@ -2,9 +2,9 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.verbose=verbose('mprocessor',true,'module',true,'solution',true,'solver',true,'convergence',true,'control',true,'qmu',true,'autodiff',true);
-md.diagnostic.requested_outputs=StressTensorEnum();
-md=solve(md,DiagnosticSolutionEnum());
+md.stressbalance.requested_outputs=StressTensorEnum();
+md=solve(md,StressbalanceSolutionEnum());
 
 	
@@ -14,5 +14,5 @@
 y=md.mesh.y;
 z=md.mesh.z;
-vel=md.results.DiagnosticSolution.Vel;
+vel=md.results.StressbalanceSolution.Vel;
 
 patch=zeros(nel,12);
Index: /issm/trunk/test/NightlyRun/runme.m
===================================================================
--- /issm/trunk/test/NightlyRun/runme.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/runme.m	(revision 16137)
@@ -21,6 +21,7 @@
 %                      'gia'   : validation of gia tests
 %                      ...
-%      'procedure'     'check' : run the test (default)
-%                      'update': update the archive
+%      'procedure'     'check' :   run the test (default)
+%                      'update':   update the archive
+%                      'valgrind': check for memory leaks (default value of md.debug.valgrind needs to be changed manually)
 %
 %   Usage:
@@ -56,5 +57,5 @@
 %GET procedure {{{
 procedure=getfieldvalue(options,'procedure','check');
-if ~ismember(procedure,{'check','update'})
+if ~ismember(procedure,{'check','update','valgrind'})
 	disp('runme warning: procedure not supported, defaulting to test ''check''')
 	procedure='check';
@@ -148,4 +149,57 @@
 			disp(sprintf(['File ./../Archives/' archive_name '.nc saved\n']));
 
+		%CHECK for memory leaks?
+		elseif strcmpi(procedure,'valgrind'),
+			fields = fieldnames(md.results);
+			for i=1:numel(fields)
+				if ~isfield(md.results.(fields{i}),'errlog'),
+					disp(['Skipping ' fields{i}]);
+					continue;
+				else
+					disp(['Extracting results of ' fields{i}]);
+				end
+				results = md.results.(fields{i});
+				errlog  = cellstr(results(1).errlog);
+
+				%Check leaks
+				lines  = strfind(errlog,'definitely lost:');
+				lines  = find(~cellfun(@isempty,lines));
+				leaks   = 0;
+				for j=1:numel(lines)
+					Line    = errlog(lines(j));
+					Numbers = sscanf(Line{1},'==%i==   definitely lost: %s bytes in %i blocks',[1 Inf]);
+					leaks   = leaks + str2num(strrep(char(Numbers(2:end-1)),',',''));
+				end
+				%Check conditional jumps
+				lines  = strfind(errlog,'Conditional jump or move depends on uninitialised value');
+				lines  = find(~cellfun(@isempty,lines));
+				jumps   = numel(lines);
+				%Check invalid read/write
+				lines  = strfind(errlog,'Invalid');
+				lines  = find(~cellfun(@isempty,lines));
+				inval  = numel(lines);
+				if leaks==0,
+					disp(sprintf(['SUCCESS difference: 0 < 0 test id: %i test name: %s field: valgrind mem. leaks'],id,id_string));
+				else
+					disp(sprintf(['ERROR   difference: %i > 0 test id: %i test name: %s field: valgrind mem. leaks'],leaks,id,id_string));
+					disp('STOP');
+					return;
+				end
+				if jumps==0,
+					disp(sprintf(['SUCCESS difference: 0 < 0 test id: %i test name: %s field: valgrind cond. jumps'],id,id_string));
+				else
+					disp(sprintf(['ERROR   difference: %i > 0 test id: %i test name: %s field: valgrind cond. jumps'],jumps,id,id_string));
+					disp('STOP');
+					return;
+				end
+				if inval==0,
+					disp(sprintf(['SUCCESS difference: 0 < 0 test id: %i test name: %s field: valgrind invalid read/write'],id,id_string));
+				else
+					disp(sprintf(['ERROR   difference: %i > 0 test id: %i test name: %s field: valgrind invalid read/write'],inval,id,id_string));
+					disp('STOP');
+					return;
+				end
+			end
+
 		%ELSE: CHECK TEST
 		else,
Index: /issm/trunk/test/NightlyRun/test101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test101.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test101.m	(revision 16137)
@@ -2,8 +2,8 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.diagnostic.requested_outputs=StressTensorEnum();
-md=solve(md,DiagnosticSolutionEnum());
+md.stressbalance.requested_outputs=StressTensorEnum();
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -13,10 +13,10 @@
 	1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.StressTensorxx),...
-	(md.results.DiagnosticSolution.StressTensoryy),...
-	(md.results.DiagnosticSolution.StressTensorxy),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.StressTensorxx),...
+	(md.results.StressbalanceSolution.StressTensoryy),...
+	(md.results.StressbalanceSolution.StressTensorxy),...
 	};
Index: /issm/trunk/test/NightlyRun/test101.py
===================================================================
--- /issm/trunk/test/NightlyRun/test101.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test101.py	(revision 16137)
@@ -11,8 +11,8 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.diagnostic.requested_outputs=StressTensorEnum()
-md=solve(md,DiagnosticSolutionEnum())
+md.stressbalance.requested_outputs=StressTensorEnum()
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -22,10 +22,10 @@
 	1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.StressTensorxx,\
-	md.results.DiagnosticSolution.StressTensoryy,\
-	md.results.DiagnosticSolution.StressTensorxy,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.StressTensorxx,\
+	md.results.StressbalanceSolution.StressTensoryy,\
+	md.results.StressbalanceSolution.StressTensorxy,\
 	]
Index: /issm/trunk/test/NightlyRun/test102.m
===================================================================
--- /issm/trunk/test/NightlyRun/test102.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test102.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test102.py
===================================================================
--- /issm/trunk/test/NightlyRun/test102.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test102.py	(revision 16137)
@@ -12,7 +12,7 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,2.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -20,9 +20,9 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
 
Index: /issm/trunk/test/NightlyRun/test103.m
===================================================================
--- /issm/trunk/test/NightlyRun/test103.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test103.m	(revision 16137)
@@ -3,8 +3,8 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.diagnostic.requested_outputs=StressTensorEnum();
-md=solve(md,DiagnosticSolutionEnum());
+md.stressbalance.requested_outputs=StressTensorEnum();
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -14,14 +14,14 @@
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.StressTensorxx),...
-	(md.results.DiagnosticSolution.StressTensoryy),...
-	(md.results.DiagnosticSolution.StressTensorzz),...
-	(md.results.DiagnosticSolution.StressTensorxy),...
-	(md.results.DiagnosticSolution.StressTensorxz),...
-	(md.results.DiagnosticSolution.StressTensoryz),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.StressTensorxx),...
+	(md.results.StressbalanceSolution.StressTensoryy),...
+	(md.results.StressbalanceSolution.StressTensorzz),...
+	(md.results.StressbalanceSolution.StressTensorxy),...
+	(md.results.StressbalanceSolution.StressTensorxz),...
+	(md.results.StressbalanceSolution.StressTensoryz),...
 	};
Index: /issm/trunk/test/NightlyRun/test103.py
===================================================================
--- /issm/trunk/test/NightlyRun/test103.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test103.py	(revision 16137)
@@ -12,8 +12,8 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,2.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.diagnostic.requested_outputs=StressTensorEnum()
-md=solve(md,DiagnosticSolutionEnum())
+md.stressbalance.requested_outputs=StressTensorEnum()
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -23,14 +23,14 @@
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.StressTensorxx,\
-	md.results.DiagnosticSolution.StressTensoryy,\
-	md.results.DiagnosticSolution.StressTensorzz,\
-	md.results.DiagnosticSolution.StressTensorxy,\
-	md.results.DiagnosticSolution.StressTensorxz,\
-	md.results.DiagnosticSolution.StressTensoryz,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.StressTensorxx,\
+	md.results.StressbalanceSolution.StressTensoryy,\
+	md.results.StressbalanceSolution.StressTensorzz,\
+	md.results.StressbalanceSolution.StressTensorxy,\
+	md.results.StressbalanceSolution.StressTensorxz,\
+	md.results.StressbalanceSolution.StressTensoryz,\
 	]
Index: /issm/trunk/test/NightlyRun/test104.m
===================================================================
--- /issm/trunk/test/NightlyRun/test104.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test104.m	(revision 16137)
@@ -3,16 +3,16 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'FS','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08};
+field_tolerances={1e-08,1e-08,1e-06,1e-08,1e-08};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test104.py
===================================================================
--- /issm/trunk/test/NightlyRun/test104.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test104.py	(revision 16137)
@@ -12,16 +12,16 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,2.)
-md=setflowequation(md,'stokes','all')
+md=setflowequation(md,'FS','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-08,1e-08,1e-07,1e-08,1e-08]
+field_tolerances=[1e-08,1e-08,1e-06,1e-08,1e-08]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test105.m
===================================================================
--- /issm/trunk/test/NightlyRun/test105.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test105.m	(revision 16137)
@@ -2,7 +2,7 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -10,4 +10,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test105.py
===================================================================
--- /issm/trunk/test/NightlyRun/test105.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test105.py	(revision 16137)
@@ -11,7 +11,7 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -19,4 +19,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test106.m
===================================================================
--- /issm/trunk/test/NightlyRun/test106.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test106.m	(revision 16137)
@@ -3,9 +3,9 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.prognostic.stabilization=3;
-md.prognostic.spcthickness=md.geometry.thickness;
-md=solve(md,PrognosticSolutionEnum());
+md.masstransport.stabilization=3;
+md.masstransport.spcthickness=md.geometry.thickness;
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -13,4 +13,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test106.py
===================================================================
--- /issm/trunk/test/NightlyRun/test106.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test106.py	(revision 16137)
@@ -13,9 +13,9 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.prognostic.stabilization=3
-md.prognostic.spcthickness=md.geometry.thickness
-md=solve(md,PrognosticSolutionEnum())
+md.masstransport.stabilization=3
+md.masstransport.spcthickness=md.geometry.thickness
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -23,4 +23,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test107.m
===================================================================
--- /issm/trunk/test/NightlyRun/test107.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test107.m	(revision 16137)
@@ -2,8 +2,8 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md=extrude(md,5,3.);
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,4 +11,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test107.py
===================================================================
--- /issm/trunk/test/NightlyRun/test107.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test107.py	(revision 16137)
@@ -11,8 +11,8 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.extrude(5,3.)
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -20,4 +20,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test108.m
===================================================================
--- /issm/trunk/test/NightlyRun/test108.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test108.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.timestepping.time_step=0;
 md.cluster=generic('name',oshostname(),'np',3);
Index: /issm/trunk/test/NightlyRun/test108.py
===================================================================
--- /issm/trunk/test/NightlyRun/test108.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test108.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.timestepping.time_step=0
 md.cluster=generic('name',oshostname(),'np',3)
Index: /issm/trunk/test/NightlyRun/test109.m
===================================================================
--- /issm/trunk/test/NightlyRun/test109.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test109.m	(revision 16137)
@@ -3,8 +3,8 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
Index: /issm/trunk/test/NightlyRun/test109.py
===================================================================
--- /issm/trunk/test/NightlyRun/test109.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test109.py	(revision 16137)
@@ -12,8 +12,8 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.transient.isdiagnostic=False
-md.transient.isprognostic=False
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
 md.transient.isthermal=True
 md.transient.isgroundingline=False
Index: /issm/trunk/test/NightlyRun/test110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test110.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test110.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.transient.requested_outputs=IceVolumeEnum();
Index: /issm/trunk/test/NightlyRun/test110.py
===================================================================
--- /issm/trunk/test/NightlyRun/test110.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test110.py	(revision 16137)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.transient.requested_outputs=IceVolumeEnum()
Index: /issm/trunk/test/NightlyRun/test1101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1101.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1101.m	(revision 16137)
@@ -18,14 +18,14 @@
 	md=extrude(md,9,1.);
 
-	md=setflowequation(md,'pattyn','all');
+	md=setflowequation(md,'HO','all');
 
 	%Create dirichlet on the bed only
-	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	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);
 
 	pos=find(md.mesh.vertexonbed);
-	md.diagnostic.spcvx(pos)=0.;
-	md.diagnostic.spcvy(pos)=0.;
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
 
 	%Create MPCs to have periodic boundary conditions
@@ -36,15 +36,15 @@
 	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x));
 
-	md.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
 
-	%Compute the diagnostic
+	%Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum());
+	md=solve(md,StressbalanceSolutionEnum());
 
 	%Plot the results and save them
-	vx=(md.results.DiagnosticSolution.Vx);
-	vy=(md.results.DiagnosticSolution.Vy);
-	vz=(md.results.DiagnosticSolution.Vz);
-	results{i}=md.results.DiagnosticSolution;
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
 	minvx(i)=min(vx(end-md.mesh.numberofvertices2d+1:end));
 	maxvx(i)=max(vx(end-md.mesh.numberofvertices2d+1:end));
@@ -54,18 +54,18 @@
 	if printingflag, 
 		set(gcf,'Color','w')
-		printmodel(['ismipapattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipapattynvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+		printmodel(['ismipaHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaHOvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 	end
 	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
 	if printingflag, 
 		set(gcf,'Color','w')
-		printmodel(['ismipapattynvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipapattynvy' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+		printmodel(['ismipaHOvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaHOvy' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 	end
 	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
 	if printingflag, 
 		set(gcf,'Color','w')
-		printmodel(['ismipapattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipapattynvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+		printmodel(['ismipaHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaHOvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 	end
 
@@ -91,6 +91,6 @@
 	if printingflag, 
 		set(gcf,'Color','w')
-		printmodel(['ismipapattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipapattynvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+		printmodel(['ismipaHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaHOvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 	end
 end
@@ -100,12 +100,12 @@
 if printingflag, 
 	set(gcf,'Color','w')
-	printmodel('ismipapattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-	system(['mv ismipapattynminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	printmodel('ismipaHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipaHOminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 end
 plot([5 10 20 40 80 160],maxvx);ylim([0 120]);xlim([0 160])
 if printingflag, 
 	set(gcf,'Color','w')
-	printmodel('ismipapattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-	system(['mv ismipapattynmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	printmodel('ismipaHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipaHOmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 end
 
Index: /issm/trunk/test/NightlyRun/test1101.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1101.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1101.py	(revision 16137)
@@ -32,14 +32,14 @@
 	md.extrude(9,1.)
 
-	md=setflowequation(md,'pattyn','all')
+	md=setflowequation(md,'HO','all')
 
 	#Create dirichlet on the bed only
-	md.diagnostic.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
 
 	pos=numpy.nonzero(md.mesh.vertexonbed)
-	md.diagnostic.spcvx[pos]=0.
-	md.diagnostic.spcvy[pos]=0.
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
 
 	#Create MPCs to have periodic boundary conditions
@@ -50,15 +50,15 @@
 	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]
 
-	md.diagnostic.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
 
-	#Compute the diagnostic
+	#Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8)
-	md=solve(md,DiagnosticSolutionEnum())
+	md=solve(md,StressbalanceSolutionEnum())
 
 	#Plot the results and save them
-	vx=md.results.DiagnosticSolution.Vx
-	vy=md.results.DiagnosticSolution.Vy
-	vz=md.results.DiagnosticSolution.Vz
-	results.append(md.results.DiagnosticSolution)
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
 	minvx.append(numpy.min(vx[-md.mesh.numberofvertices2d:]))
 	maxvx.append(numpy.max(vx[-md.mesh.numberofvertices2d:]))
@@ -69,18 +69,18 @@
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipapattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipapattynvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#		printmodel(['ismipaHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaHOvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 #	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
 	if printingflag:
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipapattynvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipapattynvy%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#		printmodel(['ismipaHOvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaHOvy%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 #	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
 	if printingflag:
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipapattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipapattynvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#		printmodel(['ismipaHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaHOvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 
 	if   (L==5000.):
@@ -111,6 +111,6 @@
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipapattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipapattynvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#		printmodel(['ismipaHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaHOvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 
 #Now plot the min and max values of vx for each size of the square
@@ -119,12 +119,12 @@
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('ismipapattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#	shutil.move('ismipapattynminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#	printmodel('ismipaHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipaHOminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 #plot([5 10 20 40 80 160],maxvx);ylim([0 120]);xlim([0 160])
 if printingflag:
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('ismipapattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#	shutil.move('ismipapattynmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#	printmodel('ismipaHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipaHOmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 
 #Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test1102.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1102.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1102.m	(revision 16137)
@@ -25,11 +25,11 @@
 	md=parameterize(md,'../Par/ISMIPA.par');
 	md=extrude(md,10,1.);
-	md=setflowequation(md,'stokes','all');
+	md=setflowequation(md,'FS','all');
 
 	%Create dirichlet on the bed only
 	pos=find(md.mesh.vertexonbed);
-	md.diagnostic.spcvx(pos)=0.;
-	md.diagnostic.spcvy(pos)=0.;
-	md.diagnostic.spcvz(pos)=0.;
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
+	md.stressbalance.spcvz(pos)=0.;
 
 %	%Create MPCs to have periodic boundary conditions
@@ -42,19 +42,19 @@
 %	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x) & ~md.mesh.vertexonbed);
 
-%	md.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+%	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
 
-	%Compute the diagnostic
-	md.diagnostic.abstol=NaN;
-	md.diagnostic.reltol=NaN;
-	md.diagnostic.restol=1.;
+	%Compute the stressbalance
+	md.stressbalance.abstol=NaN;
+	md.stressbalance.reltol=NaN;
+	md.stressbalance.restol=1.;
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum());
+	md=solve(md,StressbalanceSolutionEnum());
 
 	%Plot the results and save them
-	vx=(md.results.DiagnosticSolution.Vx);
-	vy=(md.results.DiagnosticSolution.Vy);
-	vz=(md.results.DiagnosticSolution.Vz);
-	pressure=(md.results.DiagnosticSolution.Pressure);
-	results{i}=md.results.DiagnosticSolution;
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	pressure=(md.results.StressbalanceSolution.Pressure);
+	results{i}=md.results.StressbalanceSolution;
 	minvx(i)=min(vx(end-md.mesh.numberofvertices2d+1:end));
 	maxvx(i)=max(vx(end-md.mesh.numberofvertices2d+1:end));
@@ -64,18 +64,18 @@
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipastokesvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipastokesvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+		printmodel(['ismipaFSvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaFSvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 	end
 	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipastokesvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipastokesvy' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+		printmodel(['ismipaFSvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaFSvy' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 	end
 	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',4)
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipastokesvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipastokesvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+		printmodel(['ismipaFSvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaFSvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 	end
 
@@ -101,6 +101,6 @@
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipastokesvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipastokesvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+		printmodel(['ismipaFSvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipaFSvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 	end
 end
@@ -110,12 +110,12 @@
 if printingflag,
 	set(gcf,'Color','w')
-	printmodel('ismipastokesminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-	system(['mv ismipastokesminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	printmodel('ismipaFSminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipaFSminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 end
 plot([5 10 20 40 80 160],maxvx);ylim([0 120])
 if printingflag,
 	set(gcf,'Color','w')
-	printmodel('ismipastokesmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-	system(['mv ismipastokesmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
+	printmodel('ismipaFSmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipaFSmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestA']);
 end
 
Index: /issm/trunk/test/NightlyRun/test1102.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1102.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1102.py	(revision 16137)
@@ -39,11 +39,11 @@
 	md=parameterize(md,'../Par/ISMIPA.py')
 	md.extrude(10,1.)
-	md=setflowequation(md,'stokes','all')
+	md=setflowequation(md,'FS','all')
 
 	#Create dirichlet on the bed only
 	pos=numpy.nonzero(md.mesh.vertexonbed)
-	md.diagnostic.spcvx[pos]=0.
-	md.diagnostic.spcvy[pos]=0.
-	md.diagnostic.spcvz[pos]=0.
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
+	md.stressbalance.spcvz[pos]=0.
 
 #	#Create MPCs to have periodic boundary conditions
@@ -56,19 +56,19 @@
 #	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x),numpy.logical_not(md.mesh.vertexonbed)))[0]
 
-#	md.diagnostic.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+#	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
 
-	#Compute the diagnostic
-	md.diagnostic.abstol=float('NaN')
-	md.diagnostic.reltol=float('NaN')
-	md.diagnostic.restol=1.
+	#Compute the stressbalance
+	md.stressbalance.abstol=float('NaN')
+	md.stressbalance.reltol=float('NaN')
+	md.stressbalance.restol=1.
 	md.cluster=generic('name',oshostname(),'np',8)
-	md=solve(md,DiagnosticSolutionEnum())
+	md=solve(md,StressbalanceSolutionEnum())
 
 	#Plot the results and save them
-	vx=md.results.DiagnosticSolution.Vx
-	vy=md.results.DiagnosticSolution.Vy
-	vz=md.results.DiagnosticSolution.Vz
-	pressure=md.results.DiagnosticSolution.Pressure
-	results.append(md.results.DiagnosticSolution)
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	pressure=md.results.StressbalanceSolution.Pressure
+	results.append(md.results.StressbalanceSolution)
 	minvx.append(numpy.min(vx[-md.mesh.numberofvertices2d:]))
 	maxvx.append(numpy.max(vx[-md.mesh.numberofvertices2d:]))
@@ -79,18 +79,18 @@
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipastokesvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipastokesvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#		printmodel(['ismipaFSvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaFSvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 #	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
 	if printingflag:
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipastokesvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipastokesvy%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#		printmodel(['ismipaFSvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaFSvy%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 #	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',4)
 	if printingflag:
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipastokesvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipastokesvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#		printmodel(['ismipaFSvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaFSvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 
 	if   (L==5000.):
@@ -121,6 +121,6 @@
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipastokesvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipastokesvxsec.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#		printmodel(['ismipaFSvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipaFSvxsec.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 
 #Now plot the min and max values of vx for each size of the square
@@ -129,12 +129,12 @@
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('ismipastokesminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#	shutil.move('ismipastokesminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#	printmodel('ismipaFSminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipaFSminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 #plot([5 10 20 40 80 160],maxvx);ylim([0 120])
 if printingflag:
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('ismipastokesmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#	shutil.move('ismipastokesmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
+#	printmodel('ismipaFSmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipaFSmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestA')
 
 #Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test1103.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1103.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1103.m	(revision 16137)
@@ -18,13 +18,13 @@
 	md=extrude(md,10,1.);
 
-	md=setflowequation(md,'pattyn','all');
+	md=setflowequation(md,'HO','all');
 
 	%Create dirichlet on the bed only
-	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	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);
 	pos=find(md.mesh.vertexonbed);
-	md.diagnostic.spcvx(pos)=0.;
-	md.diagnostic.spcvy(pos)=0.;
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
 
 	%Create MPCs to have periodic boundary conditions
@@ -35,15 +35,15 @@
 	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x));
 
-	md.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
 
-	%Compute the diagnostic
+	%Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum());
+	md=solve(md,StressbalanceSolutionEnum());
 
 	%Plot the results and save them
-	vx=(md.results.DiagnosticSolution.Vx);
-	vy=(md.results.DiagnosticSolution.Vy);
-	vz=(md.results.DiagnosticSolution.Vz);
-	results{i}=md.results.DiagnosticSolution;
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
 	minvx(i)=min(vx(end-md.mesh.numberofvertices2d+1:end));
 	maxvx(i)=max(vx(end-md.mesh.numberofvertices2d+1:end));
@@ -53,12 +53,12 @@
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipbpattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipbpattynvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
+		printmodel(['ismipbHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipbHOvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
 	end
 	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipbpattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipbpattynvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
+		printmodel(['ismipbHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipbHOvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
 	end
 
@@ -84,6 +84,6 @@
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipbpattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipbpattynvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
+		printmodel(['ismipbHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipbHOvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
 	end
 end
@@ -93,12 +93,12 @@
 if printingflag,
 	set(gcf,'Color','w')
-	printmodel('ismipbpattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-	system(['mv ismipbpattynminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
+	printmodel('ismipbHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipbHOminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
 end
 plot([5 10 20 40 80 160],maxvx);ylim([0 120]);xlim([0 160])
 if printingflag,
 	set(gcf,'Color','w')
-	printmodel('ismipbpattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-	system(['mv ismipbpattynmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
+	printmodel('ismipbHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipbHOmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestB']);
 end
 
Index: /issm/trunk/test/NightlyRun/test1103.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1103.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1103.py	(revision 16137)
@@ -32,13 +32,13 @@
 	md.extrude(10,1.)
 
-	md=setflowequation(md,'pattyn','all')
+	md=setflowequation(md,'HO','all')
 
 	#Create dirichlet on the bed only
-	md.diagnostic.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
 	pos=numpy.nonzero(md.mesh.vertexonbed)
-	md.diagnostic.spcvx[pos]=0.
-	md.diagnostic.spcvy[pos]=0.
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
 
 	#Create MPCs to have periodic boundary conditions
@@ -49,15 +49,15 @@
 	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]
 
-	md.diagnostic.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
 
-	#Compute the diagnostic
+	#Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8)
-	md=solve(md,DiagnosticSolutionEnum())
+	md=solve(md,StressbalanceSolutionEnum())
 
 	#Plot the results and save them
-	vx=md.results.DiagnosticSolution.Vx
-	vy=md.results.DiagnosticSolution.Vy
-	vz=md.results.DiagnosticSolution.Vz
-	results.append(md.results.DiagnosticSolution)
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
 	minvx.append(numpy.min(vx[md.mesh.numberofvertices2d:]))
 	maxvx.append(numpy.max(vx[md.mesh.numberofvertices2d:]))
@@ -68,12 +68,12 @@
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipbpattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipbpattynvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
+#		printmodel(['ismipbHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipbHOvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
 #	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km')
 	if printingflag:
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipbpattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipbpattynvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
+#		printmodel(['ismipbHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipbHOvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
 
 	if   (L==5000.):
@@ -104,6 +104,6 @@
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipbpattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipbpattynvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
+#		printmodel(['ismipbHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipbHOvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
 
 #Now plot the min and max values of vx for each size of the square
@@ -112,12 +112,12 @@
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('ismipbpattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#	shutil.move('ismipbpattynminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
+#	printmodel('ismipbHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipbHOminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
 #plot([5 10 20 40 80 160],maxvx);ylim([0 120]);xlim([0 160])
 if printingflag:
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('ismipbpattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#	shutil.move('ismipbpattynmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
+#	printmodel('ismipbHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipbHOmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestB')
 
 #Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test1104.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1104.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1104.m	(revision 16137)
@@ -14,14 +14,14 @@
 	md=parameterize(md,'../Par/ISMIPB.par');
 	md=extrude(md,10,1.);
-	md=setflowequation(md,'pattyn','all');
+	md=setflowequation(md,'HO','all');
 
 	%Create dirichlet on the bed only
-	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	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);
 
 	pos=find(md.mesh.vertexonbed);
-	md.diagnostic.spcvx(pos)=0.;
-	md.diagnostic.spcvy(pos)=0.;
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
 
 	%Create MPCs to have periodic boundary conditions
@@ -32,22 +32,22 @@
 	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x));
 
-	md.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
 
-	%Compute the diagnostic
-	md.diagnostic.abstol=NaN;
+	%Compute the stressbalance
+	md.stressbalance.abstol=NaN;
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum());
+	md=solve(md,StressbalanceSolutionEnum());
 	pos=find(md.mesh.x==0. | md.mesh.y==0. | md.mesh.x==max(md.mesh.x) | md.mesh.y==max(md.mesh.y));
-	md.diagnostic.spcvx(pos)=md.results.DiagnosticSolution.Vx(pos);
-	md.diagnostic.spcvy(pos)=md.results.DiagnosticSolution.Vy(pos);
-	md.diagnostic.vertex_pairing=[];
-	md=setflowequation(md,'stokes','all');
-	md=solve(md,DiagnosticSolutionEnum());
+	md.stressbalance.spcvx(pos)=md.results.StressbalanceSolution.Vx(pos);
+	md.stressbalance.spcvy(pos)=md.results.StressbalanceSolution.Vy(pos);
+	md.stressbalance.vertex_pairing=[];
+	md=setflowequation(md,'FS','all');
+	md=solve(md,StressbalanceSolutionEnum());
 
 	%Plot the results and save them
-	vx=(md.results.DiagnosticSolution.Vx);
-	vy=(md.results.DiagnosticSolution.Vy);
-	vz=(md.results.DiagnosticSolution.Vz);
-	results{i}=md.results.DiagnosticSolution;
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
 
 	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
Index: /issm/trunk/test/NightlyRun/test1104.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1104.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1104.py	(revision 16137)
@@ -26,14 +26,14 @@
 	md=parameterize(md,'../Par/ISMIPB.py')
 	md.extrude(10,1.)
-	md=setflowequation(md,'pattyn','all')
+	md=setflowequation(md,'HO','all')
 
 	#Create dirichlet on the bed only
-	md.diagnostic.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
 
 	pos=numpy.nonzero(md.mesh.vertexonbed)
-	md.diagnostic.spcvx[pos]=0.
-	md.diagnostic.spcvy[pos]=0.
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
 
 	#Create MPCs to have periodic boundary conditions
@@ -44,22 +44,22 @@
 	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]
 
-	md.diagnostic.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
 
-	#Compute the diagnostic
-	md.diagnostic.abstol=float('NaN')
+	#Compute the stressbalance
+	md.stressbalance.abstol=float('NaN')
 	md.cluster=generic('name',oshostname(),'np',8)
-	md=solve(md,DiagnosticSolutionEnum())
+	md=solve(md,StressbalanceSolutionEnum())
 	pos=numpy.nonzero(logical_or_n(md.mesh.x==0.,md.mesh.y==0.,md.mesh.x==numpy.max(md.mesh.x),md.mesh.y==numpy.max(md.mesh.y)))
-	md.diagnostic.spcvx[pos]=md.results.DiagnosticSolution.Vx[pos]
-	md.diagnostic.spcvy[pos]=md.results.DiagnosticSolution.Vy[pos]
-	md.diagnostic.vertex_pairing=numpy.empty((0,2),int)
-	md=setflowequation(md,'stokes','all')
-	md=solve(md,DiagnosticSolutionEnum())
+	md.stressbalance.spcvx[pos]=md.results.StressbalanceSolution.Vx[pos]
+	md.stressbalance.spcvy[pos]=md.results.StressbalanceSolution.Vy[pos]
+	md.stressbalance.vertex_pairing=numpy.empty((0,2),int)
+	md=setflowequation(md,'FS','all')
+	md=solve(md,StressbalanceSolutionEnum())
 
 	#Plot the results and save them
-	vx=md.results.DiagnosticSolution.Vx
-	vy=md.results.DiagnosticSolution.Vy
-	vz=md.results.DiagnosticSolution.Vz
-	results.append(md.results.DiagnosticSolution)
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
 
 #	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
Index: /issm/trunk/test/NightlyRun/test1105.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1105.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1105.m	(revision 16137)
@@ -18,10 +18,10 @@
 	md=extrude(md,10,1.);
 
-	md=setflowequation(md,'pattyn','all');
+	md=setflowequation(md,'HO','all');
 
 	%Create MPCs to have periodic boundary conditions
-	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	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);
 
 	posx=find(md.mesh.x==0. & md.mesh.y~=0. & md.mesh.y~=L);
@@ -31,43 +31,43 @@
 	posy2=find(md.mesh.y==L & md.mesh.x~=0. & md.mesh.x~=L);
 
-	md.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
 
 	%Add spc on the corners
 	pos=find((md.mesh.x==0. | md.mesh.x==L) & (md.mesh.y==0. | md.mesh.y==L) & md.mesh.vertexonbed);
-	md.diagnostic.spcvx(pos)=0.;
-	md.diagnostic.spcvy(pos)=0.;
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
 	if(L==5000.),
-		md.diagnostic.spcvx(pos)=15.66;
-		md.diagnostic.spcvy(pos)=-0.1967;
+		md.stressbalance.spcvx(pos)=15.66;
+		md.stressbalance.spcvy(pos)=-0.1967;
 	elseif(L==10000.),
-		md.diagnostic.spcvx(pos)=16.04;
-		md.diagnostic.spcvy(pos)=-0.1977;
+		md.stressbalance.spcvx(pos)=16.04;
+		md.stressbalance.spcvy(pos)=-0.1977;
 	elseif(L==20000.),
-		md.diagnostic.spcvx(pos)=16.53;
-		md.diagnostic.spcvy(pos)=-1.27;
+		md.stressbalance.spcvx(pos)=16.53;
+		md.stressbalance.spcvy(pos)=-1.27;
 	elseif(L==40000.),
-		md.diagnostic.spcvx(pos)=17.23;
-		md.diagnostic.spcvy(pos)=-3.17;
+		md.stressbalance.spcvx(pos)=17.23;
+		md.stressbalance.spcvy(pos)=-3.17;
 	elseif(L==80000.),
-		md.diagnostic.spcvx(pos)=16.68;
-		md.diagnostic.spcvy(pos)=-2.69;
+		md.stressbalance.spcvx(pos)=16.68;
+		md.stressbalance.spcvy(pos)=-2.69;
 	elseif(L==160000.),
-		md.diagnostic.spcvx(pos)=16.03;
-		md.diagnostic.spcvy(pos)=-1.27;
+		md.stressbalance.spcvx(pos)=16.03;
+		md.stressbalance.spcvy(pos)=-1.27;
 	end
 	
 	%Spc the bed at zero for vz
 	pos=find(md.mesh.vertexonbed);
-	md.diagnostic.spcvz(pos)=0.;
+	md.stressbalance.spcvz(pos)=0.;
 
-	%Compute the diagnostic
+	%Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum());
+	md=solve(md,StressbalanceSolutionEnum());
 
 	%Plot the results and save them
-	vx=(md.results.DiagnosticSolution.Vx);
-	vy=(md.results.DiagnosticSolution.Vy);
-	vz=(md.results.DiagnosticSolution.Vz);
-	results{i}=md.results.DiagnosticSolution;
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
 	minvx(i)=min(vx(end-md.mesh.numberofvertices2d+1:end));
 	maxvx(i)=max(vx(end-md.mesh.numberofvertices2d+1:end));
@@ -77,18 +77,18 @@
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipcpattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipcpattynvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+		printmodel(['ismipcHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcHOvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
 	end
 	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipcpattynvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipcpattynvy' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+		printmodel(['ismipcHOvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcHOvy' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
 	end
 	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',4)
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipcpattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipcpattynvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+		printmodel(['ismipcHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcHOvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
 	end
 
@@ -114,6 +114,6 @@
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipcpattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipcpattynvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+		printmodel(['ismipcHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipcHOvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
 	end
 end
@@ -123,12 +123,12 @@
 if printingflag,
 	set(gcf,'Color','w')
-	printmodel('ismipcpattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-	system(['mv ismipcpattynminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+	printmodel('ismipcHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipcHOminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
 end
 plot([5 10 20 40 80 160],maxvx);ylim([0 200]); xlim([0 160])
 if printingflag,
 	set(gcf,'Color','w')
-	printmodel('ismipcpattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-	system(['mv ismipcpattynmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
+	printmodel('ismipcHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipcHOmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestC']);
 end
 
@@ -148,5 +148,5 @@
 	1e-09,1e-09,1e-08,...
 	1e-09,1e-08,1e-08,...
-	1e-09,1e-08,1e-08,...
+	1e-08,1e-08,1e-08,...
 };
 field_values={};
Index: /issm/trunk/test/NightlyRun/test1105.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1105.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1105.py	(revision 16137)
@@ -32,10 +32,10 @@
 	md.extrude(10,1.)
 
-	md=setflowequation(md,'pattyn','all')
+	md=setflowequation(md,'HO','all')
 
 	#Create MPCs to have periodic boundary conditions
-	md.diagnostic.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
 
 	posx=numpy.nonzero(logical_and_n(md.mesh.x==0.,md.mesh.y!=0.,md.mesh.y!=L))[0]
@@ -45,42 +45,42 @@
 	posy2=numpy.nonzero(logical_and_n(md.mesh.y==L,md.mesh.x!=0.,md.mesh.x!=L))[0]
 
-	md.diagnostic.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
 
 	#Add spc on the corners
 	pos=numpy.nonzero(logical_and_n(numpy.logical_or(md.mesh.x==0.,md.mesh.x==L),numpy.logical_or(md.mesh.y==0.,md.mesh.y==L),md.mesh.vertexonbed))
-	md.diagnostic.spcvx[pos]=0.
-	md.diagnostic.spcvy[pos]=0.
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
 	if   (L==5000.):
-		md.diagnostic.spcvx[pos]=15.66
-		md.diagnostic.spcvy[pos]=-0.1967
+		md.stressbalance.spcvx[pos]=15.66
+		md.stressbalance.spcvy[pos]=-0.1967
 	elif (L==10000.):
-		md.diagnostic.spcvx[pos]=16.04
-		md.diagnostic.spcvy[pos]=-0.1977
+		md.stressbalance.spcvx[pos]=16.04
+		md.stressbalance.spcvy[pos]=-0.1977
 	elif (L==20000.):
-		md.diagnostic.spcvx[pos]=16.53
-		md.diagnostic.spcvy[pos]=-1.27
+		md.stressbalance.spcvx[pos]=16.53
+		md.stressbalance.spcvy[pos]=-1.27
 	elif (L==40000.):
-		md.diagnostic.spcvx[pos]=17.23
-		md.diagnostic.spcvy[pos]=-3.17
+		md.stressbalance.spcvx[pos]=17.23
+		md.stressbalance.spcvy[pos]=-3.17
 	elif (L==80000.):
-		md.diagnostic.spcvx[pos]=16.68
-		md.diagnostic.spcvy[pos]=-2.69
+		md.stressbalance.spcvx[pos]=16.68
+		md.stressbalance.spcvy[pos]=-2.69
 	elif (L==160000.):
-		md.diagnostic.spcvx[pos]=16.03
-		md.diagnostic.spcvy[pos]=-1.27
+		md.stressbalance.spcvx[pos]=16.03
+		md.stressbalance.spcvy[pos]=-1.27
 	
 	#Spc the bed at zero for vz
 	pos=numpy.nonzero(md.mesh.vertexonbed)
-	md.diagnostic.spcvz[pos]=0.
+	md.stressbalance.spcvz[pos]=0.
 
-	#Compute the diagnostic
+	#Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8)
-	md=solve(md,DiagnosticSolutionEnum())
+	md=solve(md,StressbalanceSolutionEnum())
 
 	#Plot the results and save them
-	vx=md.results.DiagnosticSolution.Vx
-	vy=md.results.DiagnosticSolution.Vy
-	vz=md.results.DiagnosticSolution.Vz
-	results.append(md.results.DiagnosticSolution)
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
 	minvx.append(numpy.min(vx[-md.mesh.numberofvertices2d:]))
 	maxvx.append(numpy.max(vx[-md.mesh.numberofvertices2d:]))
@@ -91,18 +91,18 @@
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipcpattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipcpattynvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+#		printmodel(['ismipcHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipcHOvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
 #	plotmodel(md,'data',vy,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
 	if printingflag:
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipcpattynvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipcpattynvy%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+#		printmodel(['ismipcHOvy' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipcHOvy%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
 #	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',4)
 	if printingflag:
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipcpattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipcpattynvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+#		printmodel(['ismipcHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipcHOvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
 
 	if   (L==5000.):
@@ -133,6 +133,6 @@
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipcpattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipcpattynvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+#		printmodel(['ismipcHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipcHOvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
 
 #Now plot the min and max values of vx for each size of the square
@@ -141,12 +141,12 @@
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('ismipcpattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#	shutil.move('ismipcpattynminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+#	printmodel('ismipcHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipcHOminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
 #plot([5 10 20 40 80 160],maxvx);ylim([0 200]); xlim([0 160])
 if printingflag:
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('ismipcpattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#	shutil.move('ismipcpattynmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
+#	printmodel('ismipcHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipcHOmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestC')
 
 #Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test1106.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1106.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1106.m	(revision 16137)
@@ -15,37 +15,37 @@
 	%Add spc on the borders
 	pos=find(md.mesh.x==0. | md.mesh.x==max(md.mesh.x) | md.mesh.y==0. | md.mesh.y==max(md.mesh.y));
-	md.diagnostic.spcvx(pos)=0.;
-	md.diagnostic.spcvy(pos)=0.;
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
 	if(L==5000.),
-		md.diagnostic.spcvx(pos)=15.66;
-		md.diagnostic.spcvy(pos)=-0.1967;
+		md.stressbalance.spcvx(pos)=15.66;
+		md.stressbalance.spcvy(pos)=-0.1967;
 	elseif(L==10000.),
-		md.diagnostic.spcvx(pos)=16.04;
-		md.diagnostic.spcvy(pos)=-0.1977;
+		md.stressbalance.spcvx(pos)=16.04;
+		md.stressbalance.spcvy(pos)=-0.1977;
 	elseif(L==20000.),
-		md.diagnostic.spcvx(pos)=16.53;
-		md.diagnostic.spcvy(pos)=-1.27;
+		md.stressbalance.spcvx(pos)=16.53;
+		md.stressbalance.spcvy(pos)=-1.27;
 	elseif(L==40000.),
-		md.diagnostic.spcvx(pos)=17.23;
-		md.diagnostic.spcvy(pos)=-3.17;
+		md.stressbalance.spcvx(pos)=17.23;
+		md.stressbalance.spcvy(pos)=-3.17;
 	elseif(L==80000.),
-		md.diagnostic.spcvx(pos)=16.68;
-		md.diagnostic.spcvy(pos)=-2.69;
+		md.stressbalance.spcvx(pos)=16.68;
+		md.stressbalance.spcvy(pos)=-2.69;
 	elseif(L==160000.),
-		md.diagnostic.spcvx(pos)=16.03;
-		md.diagnostic.spcvy(pos)=-1.27;
+		md.stressbalance.spcvx(pos)=16.03;
+		md.stressbalance.spcvy(pos)=-1.27;
 	end
 
-	md=setflowequation(md,'stokes','all');
+	md=setflowequation(md,'FS','all');
 
-	%Compute the diagnostic
+	%Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum());
+	md=solve(md,StressbalanceSolutionEnum());
 
 	%Plot the results and save them
-	vx=(md.results.DiagnosticSolution.Vx);
-	vy=(md.results.DiagnosticSolution.Vy);
-	vz=(md.results.DiagnosticSolution.Vz);
-	results{i}=md.results.DiagnosticSolution;
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
 
 	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
@@ -63,9 +63,9 @@
 field_tolerances={...
 	1e-12,1e-12,1e-11,...
+	1e-12,2e-12,2e-12,...
 	1e-12,1e-12,1e-12,...
-	1e-12,1e-12,1e-12,...
-	1e-12,1e-12,1e-12,...
-	1e-12,1e-12,1e-12,...
-	1e-12,1e-11,1e-12,...
+	1e-12,2e-12,2e-12,...
+	1e-12,2e-12,2e-12,...
+	1e-12,2e-11,2e-12,...
 };
 field_values={};
Index: /issm/trunk/test/NightlyRun/test1106.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1106.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1106.py	(revision 16137)
@@ -27,36 +27,36 @@
 	#Add spc on the borders
 	pos=numpy.nonzero(logical_or_n(md.mesh.x==0.,md.mesh.x==numpy.max(md.mesh.x),md.mesh.y==0.,md.mesh.y==numpy.max(md.mesh.y)))
-	md.diagnostic.spcvx[pos]=0.
-	md.diagnostic.spcvy[pos]=0.
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
 	if   (L==5000.):
-		md.diagnostic.spcvx[pos]=15.66
-		md.diagnostic.spcvy[pos]=-0.1967
+		md.stressbalance.spcvx[pos]=15.66
+		md.stressbalance.spcvy[pos]=-0.1967
 	elif (L==10000.):
-		md.diagnostic.spcvx[pos]=16.04
-		md.diagnostic.spcvy[pos]=-0.1977
+		md.stressbalance.spcvx[pos]=16.04
+		md.stressbalance.spcvy[pos]=-0.1977
 	elif (L==20000.):
-		md.diagnostic.spcvx[pos]=16.53
-		md.diagnostic.spcvy[pos]=-1.27
+		md.stressbalance.spcvx[pos]=16.53
+		md.stressbalance.spcvy[pos]=-1.27
 	elif (L==40000.):
-		md.diagnostic.spcvx[pos]=17.23
-		md.diagnostic.spcvy[pos]=-3.17
+		md.stressbalance.spcvx[pos]=17.23
+		md.stressbalance.spcvy[pos]=-3.17
 	elif (L==80000.):
-		md.diagnostic.spcvx[pos]=16.68
-		md.diagnostic.spcvy[pos]=-2.69
+		md.stressbalance.spcvx[pos]=16.68
+		md.stressbalance.spcvy[pos]=-2.69
 	elif (L==160000.):
-		md.diagnostic.spcvx[pos]=16.03
-		md.diagnostic.spcvy[pos]=-1.27
+		md.stressbalance.spcvx[pos]=16.03
+		md.stressbalance.spcvy[pos]=-1.27
 
-	md=setflowequation(md,'stokes','all')
+	md=setflowequation(md,'FS','all')
 
-	#Compute the diagnostic
+	#Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8)
-	md=solve(md,DiagnosticSolutionEnum())
+	md=solve(md,StressbalanceSolutionEnum())
 
 	#Plot the results and save them
-	vx=md.results.DiagnosticSolution.Vx
-	vy=md.results.DiagnosticSolution.Vy
-	vz=md.results.DiagnosticSolution.Vz
-	results.append(md.results.DiagnosticSolution)
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
 
 #	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
Index: /issm/trunk/test/NightlyRun/test1107.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1107.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1107.m	(revision 16137)
@@ -18,10 +18,10 @@
 	md=extrude(md,10,1.);
 
-	md=setflowequation(md,'pattyn','all');
+	md=setflowequation(md,'HO','all');
 
 	%We need one grd on dirichlet: the 4 corners are set to zero
-	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	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);
 
 	%Create MPCs to have periodic boundary conditions
@@ -32,37 +32,37 @@
 	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x));
 
-	md.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
 
 	%Add spc on the corners
 	pos=find((md.mesh.x==0. | md.mesh.x==L) & (md.mesh.y==0. | md.mesh.y==L) & md.mesh.vertexonbed);
-	md.diagnostic.spcvy(:)=0.;
-	md.diagnostic.spcvx(pos)=0.;
+	md.stressbalance.spcvy(:)=0.;
+	md.stressbalance.spcvx(pos)=0.;
 	if(L==5000.),
-		md.diagnostic.spcvx(pos)=16.0912;
+		md.stressbalance.spcvx(pos)=16.0912;
 	elseif(L==10000.),
-		md.diagnostic.spcvx(pos)=16.52;
+		md.stressbalance.spcvx(pos)=16.52;
 	elseif(L==20000.),
-		md.diagnostic.spcvx(pos)=17.77;
+		md.stressbalance.spcvx(pos)=17.77;
 	elseif(L==40000.),
-		md.diagnostic.spcvx(pos)=19.88;
+		md.stressbalance.spcvx(pos)=19.88;
 	elseif(L==80000.),
-		md.diagnostic.spcvx(pos)=18.65;
+		md.stressbalance.spcvx(pos)=18.65;
 	elseif(L==160000.),
-		md.diagnostic.spcvx(pos)=16.91;
+		md.stressbalance.spcvx(pos)=16.91;
 	end
 	
 	%Spc the bed at zero for vz
 	pos=find(md.mesh.vertexonbed);
-	md.diagnostic.spcvz(pos)=0.;
+	md.stressbalance.spcvz(pos)=0.;
 
-	%Compute the diagnostic
+	%Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum());
+	md=solve(md,StressbalanceSolutionEnum());
 
 	%Plot the results and save them
-	vx=(md.results.DiagnosticSolution.Vx);
-	vy=(md.results.DiagnosticSolution.Vy);
-	vz=(md.results.DiagnosticSolution.Vz);
-	results{i}=md.results.DiagnosticSolution;
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
 	minvx(i)=min(vx(end-md.mesh.numberofvertices2d+1:end));
 	maxvx(i)=max(vx(end-md.mesh.numberofvertices2d+1:end));
@@ -72,12 +72,12 @@
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipdpattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipdpattynvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
+		printmodel(['ismipdHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipdHOvx' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
 	end
 	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipdpattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipdpattynvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
+		printmodel(['ismipdHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipdHOvz' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
 	end
 
@@ -103,6 +103,6 @@
 	if printingflag,
 		set(gcf,'Color','w')
-		printmodel(['ismipdpattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-		system(['mv ismipdpattynvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
+		printmodel(['ismipdHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+		system(['mv ismipdHOvxsec' num2str(L) '.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
 	end
 end
@@ -112,12 +112,12 @@
 if printingflag,
 	set(gcf,'Color','w')
-	printmodel('ismipdpattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-	system(['mv ismipdpattynminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
+	printmodel('ismipdHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipdHOminvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
 end
 plot([5 10 20 40 80 160],maxvx);ylim([0 300]);xlim([0 160])
 if printingflag,
 	set(gcf,'Color','w')
-	printmodel('ismipdpattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-	system(['mv ismipdpattynmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
+	printmodel('ismipdHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+	system(['mv ismipdHOmaxvx.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestD']);
 end
 
Index: /issm/trunk/test/NightlyRun/test1107.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1107.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1107.py	(revision 16137)
@@ -32,10 +32,10 @@
 	md.extrude(10,1.)
 
-	md=setflowequation(md,'pattyn','all')
+	md=setflowequation(md,'HO','all')
 
 	#We need one grd on dirichlet: the 4 corners are set to zero
-	md.diagnostic.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
 
 	#Create MPCs to have periodic boundary conditions
@@ -48,36 +48,36 @@
 	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]
 
-	md.diagnostic.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
 
 	#Add spc on the corners
 	pos=numpy.nonzero(logical_and_n(numpy.logical_or(md.mesh.x==0.,md.mesh.x==L),numpy.logical_or(md.mesh.y==0.,md.mesh.y==L),md.mesh.vertexonbed))
-	md.diagnostic.spcvy[:]=0.
-	md.diagnostic.spcvx[pos]=0.
+	md.stressbalance.spcvy[:]=0.
+	md.stressbalance.spcvx[pos]=0.
 	if   (L==5000.):
-		md.diagnostic.spcvx[pos]=16.0912
+		md.stressbalance.spcvx[pos]=16.0912
 	elif (L==10000.):
-		md.diagnostic.spcvx[pos]=16.52
+		md.stressbalance.spcvx[pos]=16.52
 	elif (L==20000.):
-		md.diagnostic.spcvx[pos]=17.77
+		md.stressbalance.spcvx[pos]=17.77
 	elif (L==40000.):
-		md.diagnostic.spcvx[pos]=19.88
+		md.stressbalance.spcvx[pos]=19.88
 	elif (L==80000.):
-		md.diagnostic.spcvx[pos]=18.65
+		md.stressbalance.spcvx[pos]=18.65
 	elif (L==160000.):
-		md.diagnostic.spcvx[pos]=16.91
+		md.stressbalance.spcvx[pos]=16.91
 	
 	#Spc the bed at zero for vz
 	pos=numpy.nonzero(md.mesh.vertexonbed)
-	md.diagnostic.spcvz[pos]=0.
+	md.stressbalance.spcvz[pos]=0.
 
-	#Compute the diagnostic
+	#Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8)
-	md=solve(md,DiagnosticSolutionEnum())
+	md=solve(md,StressbalanceSolutionEnum())
 
 	#Plot the results and save them
-	vx=md.results.DiagnosticSolution.Vx
-	vy=md.results.DiagnosticSolution.Vy
-	vz=md.results.DiagnosticSolution.Vz
-	results.append(md.results.DiagnosticSolution)
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
 	minvx.append(numpy.min(vx[-md.mesh.numberofvertices2d:]))
 	maxvx.append(numpy.max(vx[-md.mesh.numberofvertices2d:]))
@@ -88,12 +88,12 @@
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipdpattynvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipdpattynvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
+#		printmodel(['ismipdHOvx' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipdHOvx%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
 #	plotmodel(md,'data',vz,'layer#all',md.mesh.numberoflayers,'xlim',[0 L/10^3],'ylim',[0 L/10^3],'unit','km','figure',3)
 	if printingflag:
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipdpattynvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipdpattynvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
+#		printmodel(['ismipdHOvz' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipdHOvz%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
 
 	if   (L==5000.):
@@ -124,6 +124,6 @@
 		pass
 #		set(gcf,'Color','w')
-#		printmodel(['ismipdpattynvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#		shutil.move("ismipdpattynvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
+#		printmodel(['ismipdHOvxsec' num2str(L)],'png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#		shutil.move("ismipdHOvxsec%d.png" % L,ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
 
 #Now plot the min and max values of vx for each size of the square
@@ -132,12 +132,12 @@
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('ismipdpattynminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#	shutil.move('ismipdpattynminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
+#	printmodel('ismipdHOminvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipdHOminvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
 #plot([5 10 20 40 80 160],maxvx);ylim([0 300]);xlim([0 160])
 if printingflag:
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('ismipdpattynmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-#	shutil.move('ismipdpattynmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
+#	printmodel('ismipdHOmaxvx','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+#	shutil.move('ismipdHOmaxvx.png',ISSM_DIR+'/website/doc_pdf/validation/Images/ISMIP/TestD')
 
 #Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test1108.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1108.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1108.m	(revision 16137)
@@ -15,15 +15,15 @@
 	md=extrude(md,10,1.);
 
-	md=setflowequation(md,'pattyn','all');
+	md=setflowequation(md,'HO','all');
 
 	%We need one grid on dirichlet: the 4 corners are set to zero
-	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	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);
 	
 	pos=find(md.mesh.vertexonbed & (md.mesh.x==0. | md.mesh.x==max(md.mesh.x)) & (md.mesh.y==0. | md.mesh.y==max(md.mesh.y)));
-	md.diagnostic.spcvx(pos)=0.;
-	md.diagnostic.spcvy(pos)=0.;
-	md.diagnostic.spcvz(pos)=0.;
+	md.stressbalance.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
+	md.stressbalance.spcvz(pos)=0.;
 
 	%Create MPCs to have periodic boundary conditions
@@ -34,28 +34,28 @@
 	posy2=find(md.mesh.y==max(md.mesh.y) & md.mesh.x~=0. & md.mesh.x~=max(md.mesh.x));
 
-	md.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
 
-	%Compute the diagnostic
+	%Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8);
 	md.verbose=verbose('convergence',true);
-	md=solve(md,DiagnosticSolutionEnum());
-	md.diagnostic.reltol=NaN;
-	md.diagnostic.abstol=NaN;
-	md.diagnostic.vertex_pairing=[];
+	md=solve(md,StressbalanceSolutionEnum());
+	md.stressbalance.reltol=NaN;
+	md.stressbalance.abstol=NaN;
+	md.stressbalance.vertex_pairing=[];
 	%We need one grd on dirichlet: the 4 corners are set to zero
-	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	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);
 	pos=find(md.mesh.y==0. | md.mesh.x==0. | md.mesh.x==max(md.mesh.x) | md.mesh.y==max(md.mesh.y)); %Don't take the same nodes two times
-	md.diagnostic.spcvx(pos)=md.results.DiagnosticSolution.Vx(pos);
-	md.diagnostic.spcvy(pos)=md.results.DiagnosticSolution.Vy(pos);
-	md=setflowequation(md,'stokes','all');
-	md=solve(md,DiagnosticSolutionEnum());
+	md.stressbalance.spcvx(pos)=md.results.StressbalanceSolution.Vx(pos);
+	md.stressbalance.spcvy(pos)=md.results.StressbalanceSolution.Vy(pos);
+	md=setflowequation(md,'FS','all');
+	md=solve(md,StressbalanceSolutionEnum());
 
 	%Plot the results and save them
-	vx=(md.results.DiagnosticSolution.Vx);
-	vy=(md.results.DiagnosticSolution.Vy);
-	vz=(md.results.DiagnosticSolution.Vz);
-	results{i}=md.results.DiagnosticSolution;
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
 
 	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
@@ -75,5 +75,5 @@
 	1e-08,1e-08,1e-08,...
 	1e-08,1e-07,1e-07,...
-	1e-08,1e-08,1e-08,...
+	1e-08,1e-08,2e-08,...
 	1e-08,1e-07,1e-07,...
 	1e-07,1e-06,1e-07,...
Index: /issm/trunk/test/NightlyRun/test1108.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1108.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1108.py	(revision 16137)
@@ -27,15 +27,15 @@
 	md.extrude(10,1.)
 
-	md=setflowequation(md,'pattyn','all')
+	md=setflowequation(md,'HO','all')
 
 	#We need one grd on dirichlet: the 4 corners are set to zero
-	md.diagnostic.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
 	
 	pos=numpy.nonzero(logical_and_n(md.mesh.vertexonbed,numpy.logical_or(md.mesh.x==0.,md.mesh.x==numpy.max(md.mesh.x)),numpy.logical_or(md.mesh.y==0.,md.mesh.y==numpy.max(md.mesh.y))))
-	md.diagnostic.spcvx[pos]=0.
-	md.diagnostic.spcvy[pos]=0.
-	md.diagnostic.spcvz[pos]=0.
+	md.stressbalance.spcvx[pos]=0.
+	md.stressbalance.spcvy[pos]=0.
+	md.stressbalance.spcvz[pos]=0.
 
 	#Create MPCs to have periodic boundary conditions
@@ -46,28 +46,28 @@
 	posy2=numpy.nonzero(logical_and_n(md.mesh.y==numpy.max(md.mesh.y),md.mesh.x!=0.,md.mesh.x!=numpy.max(md.mesh.x)))[0]
 
-	md.diagnostic.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
+	md.stressbalance.vertex_pairing=numpy.vstack((numpy.hstack((posx.reshape(-1,1)+1,posx2.reshape(-1,1)+1)),numpy.hstack((posy.reshape(-1,1)+1,posy2.reshape(-1,1)+1))))
 
-	#Compute the diagnostic
+	#Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8)
 	md.verbose=verbose('convergence',True)
-	md=solve(md,DiagnosticSolutionEnum())
-	md.diagnostic.reltol=float('NaN')
-	md.diagnostic.abstol=float('NaN')
-	md.diagnostic.vertex_pairing=numpy.empty((0,2))
+	md=solve(md,StressbalanceSolutionEnum())
+	md.stressbalance.reltol=float('NaN')
+	md.stressbalance.abstol=float('NaN')
+	md.stressbalance.vertex_pairing=numpy.empty((0,2))
 	#We need one grid on dirichlet: the 4 corners are set to zero
-	md.diagnostic.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-	md.diagnostic.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvx=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvy=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+	md.stressbalance.spcvz=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
 	pos=numpy.nonzero(logical_or_n(md.mesh.y==0.,md.mesh.x==0.,md.mesh.x==numpy.max(md.mesh.x),md.mesh.y==numpy.max(md.mesh.y)))    #Don't take the same nodes two times
-	md.diagnostic.spcvx[pos]=md.results.DiagnosticSolution.Vx[pos]
-	md.diagnostic.spcvy[pos]=md.results.DiagnosticSolution.Vy[pos]
-	md=setflowequation(md,'stokes','all')
-	md=solve(md,DiagnosticSolutionEnum())
+	md.stressbalance.spcvx[pos]=md.results.StressbalanceSolution.Vx[pos]
+	md.stressbalance.spcvy[pos]=md.results.StressbalanceSolution.Vy[pos]
+	md=setflowequation(md,'FS','all')
+	md=solve(md,StressbalanceSolutionEnum())
 
 	#Plot the results and save them
-	vx=md.results.DiagnosticSolution.Vx
-	vy=md.results.DiagnosticSolution.Vy
-	vz=md.results.DiagnosticSolution.Vz
-	results.append(md.results.DiagnosticSolution)
+	vx=md.results.StressbalanceSolution.Vx
+	vy=md.results.StressbalanceSolution.Vy
+	vz=md.results.StressbalanceSolution.Vz
+	results.append(md.results.StressbalanceSolution)
 
 #	plotmodel(md,'data',vx,'data',vy,'data',vz,'layer#all',md.mesh.numberoflayers)
Index: /issm/trunk/test/NightlyRun/test1109.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1109.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1109.m	(revision 16137)
@@ -20,7 +20,7 @@
 
 	if i==1 | i==3,
-		md=setflowequation(md,'pattyn','all');
+		md=setflowequation(md,'HO','all');
 	elseif i==2 | i==4,
-		md=setflowequation(md,'stokes','all');
+		md=setflowequation(md,'FS','all');
 	end
 
@@ -28,31 +28,31 @@
 	posx=find(md.mesh.x==0.);
 	posx2=find(md.mesh.x==max(md.mesh.x));
-	md.diagnostic.vertex_pairing=[posx,posx2];
+	md.stressbalance.vertex_pairing=[posx,posx2];
 
 	%Create spcs on the bed 
 	pos=find(md.mesh.vertexonbed);
-	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvx(pos)=0.;
-	md.diagnostic.spcvy(pos)=0.;
-	md.diagnostic.spcvz(pos)=0.;
+	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.spcvx(pos)=0.;
+	md.stressbalance.spcvy(pos)=0.;
+	md.stressbalance.spcvz(pos)=0.;
 
 	%Remove the spc where there is some sliding (case 3 and 4):
 	if i==3 | i==4,
 		pos=find(md.mesh.y/max(md.mesh.y)>=0.44 & md.mesh.y/max(md.mesh.y)<=0.5);
-		md.diagnostic.spcvx(pos)=NaN;
-		md.diagnostic.spcvy(pos)=NaN;
-		md.diagnostic.spcvz(pos)=NaN;
+		md.stressbalance.spcvx(pos)=NaN;
+		md.stressbalance.spcvy(pos)=NaN;
+		md.stressbalance.spcvz(pos)=NaN;
 	end
 
-	%Compute the diagnostic
+	%Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum());
+	md=solve(md,StressbalanceSolutionEnum());
 
-	vx=(md.results.DiagnosticSolution.Vx);
-	vy=(md.results.DiagnosticSolution.Vy);
-	vz=(md.results.DiagnosticSolution.Vz);
-	results{i}=md.results.DiagnosticSolution;
+	vx=(md.results.StressbalanceSolution.Vx);
+	vy=(md.results.StressbalanceSolution.Vy);
+	vz=(md.results.StressbalanceSolution.Vz);
+	results{i}=md.results.StressbalanceSolution;
 
 	if i==1,
@@ -60,6 +60,6 @@
 		if printingflag,
 			set(gcf,'Color','w')
-			printmodel('ismipepattynvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipepattynvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
+			printmodel('ismipeHOvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipeHOvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
 		end
 	elseif i==2,
@@ -67,6 +67,6 @@
 		if printingflag,
 			set(gcf,'Color','w')
-			printmodel('ismipestokesvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipestokesvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
+			printmodel('ismipeFSvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipeFSvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
 		end
 	elseif i==3,
@@ -74,6 +74,6 @@
 		if printingflag,
 			set(gcf,'Color','w')
-			printmodel('ismipepattynvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipepattynvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
+			printmodel('ismipeHOvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipeHOvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
 		end
 	elseif i==4,
@@ -81,6 +81,6 @@
 		if printingflag,
 			set(gcf,'Color','w')
-			printmodel('ismipestokesvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipestokesvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
+			printmodel('ismipeFSvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipeFSvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestE']);
 		end
 	end
Index: /issm/trunk/test/NightlyRun/test111.m
===================================================================
--- /issm/trunk/test/NightlyRun/test111.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test111.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.transient.requested_outputs=IceVolumeEnum();
Index: /issm/trunk/test/NightlyRun/test111.py
===================================================================
--- /issm/trunk/test/NightlyRun/test111.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test111.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.transient.requested_outputs=IceVolumeEnum()
Index: /issm/trunk/test/NightlyRun/test1110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1110.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1110.m	(revision 16137)
@@ -16,23 +16,23 @@
 
 	if (i==1 | i==2),
-		md=setflowequation(md,'pattyn','all');
+		md=setflowequation(md,'HO','all');
 	else
-		md=setflowequation(md,'stokes','all');
+		md=setflowequation(md,'FS','all');
 	end
 
-	md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-	md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+	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);
 	if (i==1 | i==3),
 		%Create dirichlet on the bed if no slip
 		pos=find(md.mesh.vertexonbed);
-		md.diagnostic.spcvx(pos)=0.;
-		md.diagnostic.spcvy(pos)=0.;
-		md.diagnostic.spcvz(pos)=0.;
+		md.stressbalance.spcvx(pos)=0.;
+		md.stressbalance.spcvy(pos)=0.;
+		md.stressbalance.spcvz(pos)=0.;
 	else
 		pos=find(md.mesh.vertexonbed & (md.mesh.x==0. | md.mesh.x==max(md.mesh.x)) & (md.mesh.y==0. | md.mesh.y==max(md.mesh.y)));
-		md.diagnostic.spcvx(pos)=100.; %because we need a dirichlet somewhere
-		md.diagnostic.spcvy(pos)=0.;
-		md.diagnostic.spcvz(pos)=0.;
+		md.stressbalance.spcvx(pos)=100.; %because we need a dirichlet somewhere
+		md.stressbalance.spcvy(pos)=0.;
+		md.stressbalance.spcvz(pos)=0.;
 	end
 	pos=find(~md.mesh.vertexonbed);
@@ -46,14 +46,14 @@
 	posy2=find(md.mesh.y==max(md.mesh.y));
 
-	md.diagnostic.vertex_pairing=[posx,posx2;posy,posy2];
-	md.prognostic.vertex_pairing=[posx,posx2;posy,posy2];
+	md.stressbalance.vertex_pairing=[posx,posx2;posy,posy2];
+	md.masstransport.vertex_pairing=[posx,posx2;posy,posy2];
 
 	md.timestepping.time_step=3.;
 	md.timestepping.final_time=300.;
 	md.settings.output_frequency=50;
-	md.prognostic.stabilization=1;
-	md.diagnostic.maxiter=1;
+	md.masstransport.stabilization=1;
+	md.stressbalance.maxiter=1;
 	
-	%Compute the diagnostic
+	%Compute the stressbalance
 	md.cluster=generic('name',oshostname(),'np',8);
 	md.verbose=verbose('convergence',true,'solution',true);
@@ -72,15 +72,15 @@
 		set(gcf,'Color','w')
 		if i==1,
-			printmodel('ismipfpattynvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipfpattynvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+			printmodel('ismipfHOvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfHOvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
 		elseif i==2,
-			printmodel('ismipfpattynvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipfpattynvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+			printmodel('ismipfHOvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfHOvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
 		elseif i==3,
-			printmodel('ismipfstokesvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipfstokesvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+			printmodel('ismipfFSvxfrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfFSvxfrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
 		elseif i==4,
-			printmodel('ismipfstokesvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipfstokesvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+			printmodel('ismipfFSvxsliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfFSvxsliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
 		end
 	end
@@ -90,15 +90,15 @@
 		set(gcf,'Color','w')
 		if i==1,
-			printmodel('ismipfpattyndeltasurfacefrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipfpattyndeltasurfacefrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+			printmodel('ismipfHOdeltasurfacefrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfHOdeltasurfacefrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
 		elseif i==2,
-			printmodel('ismipfpattyndeltasurfacesliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipfpattyndeltasurfacesliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+			printmodel('ismipfHOdeltasurfacesliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfHOdeltasurfacesliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
 		elseif i==3,
-			printmodel('ismipfstokesdeltasurfacefrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipfstokesdeltasurfacefrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+			printmodel('ismipfFSdeltasurfacefrozen','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfFSdeltasurfacefrozen.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
 		elseif i==4,
-			printmodel('ismipfstokesdeltasurfacesliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
-			system(['mv ismipfstokesdeltasurfacesliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
+			printmodel('ismipfFSdeltasurfacesliding','png','margin','on','marginsize',25,'frame','off','resolution',1.5,'hardcopy','off');
+			system(['mv ismipfFSdeltasurfacesliding.png ' ISSM_DIR '/website/doc_pdf/validation/Images/ISMIP/TestF']);
 		end
 	end
Index: /issm/trunk/test/NightlyRun/test112.m
===================================================================
--- /issm/trunk/test/NightlyRun/test112.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test112.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,SurfaceSlopeSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test112.py
===================================================================
--- /issm/trunk/test/NightlyRun/test112.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test112.py	(revision 16137)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,SurfaceSlopeSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test113.m
===================================================================
--- /issm/trunk/test/NightlyRun/test113.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test113.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,5,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,SurfaceSlopeSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test113.py
===================================================================
--- /issm/trunk/test/NightlyRun/test113.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test113.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(5,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,SurfaceSlopeSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test114.m
===================================================================
--- /issm/trunk/test/NightlyRun/test114.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test114.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,BedSlopeSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test114.py
===================================================================
--- /issm/trunk/test/NightlyRun/test114.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test114.py	(revision 16137)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,BedSlopeSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test115.m
===================================================================
--- /issm/trunk/test/NightlyRun/test115.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test115.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,5,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,BedSlopeSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test115.py
===================================================================
--- /issm/trunk/test/NightlyRun/test115.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test115.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(5,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,BedSlopeSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test116.m
===================================================================
--- /issm/trunk/test/NightlyRun/test116.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test116.m	(revision 16137)
@@ -5,5 +5,5 @@
 pos=find(md.mesh.vertexonboundary);
 md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,BalancethicknessSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test116.py
===================================================================
--- /issm/trunk/test/NightlyRun/test116.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test116.py	(revision 16137)
@@ -15,5 +15,5 @@
 pos=numpy.nonzero(md.mesh.vertexonboundary)
 md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,BalancethicknessSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test117.m
===================================================================
--- /issm/trunk/test/NightlyRun/test117.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test117.m	(revision 16137)
@@ -6,5 +6,5 @@
 pos=find(md.mesh.vertexonboundary);
 md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,BalancethicknessSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test117.py
===================================================================
--- /issm/trunk/test/NightlyRun/test117.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test117.py	(revision 16137)
@@ -16,5 +16,5 @@
 pos=numpy.nonzero(md.mesh.vertexonboundary)
 md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,BalancethicknessSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test118.m
===================================================================
--- /issm/trunk/test/NightlyRun/test118.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test118.m	(revision 16137)
@@ -5,5 +5,5 @@
 md.balancethickness.stabilization=3;
 md.initialization.vy=md.initialization.vy+400;
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,BalancethicknessSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test118.py
===================================================================
--- /issm/trunk/test/NightlyRun/test118.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test118.py	(revision 16137)
@@ -15,5 +15,5 @@
 md.balancethickness.stabilization=3
 md.initialization.vy=md.initialization.vy+400.
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,BalancethicknessSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test119.m
===================================================================
--- /issm/trunk/test/NightlyRun/test119.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test119.m	(revision 16137)
@@ -18,5 +18,5 @@
 %Fields and tolerances to track changes
 field_names     ={'x1','y1','x2','y2','nbelements','elapsed time'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,0.8};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1.5};
 field_values={...
 	x1, y1,...
Index: /issm/trunk/test/NightlyRun/test119.py
===================================================================
--- /issm/trunk/test/NightlyRun/test119.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test119.py	(revision 16137)
@@ -23,5 +23,5 @@
 #Fields and tolerances to track changes
 field_names     =['x1','y1','x2','y2','nbelements','elapsed time']
-field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,0.8]
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1.5]
 field_values=[\
 	x1, y1,\
Index: /issm/trunk/test/NightlyRun/test120.m
===================================================================
--- /issm/trunk/test/NightlyRun/test120.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test120.m	(revision 16137)
@@ -3,13 +3,14 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.timestepping.time_step=0;
 md.cluster=generic('name',oshostname(),'np',3);
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
 md=solve(md,EnthalpySolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Enthalpy','Waterfraction','Temperature'};
-field_tolerances={1e-13,1e-10,1e-13};
+field_tolerances={1e-13,1.45e-10,1e-13};
 field_values={...
 	(md.results.EnthalpySolution.Enthalpy),...
Index: /issm/trunk/test/NightlyRun/test120.py
===================================================================
--- /issm/trunk/test/NightlyRun/test120.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test120.py	(revision 16137)
@@ -13,13 +13,14 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.timestepping.time_step=0
 md.cluster=generic('name',oshostname(),'np',3)
 md.initialization.waterfraction=numpy.zeros(md.mesh.numberofvertices)
+md.initialization.watercolumn=numpy.zeros(md.mesh.numberofvertices)
 md=solve(md,EnthalpySolutionEnum())
 
 #Fields and tolerances to track changes
 field_names     =['Enthalpy','Waterfraction','Temperature']
-field_tolerances=[1e-13,1e-10,1e-13]
+field_tolerances=[1e-13,1.45e-10,1e-13]
 field_values=[\
 	md.results.EnthalpySolution.Enthalpy,\
Index: /issm/trunk/test/NightlyRun/test1201.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1201.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1201.m	(revision 16137)
@@ -5,10 +5,10 @@
 
 for stabilization=1:3;
-	%The goal is to test the prognostic model
+	%The goal is to test the masstransport model
 	md=bamg(model(),'domain','../Exp/SquareEISMINT.exp','hmax',3000.);
 	md=setmask(md,'all','');
 	md=parameterize(md,'../Par/SquareEISMINT.par');
 	md.surfaceforcings.mass_balance(:)=0.;
-	md=setflowequation(md,'macayeal','all');
+	md=setflowequation(md,'SSA','all');
 	md.cluster=generic('name',oshostname(),'np',8);
 
@@ -19,7 +19,7 @@
 	%Stabilization
 	if stabilization==2,
-		md.prognostic.stabilization=0;
+		md.masstransport.stabilization=0;
 	else
-		md.prognostic.stabilization=stabilization;
+		md.masstransport.stabilization=stabilization;
 	end
 
@@ -27,13 +27,13 @@
 	pos=find(md.mesh.y>199999.9);
 	times=0:1:500;
-	md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices+1,length(times));
-	md.prognostic.spcthickness(end,:)=times;
-	md.prognostic.spcthickness(pos,:)=repmat(500.+100.*sin(2.*pi*times/200.),length(pos),1);
+	md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices+1,length(times));
+	md.masstransport.spcthickness(end,:)=times;
+	md.masstransport.spcthickness(pos,:)=repmat(500.+100.*sin(2.*pi*times/200.),length(pos),1);
 	if stabilization==3,
-		pos=find(isnan(md.prognostic.spcthickness)); md.prognostic.spcthickness(pos)=500.; %No NaN for DG
+		pos=find(isnan(md.masstransport.spcthickness)); md.masstransport.spcthickness(pos)=500.; %No NaN for DG
 	end
 
 	%solve
-	md.transient.isdiagnostic=0;
+	md.transient.isstressbalance=0;
 	md.settings.output_frequency=500; %keep only last step
 	md.verbose=verbose();
Index: /issm/trunk/test/NightlyRun/test1201.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1201.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1201.py	(revision 16137)
@@ -18,10 +18,10 @@
 
 for stabilization in xrange(1,4):
-	#The goal is to test the prognostic model
+	#The goal is to test the masstransport model
 	md=bamg(model(),'domain','../Exp/SquareEISMINT.exp','hmax',3000.)
 	md=setmask(md,'all','')
 	md=parameterize(md,'../Par/SquareEISMINT.py')
 	md.surfaceforcings.mass_balance[:]=0.
-	md=setflowequation(md,'macayeal','all')
+	md=setflowequation(md,'SSA','all')
 	md.cluster=generic('name',oshostname(),'np',8)
 
@@ -32,20 +32,20 @@
 	#Stabilization
 	if stabilization==2:
-		md.prognostic.stabilization=0
+		md.masstransport.stabilization=0
 	else:
-		md.prognostic.stabilization=stabilization
+		md.masstransport.stabilization=stabilization
 
 	#spc thickness
 	pos=numpy.nonzero(md.mesh.y>199999.9)[0]
 	times=numpy.arange(0,501)
-	md.prognostic.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices+1,numpy.size(times)))
-	md.prognostic.spcthickness[-1,:]=times
-	md.prognostic.spcthickness[pos,:]=numpy.tile(500.+100.*numpy.sin(2.*numpy.pi*times/200.),(numpy.size(pos),1))
+	md.masstransport.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices+1,numpy.size(times)))
+	md.masstransport.spcthickness[-1,:]=times
+	md.masstransport.spcthickness[pos,:]=numpy.tile(500.+100.*numpy.sin(2.*numpy.pi*times/200.),(numpy.size(pos),1))
 	if stabilization==3:
-		pos=numpy.nonzero(numpy.isnan(md.prognostic.spcthickness))
-		md.prognostic.spcthickness[pos]=500.    #No NaN for DG
+		pos=numpy.nonzero(numpy.isnan(md.masstransport.spcthickness))
+		md.masstransport.spcthickness[pos]=500.    #No NaN for DG
 
 	#solve
-	md.transient.isdiagnostic=False
+	md.transient.isstressbalance=False
 	md.settings.output_frequency=500    #keep only last step
 	md.verbose=verbose()
Index: /issm/trunk/test/NightlyRun/test1202.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1202.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1202.m	(revision 16137)
@@ -1,3 +1,3 @@
-%Test on the diagnostic model and the prognostic in 2d.
+%Test on the stressbalance model and the masstransport in 2d.
 printingflag=false;
 
@@ -7,13 +7,13 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareEISMINT.par');
-md=setflowequation(md,'macayeal','all'); %MacAyeal's model and 2d
+md=setflowequation(md,'SSA','all'); %SSA's model and 2d
 
-%Compute solution for MacAyeal's model 
+%Compute solution for SSA's model 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %plot results
-vx=(md.results.DiagnosticSolution.Vx);
-vy=(md.results.DiagnosticSolution.Vy);
+vx=(md.results.StressbalanceSolution.Vx);
+vy=(md.results.StressbalanceSolution.Vy);
 
 plotmodel(md,'data',vx,'contourlevels',{0,20,40,60,60,100,120,140,160,180,-20,-40,-60,-80,-100,-120,-140,-160,-180}, ...
Index: /issm/trunk/test/NightlyRun/test1202.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1202.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1202.py	(revision 16137)
@@ -10,5 +10,5 @@
 
 """
-Test on the diagnostic model and the prognostic in 2d
+Test on the stressbalance model and the masstransport in 2d
 """
 
@@ -20,13 +20,13 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareEISMINT.py')
-md=setflowequation(md,'macayeal','all')    #MacAyeal's model and 2d
+md=setflowequation(md,'SSA','all')    #SSA's model and 2d
 
-#Compute solution for MacAyeal's model 
+#Compute solution for SSA's model 
 md.cluster=generic('name',oshostname(),'np',8)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #plot results
-vx=md.results.DiagnosticSolution.Vx
-vy=md.results.DiagnosticSolution.Vy
+vx=md.results.StressbalanceSolution.Vx
+vy=md.results.StressbalanceSolution.Vy
 
 #plotmodel(md,'data',vx,'contourlevels',{0,20,40,60,60,100,120,140,160,180,-20,-40,-60,-80,-100,-120,-140,-160,-180}, ...
Index: /issm/trunk/test/NightlyRun/test1203.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1203.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1203.m	(revision 16137)
@@ -1,3 +1,3 @@
-%Test on the diagnostic model and the prognostic in 2d
+%Test on the stressbalance model and the masstransport in 2d
 printingflag=false;
 
@@ -7,16 +7,16 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareEISMINT.par');
-md=setflowequation(md,'macayeal','all'); %MacAyeal's model and 2d
+md=setflowequation(md,'SSA','all'); %SSA's model and 2d
 
 %Impose a non zero velocity on the upper boundary condition (y=max(y))
 pos=find(md.mesh.y==max(md.mesh.y));
-md.diagnostic.spcvy(pos)=400.*(((md.mesh.x(pos)-100000.)/25000.).^2-ones(size(pos,1),1)).*heaviside((1.+eps)*ones(size(pos,1),1)-((md.mesh.x(pos)-100000.)/25000.).^2);
+md.stressbalance.spcvy(pos)=400.*(((md.mesh.x(pos)-100000.)/25000.).^2-ones(size(pos,1),1)).*heaviside((1.+eps)*ones(size(pos,1),1)-((md.mesh.x(pos)-100000.)/25000.).^2);
 
-%Compute solution for MacAyeal's model 
+%Compute solution for SSA's model 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
-vx=(md.results.DiagnosticSolution.Vx);
-vy=(md.results.DiagnosticSolution.Vy);
+vx=(md.results.StressbalanceSolution.Vx);
+vy=(md.results.StressbalanceSolution.Vy);
 
 %plot results
Index: /issm/trunk/test/NightlyRun/test1203.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1203.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1203.py	(revision 16137)
@@ -11,5 +11,5 @@
 
 """
-Test on the diagnostic model and the prognostic in 2d
+Test on the stressbalance model and the masstransport in 2d
 """
 
@@ -21,16 +21,16 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareEISMINT.py')
-md=setflowequation(md,'macayeal','all')    #MacAyeal's model and 2d
+md=setflowequation(md,'SSA','all')    #SSA's model and 2d
 
 #Impose a non zero velocity on the upper boundary condition (y=max(y))
 pos=numpy.nonzero(md.mesh.y==numpy.max(md.mesh.y))
-md.diagnostic.spcvy[pos]=400.*(((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2-numpy.ones((numpy.size(pos),1)))*heaviside((1.+sys.float_info.epsilon)*numpy.ones((numpy.size(pos),1))-((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2)
+md.stressbalance.spcvy[pos]=400.*(((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2-numpy.ones((numpy.size(pos),1)))*heaviside((1.+sys.float_info.epsilon)*numpy.ones((numpy.size(pos),1))-((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2)
 
-#Compute solution for MacAyeal's model 
+#Compute solution for SSA's model 
 md.cluster=generic('name',oshostname(),'np',8)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
-vx=md.results.DiagnosticSolution.Vx
-vy=md.results.DiagnosticSolution.Vy
+vx=md.results.StressbalanceSolution.Vx
+vy=md.results.StressbalanceSolution.Vy
 
 #plot results
Index: /issm/trunk/test/NightlyRun/test1204.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1204.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1204.m	(revision 16137)
@@ -1,3 +1,3 @@
-%Test on the diagnostic model and the prognostic in 2d
+%Test on the stressbalance model and the masstransport in 2d
 printingflag=false;
 
@@ -7,21 +7,21 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareEISMINT.par');
-md=setflowequation(md,'macayeal','all'); %MacAyeal's model and 2d
+md=setflowequation(md,'SSA','all'); %SSA's model and 2d
 
 %Impose a non zero velocity on the upper boundary condition (y=max(y))
 pos=find(md.mesh.y==max(md.mesh.y));
-md.diagnostic.spcvy(pos)=400.*(((md.mesh.x(pos)-100000.)/25000.).^2-ones(size(pos,1),1)).*heaviside((1.+eps)*ones(size(pos,1),1)-((md.mesh.x(pos)-100000.)/25000.).^2);
+md.stressbalance.spcvy(pos)=400.*(((md.mesh.x(pos)-100000.)/25000.).^2-ones(size(pos,1),1)).*heaviside((1.+eps)*ones(size(pos,1),1)-((md.mesh.x(pos)-100000.)/25000.).^2);
 
-%Compute solution for MacAyeal's model 
+%Compute solution for SSA's model 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %plot results
-md.initialization.vx=(md.results.DiagnosticSolution.Vx);
-md.initialization.vy=(md.results.DiagnosticSolution.Vy);
+md.initialization.vx=(md.results.StressbalanceSolution.Vx);
+md.initialization.vy=(md.results.StressbalanceSolution.Vy);
 
 md.timestepping.time_step=1.;
 md.timestepping.final_time=5000.;
-md.prognostic.stabilization=1;
+md.masstransport.stabilization=1;
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test1204.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1204.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1204.py	(revision 16137)
@@ -11,5 +11,5 @@
 
 """
-Test on the diagnostic model and the prognostic in 2d
+Test on the stressbalance model and the masstransport in 2d
 """
 
@@ -21,21 +21,21 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareEISMINT.py')
-md=setflowequation(md,'macayeal','all')    #MacAyeal's model and 2d
+md=setflowequation(md,'SSA','all')    #SSA's model and 2d
 
 #Impose a non zero velocity on the upper boundary condition (y=max(y))
 pos=numpy.nonzero(md.mesh.y==max(md.mesh.y))
-md.diagnostic.spcvy[pos]=400.*(((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2-numpy.ones((numpy.size(pos),1)))*heaviside((1.+sys.float_info.epsilon)*numpy.ones((numpy.size(pos),1))-((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2)
+md.stressbalance.spcvy[pos]=400.*(((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2-numpy.ones((numpy.size(pos),1)))*heaviside((1.+sys.float_info.epsilon)*numpy.ones((numpy.size(pos),1))-((md.mesh.x[pos].reshape(-1,1)-100000.)/25000.)**2)
 
-#Compute solution for MacAyeal's model 
+#Compute solution for SSA's model 
 md.cluster=generic('name',oshostname(),'np',8)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #plot results
-md.initialization.vx=md.results.DiagnosticSolution.Vx
-md.initialization.vy=md.results.DiagnosticSolution.Vy
+md.initialization.vx=md.results.StressbalanceSolution.Vx
+md.initialization.vy=md.results.StressbalanceSolution.Vy
 
 md.timestepping.time_step=1.
 md.timestepping.final_time=5000.
-md.prognostic.stabilization=1
+md.masstransport.stabilization=1
 md=solve(md,TransientSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test1205.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1205.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1205.m	(revision 16137)
@@ -1,3 +1,3 @@
-%The aim of this program is to compare a model with an analytical solution given in MacAyeal EISMINT : Lessons in Ice-Sheet Modeling.
+%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;
 
@@ -19,19 +19,19 @@
 %We extrude the model to have a 3d model
 md=extrude(md,numlayers,1.);
-md=setflowequation(md,'hutter','all');
+md=setflowequation(md,'SIA','all');
 
 %Spc the nodes on the bed
 pos=find(md.mesh.vertexonbed);
-md.diagnostic.spcvx(pos)=0.;
-md.diagnostic.spcvy(pos)=0.;
-md.diagnostic.spcvz(pos)=0.;
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
 
 %Now we can solve the problem 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Calculate the depth averaged velocity field (2d):
-vx=(md.results.DiagnosticSolution.Vx);
-vy=(md.results.DiagnosticSolution.Vy);
+vx=(md.results.StressbalanceSolution.Vx);
+vy=(md.results.StressbalanceSolution.Vy);
 vel=zeros(md.mesh.numberofvertices2d,1);
 
@@ -83,6 +83,6 @@
 if printingflag,
 	set(gcf,'Color','w')
-	printmodel('hutterstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
-	system(['mv hutterstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+	printmodel('SIAstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+	system(['mv SIAstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
 end
 
Index: /issm/trunk/test/NightlyRun/test1205.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1205.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1205.py	(revision 16137)
@@ -10,5 +10,5 @@
 
 """
-The aim of this program is to compare a model with an analytical solution given in MacAyeal EISMINT : Lessons in Ice-Sheet Modeling.
+The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
 """
 
@@ -32,19 +32,19 @@
 #We extrude the model to have a 3d model
 md.extrude(numlayers,1.);
-md=setflowequation(md,'hutter','all')
+md=setflowequation(md,'SIA','all')
 
 #Spc the nodes on the bed
 pos=numpy.nonzero(md.mesh.vertexonbed)
-md.diagnostic.spcvx[pos]=0.
-md.diagnostic.spcvy[pos]=0.
-md.diagnostic.spcvz[pos]=0.
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
 
 #Now we can solve the problem 
 md.cluster=generic('name',oshostname(),'np',8)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Calculate the depth averaged velocity field (2d):
-vx=md.results.DiagnosticSolution.Vx
-vy=md.results.DiagnosticSolution.Vy
+vx=md.results.StressbalanceSolution.Vx
+vy=md.results.StressbalanceSolution.Vy
 vel=numpy.zeros((md.mesh.numberofvertices2d,1))
 
@@ -95,6 +95,6 @@
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('hutterstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
-#	system(['mv hutterstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+#	printmodel('SIAstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+#	system(['mv SIAstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
 
 #Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test1206.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1206.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1206.m	(revision 16137)
@@ -1,3 +1,3 @@
-%The aim of this program is to compare a model with an analytical solution given in MacAyeal EISMINT : Lessons in Ice-Sheet Modeling.
+%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;
 
@@ -19,19 +19,19 @@
 %We extrude the model to have a 3d model
 md=extrude(md,numlayers,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 
 %Spc the nodes on the bed
 pos=find(md.mesh.vertexonbed);
-md.diagnostic.spcvx(pos)=0.;
-md.diagnostic.spcvy(pos)=0.;
-md.diagnostic.spcvz(pos)=0.;
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
 
 %Now we can solve the problem 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Calculate the depth averaged velocity field (2d):
-vx=(md.results.DiagnosticSolution.Vx);
-vy=(md.results.DiagnosticSolution.Vy);
+vx=(md.results.StressbalanceSolution.Vx);
+vy=(md.results.StressbalanceSolution.Vy);
 vel=zeros(md.mesh.numberofvertices2d,1);
 
@@ -82,6 +82,6 @@
 if printingflag,
 	set(gcf,'Color','w')
-	printmodel('pattynstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
-	system(['mv pattynstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+	printmodel('HOstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+	system(['mv HOstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
 end
 
Index: /issm/trunk/test/NightlyRun/test1206.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1206.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1206.py	(revision 16137)
@@ -10,5 +10,5 @@
 
 """
-The aim of this program is to compare a model with an analytical solution given in MacAyeal EISMINT : Lessons in Ice-Sheet Modeling.
+The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
 """
 
@@ -32,19 +32,19 @@
 #We extrude the model to have a 3d model
 md.extrude(numlayers,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 
 #Spc the nodes on the bed
 pos=numpy.nonzero(md.mesh.vertexonbed)
-md.diagnostic.spcvx[pos]=0.
-md.diagnostic.spcvy[pos]=0.
-md.diagnostic.spcvz[pos]=0.
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
 
 #Now we can solve the problem 
 md.cluster=generic('name',oshostname(),'np',8)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Calculate the depth averaged velocity field (2d):
-vx=md.results.DiagnosticSolution.Vx
-vy=md.results.DiagnosticSolution.Vy
+vx=md.results.StressbalanceSolution.Vx
+vy=md.results.StressbalanceSolution.Vy
 vel=numpy.zeros((md.mesh.numberofvertices2d,1))
 
@@ -94,6 +94,6 @@
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('pattynstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
-#	system(['mv pattynstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+#	printmodel('HOstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+#	system(['mv HOstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
 
 #Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test1207.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1207.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1207.m	(revision 16137)
@@ -1,3 +1,3 @@
-%The aim of this program is to compare a model with an analytical solution given in MacAyeal EISMINT : Lessons in Ice-Sheet Modeling.
+%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;
 
@@ -19,19 +19,19 @@
 %We extrude the model to have a 3d model
 md=extrude(md,numlayers,1.);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'FS','all');
 
 %Spc the nodes on the bed
 pos=find(md.mesh.vertexonbed);
-md.diagnostic.spcvx(pos)=0.;
-md.diagnostic.spcvy(pos)=0.;
-md.diagnostic.spcvz(pos)=0.;
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
 
 %Now we can solve the problem 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Calculate the depth averaged velocity field (2d):
-vx=(md.results.DiagnosticSolution.Vx);
-vy=(md.results.DiagnosticSolution.Vy);
+vx=(md.results.StressbalanceSolution.Vx);
+vy=(md.results.StressbalanceSolution.Vy);
 vel=zeros(md.mesh.numberofvertices2d,1);
 
@@ -82,6 +82,6 @@
 if printingflag,
 	set(gcf,'Color','w')
-	printmodel('stokesstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
-	system(['mv stokesstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+	printmodel('FSstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+	system(['mv FSstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
 end
 
Index: /issm/trunk/test/NightlyRun/test1207.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1207.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1207.py	(revision 16137)
@@ -10,5 +10,5 @@
 
 """
-The aim of this program is to compare a model with an analytical solution given in MacAyeal EISMINT : Lessons in Ice-Sheet Modeling.
+The aim of this program is to compare a model with an analytical solution given in SSA EISMINT : Lessons in Ice-Sheet Modeling.
 """
 
@@ -32,19 +32,19 @@
 #We extrude the model to have a 3d model
 md.extrude(numlayers,1.)
-md=setflowequation(md,'stokes','all')
+md=setflowequation(md,'FS','all')
 
 #Spc the nodes on the bed
 pos=numpy.nonzero(md.mesh.vertexonbed)
-md.diagnostic.spcvx[pos]=0.
-md.diagnostic.spcvy[pos]=0.
-md.diagnostic.spcvz[pos]=0.
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
 
 #Now we can solve the problem 
 md.cluster=generic('name',oshostname(),'np',8)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Calculate the depth averaged velocity field (2d):
-vx=md.results.DiagnosticSolution.Vx
-vy=md.results.DiagnosticSolution.Vy
+vx=md.results.StressbalanceSolution.Vx
+vy=md.results.StressbalanceSolution.Vy
 vel=numpy.zeros((md.mesh.numberofvertices2d,1))
 
@@ -94,6 +94,6 @@
 	pass
 #	set(gcf,'Color','w')
-#	printmodel('stokesstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
-#	system(['mv stokesstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
+#	printmodel('FSstatic','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off');
+#	system(['mv FSstatic.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT/IceSheet']);
 
 #Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test1208.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1208.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1208.m	(revision 16137)
@@ -10,11 +10,11 @@
 %We extrude the model to have a 3d model
 md=extrude(md,numlayers,1.);
-md=setflowequation(md,'hutter','all');
+md=setflowequation(md,'SIA','all');
 
 %Spc the nodes on the bed
 pos=find(md.mesh.vertexonbed);
-md.diagnostic.spcvx(pos)=0.;
-md.diagnostic.spcvy(pos)=0.;
-md.diagnostic.spcvz(pos)=0.;
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
 
 %Adapt the time steps to the resolution
@@ -22,5 +22,5 @@
 md.settings.output_frequency=500;
 md.timestepping.final_time=30000.;
-md.prognostic.stabilization=1;
+md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
 
Index: /issm/trunk/test/NightlyRun/test1208.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1208.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1208.py	(revision 16137)
@@ -23,11 +23,11 @@
 #We extrude the model to have a 3d model
 md.extrude(numlayers,1.)
-md=setflowequation(md,'hutter','all')
+md=setflowequation(md,'SIA','all')
 
 #Spc the nodes on the bed
 pos=numpy.nonzero(md.mesh.vertexonbed)
-md.diagnostic.spcvx[pos]=0.
-md.diagnostic.spcvy[pos]=0.
-md.diagnostic.spcvz[pos]=0.
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
 
 #Adapt the time steps to the resolution
@@ -35,5 +35,5 @@
 md.settings.output_frequency=500
 md.timestepping.final_time=30000.
-md.prognostic.stabilization=1
+md.masstransport.stabilization=1
 md.thermal.stabilization=1
 
Index: /issm/trunk/test/NightlyRun/test121.m
===================================================================
--- /issm/trunk/test/NightlyRun/test121.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test121.m	(revision 16137)
@@ -3,9 +3,10 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
@@ -17,5 +18,5 @@
 	'Enthalpy2','Waterfraction2','Temperature2',...
 	'Enthalpy3','Waterfraction3','Temperature3'};
-field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-10,1e-13};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-9,1e-13};
 field_values={...
 	(md.results.TransientSolution(1).Enthalpy),...
Index: /issm/trunk/test/NightlyRun/test121.py
===================================================================
--- /issm/trunk/test/NightlyRun/test121.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test121.py	(revision 16137)
@@ -12,9 +12,10 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3);
 md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
-md.transient.isdiagnostic=False
-md.transient.isprognostic=False
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
 md.transient.isthermal=True
 md.transient.isgroundingline=False
@@ -26,5 +27,5 @@
 	'Enthalpy2','Waterfraction2','Temperature2',\
 	'Enthalpy3','Waterfraction3','Temperature3']
-field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-10,1e-13]
+field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-9,1e-13]
 field_values=[\
 	md.results.TransientSolution[0].Enthalpy,\
Index: /issm/trunk/test/NightlyRun/test122.m
===================================================================
--- /issm/trunk/test/NightlyRun/test122.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test122.m	(revision 16137)
@@ -3,6 +3,7 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
 md.thermal.isenthalpy=1;
 md.thermal.stabilization=2;
Index: /issm/trunk/test/NightlyRun/test122.py
===================================================================
--- /issm/trunk/test/NightlyRun/test122.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test122.py	(revision 16137)
@@ -12,6 +12,7 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
 md.thermal.isenthalpy=1
 md.thermal.stabilization=2
Index: /issm/trunk/test/NightlyRun/test1301.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1301.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1301.m	(revision 16137)
@@ -10,5 +10,5 @@
 md=parameterize(md,'../Par/SquareThermal.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 
 %Some conditions specific to melting test
Index: /issm/trunk/test/NightlyRun/test1301.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1301.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1301.py	(revision 16137)
@@ -24,5 +24,5 @@
 md=parameterize(md,'../Par/SquareThermal.py')
 md.extrude(3,2.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 
 #Some conditions specific to melting test
Index: /issm/trunk/test/NightlyRun/test1302.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1302.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1302.m	(revision 16137)
@@ -9,5 +9,5 @@
 md=parameterize(md,'../Par/SquareThermal.par');
 md=extrude(md,30,1.);   %NB: the more one extrudes, the better (10-> relative~0.35%, 20->0.1%, 30->0.05%)
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 
 %Thermal boundary conditions
Index: /issm/trunk/test/NightlyRun/test1302.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1302.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1302.py	(revision 16137)
@@ -23,5 +23,5 @@
 md=parameterize(md,'../Par/SquareThermal.py')
 md.extrude(30,1.)    #NB: the more one extrudes, the better (10-> relative~0.35%, 20->0.1%, 30->0.05%)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 
 #Thermal boundary conditions
Index: /issm/trunk/test/NightlyRun/test1303.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1303.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1303.m	(revision 16137)
@@ -10,5 +10,5 @@
 md=parameterize(md,'../Par/SquareThermal.par');
 md=extrude(md,11,2.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 
 pos1=find(md.mesh.elementonbed);     md.thermal.spctemperature(md.mesh.elements(pos1,1:3))=10.;
Index: /issm/trunk/test/NightlyRun/test1303.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1303.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1303.py	(revision 16137)
@@ -24,5 +24,5 @@
 md=parameterize(md,'../Par/SquareThermal.py')
 md.extrude(11,2.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 
 pos1=numpy.nonzero(md.mesh.elementonbed)[0]
Index: /issm/trunk/test/NightlyRun/test1304.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1304.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1304.m	(revision 16137)
@@ -10,5 +10,5 @@
 md=parameterize(md,'../Par/SquareThermal.par');
 md=extrude(md,11,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 
 pos2=find(md.mesh.elementonsurface); md.thermal.spctemperature(md.mesh.elements(pos2,4:6))=0.;
Index: /issm/trunk/test/NightlyRun/test1304.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1304.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1304.py	(revision 16137)
@@ -24,5 +24,5 @@
 md=parameterize(md,'../Par/SquareThermal.py')
 md.extrude(11,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 
 pos2=numpy.nonzero(md.mesh.elementonsurface)[0]
Index: /issm/trunk/test/NightlyRun/test1501.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1501.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1501.m	(revision 16137)
@@ -4,5 +4,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.transient.isthermal=0;
@@ -17,9 +17,9 @@
 md.basalforcings.melting_rate= smb;
 
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 for i=1:10
-	 md=solve(md,PrognosticSolutionEnum());
-	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.PrognosticSolution.Thickness)-md.geometry.thickness);
+	 md=solve(md,MasstransportSolutionEnum());
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.MasstransportSolution.Thickness)-md.geometry.thickness);
 end
 
Index: /issm/trunk/test/NightlyRun/test1501.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1501.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1501.py	(revision 16137)
@@ -15,5 +15,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.transient.isthermal=False
@@ -28,9 +28,9 @@
 md.basalforcings.melting_rate= smb
 
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 for i in xrange(1,11):
-	 md=solve(md,PrognosticSolutionEnum())
-	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.PrognosticSolution.Thickness)-md.geometry.thickness)
+	 md=solve(md,MasstransportSolutionEnum())
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.MasstransportSolution.Thickness)-md.geometry.thickness)
 
 #Set up transient
Index: /issm/trunk/test/NightlyRun/test1502.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1502.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1502.m	(revision 16137)
@@ -4,5 +4,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md=extrude(md,3,1.);
 md.cluster=generic('name',oshostname(),'np',2);
@@ -18,9 +18,9 @@
 md.basalforcings.melting_rate= smb;
 
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 for i=1:10
-	 md=solve(md,PrognosticSolutionEnum());
-	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.PrognosticSolution.Thickness)-md.geometry.thickness);
+	 md=solve(md,MasstransportSolutionEnum());
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.MasstransportSolution.Thickness)-md.geometry.thickness);
 end
 
Index: /issm/trunk/test/NightlyRun/test1502.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1502.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1502.py	(revision 16137)
@@ -15,5 +15,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.extrude(3,1.)
 md.cluster=generic('name',oshostname(),'np',2)
@@ -29,9 +29,9 @@
 md.basalforcings.melting_rate= smb
 
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 for i in xrange(1,11):
-	 md=solve(md,PrognosticSolutionEnum())
-	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.PrognosticSolution.Thickness)-md.geometry.thickness)
+	 md=solve(md,MasstransportSolutionEnum())
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.MasstransportSolution.Thickness)-md.geometry.thickness)
 
 #Set up transient
Index: /issm/trunk/test/NightlyRun/test1601.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1601.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1601.m	(revision 16137)
@@ -2,6 +2,6 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.diagnostic.spcvx(find(md.mesh.y>0.))=NaN;
+md=setflowequation(md,'SSA','all');
+md.stressbalance.spcvx(find(md.mesh.y>0.))=NaN;
 md.initialization.vx(:)=0.;
 md.initialization.vy(:)=0.;
@@ -9,6 +9,6 @@
 
 md.cluster=generic('name',oshostname(),'np',2);
-md=solve(md,DiagnosticSolutionEnum());
-vel0=md.results.DiagnosticSolution.Vel;
+md=solve(md,StressbalanceSolutionEnum());
+vel0=md.results.StressbalanceSolution.Vel;
 
 theta=30.*pi/180.;
@@ -18,8 +18,8 @@
 md.mesh.y=sin(theta)*x+cos(theta)*y;
 
-md.diagnostic.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1);
-md.diagnostic.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1);
-md=solve(md,DiagnosticSolutionEnum());
-vel1=md.results.DiagnosticSolution.Vel;
+md.stressbalance.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1);
+md.stressbalance.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1);
+md=solve(md,StressbalanceSolutionEnum());
+vel1=md.results.StressbalanceSolution.Vel;
 
 plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
@@ -28,9 +28,9 @@
 %Now, put CS back to normal except on the side where the spc are applied
 pos=find(x==0. | x==1000000.);
-md.diagnostic.referential(:)=NaN;
-md.diagnostic.referential(pos,1:3)=repmat([cos(theta),sin(theta),0],size(pos,1),1);
-md.diagnostic.referential(pos,4:6)=repmat([0,0,1],size(pos,1),1);
-md=solve(md,DiagnosticSolutionEnum());
-vel2=md.results.DiagnosticSolution.Vel;
+md.stressbalance.referential(:)=NaN;
+md.stressbalance.referential(pos,1:3)=repmat([cos(theta),sin(theta),0],size(pos,1),1);
+md.stressbalance.referential(pos,4:6)=repmat([0,0,1],size(pos,1),1);
+md=solve(md,StressbalanceSolutionEnum());
+vel2=md.results.StressbalanceSolution.Vel;
 
 plotmodel(md,'data',vel0,'data',vel2,'data',vel2-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
Index: /issm/trunk/test/NightlyRun/test1601.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1601.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1601.py	(revision 16137)
@@ -13,6 +13,6 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
-md.diagnostic.spcvx[numpy.nonzero(md.mesh.y>0.)]=float('NaN')
+md=setflowequation(md,'SSA','all')
+md.stressbalance.spcvx[numpy.nonzero(md.mesh.y>0.)]=float('NaN')
 md.initialization.vx[:]=0.
 md.initialization.vy[:]=0.
@@ -20,6 +20,6 @@
 
 md.cluster=generic('name',oshostname(),'np',2)
-md=solve(md,DiagnosticSolutionEnum())
-vel0=md.results.DiagnosticSolution.Vel
+md=solve(md,StressbalanceSolutionEnum())
+vel0=md.results.StressbalanceSolution.Vel
 
 theta=30.*numpy.pi/180.
@@ -29,8 +29,8 @@
 md.mesh.y=numpy.sin(theta)*x+numpy.cos(theta)*y
 
-md.diagnostic.referential[:,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(md.mesh.numberofvertices,1))
-md.diagnostic.referential[:,3: ]=numpy.tile([0,0,1],(md.mesh.numberofvertices,1))
-md=solve(md,DiagnosticSolutionEnum())
-vel1=md.results.DiagnosticSolution.Vel
+md.stressbalance.referential[:,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(md.mesh.numberofvertices,1))
+md.stressbalance.referential[:,3: ]=numpy.tile([0,0,1],(md.mesh.numberofvertices,1))
+md=solve(md,StressbalanceSolutionEnum())
+vel1=md.results.StressbalanceSolution.Vel
 
 #plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
@@ -39,9 +39,9 @@
 #Now, put CS back to normal except on the side where the spc are applied
 pos=numpy.nonzero(numpy.logical_or(x==0.,x==1000000.))[0]
-md.diagnostic.referential[:]=float('NaN')
-md.diagnostic.referential[pos,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(len(pos),1))
-md.diagnostic.referential[pos,3: ]=numpy.tile([0,0,1],(len(pos),1))
-md=solve(md,DiagnosticSolutionEnum())
-vel2=md.results.DiagnosticSolution.Vel
+md.stressbalance.referential[:]=float('NaN')
+md.stressbalance.referential[pos,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(len(pos),1))
+md.stressbalance.referential[pos,3: ]=numpy.tile([0,0,1],(len(pos),1))
+md=solve(md,StressbalanceSolutionEnum())
+vel2=md.results.StressbalanceSolution.Vel
 
 #plotmodel(md,'data',vel0,'data',vel2,'data',vel2-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
Index: /issm/trunk/test/NightlyRun/test1602.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1602.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1602.m	(revision 16137)
@@ -3,6 +3,6 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,5,1.);
-md=setflowequation(md,'pattyn','all');
-md.diagnostic.spcvx(find(md.mesh.y>0.))=NaN;
+md=setflowequation(md,'HO','all');
+md.stressbalance.spcvx(find(md.mesh.y>0.))=NaN;
 md.initialization.vx(:)=0.;
 md.initialization.vy(:)=0.;
@@ -10,6 +10,6 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
-vel0=md.results.DiagnosticSolution.Vel;
+md=solve(md,StressbalanceSolutionEnum());
+vel0=md.results.StressbalanceSolution.Vel;
 
 theta=30.*pi/180.;
@@ -19,8 +19,8 @@
 md.mesh.y=sin(theta)*x+cos(theta)*y;
 
-md.diagnostic.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1);
-md.diagnostic.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1);
-md=solve(md,DiagnosticSolutionEnum());
-vel1=md.results.DiagnosticSolution.Vel;
+md.stressbalance.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1);
+md.stressbalance.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1);
+md=solve(md,StressbalanceSolutionEnum());
+vel1=md.results.StressbalanceSolution.Vel;
 
 plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference','view#all',2)
Index: /issm/trunk/test/NightlyRun/test1602.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1602.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test1602.py	(revision 16137)
@@ -14,6 +14,6 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(5,1.)
-md=setflowequation(md,'pattyn','all')
-md.diagnostic.spcvx[numpy.nonzero(md.mesh.y>0.)]=float('NaN')
+md=setflowequation(md,'HO','all')
+md.stressbalance.spcvx[numpy.nonzero(md.mesh.y>0.)]=float('NaN')
 md.initialization.vx[:]=0.
 md.initialization.vy[:]=0.
@@ -21,6 +21,6 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
-vel0=md.results.DiagnosticSolution.Vel
+md=solve(md,StressbalanceSolutionEnum())
+vel0=md.results.StressbalanceSolution.Vel
 
 theta=30.*numpy.pi/180.
@@ -30,8 +30,8 @@
 md.mesh.y=numpy.sin(theta)*x+numpy.cos(theta)*y
 
-md.diagnostic.referential[:,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(md.mesh.numberofvertices,1))
-md.diagnostic.referential[:,3: ]=numpy.tile([0,0,1],(md.mesh.numberofvertices,1))
-md=solve(md,DiagnosticSolutionEnum())
-vel1=md.results.DiagnosticSolution.Vel
+md.stressbalance.referential[:,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(md.mesh.numberofvertices,1))
+md.stressbalance.referential[:,3: ]=numpy.tile([0,0,1],(md.mesh.numberofvertices,1))
+md=solve(md,StressbalanceSolutionEnum())
+vel1=md.results.StressbalanceSolution.Vel
 
 #plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference','view#all',2)
Index: /issm/trunk/test/NightlyRun/test201.m
===================================================================
--- /issm/trunk/test/NightlyRun/test201.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test201.m	(revision 16137)
@@ -2,7 +2,7 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -10,7 +10,7 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test201.py
===================================================================
--- /issm/trunk/test/NightlyRun/test201.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test201.py	(revision 16137)
@@ -12,7 +12,7 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -20,7 +20,7 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test202.m
===================================================================
--- /issm/trunk/test/NightlyRun/test202.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test202.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test202.py
===================================================================
--- /issm/trunk/test/NightlyRun/test202.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test202.py	(revision 16137)
@@ -13,7 +13,7 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,2.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 
@@ -23,8 +23,8 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test203.m
===================================================================
--- /issm/trunk/test/NightlyRun/test203.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test203.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test203.py
===================================================================
--- /issm/trunk/test/NightlyRun/test203.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test203.py	(revision 16137)
@@ -13,7 +13,7 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,2.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 
@@ -23,8 +23,8 @@
 field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test204.m
===================================================================
--- /issm/trunk/test/NightlyRun/test204.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test204.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'FS','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test204.py
===================================================================
--- /issm/trunk/test/NightlyRun/test204.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test204.py	(revision 16137)
@@ -13,7 +13,7 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,2.)
-md=setflowequation(md,'stokes','all')
+md=setflowequation(md,'FS','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 
@@ -23,8 +23,8 @@
 field_tolerances=[1e-08,1e-08,1e-07,1e-08,1e-08]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test205.m
===================================================================
--- /issm/trunk/test/NightlyRun/test205.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test205.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal','coupling','penalties');
+md=setflowequation(md,'HO','../Exp/SquareHalfRight.exp','fill','SSA','coupling','penalties');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-05,1e-05,1e-05,1e-05,1e-05};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test205.py
===================================================================
--- /issm/trunk/test/NightlyRun/test205.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test205.py	(revision 16137)
@@ -13,7 +13,7 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,2.)
-md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal','coupling','penalties')
+md=setflowequation(md,'HO','../Exp/SquareHalfRight.exp','fill','SSA','coupling','penalties')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 
@@ -23,8 +23,8 @@
 field_tolerances=[1e-05,1e-05,1e-05,1e-05,1e-05]
 field_values=[\
-md.results.DiagnosticSolution.Vx,\
-md.results.DiagnosticSolution.Vy,\
-md.results.DiagnosticSolution.Vz,\
-md.results.DiagnosticSolution.Vel,\
-md.results.DiagnosticSolution.Pressure,\
+md.results.StressbalanceSolution.Vx,\
+md.results.StressbalanceSolution.Vy,\
+md.results.StressbalanceSolution.Vz,\
+md.results.StressbalanceSolution.Vel,\
+md.results.StressbalanceSolution.Pressure,\
 ]
Index: /issm/trunk/test/NightlyRun/test206.m
===================================================================
--- /issm/trunk/test/NightlyRun/test206.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test206.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.timestepping.time_step=0;
 md.cluster=generic('name',oshostname(),'np',3);
@@ -10,5 +10,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13};
+field_tolerances={1e-13,1.35e-6};
 field_values={...
 	(md.results.ThermalSolution.Temperature),...
Index: /issm/trunk/test/NightlyRun/test206.py
===================================================================
--- /issm/trunk/test/NightlyRun/test206.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test206.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.timestepping.time_step=0
 md.cluster=generic('name',oshostname(),'np',3)
@@ -22,5 +22,5 @@
 
 field_names     =['Temperature','BasalforcingsMeltingRate']
-field_tolerances=[1e-13,1e-13]
+field_tolerances=[1e-13,1.35e-6]
 field_values=[\
 	md.results.ThermalSolution.Temperature,\
Index: /issm/trunk/test/NightlyRun/test207.m
===================================================================
--- /issm/trunk/test/NightlyRun/test207.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test207.m	(revision 16137)
@@ -3,8 +3,8 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
Index: /issm/trunk/test/NightlyRun/test207.py
===================================================================
--- /issm/trunk/test/NightlyRun/test207.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test207.py	(revision 16137)
@@ -13,8 +13,8 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.transient.isdiagnostic=False
-md.transient.isprognostic=False
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
 md.transient.isthermal=True
 md.transient.isgroundingline=False
Index: /issm/trunk/test/NightlyRun/test208.m
===================================================================
--- /issm/trunk/test/NightlyRun/test208.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test208.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test208.py
===================================================================
--- /issm/trunk/test/NightlyRun/test208.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test208.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test209.m
===================================================================
--- /issm/trunk/test/NightlyRun/test209.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test209.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
@@ -13,6 +13,6 @@
 field_tolerances={...
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,...
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,...
-	1e-13,1e-13,1e-08,1e-13,1e-13,1e-10,1e-10,1e-10,1e-13,1e-8};
+	1e-13,1e-13,2e-9,1e-13,3.8e-11,3.85e-11,3.85e-11,3.85e-11,1e-13,1.55e-8,...
+	2.65e-11,2.55e-12,1e-08,2.4e-12,3.9e-11,1e-10,1e-10,1e-10,7.4e-12,1.85e-8};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test209.py
===================================================================
--- /issm/trunk/test/NightlyRun/test209.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test209.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
@@ -25,6 +25,7 @@
 field_tolerances=[\
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,\
-	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,\
-	1e-13,1e-13,1e-08,1e-13,1e-13,1e-10,1e-10,1e-10,1e-13,1e-8]
+	1e-13,1e-13,2e-9,1e-13,3.8e-11,3.85e-11,3.85e-11,3.85e-11,1e-13,1.55e-8,\
+	2.65e-11,2.55e-12,1e-08,2.4e-12,3.9e-11,1e-10,1e-10,1e-10,7.4e-12,1.85e-8]
+
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test210.m
===================================================================
--- /issm/trunk/test/NightlyRun/test210.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test210.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test210.py
===================================================================
--- /issm/trunk/test/NightlyRun/test210.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test210.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test211.m
===================================================================
--- /issm/trunk/test/NightlyRun/test211.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test211.m	(revision 16137)
@@ -3,6 +3,6 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'stokes','all');
-md.diagnostic.reltol=NaN;
+md=setflowequation(md,'FS','all');
+md.stressbalance.reltol=NaN;
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test211.py
===================================================================
--- /issm/trunk/test/NightlyRun/test211.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test211.py	(revision 16137)
@@ -13,6 +13,6 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'stokes','all')
-md.diagnostic.reltol=NaN
+md=setflowequation(md,'FS','all')
+md.stressbalance.reltol=NaN
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
@@ -28,5 +28,5 @@
 	1e-08,1e-08,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,\
 	1e-08,1e-08,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06,\
-	1e-07,1e-07,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06]
+	1e-07,1e-07,1e-06,2e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test212.m
===================================================================
--- /issm/trunk/test/NightlyRun/test212.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test212.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 
 %control parameters
@@ -18,5 +18,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -24,10 +24,10 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	(md.results.DiagnosticSolution.J),...
-	(md.results.DiagnosticSolution.MaterialsRheologyBbar),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
+	(md.results.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.MaterialsRheologyBbar),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
 };
Index: /issm/trunk/test/NightlyRun/test212.py
===================================================================
--- /issm/trunk/test/NightlyRun/test212.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test212.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 
 
@@ -32,5 +32,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 
@@ -40,10 +40,10 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-md.results.DiagnosticSolution.Gradient1,\
-md.results.DiagnosticSolution.J,\
-md.results.DiagnosticSolution.MaterialsRheologyBbar,\
-md.results.DiagnosticSolution.Pressure,\
-md.results.DiagnosticSolution.Vel,\
-md.results.DiagnosticSolution.Vx,\
-md.results.DiagnosticSolution.Vy,\
+md.results.StressbalanceSolution.Gradient1,\
+md.results.StressbalanceSolution.J,\
+md.results.StressbalanceSolution.MaterialsRheologyBbar,\
+md.results.StressbalanceSolution.Pressure,\
+md.results.StressbalanceSolution.Vel,\
+md.results.StressbalanceSolution.Vx,\
+md.results.StressbalanceSolution.Vy,\
 ]
Index: /issm/trunk/test/NightlyRun/test213.m
===================================================================
--- /issm/trunk/test/NightlyRun/test213.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test213.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 
 %control parameters
@@ -19,5 +19,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -25,10 +25,10 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.MaterialsRheologyB),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
+	(md.results.StressbalanceSolution.Gradient1),...
+	md.results.StressbalanceSolution.J,...
+	(md.results.StressbalanceSolution.MaterialsRheologyB),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
 };
Index: /issm/trunk/test/NightlyRun/test213.py
===================================================================
--- /issm/trunk/test/NightlyRun/test213.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test213.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 
 
@@ -33,5 +33,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 
@@ -42,10 +42,10 @@
 #field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Gradient1,\
-	md.results.DiagnosticSolution.J,\
-	md.results.DiagnosticSolution.MaterialsRheologyB,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
+	md.results.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.MaterialsRheologyB,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
 ]
Index: /issm/trunk/test/NightlyRun/test214.m
===================================================================
--- /issm/trunk/test/NightlyRun/test214.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test214.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 
 %control parameters
@@ -19,5 +19,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -25,10 +25,10 @@
 field_tolerances={1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	(md.results.DiagnosticSolution.J),...
-	(md.results.DiagnosticSolution.MaterialsRheologyB),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
+	(md.results.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.MaterialsRheologyB),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
 };
Index: /issm/trunk/test/NightlyRun/test214.py
===================================================================
--- /issm/trunk/test/NightlyRun/test214.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test214.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 
 
@@ -33,5 +33,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 
@@ -41,10 +41,10 @@
 field_tolerances=[1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08]
 field_values=[\
-	md.results.DiagnosticSolution.Gradient1,\
-	md.results.DiagnosticSolution.J,\
-	md.results.DiagnosticSolution.MaterialsRheologyB,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy
+	md.results.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.MaterialsRheologyB,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy
 ]
Index: /issm/trunk/test/NightlyRun/test215.m
===================================================================
--- /issm/trunk/test/NightlyRun/test215.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test215.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'FS','all');
 
 %control parameters
@@ -19,5 +19,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -25,10 +25,10 @@
 field_tolerances={1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	(md.results.DiagnosticSolution.J),...
-	(md.results.DiagnosticSolution.MaterialsRheologyB),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
+	(md.results.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.MaterialsRheologyB),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
 };
Index: /issm/trunk/test/NightlyRun/test215.py
===================================================================
--- /issm/trunk/test/NightlyRun/test215.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test215.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'stokes','all')
+md=setflowequation(md,'FS','all')
 
 
@@ -33,5 +33,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 
@@ -41,10 +41,10 @@
 field_tolerances=[1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Gradient1,\
-	md.results.DiagnosticSolution.J,\
-	md.results.DiagnosticSolution.MaterialsRheologyB,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy
+	md.results.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.MaterialsRheologyB,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy
 ]
Index: /issm/trunk/test/NightlyRun/test216.m
===================================================================
--- /issm/trunk/test/NightlyRun/test216.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test216.m	(revision 16137)
@@ -2,6 +2,6 @@
 md=meshprocessrifts(md,'../Exp/Square.exp');
 md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=parameterize(md,'../Par/SquareShelf2.par');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
@@ -9,16 +9,16 @@
 md.rifts.riftstruct.fill=MelangeEnum();
 md.rifts.riftstruct.fraction=0;
-md.diagnostic.rift_penalty_lock=2;
-md.diagnostic.rift_penalty_threshold=0;
+md.stressbalance.rift_penalty_lock=2;
+md.stressbalance.rift_penalty_threshold=0;
 md.rifts.riftstruct.fractionincrement=.1;
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={1e-11,1e-11,1e-11,1e-11};
+field_tolerances={4e-11,2e-11,2e-11,2e-11};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test216.py
===================================================================
--- /issm/trunk/test/NightlyRun/test216.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test216.py	(revision 16137)
@@ -13,6 +13,6 @@
 md=meshprocessrifts(md,'../Exp/Square.exp')
 md=setmask(md,'all','')
-md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=parameterize(md,'../Par/SquareShelf2.py')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 
@@ -21,17 +21,17 @@
 md.rifts.riftstruct[0]['fill']=MelangeEnum()
 md.rifts.riftstruct[0]['fraction']=0
-md.diagnostic.rift_penalty_lock=2
-md.diagnostic.rift_penalty_threshold=0
+md.stressbalance.rift_penalty_lock=2
+md.stressbalance.rift_penalty_threshold=0
 md.rifts.riftstruct[0]['fractionincrement']=0.1
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 # Fields and tolerances to track changes
 
 field_names     =['Vx','Vy','Vel','Pressure']
-field_tolerances=[1e-11,1e-11,1e-11,1e-11]
+field_tolerances=[2.5e-11,1.5e-11,1e-11,1.5e-11]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test217.m
===================================================================
--- /issm/trunk/test/NightlyRun/test217.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test217.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
@@ -10,5 +10,5 @@
 
 %tighten
-md.diagnostic.restol=10^-4;
+md.stressbalance.restol=10^-4;
 
 %needed later
@@ -37,26 +37,24 @@
 
 %Boundary conditions:
-md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+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);
 
 %constrain flanks to 0 normal velocity
 pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvz(pos)=NaN;
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvz(pos)=NaN;
 
 %constrain grounding line to 0 velocity
 pos=find(md.mesh.y==ymin);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvy(pos)=0;
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvy(pos)=0;
 
 %icefront
 nodeonicefront=zeros(md.mesh.numberofvertices,1);
 pos=find(md.mesh.y==ymax); nodeonicefront(pos)=1;
-pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2))); diagnostic.icefront=md.mesh.segments(pos,:);
-diagnostic.icefront=[diagnostic.icefront 1*md.mask.elementonfloatingice(diagnostic.icefront(:,end))];
-md.diagnostic.icefront=diagnostic.icefront;
+md.mask.ice_levelset=1-nodeonicefront;
 
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %create analytical solution: strain rate is constant = ((rho_ice*g*h)/4B)^3 (Paterson, 4th Edition, page 292.
@@ -67,3 +65,3 @@
 field_names     ={'Vy'};
 field_tolerances={1e-13};
-field_values={(md.results.DiagnosticSolution.Vy)};
+field_values={(md.results.StressbalanceSolution.Vy)};
Index: /issm/trunk/test/NightlyRun/test217.py
===================================================================
--- /issm/trunk/test/NightlyRun/test217.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test217.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 
@@ -21,5 +21,5 @@
 
 # tighten
-md.diagnostic.restol=10**-4
+md.stressbalance.restol=10**-4
 
 # needed later
@@ -48,17 +48,17 @@
 
 # Boundary conditions:
-md.diagnostic.spcvx=float(nan)*ones((md.mesh.numberofvertices,1))
-md.diagnostic.spcvy=float(nan)*ones((md.mesh.numberofvertices,1))
-md.diagnostic.spcvz=float(nan)*ones((md.mesh.numberofvertices,1))
+md.stressbalance.spcvx=float(nan)*ones((md.mesh.numberofvertices,1))
+md.stressbalance.spcvy=float(nan)*ones((md.mesh.numberofvertices,1))
+md.stressbalance.spcvz=float(nan)*ones((md.mesh.numberofvertices,1))
 
 # constrain flanks to 0 normal velocity
 pos=numpy.nonzero(numpy.logical_or(md.mesh.x==xmin,md.mesh.x==xmax))
-md.diagnostic.spcvx[pos]=0
-md.diagnostic.spcvz[pos]=float(nan)
+md.stressbalance.spcvx[pos]=0
+md.stressbalance.spcvz[pos]=float(nan)
 
 # constrain grounding line to 0 velocity
 pos=numpy.nonzero(md.mesh.y==ymin)
-md.diagnostic.spcvx[pos]=0
-md.diagnostic.spcvy[pos]=0
+md.stressbalance.spcvx[pos]=0
+md.stressbalance.spcvy[pos]=0
 
 # icefront
@@ -66,10 +66,7 @@
 pos=numpy.nonzero(md.mesh.y==ymax)
 nodeonicefront[pos]=1
-pos=numpy.nonzero(numpy.logical_or(nodeonicefront[md.mesh.segments[:,0].astype(int)-1],nodeonicefront[md.mesh.segments[:,1].astype(int)-1]))[0]
-diagnostic.icefront=md.mesh.segments[pos,:]
-diagnostic.icefront=numpy.hstack((diagnostic.icefront,1.*md.mask.elementonfloatingice[diagnostic.icefront[:,-1].astype(int)-1].reshape(-1,1)))
-md.diagnostic.icefront=diagnostic.icefront
+md.mask.ice_levelset=1-nodeonicefront
 
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 # create analytical solution: strain rate is constant = ((rho_ice*g*h)/4B)^3 (Paterson, 4th Edition, page 292.
@@ -81,4 +78,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vy,\
+	md.results.StressbalanceSolution.Vy,\
 	]
Index: /issm/trunk/test/NightlyRun/test218.m
===================================================================
--- /issm/trunk/test/NightlyRun/test218.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test218.m	(revision 16137)
@@ -1,6 +1,6 @@
 md=squaremesh(model(),1000000,1000000,5,5);
 md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=parameterize(md,'../Par/SquareShelf2.par');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
@@ -34,24 +34,17 @@
 
 %Boundary conditions:
-md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+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);
 
 %constrain flanks to 0 normal velocity
 pos=find(md.mesh.x==xmin | md.mesh.x==xmax);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvz(pos)=NaN;
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvz(pos)=NaN;
 
 %constrain grounding line to 0 velocity
 pos=find(md.mesh.y==ymin);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvy(pos)=0;
-
-%icefront
-nodeonicefront=zeros(md.mesh.numberofvertices,1);
-pos=find(md.mesh.y==ymax); nodeonicefront(pos)=1;
-pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2))); diagnostic.icefront=md.mesh.segments(pos,:);
-diagnostic.icefront=[diagnostic.icefront 1*md.mask.elementonfloatingice(diagnostic.icefront(:,end))];
-md.diagnostic.icefront=diagnostic.icefront;
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvy(pos)=0;
 
 %partitioning
@@ -72,14 +65,14 @@
 %parameters
 md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.analysis_driver='stressbalance';
 md.qmu.params.evaluation_concurrency=1;
 md.qmu.params.interval_type='forward';
 
 %imperative! 
-md.diagnostic.reltol=10^-10; %tighten for qmu analysese
+md.stressbalance.reltol=10^-10; %tighten for qmu analysese
 md.qmu.isdakota=1;
 
 %solve
-md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
+md=solve(md,StressbalanceSolutionEnum(),'overwrite','y');
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test219.m
===================================================================
--- /issm/trunk/test/NightlyRun/test219.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test219.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal');
+md=setflowequation(md,'HO','../Exp/SquareHalfRight.exp','fill','SSA');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test219.py
===================================================================
--- /issm/trunk/test/NightlyRun/test219.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test219.py	(revision 16137)
@@ -13,7 +13,7 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,2.)
-md=setflowequation(md,'pattyn','../Exp/SquareHalfRight.exp','fill','macayeal')
+md=setflowequation(md,'HO','../Exp/SquareHalfRight.exp','fill','SSA')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 # Fields and tolerances to track changes
@@ -22,8 +22,8 @@
 field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test220.m
===================================================================
--- /issm/trunk/test/NightlyRun/test220.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test220.m	(revision 16137)
@@ -1,9 +1,9 @@
 md=triangle(model(),'../Exp/Square.exp',120000.);
 md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
+md=parameterize(md,'../Par/SquareShelf2.par');
 md=extrude(md,2,1.);
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn');
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','HO');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test220.py
===================================================================
--- /issm/trunk/test/NightlyRun/test220.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test220.py	(revision 16137)
@@ -11,9 +11,9 @@
 md=triangle(model(),'../Exp/Square.exp',120000.)
 md=setmask(md,'all','')
-md=parameterize(md,'../Par/SquareShelf.py')
+md=parameterize(md,'../Par/SquareShelf2.py')
 md.extrude(2,1.)
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn')
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','HO')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 # Fields and tolerances to track changes
@@ -22,8 +22,8 @@
 field_tolerances=[1e-09,1e-09,1e-06,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test221.m
===================================================================
--- /issm/trunk/test/NightlyRun/test221.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test221.m	(revision 16137)
@@ -1,10 +1,10 @@
 md=triangle(model(),'../Exp/Square.exp',120000.);
 md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
+md=parameterize(md,'../Par/SquareShelf2.par');
 md=extrude(md,2,1.);
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal');
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','SSA');
 md.cluster=generic('name',oshostname(),'np',3);
-md.diagnostic.viscosity_overshoot=0;
-md=solve(md,DiagnosticSolutionEnum());
+md.stressbalance.viscosity_overshoot=0;
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -12,8 +12,8 @@
 field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test221.py
===================================================================
--- /issm/trunk/test/NightlyRun/test221.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test221.py	(revision 16137)
@@ -10,10 +10,10 @@
 md=triangle(model(),'../Exp/Square.exp',120000.)
 md=setmask(md,'all','')
-md=parameterize(md,'../Par/SquareShelf.py')
+md=parameterize(md,'../Par/SquareShelf2.py')
 md.extrude(2,1.)
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal')
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','SSA')
 md.cluster=generic('name',oshostname(),'np',3)
-md.diagnostic.viscosity_overshoot=0
-md=solve(md,DiagnosticSolutionEnum())
+md.stressbalance.viscosity_overshoot=0
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -21,8 +21,8 @@
 field_tolerances=[1e-09,1e-09,1e-06,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test222.m
===================================================================
--- /issm/trunk/test/NightlyRun/test222.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test222.m	(revision 16137)
@@ -2,7 +2,7 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.prognostic.hydrostatic_adjustment='Incremental';
+md.masstransport.hydrostatic_adjustment='Incremental';
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test222.py
===================================================================
--- /issm/trunk/test/NightlyRun/test222.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test222.py	(revision 16137)
@@ -11,7 +11,7 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.prognostic.hydrostatic_adjustment='Incremental'
+md.masstransport.hydrostatic_adjustment='Incremental'
 md=solve(md,TransientSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test223.m
===================================================================
--- /issm/trunk/test/NightlyRun/test223.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test223.m	(revision 16137)
@@ -2,8 +2,8 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.geometry.bed=md.geometry.bed+50.; md.geometry.surface=md.geometry.surface+50.;
 md.cluster=generic('name',oshostname(),'np',1);
-md.prognostic.hydrostatic_adjustment='Incremental';
+md.masstransport.hydrostatic_adjustment='Incremental';
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test223.py
===================================================================
--- /issm/trunk/test/NightlyRun/test223.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test223.py	(revision 16137)
@@ -11,9 +11,9 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.geometry.bed=md.geometry.bed+50.
 md.geometry.surface=md.geometry.surface+50.
 md.cluster=generic('name',oshostname(),'np',1)
-md.prognostic.hydrostatic_adjustment='Incremental'
+md.masstransport.hydrostatic_adjustment='Incremental'
 md=solve(md,TransientSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test224.m
===================================================================
--- /issm/trunk/test/NightlyRun/test224.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test224.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.prognostic.hydrostatic_adjustment='Incremental';
+md.masstransport.hydrostatic_adjustment='Incremental';
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test224.py
===================================================================
--- /issm/trunk/test/NightlyRun/test224.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test224.py	(revision 16137)
@@ -12,7 +12,7 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.prognostic.hydrostatic_adjustment='Incremental'
+md.masstransport.hydrostatic_adjustment='Incremental'
 md=solve(md,TransientSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test225.m
===================================================================
--- /issm/trunk/test/NightlyRun/test225.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test225.m	(revision 16137)
@@ -4,7 +4,7 @@
 md.geometry.bed=md.geometry.bed+50.; md.geometry.surface=md.geometry.surface+50.;
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.prognostic.hydrostatic_adjustment='Incremental';
+md.masstransport.hydrostatic_adjustment='Incremental';
 md=solve(md,TransientSolutionEnum());
 
@@ -15,6 +15,6 @@
 field_tolerances={...
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
-	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+	2e-09,1e-09,2e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,...
+	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test225.py
===================================================================
--- /issm/trunk/test/NightlyRun/test225.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test225.py	(revision 16137)
@@ -14,7 +14,7 @@
 md.geometry.surface=md.geometry.surface+50.
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.prognostic.hydrostatic_adjustment='Incremental'
+md.masstransport.hydrostatic_adjustment='Incremental'
 md=solve(md,TransientSolutionEnum())
 
@@ -25,6 +25,6 @@
 field_tolerances=[\
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,\
-	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,\
-	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05]
+	2e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,\
+	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test226.m
===================================================================
--- /issm/trunk/test/NightlyRun/test226.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test226.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_adapt=1.;
Index: /issm/trunk/test/NightlyRun/test226.py
===================================================================
--- /issm/trunk/test/NightlyRun/test226.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test226.py	(revision 16137)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_adapt=1.
Index: /issm/trunk/test/NightlyRun/test227.m
===================================================================
--- /issm/trunk/test/NightlyRun/test227.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test227.m	(revision 16137)
@@ -3,8 +3,8 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_adapt=1.;
-md.timestepping.final_time=10.;
+md.timestepping.final_time=15.;
 md=solve(md,TransientSolutionEnum());
 
@@ -16,5 +16,5 @@
 	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-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,...
-	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
+	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test227.py
===================================================================
--- /issm/trunk/test/NightlyRun/test227.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test227.py	(revision 16137)
@@ -12,8 +12,8 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_adapt=1.
-md.timestepping.final_time=10.
+md.timestepping.final_time=15.
 md=solve(md,TransientSolutionEnum())
 
@@ -25,5 +25,5 @@
 	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-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-06,\
-	1e-09,1e-09,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05]
+	1e-08,1e-08,1e-08,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test228.m
===================================================================
--- /issm/trunk/test/NightlyRun/test228.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test228.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
Index: /issm/trunk/test/NightlyRun/test228.py
===================================================================
--- /issm/trunk/test/NightlyRun/test228.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test228.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 
Index: /issm/trunk/test/NightlyRun/test229.m
===================================================================
--- /issm/trunk/test/NightlyRun/test229.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test229.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
Index: /issm/trunk/test/NightlyRun/test229.py
===================================================================
--- /issm/trunk/test/NightlyRun/test229.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test229.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 
Index: /issm/trunk/test/NightlyRun/test230.m
===================================================================
--- /issm/trunk/test/NightlyRun/test230.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test230.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
Index: /issm/trunk/test/NightlyRun/test230.py
===================================================================
--- /issm/trunk/test/NightlyRun/test230.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test230.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 
Index: /issm/trunk/test/NightlyRun/test231.m
===================================================================
--- /issm/trunk/test/NightlyRun/test231.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test231.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
Index: /issm/trunk/test/NightlyRun/test231.py
===================================================================
--- /issm/trunk/test/NightlyRun/test231.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test231.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 
Index: /issm/trunk/test/NightlyRun/test232.m
===================================================================
--- /issm/trunk/test/NightlyRun/test232.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test232.m	(revision 16137)
@@ -3,11 +3,11 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.thermal.spctemperature=[md.thermal.spctemperature, md.thermal.spctemperature+5., md.thermal.spctemperature+10., md.thermal.spctemperature+15.; 1.5 2.5 3.5 4.];
 md.timestepping.time_step=1;
 md.timestepping.final_time=4;
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
Index: /issm/trunk/test/NightlyRun/test232.py
===================================================================
--- /issm/trunk/test/NightlyRun/test232.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test232.py	(revision 16137)
@@ -13,11 +13,11 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.thermal.spctemperature=numpy.vstack((numpy.hstack((md.thermal.spctemperature, md.thermal.spctemperature+5., md.thermal.spctemperature+10., md.thermal.spctemperature+15.)), [1.5,2.5,3.5,4.]))
 md.timestepping.time_step=1.
 md.timestepping.final_time=4.
-md.transient.isdiagnostic=False
-md.transient.isprognostic=False
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
 md.transient.isthermal=True
 md.transient.isgroundingline=False
Index: /issm/trunk/test/NightlyRun/test233.m
===================================================================
--- /issm/trunk/test/NightlyRun/test233.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test233.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.thermal.spctemperature=[md.thermal.spctemperature, md.thermal.spctemperature+5.; 1. 2.];
Index: /issm/trunk/test/NightlyRun/test233.py
===================================================================
--- /issm/trunk/test/NightlyRun/test233.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test233.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.thermal.spctemperature=numpy.vstack((numpy.hstack((md.thermal.spctemperature, md.thermal.spctemperature+5.)), [1.,2.]))
Index: /issm/trunk/test/NightlyRun/test234.m
===================================================================
--- /issm/trunk/test/NightlyRun/test234.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test234.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
@@ -42,7 +42,7 @@
 md.qmu.method=dakota_method('nond_samp');
 md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),'seed',1234,'samples',20,'sample_type','lhs');
-dver=textscan(dakotaversion(),'%[0123456789].%[0123456789].%[0123456789]')
+dver=textscan(IssmConfig('_DAKOTA_VERSION_'),'%[0123456789].%[0123456789].%[0123456789]');
 if ((str2num(dver{1}{1})==4 && str2num(dver{2}{1})>2) || str2num(dver{1}{1})>4)
-	md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),'rng','rnum2')
+	md.qmu.method(end)=dmeth_params_set(md.qmu.method(end),'rng','rnum2');
 end
 
@@ -56,5 +56,5 @@
 md.qmu.isdakota=1;
 
-md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
 md.transient.requested_outputs=IceVolumeEnum();
 
Index: /issm/trunk/test/NightlyRun/test235.m
===================================================================
--- /issm/trunk/test/NightlyRun/test235.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test235.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
@@ -51,5 +51,5 @@
 md.qmu.isdakota=1;
 
-md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
 md.transient.requested_outputs=IceVolumeEnum();
 
Index: /issm/trunk/test/NightlyRun/test236.m
===================================================================
--- /issm/trunk/test/NightlyRun/test236.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test236.m	(revision 16137)
@@ -46,5 +46,5 @@
 
 % 
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test236.py
===================================================================
--- /issm/trunk/test/NightlyRun/test236.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test236.py	(revision 16137)
@@ -57,5 +57,5 @@
 
 # 
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test237.m
===================================================================
--- /issm/trunk/test/NightlyRun/test237.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test237.m	(revision 16137)
@@ -48,6 +48,6 @@
 %
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
-md.cluster=generic('name',oshostname(),'np',3);
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',1);
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test237.py
===================================================================
--- /issm/trunk/test/NightlyRun/test237.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test237.py	(revision 16137)
@@ -59,6 +59,6 @@
 #
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
-md.cluster=generic('name',oshostname(),'np',3)
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',1)
 md=solve(md,TransientSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test270.m
===================================================================
--- /issm/trunk/test/NightlyRun/test270.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test270.m	(revision 16137)
@@ -6,7 +6,7 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 md.materials.rheology_Z=0.5*ones(md.mesh.numberofvertices,1);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -14,7 +14,7 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test270.py
===================================================================
--- /issm/trunk/test/NightlyRun/test270.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test270.py	(revision 16137)
@@ -18,7 +18,7 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 md.materials.rheology_Z=0.5*numpy.ones((md.mesh.numberofvertices,1))
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -26,7 +26,7 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test272.m
===================================================================
--- /issm/trunk/test/NightlyRun/test272.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test272.m	(revision 16137)
@@ -6,5 +6,5 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 md.materials.rheology_Z=0.5*ones(md.mesh.numberofvertices,1);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 
 %control parameters
@@ -23,5 +23,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -29,10 +29,10 @@
 field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
 field_values={...
-   (md.results.DiagnosticSolution.Gradient1),...
-   (md.results.DiagnosticSolution.J),...
-   (md.results.DiagnosticSolution.MaterialsRheologyZbar),...
-   (md.results.DiagnosticSolution.Pressure),...
-   (md.results.DiagnosticSolution.Vel),...
-   (md.results.DiagnosticSolution.Vx),...
-   (md.results.DiagnosticSolution.Vy)
+   (md.results.StressbalanceSolution.Gradient1),...
+   (md.results.StressbalanceSolution.J),...
+   (md.results.StressbalanceSolution.MaterialsRheologyZbar),...
+   (md.results.StressbalanceSolution.Pressure),...
+   (md.results.StressbalanceSolution.Vel),...
+   (md.results.StressbalanceSolution.Vx),...
+   (md.results.StressbalanceSolution.Vy)
 };
Index: /issm/trunk/test/NightlyRun/test272.py
===================================================================
--- /issm/trunk/test/NightlyRun/test272.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test272.py	(revision 16137)
@@ -18,5 +18,5 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 md.materials.rheology_Z=0.5*numpy.ones((md.mesh.numberofvertices,1))
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 
 #control parameters
@@ -35,5 +35,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -41,10 +41,10 @@
 field_tolerances=[1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12]
 field_values=[\
-   md.results.DiagnosticSolution.Gradient1,\
-   md.results.DiagnosticSolution.J,\
-   md.results.DiagnosticSolution.MaterialsRheologyZbar,\
-   md.results.DiagnosticSolution.Pressure,\
-   md.results.DiagnosticSolution.Vel,\
-   md.results.DiagnosticSolution.Vx,\
-   md.results.DiagnosticSolution.Vy,\
+   md.results.StressbalanceSolution.Gradient1,\
+   md.results.StressbalanceSolution.J,\
+   md.results.StressbalanceSolution.MaterialsRheologyZbar,\
+   md.results.StressbalanceSolution.Pressure,\
+   md.results.StressbalanceSolution.Vel,\
+   md.results.StressbalanceSolution.Vx,\
+   md.results.StressbalanceSolution.Vy,\
 ]
Index: /issm/trunk/test/NightlyRun/test274.m
===================================================================
--- /issm/trunk/test/NightlyRun/test274.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test274.m	(revision 16137)
@@ -2,21 +2,21 @@
 md=meshprocessrifts(md,'../Exp/Square.exp');
 md=setmask(md,'all','');
-md=parameterize(md,'../Par/SquareShelf.par');
+md=parameterize(md,'../Par/SquareShelf2.par');
 md.materials=matdamageice();
 md.materials.rheology_B=paterson(md.initialization.temperature);
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 md.materials.rheology_Z=0.5*ones(md.mesh.numberofvertices,1);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vel','Pressure'};
-field_tolerances={1e-11,1e-11,1e-11,1e-11};
+field_tolerances={4.5e-8,1.35e-8,1.55e-8,1e-11};
 field_values={...
-	   (md.results.DiagnosticSolution.Vx),...
-	   (md.results.DiagnosticSolution.Vy),...
-	   (md.results.DiagnosticSolution.Vel),...
-	   (md.results.DiagnosticSolution.Pressure),...
+	   (md.results.StressbalanceSolution.Vx),...
+	   (md.results.StressbalanceSolution.Vy),...
+	   (md.results.StressbalanceSolution.Vel),...
+	   (md.results.StressbalanceSolution.Pressure),...
 	   };
Index: /issm/trunk/test/NightlyRun/test274.py
===================================================================
--- /issm/trunk/test/NightlyRun/test274.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test274.py	(revision 16137)
@@ -15,21 +15,21 @@
 md=meshprocessrifts(md,'../Exp/Square.exp')
 md=setmask(md,'all','')
-md=parameterize(md,'../Par/SquareShelf.py')
+md=parameterize(md,'../Par/SquareShelf2.py')
 md.materials=matdamageice()
 md.materials.rheology_B=paterson(md.initialization.temperature)
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 md.materials.rheology_Z=0.5*numpy.ones((md.mesh.numberofvertices,1))
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vel','Pressure']
-field_tolerances=[1e-11,1e-11,1e-11,1e-11]
+field_tolerances=[4.5e-8,1.35e-8,1.55e-8,1e-11]
 field_values=[\
-	   md.results.DiagnosticSolution.Vx,\
-	   md.results.DiagnosticSolution.Vy,\
-	   md.results.DiagnosticSolution.Vel,\
-	   md.results.DiagnosticSolution.Pressure,\
+	   md.results.StressbalanceSolution.Vx,\
+	   md.results.StressbalanceSolution.Vy,\
+	   md.results.StressbalanceSolution.Vel,\
+	   md.results.StressbalanceSolution.Pressure,\
 	   ]
Index: /issm/trunk/test/NightlyRun/test280.m
===================================================================
--- /issm/trunk/test/NightlyRun/test280.m	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test280.m	(revision 16137)
@@ -0,0 +1,21 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+field_names={};
+field_tolerances={};
+field_values={};
+for i={'P1bubble','P1bubblecondensed','P2'}
+	md.flowequation.fe_SSA=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{:},1e-12,1e-13,1e-13,1e-13};
+	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/test280.py
===================================================================
--- /issm/trunk/test/NightlyRun/test280.py	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test280.py	(revision 16137)
@@ -0,0 +1,30 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from ContourToMesh import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+field_names=[]
+field_tolerances=[]
+field_values=[]
+for i in ['P1bubble','P1bubblecondensed','P2']:
+	md.flowequation.fe_SSA=i
+	md=solve(md,StressbalanceSolutionEnum())
+	field_names     =field_names+['Vx'+i,'Vy'+i,'Vel'+i,'Pressure'+i]
+	field_tolerances=field_tolerances+[1e-12,1e-13,1e-13,1e-13]
+	field_values=field_values+[\
+		md.results.StressbalanceSolution.Vx,\
+		md.results.StressbalanceSolution.Vy,\
+		md.results.StressbalanceSolution.Vel,\
+		md.results.StressbalanceSolution.Pressure,\
+		]
Index: /issm/trunk/test/NightlyRun/test285.m
===================================================================
--- /issm/trunk/test/NightlyRun/test285.m	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test285.m	(revision 16137)
@@ -0,0 +1,23 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+field_names={};
+field_tolerances={};
+field_values={};
+for i={'P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2'}
+	md.flowequation.fe_HO=i{1};
+	md=solve(md,StressbalanceSolutionEnum());
+	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vz' i{1}],['Vel' i{1}],['Pressure' i{1}]};
+	field_tolerances={field_tolerances{:},1e-08,1e-08,1e-08,1e-08,1e-13};
+	field_values={field_values{:},...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
+end
Index: /issm/trunk/test/NightlyRun/test285.py
===================================================================
--- /issm/trunk/test/NightlyRun/test285.py	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test285.py	(revision 16137)
@@ -0,0 +1,32 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from ContourToMesh import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.py');
+md.extrude(3,2.)
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+field_names=[]
+field_tolerances=[]
+field_values=[]
+for i in ['P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2']:
+	md.flowequation.fe_HO=i
+	md=solve(md,StressbalanceSolutionEnum())
+	field_names     =field_names+['Vx'+i,'Vy'+i,'Vz'+i,'Vel'+i,'Pressure'+i]
+	field_tolerances=field_tolerances+[1e-08,1e-08,1e-08,1e-08,1e-13]
+	field_values=field_values+[\
+		md.results.StressbalanceSolution.Vx,\
+		md.results.StressbalanceSolution.Vy,\
+		md.results.StressbalanceSolution.Vz,\
+		md.results.StressbalanceSolution.Vel,\
+		md.results.StressbalanceSolution.Pressure,\
+		]
Index: /issm/trunk/test/NightlyRun/test290.m
===================================================================
--- /issm/trunk/test/NightlyRun/test290.m	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test290.m	(revision 16137)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.par');
+md=extrude(md,3,2.);
+md=setflowequation(md,'FS','all');
+md.flowequation.fe_FS='TaylorHood';
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-7,1e-7,1e-6,1e-7,1e-7};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/trunk/test/NightlyRun/test290.py
===================================================================
--- /issm/trunk/test/NightlyRun/test290.py	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test290.py	(revision 16137)
@@ -0,0 +1,29 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from ContourToMesh import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.);
+md=setmask(md,'all','');
+md=parameterize(md,'../Par/SquareShelf.py');
+md.extrude(3,2.)
+md=setflowequation(md,'FS','all');
+md.flowequation.fe_FS='TaylorHood';
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+#Fields and tolerances to track changes
+field_names     =['Vx', 'Vy', 'Vz', 'Vel','Pressure'];
+field_tolerances=[1e-7,1e-7,2e-7,1e-7,1e-7];
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	];
Index: /issm/trunk/test/NightlyRun/test3001.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3001.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3001.m	(revision 16137)
@@ -2,12 +2,12 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
 md.toolkits.DefaultAnalysis=issmsolver();
-md.diagnostic.requested_outputs=StressTensorEnum();
+md.stressbalance.requested_outputs=StressTensorEnum();
 md.autodiff.isautodiff=true;
 md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -17,10 +17,10 @@
 	1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.StressTensorxx),...
-	(md.results.DiagnosticSolution.StressTensoryy),...
-	(md.results.DiagnosticSolution.StressTensorxy),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.StressTensorxx),...
+	(md.results.StressbalanceSolution.StressTensoryy),...
+	(md.results.StressbalanceSolution.StressTensorxy),...
 	};
Index: /issm/trunk/test/NightlyRun/test3001.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3001.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3001.py	(revision 16137)
@@ -11,10 +11,10 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',1)
-md.diagnostic.requested_outputs=StressTensorEnum()
+md.stressbalance.requested_outputs=StressTensorEnum()
 md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -24,10 +24,10 @@
 	1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.StressTensorxx,\
-	md.results.DiagnosticSolution.StressTensoryy,\
-	md.results.DiagnosticSolution.StressTensorxy,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.StressTensorxx,\
+	md.results.StressbalanceSolution.StressTensoryy,\
+	md.results.StressbalanceSolution.StressTensorxy,\
 	]
Index: /issm/trunk/test/NightlyRun/test3002.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3002.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3002.m	(revision 16137)
@@ -3,10 +3,10 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
 md.autodiff.isautodiff=true;
 md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -14,8 +14,8 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test3002.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3002.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3002.py	(revision 16137)
@@ -12,9 +12,9 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,2.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',1)
 md.autodiff.isautodiff=True
 md.toolkits.DefaultAnalysis=issmsolver()
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -22,8 +22,8 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test3003.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3003.m	(revision 16137)
@@ -3,11 +3,11 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',1);
-md.diagnostic.requested_outputs=StressTensorEnum();
+md.stressbalance.requested_outputs=StressTensorEnum();
 md.autodiff.isautodiff=true;
 md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -17,14 +17,14 @@
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.StressTensorxx),...
-	(md.results.DiagnosticSolution.StressTensoryy),...
-	(md.results.DiagnosticSolution.StressTensorzz),...
-	(md.results.DiagnosticSolution.StressTensorxy),...
-	(md.results.DiagnosticSolution.StressTensorxz),...
-	(md.results.DiagnosticSolution.StressTensoryz),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.StressTensorxx),...
+	(md.results.StressbalanceSolution.StressTensoryy),...
+	(md.results.StressbalanceSolution.StressTensorzz),...
+	(md.results.StressbalanceSolution.StressTensorxy),...
+	(md.results.StressbalanceSolution.StressTensorxz),...
+	(md.results.StressbalanceSolution.StressTensoryz),...
 	};
Index: /issm/trunk/test/NightlyRun/test3003.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3003.py	(revision 16137)
@@ -12,10 +12,10 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,2.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',1)
-md.diagnostic.requested_outputs=StressTensorEnum()
+md.stressbalance.requested_outputs=StressTensorEnum()
 md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -25,14 +25,14 @@
 	1e-09,1e-09,1e-09,1e-09,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.StressTensorxx,\
-	md.results.DiagnosticSolution.StressTensoryy,\
-	md.results.DiagnosticSolution.StressTensorzz,\
-	md.results.DiagnosticSolution.StressTensorxy,\
-	md.results.DiagnosticSolution.StressTensorxz,\
-	md.results.DiagnosticSolution.StressTensoryz,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.StressTensorxx,\
+	md.results.StressbalanceSolution.StressTensoryy,\
+	md.results.StressbalanceSolution.StressTensorzz,\
+	md.results.StressbalanceSolution.StressTensorxy,\
+	md.results.StressbalanceSolution.StressTensorxz,\
+	md.results.StressbalanceSolution.StressTensoryz,\
 	]
Index: /issm/trunk/test/NightlyRun/test3004.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3004.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3004.m	(revision 16137)
@@ -3,10 +3,10 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'FS','all');
 md.cluster=generic('name',oshostname(),'np',1);
 md.autodiff.isautodiff=true;
 md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -14,8 +14,8 @@
 field_tolerances={1e-08,1e-08,1e-07,1e-08,1e-08};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test3004.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3004.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3004.py	(revision 16137)
@@ -12,9 +12,9 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,2.)
-md=setflowequation(md,'stokes','all')
+md=setflowequation(md,'FS','all')
 md.cluster=generic('name',oshostname(),'np',1)
 md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -22,8 +22,8 @@
 field_tolerances=[1e-08,1e-08,1e-07,1e-08,1e-08]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test3005.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3005.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3005.m	(revision 16137)
@@ -2,10 +2,10 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
 md.autodiff.isautodiff=true;
 md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -13,4 +13,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test3005.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3005.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3005.py	(revision 16137)
@@ -11,9 +11,9 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',1)
 md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -21,4 +21,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test3006.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3006.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3006.m	(revision 16137)
@@ -3,12 +3,12 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
-md.prognostic.stabilization=3;
-md.prognostic.spcthickness=md.geometry.thickness;
+md.masstransport.stabilization=3;
+md.masstransport.spcthickness=md.geometry.thickness;
 md.autodiff.isautodiff=true;
 md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('autodiff',true);
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -16,4 +16,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test3006.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3006.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3006.py	(revision 16137)
@@ -13,11 +13,11 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',1)
-md.prognostic.stabilization=3
-md.prognostic.spcthickness=md.geometry.thickness
+md.masstransport.stabilization=3
+md.masstransport.spcthickness=md.geometry.thickness
 md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -25,4 +25,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test3007.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3007.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3007.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md=extrude(md,5,3.);
 md.cluster=generic('name',oshostname(),'np',1);
@@ -8,5 +8,5 @@
 md.verbose=verbose('autodiff',true);
 md.toolkits.DefaultAnalysis=issmsolver();
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -14,4 +14,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test3007.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3007.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3007.py	(revision 16137)
@@ -11,10 +11,10 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.extrude(5,3.)
 md.cluster=generic('name',oshostname(),'np',1)
 md.toolkits.DefaultAnalysis=issmsolver()
 md.autodiff.isautodiff=True
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -22,4 +22,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test3008.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3008.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3008.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.timestepping.time_step=0;
 md.cluster=generic('name',oshostname(),'np',1);
Index: /issm/trunk/test/NightlyRun/test3008.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3008.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3008.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.timestepping.time_step=0
 md.cluster=generic('name',oshostname(),'np',1)
Index: /issm/trunk/test/NightlyRun/test3009.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3009.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3009.m	(revision 16137)
@@ -3,8 +3,8 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
Index: /issm/trunk/test/NightlyRun/test3009.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3009.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3009.py	(revision 16137)
@@ -12,8 +12,8 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',1)
-md.transient.isdiagnostic=False
-md.transient.isprognostic=False
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
 md.transient.isthermal=True
 md.transient.isgroundingline=False
Index: /issm/trunk/test/NightlyRun/test301.m
===================================================================
--- /issm/trunk/test/NightlyRun/test301.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test301.m	(revision 16137)
@@ -2,7 +2,7 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -10,7 +10,7 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test301.py
===================================================================
--- /issm/trunk/test/NightlyRun/test301.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test301.py	(revision 16137)
@@ -11,7 +11,7 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -19,7 +19,7 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test3010.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3010.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3010.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
 md.transient.requested_outputs=IceVolumeEnum();
Index: /issm/trunk/test/NightlyRun/test3010.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3010.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3010.py	(revision 16137)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',1)
 md.toolkits.DefaultAnalysis=issmsolver()
Index: /issm/trunk/test/NightlyRun/test3015.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3015.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3015.m	(revision 16137)
@@ -6,7 +6,7 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
-md.prognostic.requested_outputs=IceVolumeEnum();
+md.masstransport.requested_outputs=IceVolumeEnum();
 md.verbose=verbose('autodiff',true);
 md.toolkits.DefaultAnalysis=issmsolver();
@@ -42,6 +42,6 @@
 md=SetIceShelfBC(md);
 
-md=solve(md,PrognosticSolutionEnum());
-V0=md.results.PrognosticSolution.IceVolume;
+md=solve(md,MasstransportSolutionEnum());
+V0=md.results.MasstransportSolution.IceVolume;
 
 %backward
@@ -53,6 +53,6 @@
 md=SetIceShelfBC(md);
 
-md=solve(md,PrognosticSolutionEnum());
-V2=md.results.PrognosticSolution.IceVolume;
+md=solve(md,MasstransportSolutionEnum());
+V2=md.results.MasstransportSolution.IceVolume;
 
 %compute resulting derivative
@@ -67,7 +67,7 @@
 md=SetIceShelfBC(md);
 
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 %retrieve directly
-dVdh_ad=md.results.PrognosticSolution.AutodiffJacobian;
+dVdh_ad=md.results.MasstransportSolution.AutodiffJacobian;
 
 disp(sprintf('dV/dh: analytical:  %16.16g\n       using adolc:  %16.16g\n',dVdh_an,dVdh_ad));
Index: /issm/trunk/test/NightlyRun/test3015.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3015.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3015.py	(revision 16137)
@@ -20,7 +20,7 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.prognostic.requested_outputs=IceVolumeEnum()
+md.masstransport.requested_outputs=IceVolumeEnum()
 md.verbose=verbose('autodiff',True)
 
@@ -55,6 +55,6 @@
 md=SetIceShelfBC(md)
 
-md=solve(md,PrognosticSolutionEnum())
-V0=md.results.PrognosticSolution.IceVolume
+md=solve(md,MasstransportSolutionEnum())
+V0=md.results.MasstransportSolution.IceVolume
 
 #backward
@@ -66,6 +66,6 @@
 md=SetIceShelfBC(md)
 
-md=solve(md,PrognosticSolutionEnum())
-V2=md.results.PrognosticSolution.IceVolume
+md=solve(md,MasstransportSolutionEnum())
+V2=md.results.MasstransportSolution.IceVolume
 
 #compute resulting derivative
@@ -80,7 +80,7 @@
 md=SetIceShelfBC(md)
 
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 #retrieve directly
-dVdh_ad=md.results.PrognosticSolution.AutodiffJacobian
+dVdh_ad=md.results.MasstransportSolution.AutodiffJacobian
 
 print "dV/dh: analytical:  #16.16g\n       using adolc:  #16.16g\n" % (dVdh_an,dVdh_ad)
Index: /issm/trunk/test/NightlyRun/test3019.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3019.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3019.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
 md.toolkits.DefaultAnalysis=issmsolver();
Index: /issm/trunk/test/NightlyRun/test3019.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3019.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3019.py	(revision 16137)
@@ -15,5 +15,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 
Index: /issm/trunk/test/NightlyRun/test302.m
===================================================================
--- /issm/trunk/test/NightlyRun/test302.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test302.m	(revision 16137)
@@ -2,7 +2,7 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'hutter','all');
+md=setflowequation(md,'SIA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -10,7 +10,7 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test302.py
===================================================================
--- /issm/trunk/test/NightlyRun/test302.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test302.py	(revision 16137)
@@ -11,7 +11,7 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'hutter','all')
+md=setflowequation(md,'SIA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -19,7 +19,7 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test3020.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3020.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3020.m	(revision 16137)
@@ -6,9 +6,9 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
 md.transient.requested_outputs=[IceVolumeEnum();MaxVelEnum()];
 md.verbose=verbose('autodiff',true);
-md.diagnostic.restol=1e-4;
+md.stressbalance.restol=1e-4;
 md.toolkits.DefaultAnalysis=issmsolver();
 
Index: /issm/trunk/test/NightlyRun/test3020.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3020.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3020.py	(revision 16137)
@@ -20,9 +20,9 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',1)
 md.transient.requested_outputs=[IceVolumeEnum(),MaxVelEnum()]
 md.verbose=verbose('autodiff',True)
-md.diagnostic.restol=0.000001
+md.stressbalance.restol=0.000001
 md.toolkits.DefaultAnalysis=issmsolver()
 
Index: /issm/trunk/test/NightlyRun/test3021.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3021.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test3021.m	(revision 16137)
@@ -2,11 +2,11 @@
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.diagnostic.requested_outputs=StressTensorEnum();
+md.stressbalance.requested_outputs=StressTensorEnum();
 md.autodiff.isautodiff=false;
 md.toolkits.DefaultAnalysis=issmsolver();
 md.verbose=verbose('1111111');
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -16,10 +16,10 @@
 	1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.StressTensorxx),...
-	(md.results.DiagnosticSolution.StressTensoryy),...
-	(md.results.DiagnosticSolution.StressTensorxy),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.StressTensorxx),...
+	(md.results.StressbalanceSolution.StressTensoryy),...
+	(md.results.StressbalanceSolution.StressTensorxy),...
 	};
Index: /issm/trunk/test/NightlyRun/test303.m
===================================================================
--- /issm/trunk/test/NightlyRun/test303.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test303.m	(revision 16137)
@@ -2,7 +2,7 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal');
+md=setflowequation(md,'SIA','../Exp/SquareHalfRight.exp','fill','SSA');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -10,7 +10,7 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test303.py
===================================================================
--- /issm/trunk/test/NightlyRun/test303.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test303.py	(revision 16137)
@@ -11,7 +11,7 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal')
+md=setflowequation(md,'SIA','../Exp/SquareHalfRight.exp','fill','SSA')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -19,7 +19,7 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test304.m
===================================================================
--- /issm/trunk/test/NightlyRun/test304.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test304.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test304.py
===================================================================
--- /issm/trunk/test/NightlyRun/test304.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test304.py	(revision 16137)
@@ -12,7 +12,7 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,2.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -20,8 +20,8 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test305.m
===================================================================
--- /issm/trunk/test/NightlyRun/test305.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test305.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,5,2.);
-md=setflowequation(md,'hutter','all');
+md=setflowequation(md,'SIA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test305.py
===================================================================
--- /issm/trunk/test/NightlyRun/test305.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test305.py	(revision 16137)
@@ -12,7 +12,7 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(5,2.)
-md=setflowequation(md,'hutter','all')
+md=setflowequation(md,'SIA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -20,8 +20,8 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test306.m
===================================================================
--- /issm/trunk/test/NightlyRun/test306.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test306.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,4,2.);
-md=setflowequation(md,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal');
+md=setflowequation(md,'SIA','../Exp/SquareHalfRight.exp','fill','SSA');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test306.py
===================================================================
--- /issm/trunk/test/NightlyRun/test306.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test306.py	(revision 16137)
@@ -12,7 +12,7 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(4,2.)
-md=setflowequation(md,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal')
+md=setflowequation(md,'SIA','../Exp/SquareHalfRight.exp','fill','SSA')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -20,8 +20,8 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test307.m
===================================================================
--- /issm/trunk/test/NightlyRun/test307.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test307.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-09,1e-09,2e-10,2e-10,1e-10};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test307.py
===================================================================
--- /issm/trunk/test/NightlyRun/test307.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test307.py	(revision 16137)
@@ -12,7 +12,7 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -20,8 +20,8 @@
 field_tolerances=[1e-09,1e-09,2e-10,2e-10,1e-10]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test308.m
===================================================================
--- /issm/trunk/test/NightlyRun/test308.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test308.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'FS','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test308.py
===================================================================
--- /issm/trunk/test/NightlyRun/test308.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test308.py	(revision 16137)
@@ -12,7 +12,7 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'stokes','all')
+md=setflowequation(md,'FS','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -20,8 +20,8 @@
 field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test309.m
===================================================================
--- /issm/trunk/test/NightlyRun/test309.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test309.m	(revision 16137)
@@ -2,7 +2,7 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -10,4 +10,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test309.py
===================================================================
--- /issm/trunk/test/NightlyRun/test309.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test309.py	(revision 16137)
@@ -11,7 +11,7 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -19,4 +19,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test310.m
===================================================================
--- /issm/trunk/test/NightlyRun/test310.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test310.m	(revision 16137)
@@ -3,9 +3,9 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
-md.prognostic.stabilization=3;
-md.prognostic.spcthickness=md.geometry.thickness;
+md=setflowequation(md,'SSA','all');
+md.masstransport.stabilization=3;
+md.masstransport.spcthickness=md.geometry.thickness;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -13,4 +13,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test310.py
===================================================================
--- /issm/trunk/test/NightlyRun/test310.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test310.py	(revision 16137)
@@ -13,9 +13,9 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'macayeal','all')
-md.prognostic.stabilization=3
-md.prognostic.spcthickness=md.geometry.thickness
+md=setflowequation(md,'SSA','all')
+md.masstransport.stabilization=3
+md.masstransport.spcthickness=md.geometry.thickness
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -23,4 +23,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test311.m
===================================================================
--- /issm/trunk/test/NightlyRun/test311.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test311.m	(revision 16137)
@@ -2,8 +2,8 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md=extrude(md,5,0.5);
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,4 +11,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test311.py
===================================================================
--- /issm/trunk/test/NightlyRun/test311.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test311.py	(revision 16137)
@@ -11,8 +11,8 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.extrude(5,0.5)
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -20,4 +20,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test312.m
===================================================================
--- /issm/trunk/test/NightlyRun/test312.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test312.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.timestepping.time_step=0.;
 md.cluster=generic('name',oshostname(),'np',3);
Index: /issm/trunk/test/NightlyRun/test312.py
===================================================================
--- /issm/trunk/test/NightlyRun/test312.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test312.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.timestepping.time_step=0.
 md.cluster=generic('name',oshostname(),'np',3)
Index: /issm/trunk/test/NightlyRun/test313.m
===================================================================
--- /issm/trunk/test/NightlyRun/test313.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test313.m	(revision 16137)
@@ -3,9 +3,9 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.verbose=verbose('convergence',true,'solution',true);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
Index: /issm/trunk/test/NightlyRun/test313.py
===================================================================
--- /issm/trunk/test/NightlyRun/test313.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test313.py	(revision 16137)
@@ -12,9 +12,9 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.verbose=verbose('convergence',True,'solution',True)
-md.transient.isdiagnostic=False
-md.transient.isprognostic=False
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
 md.transient.isthermal=True
 md.transient.isgroundingline=False
Index: /issm/trunk/test/NightlyRun/test314.m
===================================================================
--- /issm/trunk/test/NightlyRun/test314.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test314.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'hutter','all');
+md=setflowequation(md,'SIA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test314.py
===================================================================
--- /issm/trunk/test/NightlyRun/test314.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test314.py	(revision 16137)
@@ -11,5 +11,5 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'hutter','all')
+md=setflowequation(md,'SIA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test315.m
===================================================================
--- /issm/trunk/test/NightlyRun/test315.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test315.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,5,1.2);
-md=setflowequation(md,'hutter','all');
+md=setflowequation(md,'SIA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test315.py
===================================================================
--- /issm/trunk/test/NightlyRun/test315.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test315.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(5,1.2)
-md=setflowequation(md,'hutter','all')
+md=setflowequation(md,'SIA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test316.m
===================================================================
--- /issm/trunk/test/NightlyRun/test316.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test316.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test316.py
===================================================================
--- /issm/trunk/test/NightlyRun/test316.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test316.py	(revision 16137)
@@ -11,5 +11,5 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test317.m
===================================================================
--- /issm/trunk/test/NightlyRun/test317.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test317.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test317.py
===================================================================
--- /issm/trunk/test/NightlyRun/test317.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test317.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test318.m
===================================================================
--- /issm/trunk/test/NightlyRun/test318.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test318.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,4,1.);
-md=setflowequation(md,'hutter','all');
+md=setflowequation(md,'SIA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_step=0;
@@ -10,5 +10,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13,1e-10,1e-10,1e-13,1e-11,1e-6};
+field_tolerances={1e-13,1e-13,1.5e-10,1e-10,1e-13,1e-11,1e-6};
 field_values={...
 	(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test318.py
===================================================================
--- /issm/trunk/test/NightlyRun/test318.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test318.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(4,1.)
-md=setflowequation(md,'hutter','all')
+md=setflowequation(md,'SIA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_step=0
@@ -19,5 +19,5 @@
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate']
-field_tolerances=[1e-13,1e-13,1e-10,1e-10,1e-13,1e-11,1e-6]
+field_tolerances=[1e-13,1e-13,1.5e-10,1e-10,1e-13,1e-11,1e-6]
 field_values=[\
 	md.results.SteadystateSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test319.m
===================================================================
--- /issm/trunk/test/NightlyRun/test319.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test319.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 
 %control parameters
@@ -18,5 +18,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -24,10 +24,10 @@
 field_tolerances={1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	(md.results.DiagnosticSolution.J),...
-	(md.results.DiagnosticSolution.FrictionCoefficient),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
+	(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/test319.py
===================================================================
--- /issm/trunk/test/NightlyRun/test319.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test319.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 
 #control parameters
@@ -30,5 +30,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -36,10 +36,10 @@
 field_tolerances=[1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Gradient1,\
-	md.results.DiagnosticSolution.J,\
-	md.results.DiagnosticSolution.FrictionCoefficient,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
+	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/test320.m
===================================================================
--- /issm/trunk/test/NightlyRun/test320.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test320.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 
 %control parameters
@@ -19,5 +19,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -25,10 +25,10 @@
 field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	(md.results.DiagnosticSolution.J),...
-	(md.results.DiagnosticSolution.FrictionCoefficient),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
+	(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/test320.py
===================================================================
--- /issm/trunk/test/NightlyRun/test320.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test320.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 
 #control parameters
@@ -31,5 +31,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -37,10 +37,10 @@
 field_tolerances=[1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12]
 field_values=[\
-	md.results.DiagnosticSolution.Gradient1,\
-	md.results.DiagnosticSolution.J,\
-	md.results.DiagnosticSolution.FrictionCoefficient,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
+	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/test321.m
===================================================================
--- /issm/trunk/test/NightlyRun/test321.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test321.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 
 %control parameters
@@ -19,5 +19,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -25,10 +25,10 @@
 field_tolerances={1e-08,1e-07,1e-10,1e-10,1e-09,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	(md.results.DiagnosticSolution.J),...
-	(md.results.DiagnosticSolution.FrictionCoefficient),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
+	(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/test321.py
===================================================================
--- /issm/trunk/test/NightlyRun/test321.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test321.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 
 #control parameters
@@ -31,5 +31,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -37,10 +37,10 @@
 field_tolerances=[1e-08,1e-07,1e-10,1e-10,1e-09,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Gradient1,\
-	md.results.DiagnosticSolution.J,\
-	md.results.DiagnosticSolution.FrictionCoefficient,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
+	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/test322.m
===================================================================
--- /issm/trunk/test/NightlyRun/test322.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test322.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'FS','all');
 
 %control parameters
@@ -19,5 +19,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -25,10 +25,10 @@
 field_tolerances={1e-06,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	(md.results.DiagnosticSolution.J),...
-	(md.results.DiagnosticSolution.FrictionCoefficient),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
+	(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/test322.py
===================================================================
--- /issm/trunk/test/NightlyRun/test322.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test322.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'stokes','all')
+md=setflowequation(md,'FS','all')
 
 #control parameters
@@ -31,5 +31,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -37,10 +37,10 @@
 field_tolerances=[1e-06,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Gradient1,\
-	md.results.DiagnosticSolution.J,\
-	md.results.DiagnosticSolution.FrictionCoefficient,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
+	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/test323.m
===================================================================
--- /issm/trunk/test/NightlyRun/test323.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test323.m	(revision 16137)
@@ -2,8 +2,8 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_adapt=1;
-md.timestepping.final_time=600.;
+md.timestepping.final_time=650.;
 md=solve(md,TransientSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test323.py
===================================================================
--- /issm/trunk/test/NightlyRun/test323.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test323.py	(revision 16137)
@@ -12,8 +12,8 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_adapt=1
-md.timestepping.final_time=600.
+md.timestepping.final_time=650.
 md=solve(md,TransientSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test324.m
===================================================================
--- /issm/trunk/test/NightlyRun/test324.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test324.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,5,1.2);
-md=setflowequation(md,'hutter','all');
+md=setflowequation(md,'SIA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_adapt=1;
Index: /issm/trunk/test/NightlyRun/test324.py
===================================================================
--- /issm/trunk/test/NightlyRun/test324.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test324.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(5,1.2)
-md=setflowequation(md,'hutter','all')
+md=setflowequation(md,'SIA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_adapt=1
Index: /issm/trunk/test/NightlyRun/test325.m
===================================================================
--- /issm/trunk/test/NightlyRun/test325.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test325.m	(revision 16137)
@@ -3,8 +3,9 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.timestepping.time_step=0.;
 md.cluster=generic('name',oshostname(),'np',3);
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
 md=solve(md,EnthalpySolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test325.py
===================================================================
--- /issm/trunk/test/NightlyRun/test325.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test325.py	(revision 16137)
@@ -13,8 +13,9 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.timestepping.time_step=0.
 md.cluster=generic('name',oshostname(),'np',3)
 md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
 md=solve(md,EnthalpySolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test326.m
===================================================================
--- /issm/trunk/test/NightlyRun/test326.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test326.m	(revision 16137)
@@ -3,9 +3,10 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
Index: /issm/trunk/test/NightlyRun/test326.py
===================================================================
--- /issm/trunk/test/NightlyRun/test326.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test326.py	(revision 16137)
@@ -13,9 +13,10 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
-md.transient.isdiagnostic=False
-md.transient.isprognostic=False
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
 md.transient.isthermal=True
 md.transient.isgroundingline=False
Index: /issm/trunk/test/NightlyRun/test327.m
===================================================================
--- /issm/trunk/test/NightlyRun/test327.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test327.m	(revision 16137)
@@ -3,7 +3,8 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
 md.initialization.temperature(:)=272.;
 md.thermal.spctemperature(find(md.mesh.vertexonsurface))=272.;
Index: /issm/trunk/test/NightlyRun/test327.py
===================================================================
--- /issm/trunk/test/NightlyRun/test327.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test327.py	(revision 16137)
@@ -13,7 +13,8 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
 md.initialization.temperature[:]=272.
 md.thermal.spctemperature[numpy.nonzero(md.mesh.vertexonsurface)[0]]=272.
Index: /issm/trunk/test/NightlyRun/test328.m
===================================================================
--- /issm/trunk/test/NightlyRun/test328.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test328.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.surfaceforcings.issmbgradients=1;
 md.surfaceforcings.b_pos=-100. + 0.00005*md.mesh.x - 0.0001*md.mesh.y;
Index: /issm/trunk/test/NightlyRun/test328.py
===================================================================
--- /issm/trunk/test/NightlyRun/test328.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test328.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.surfaceforcings.issmbgradients=1
 md.surfaceforcings.b_pos=-100. + 0.00005*md.mesh.x - 0.0001*md.mesh.y
Index: /issm/trunk/test/NightlyRun/test329.m
===================================================================
--- /issm/trunk/test/NightlyRun/test329.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test329.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.surfaceforcings.issmbgradients=1;
 md.surfaceforcings.b_pos=-100. + 0.00005*md.mesh.x - 0.0001*md.mesh.y;
Index: /issm/trunk/test/NightlyRun/test329.py
===================================================================
--- /issm/trunk/test/NightlyRun/test329.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test329.py	(revision 16137)
@@ -14,5 +14,5 @@
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
 md.extrude(3,1)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.surfaceforcings.issmbgradients=1
 md.surfaceforcings.b_pos=-100. + 0.00005*md.mesh.x - 0.0001*md.mesh.y
Index: /issm/trunk/test/NightlyRun/test331.m
===================================================================
--- /issm/trunk/test/NightlyRun/test331.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test331.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.initialization.watercolumn=10^-3*ones(md.mesh.numberofvertices,1);
Index: /issm/trunk/test/NightlyRun/test331.py
===================================================================
--- /issm/trunk/test/NightlyRun/test331.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test331.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=setmask(md,'','')
 md=parameterize(md,'../Par/SquareSheetConstrained.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.initialization.watercolumn=1e-3*numpy.ones((md.mesh.numberofvertices,1))
Index: /issm/trunk/test/NightlyRun/test332.m
===================================================================
--- /issm/trunk/test/NightlyRun/test332.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test332.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
 md.hydrology=(hydrologydc);
@@ -24,4 +24,4 @@
 %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, 1e-13};
+field_tolerances={1e-13, 2.5e-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 16136)
+++ /issm/trunk/test/NightlyRun/test333.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',1);
 md.hydrology=(hydrologydc);
Index: /issm/trunk/test/NightlyRun/test401.m
===================================================================
--- /issm/trunk/test/NightlyRun/test401.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test401.m	(revision 16137)
@@ -2,7 +2,7 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -10,7 +10,7 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test401.py
===================================================================
--- /issm/trunk/test/NightlyRun/test401.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test401.py	(revision 16137)
@@ -12,7 +12,7 @@
 md=setmask(md,'../Exp/SquareShelf.exp','')
 md=parameterize(md,'../Par/SquareSheetShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -20,7 +20,7 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test402.m
===================================================================
--- /issm/trunk/test/NightlyRun/test402.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test402.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,4,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test402.py
===================================================================
--- /issm/trunk/test/NightlyRun/test402.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test402.py	(revision 16137)
@@ -13,7 +13,7 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(4,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -21,8 +21,8 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test403.m
===================================================================
--- /issm/trunk/test/NightlyRun/test403.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test403.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,5,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test403.py
===================================================================
--- /issm/trunk/test/NightlyRun/test403.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test403.py	(revision 16137)
@@ -13,16 +13,16 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(5,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09]
+field_tolerances=[2e-09,1e-09,1e-09,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test404.m
===================================================================
--- /issm/trunk/test/NightlyRun/test404.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test404.m	(revision 16137)
@@ -3,16 +3,16 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'FS','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-07,1e-07,1e-06,1e-07,1e-07};
+field_tolerances={1.5e-07,1e-07,1e-06,1e-07,1e-07};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test404.py
===================================================================
--- /issm/trunk/test/NightlyRun/test404.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test404.py	(revision 16137)
@@ -13,16 +13,16 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'stokes','all')
+md=setflowequation(md,'FS','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-07,1e-07,1e-06,1e-07,1e-07]
+field_tolerances=[1.5e-07,1e-07,1e-06,1e-07,1e-07]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test405.m
===================================================================
--- /issm/trunk/test/NightlyRun/test405.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test405.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,5,1.);
-md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties');
+md=setflowequation(md,'SSA','../Exp/SquareHalfRight.exp','fill','HO','coupling','penalties');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={5e-05,5e-05,5e-05,5e-05,1e-05};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test405.py
===================================================================
--- /issm/trunk/test/NightlyRun/test405.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test405.py	(revision 16137)
@@ -13,7 +13,7 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(5,1.)
-md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties')
+md=setflowequation(md,'SSA','../Exp/SquareHalfRight.exp','fill','HO','coupling','penalties')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -21,8 +21,8 @@
 field_tolerances=[5e-05,5e-05,5e-05,5e-05,1e-05]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test406.m
===================================================================
--- /issm/trunk/test/NightlyRun/test406.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test406.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,4,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_step=0.;
Index: /issm/trunk/test/NightlyRun/test406.py
===================================================================
--- /issm/trunk/test/NightlyRun/test406.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test406.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(4,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_step=0.
Index: /issm/trunk/test/NightlyRun/test407.m
===================================================================
--- /issm/trunk/test/NightlyRun/test407.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test407.m	(revision 16137)
@@ -3,8 +3,8 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,4,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
Index: /issm/trunk/test/NightlyRun/test407.py
===================================================================
--- /issm/trunk/test/NightlyRun/test407.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test407.py	(revision 16137)
@@ -13,8 +13,8 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(4,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md.transient.isdiagnostic=False
-md.transient.isprognostic=False
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
 md.transient.isthermal=True
 md.transient.isgroundingline=False
Index: /issm/trunk/test/NightlyRun/test408.m
===================================================================
--- /issm/trunk/test/NightlyRun/test408.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test408.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test408.py
===================================================================
--- /issm/trunk/test/NightlyRun/test408.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test408.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','')
 md=parameterize(md,'../Par/SquareSheetShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test409.m
===================================================================
--- /issm/trunk/test/NightlyRun/test409.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test409.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties');
+md=setflowequation(md,'SSA','../Exp/SquareHalfRight.exp','fill','HO','coupling','penalties');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test409.py
===================================================================
--- /issm/trunk/test/NightlyRun/test409.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test409.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn','coupling','penalties')
+md=setflowequation(md,'SSA','../Exp/SquareHalfRight.exp','fill','HO','coupling','penalties')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test410.m
===================================================================
--- /issm/trunk/test/NightlyRun/test410.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test410.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_step=0;
@@ -10,5 +10,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-09,1e-09,1e-09,1e-10,1e-13,1e-10,1e-06};
+field_tolerances={1e-09,1e-09,1e-08,2e-10,1e-13,1e-10,1e-06};
 field_values={...
 	(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test410.py
===================================================================
--- /issm/trunk/test/NightlyRun/test410.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test410.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(3,2.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_step=0
@@ -20,5 +20,5 @@
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate']
-field_tolerances=[1e-09,1e-09,1e-09,1e-10,1e-13,1e-10,1e-06]
+field_tolerances=[1e-09,1e-09,1e-08,1e-09,1e-13,1e-10,1e-06]
 field_values=[\
 	md.results.SteadystateSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test411.m
===================================================================
--- /issm/trunk/test/NightlyRun/test411.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test411.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_step=0;
@@ -10,5 +10,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-09,1e-09,1e-08,1e-09,1e-09,1e-08,1e-05
+field_tolerances={2e-09,1e-09,1e-08,1e-09,1e-09,1e-08,1e-05
 };
 field_values={...
Index: /issm/trunk/test/NightlyRun/test411.py
===================================================================
--- /issm/trunk/test/NightlyRun/test411.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test411.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(3,2.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_step=0
Index: /issm/trunk/test/NightlyRun/test412.m
===================================================================
--- /issm/trunk/test/NightlyRun/test412.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test412.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
@@ -25,13 +25,13 @@
 %parameters
 md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.analysis_driver='stressbalance';
 md.qmu.params.evaluation_concurrency=1;
 md.qmu.params.interval_type='forward';
 
 %imperative! 
-md.diagnostic.reltol=10^-5; %tighten for qmu analysese
+md.stressbalance.reltol=10^-5; %tighten for qmu analysese
 
 %solve
-md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
+md=solve(md,StressbalanceSolutionEnum(),'overwrite','y');
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test413.m
===================================================================
--- /issm/trunk/test/NightlyRun/test413.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test413.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
@@ -24,5 +24,5 @@
 %parameters
 md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.analysis_driver='stressbalance';
 md.qmu.params.evaluation_concurrency=1;
 md.qmu.params.interval_type='forward';
@@ -30,9 +30,9 @@
 
 %imperative!
-md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
 md.qmu.isdakota=1;
 
 %solve
-md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
+md=solve(md,StressbalanceSolutionEnum(),'overwrite','y');
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test414.m
===================================================================
--- /issm/trunk/test/NightlyRun/test414.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test414.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.materials.rho_ice=10^7; %involved in the mass flux, make it easy
@@ -8,7 +8,7 @@
 
 %constrain all velocities to 1 m/yr, in the y-direction
-md.diagnostic.spcvx=zeros(md.mesh.numberofvertices,1);
-md.diagnostic.spcvy=ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvz=zeros(md.mesh.numberofvertices,1);
+md.stressbalance.spcvx=zeros(md.mesh.numberofvertices,1);
+md.stressbalance.spcvy=ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvz=zeros(md.mesh.numberofvertices,1);
 
 %Dakota options
@@ -41,12 +41,12 @@
 %parameters
 md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.analysis_driver='stressbalance';
 md.qmu.params.evaluation_concurrency=1;
 md.qmu.params.interval_type='forward';
 md.qmu.isdakota=1;
-md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
 
 %solve
-md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
+md=solve(md,StressbalanceSolutionEnum(),'overwrite','y');
 md.qmu.results=md.results.dakota;
 
Index: /issm/trunk/test/NightlyRun/test415.m
===================================================================
--- /issm/trunk/test/NightlyRun/test415.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test415.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 
 %control parameters
Index: /issm/trunk/test/NightlyRun/test415.py
===================================================================
--- /issm/trunk/test/NightlyRun/test415.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test415.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 
 #control parameters
Index: /issm/trunk/test/NightlyRun/test416.m
===================================================================
--- /issm/trunk/test/NightlyRun/test416.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test416.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 
 %control parameters
Index: /issm/trunk/test/NightlyRun/test416.py
===================================================================
--- /issm/trunk/test/NightlyRun/test416.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test416.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 
 #control parameters
Index: /issm/trunk/test/NightlyRun/test417.m
===================================================================
--- /issm/trunk/test/NightlyRun/test417.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test417.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.materials.rho_ice=10^7; %involved in the mass flux, make it easy
@@ -8,7 +8,7 @@
 
 %constrain all velocities to 1 m/yr, in the y-direction
-md.diagnostic.spcvx(:)=0;
-md.diagnostic.spcvy(:)=1;
-md.diagnostic.spcvz(:)=0;
+md.stressbalance.spcvx(:)=0;
+md.stressbalance.spcvy(:)=1;
+md.stressbalance.spcvz(:)=0;
 
 %Dakota options
@@ -48,7 +48,7 @@
 md.qmu.isdakota=1;
 
-md.diagnostic.reltol=10^-5; %tighten for qmu analyses
+md.stressbalance.reltol=10^-5; %tighten for qmu analyses
 
-md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
+md=solve(md,StressbalanceSolutionEnum(),'overwrite','y');
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test418.m
===================================================================
--- /issm/trunk/test/NightlyRun/test418.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test418.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
Index: /issm/trunk/test/NightlyRun/test419.m
===================================================================
--- /issm/trunk/test/NightlyRun/test419.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test419.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,5,1.);
-md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn');
+md=setflowequation(md,'SSA','../Exp/SquareHalfRight.exp','fill','HO');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test419.py
===================================================================
--- /issm/trunk/test/NightlyRun/test419.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test419.py	(revision 16137)
@@ -13,7 +13,7 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(5,1.)
-md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn')
+md=setflowequation(md,'SSA','../Exp/SquareHalfRight.exp','fill','HO')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -21,8 +21,8 @@
 field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test420.m
===================================================================
--- /issm/trunk/test/NightlyRun/test420.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test420.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
@@ -23,5 +23,5 @@
 %parameters
 md.qmu.params.direct=true;
-md.qmu.params.analysis_driver='diagnostic';
+md.qmu.params.analysis_driver='stressbalance';
 md.qmu.params.evaluation_concurrency=1;
 md.qmu.params.interval_type='forward';
@@ -29,8 +29,8 @@
 
 %imperative! 
-md.diagnostic.reltol=10^-5; %tighten for qmu analysese
+md.stressbalance.reltol=10^-5; %tighten for qmu analysese
 
 %solve
-md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
+md=solve(md,StressbalanceSolutionEnum(),'overwrite','y');
 md.qmu.results=md.results.dakota;
 
Index: /issm/trunk/test/NightlyRun/test421.m
===================================================================
--- /issm/trunk/test/NightlyRun/test421.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test421.m	(revision 16137)
@@ -3,16 +3,16 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,5,1.);
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn');
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','HO');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-08,2e-09,2e-05,1e-09,2e-09};
+field_tolerances={1e-07,1e-07,2e-05,1e-07,2e-07};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test421.py
===================================================================
--- /issm/trunk/test/NightlyRun/test421.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test421.py	(revision 16137)
@@ -13,16 +13,16 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(5,1.)
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn')
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','HO')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-08,2e-09,2e-05,1e-09,2e-09]
+field_tolerances=[1e-07,1e-07,2e-05,1e-07,2e-07]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test422.m
===================================================================
--- /issm/trunk/test/NightlyRun/test422.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test422.m	(revision 16137)
@@ -3,17 +3,17 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,5,1.);
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal');
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','SSA');
 md.cluster=generic('name',oshostname(),'np',3);
-md.diagnostic.reltol=0.4;
-md=solve(md,DiagnosticSolutionEnum());
+md.stressbalance.reltol=0.4;
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-06,1e-09,1e-09};
+field_tolerances={1e-07,2e-07,2e-06,2e-07,5e-07};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test422.py
===================================================================
--- /issm/trunk/test/NightlyRun/test422.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test422.py	(revision 16137)
@@ -13,17 +13,17 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(5,1.)
-md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','macayeal')
+md=setflowequation(md,'FS','../Exp/SquareHalfRight.exp','fill','SSA')
 md.cluster=generic('name',oshostname(),'np',3)
-md.diagnostic.reltol=0.4
-md=solve(md,DiagnosticSolutionEnum())
+md.stressbalance.reltol=0.4
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-09,1e-09,1e-06,1e-09,1e-09]
+field_tolerances=[1e-07,2e-07,1e-06,2e-07,1e-07]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test423.m
===================================================================
--- /issm/trunk/test/NightlyRun/test423.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test423.m	(revision 16137)
@@ -15,10 +15,10 @@
 md=setmask(md,flags,''); 
 md=parameterize(md,'../Par/RoundSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 
 md.transient.isthermal=0;
-md.transient.isprognostic=0;
-md.transient.isdiagnostic=1;
+md.transient.ismasstransport=0;
+md.transient.isstressbalance=1;
 md.transient.isgroundingline=1;
 
@@ -26,20 +26,21 @@
 md.groundingline.migration='AgressiveMigration';
 md=solve(md,TransientSolutionEnum());
-element_on_iceshelf_agressive=(md.results.TransientSolution.MaskElementonfloatingice);
+element_on_iceshelf_agressive=(md.results.TransientSolution.MaskGroundediceLevelset);
 vel_agressive=(md.results.TransientSolution.Vel);
 
 md.groundingline.migration='SoftMigration';
 md=solve(md,TransientSolutionEnum());
-element_on_iceshelf_soft=(md.results.TransientSolution.MaskElementonfloatingice);
+element_on_iceshelf_soft=(md.results.TransientSolution.MaskGroundediceLevelset);
 vel_soft=(md.results.TransientSolution.Vel);
 
+md.mask.groundedice_levelset=md.geometry.thickness + md.materials.rho_water/md.materials.rho_ice*md.geometry.bathymetry;
 md.groundingline.migration='SubelementMigration';
 md=solve(md,TransientSolutionEnum());
-element_on_iceshelf_subelement=(md.results.TransientSolution.GLlevelset);
+element_on_iceshelf_subelement=(md.results.TransientSolution.MaskGroundediceLevelset);
 vel_subelement=(md.results.TransientSolution.Vel);
 
 md.groundingline.migration='SubelementMigration2';
 md=solve(md,TransientSolutionEnum());
-element_on_iceshelf_subelement2=(md.results.TransientSolution.GLlevelset);
+element_on_iceshelf_subelement2=(md.results.TransientSolution.MaskGroundediceLevelset);
 vel_subelement2=(md.results.TransientSolution.Vel);
 
Index: /issm/trunk/test/NightlyRun/test423.py
===================================================================
--- /issm/trunk/test/NightlyRun/test423.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test423.py	(revision 16137)
@@ -26,10 +26,10 @@
 md=setmask(md,flags,'') 
 md=parameterize(md,'../Par/RoundSheetShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 
 md.transient.isthermal=False
-md.transient.isprognostic=False
-md.transient.isdiagnostic=True
+md.transient.ismasstransport=False
+md.transient.isstressbalance=True
 md.transient.isgroundingline=True
 
@@ -37,20 +37,21 @@
 md.groundingline.migration='AgressiveMigration'
 md=solve(md,TransientSolutionEnum())
-element_on_iceshelf_agressive=md.results.TransientSolution[0].MaskElementonfloatingice
+element_on_iceshelf_agressive=md.results.TransientSolution[0].MaskGroundediceLevelset
 vel_agressive=md.results.TransientSolution[0].Vel
 
 md.groundingline.migration='SoftMigration'
 md=solve(md,TransientSolutionEnum())
-element_on_iceshelf_soft=md.results.TransientSolution[0].MaskElementonfloatingice
+element_on_iceshelf_soft=md.results.TransientSolution[0].MaskGroundediceLevelset
 vel_soft=md.results.TransientSolution[0].Vel
 
+md.mask.groundedice_levelset=md.geometry.thickness + md.materials.rho_water/md.materials.rho_ice*md.geometry.bathymetry
 md.groundingline.migration='SubelementMigration'
 md=solve(md,TransientSolutionEnum())
-element_on_iceshelf_subelement=md.results.TransientSolution[0].GLlevelset
+element_on_iceshelf_subelement=md.results.TransientSolution[0].MaskGroundediceLevelset
 vel_subelement=md.results.TransientSolution[0].Vel
 
 md.groundingline.migration='SubelementMigration2'
 md=solve(md,TransientSolutionEnum())
-element_on_iceshelf_subelement2=md.results.TransientSolution[0].GLlevelset
+element_on_iceshelf_subelement2=md.results.TransientSolution[0].MaskGroundediceLevelset
 vel_subelement2=md.results.TransientSolution[0].Vel
 
Index: /issm/trunk/test/NightlyRun/test424.m
===================================================================
--- /issm/trunk/test/NightlyRun/test424.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test424.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.initialization.vx(:)=0.;
 md.initialization.vy(:)=0.;
@@ -10,5 +10,5 @@
 md.geometry.surface=md.geometry.bed+md.geometry.thickness;
 md.surfaceforcings.mass_balance(:)=100.;
-md.transient.isdiagnostic=0;
+md.transient.isstressbalance=0;
 md.transient.isgroundingline=1;
 md.groundingline.migration='AgressiveMigration';
@@ -28,12 +28,12 @@
 	(md.results.TransientSolution(1).Surface),...
 	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
 	(md.results.TransientSolution(2).Bed),...
 	(md.results.TransientSolution(2).Surface),...
 	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
 	(md.results.TransientSolution(3).Bed),...
 	(md.results.TransientSolution(3).Surface),...
 	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
 	};
Index: /issm/trunk/test/NightlyRun/test424.py
===================================================================
--- /issm/trunk/test/NightlyRun/test424.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test424.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','')
 md=parameterize(md,'../Par/SquareSheetShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.initialization.vx[:]=0.
 md.initialization.vy[:]=0.
@@ -20,5 +20,5 @@
 md.geometry.surface=md.geometry.bed+md.geometry.thickness
 md.surfaceforcings.mass_balance[:]=100.
-md.transient.isdiagnostic=False
+md.transient.isstressbalance=False
 md.transient.isgroundingline=True
 md.groundingline.migration='AgressiveMigration'
@@ -38,12 +38,12 @@
 	md.results.TransientSolution[0].Surface,\
 	md.results.TransientSolution[0].Thickness,\
-	md.results.TransientSolution[0].MaskElementonfloatingice,\
+	md.results.TransientSolution[0].MaskGroundediceLevelset,\
 	md.results.TransientSolution[1].Bed,\
 	md.results.TransientSolution[1].Surface,\
 	md.results.TransientSolution[1].Thickness,\
-	md.results.TransientSolution[1].MaskElementonfloatingice,\
+	md.results.TransientSolution[1].MaskGroundediceLevelset,\
 	md.results.TransientSolution[2].Bed,\
 	md.results.TransientSolution[2].Surface,\
 	md.results.TransientSolution[2].Thickness,\
-	md.results.TransientSolution[2].MaskElementonfloatingice,\
+	md.results.TransientSolution[2].MaskGroundediceLevelset,\
 	]
Index: /issm/trunk/test/NightlyRun/test425.m
===================================================================
--- /issm/trunk/test/NightlyRun/test425.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test425.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.initialization.vx(:)=0.;
 md.initialization.vy(:)=0.;
@@ -10,5 +10,5 @@
 md.geometry.surface=md.geometry.bed+md.geometry.thickness;
 md.surfaceforcings.mass_balance(:)=-150.;
-md.transient.isdiagnostic=0;
+md.transient.isstressbalance=0;
 md.transient.isgroundingline=1;
 md.groundingline.migration='SoftMigration';
@@ -28,12 +28,12 @@
 	(md.results.TransientSolution(1).Surface),...
 	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
 	(md.results.TransientSolution(2).Bed),...
 	(md.results.TransientSolution(2).Surface),...
 	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
 	(md.results.TransientSolution(3).Bed),...
 	(md.results.TransientSolution(3).Surface),...
 	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
 	};
Index: /issm/trunk/test/NightlyRun/test425.py
===================================================================
--- /issm/trunk/test/NightlyRun/test425.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test425.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=setmask(md,'../Exp/SquareShelf.exp','')
 md=parameterize(md,'../Par/SquareSheetShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.initialization.vx[:]=0.
 md.initialization.vy[:]=0.
@@ -20,5 +20,5 @@
 md.geometry.surface=md.geometry.bed+md.geometry.thickness
 md.surfaceforcings.mass_balance[:]=-150.
-md.transient.isdiagnostic=False
+md.transient.isstressbalance=False
 md.transient.isgroundingline=True
 md.groundingline.migration='SoftMigration'
@@ -38,12 +38,12 @@
 	md.results.TransientSolution[0].Surface,\
 	md.results.TransientSolution[0].Thickness,\
-	md.results.TransientSolution[0].MaskElementonfloatingice,\
+	md.results.TransientSolution[0].MaskGroundediceLevelset,\
 	md.results.TransientSolution[1].Bed,\
 	md.results.TransientSolution[1].Surface,\
 	md.results.TransientSolution[1].Thickness,\
-	md.results.TransientSolution[1].MaskElementonfloatingice,\
+	md.results.TransientSolution[1].MaskGroundediceLevelset,\
 	md.results.TransientSolution[2].Bed,\
 	md.results.TransientSolution[2].Surface,\
 	md.results.TransientSolution[2].Thickness,\
-	md.results.TransientSolution[2].MaskElementonfloatingice,\
+	md.results.TransientSolution[2].MaskGroundediceLevelset,\
 	]
Index: /issm/trunk/test/NightlyRun/test426.m
===================================================================
--- /issm/trunk/test/NightlyRun/test426.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test426.m	(revision 16137)
@@ -10,6 +10,6 @@
 md.surfaceforcings.mass_balance(:)=100.;
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
-md.transient.isdiagnostic=0;
+md=setflowequation(md,'SSA','all');
+md.transient.isstressbalance=0;
 md.transient.isgroundingline=1;
 md.groundingline.migration='AgressiveMigration';
@@ -23,18 +23,18 @@
 	'Bed3','Surface3','Thickness3','Floatingice3'};
 field_tolerances={1e-13,1e-13,1e-13,1e-13,...
-	1e-11,1e-10,1e-11,1e-13,...
-	1e-10,1e-10,1e-10,1e-13};
+	1e-11,1e-10,1e-11,1.25e-11,...
+	1e-10,1e-10,1e-10,1.15e-11};
 field_values={...
 	(md.results.TransientSolution(1).Bed),...
 	(md.results.TransientSolution(1).Surface),...
 	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
 	(md.results.TransientSolution(2).Bed),...
 	(md.results.TransientSolution(2).Surface),...
 	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
 	(md.results.TransientSolution(3).Bed),...
 	(md.results.TransientSolution(3).Surface),...
 	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
 	};
Index: /issm/trunk/test/NightlyRun/test426.py
===================================================================
--- /issm/trunk/test/NightlyRun/test426.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test426.py	(revision 16137)
@@ -20,6 +20,6 @@
 md.surfaceforcings.mass_balance[:]=100.
 md.extrude(3,1.);
-md=setflowequation(md,'macayeal','all');
-md.transient.isdiagnostic=False
+md=setflowequation(md,'SSA','all');
+md.transient.isstressbalance=False
 md.transient.isgroundingline=True
 md.groundingline.migration='AgressiveMigration'
@@ -32,19 +32,21 @@
 	'Bed2','Surface2','Thickness2','Floatingice2',\
 	'Bed3','Surface3','Thickness3','Floatingice3']
+
 field_tolerances=[1e-13,1e-13,1e-13,1e-13,\
-	1e-11,1e-10,1e-11,1e-13,\
-	1e-10,1e-10,1e-10,1e-13]
+	1e-11,1e-10,1e-11,1.25e-11,\
+	1e-10,1e-10,1e-10,1.15e-11]
+
 field_values=[\
 	md.results.TransientSolution[0].Bed,\
 	md.results.TransientSolution[0].Surface,\
 	md.results.TransientSolution[0].Thickness,\
-	md.results.TransientSolution[0].MaskElementonfloatingice,\
+	md.results.TransientSolution[0].MaskGroundediceLevelset,\
 	md.results.TransientSolution[1].Bed,\
 	md.results.TransientSolution[1].Surface,\
 	md.results.TransientSolution[1].Thickness,\
-	md.results.TransientSolution[1].MaskElementonfloatingice,\
+	md.results.TransientSolution[1].MaskGroundediceLevelset,\
 	md.results.TransientSolution[2].Bed,\
 	md.results.TransientSolution[2].Surface,\
 	md.results.TransientSolution[2].Thickness,\
-	md.results.TransientSolution[2].MaskElementonfloatingice,\
+	md.results.TransientSolution[2].MaskGroundediceLevelset,\
 	]
Index: /issm/trunk/test/NightlyRun/test427.m
===================================================================
--- /issm/trunk/test/NightlyRun/test427.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test427.m	(revision 16137)
@@ -8,9 +8,9 @@
 md.geometry.thickness(:)=1300;
 md.geometry.surface=md.geometry.bed+md.geometry.thickness;
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md=extrude(md,3,1.);
 
 md.surfaceforcings.mass_balance(:)=-150;
-md.transient.isdiagnostic=0;
+md.transient.isstressbalance=0;
 md.transient.isgroundingline=1;
 md.groundingline.migration='SoftMigration';
@@ -29,12 +29,12 @@
 	(md.results.TransientSolution(1).Surface),...
 	(md.results.TransientSolution(1).Thickness),...
-	(md.results.TransientSolution(1).MaskElementonfloatingice),...
+	(md.results.TransientSolution(1).MaskGroundediceLevelset),...
 	(md.results.TransientSolution(2).Bed),...
 	(md.results.TransientSolution(2).Surface),...
 	(md.results.TransientSolution(2).Thickness),...
-	(md.results.TransientSolution(2).MaskElementonfloatingice),...
+	(md.results.TransientSolution(2).MaskGroundediceLevelset),...
 	(md.results.TransientSolution(3).Bed),...
 	(md.results.TransientSolution(3).Surface),...
 	(md.results.TransientSolution(3).Thickness),...
-	(md.results.TransientSolution(3).MaskElementonfloatingice),...
+	(md.results.TransientSolution(3).MaskGroundediceLevelset),...
 	};
Index: /issm/trunk/test/NightlyRun/test427.py
===================================================================
--- /issm/trunk/test/NightlyRun/test427.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test427.py	(revision 16137)
@@ -18,9 +18,9 @@
 md.geometry.thickness[:]=1300
 md.geometry.surface=md.geometry.bed+md.geometry.thickness
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.extrude(3,1.)
 
 md.surfaceforcings.mass_balance[:]=-150
-md.transient.isdiagnostic=False
+md.transient.isstressbalance=False
 md.transient.isgroundingline=True
 md.groundingline.migration='SoftMigration'
@@ -39,12 +39,12 @@
 	md.results.TransientSolution[0].Surface,\
 	md.results.TransientSolution[0].Thickness,\
-	md.results.TransientSolution[0].MaskElementonfloatingice,\
+	md.results.TransientSolution[0].MaskGroundediceLevelset,\
 	md.results.TransientSolution[1].Bed,\
 	md.results.TransientSolution[1].Surface,\
 	md.results.TransientSolution[1].Thickness,\
-	md.results.TransientSolution[1].MaskElementonfloatingice,\
+	md.results.TransientSolution[1].MaskGroundediceLevelset,\
 	md.results.TransientSolution[2].Bed,\
 	md.results.TransientSolution[2].Surface,\
 	md.results.TransientSolution[2].Thickness,\
-	md.results.TransientSolution[2].MaskElementonfloatingice,\
+	md.results.TransientSolution[2].MaskGroundediceLevelset,\
 	]
Index: /issm/trunk/test/NightlyRun/test428.m
===================================================================
--- /issm/trunk/test/NightlyRun/test428.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test428.m	(revision 16137)
@@ -2,9 +2,9 @@
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
-md.diagnostic.isnewton=1;
-md.diagnostic.restol=0.0001;
+md=setflowequation(md,'SSA','all');
+md.stressbalance.isnewton=1;
+md.stressbalance.restol=0.0001;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -12,7 +12,7 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test428.py
===================================================================
--- /issm/trunk/test/NightlyRun/test428.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test428.py	(revision 16137)
@@ -12,9 +12,9 @@
 md=setmask(md,'../Exp/SquareShelf.exp','')
 md=parameterize(md,'../Par/SquareSheetShelf.py')
-md=setflowequation(md,'macayeal','all')
-md.diagnostic.isnewton=1
-md.diagnostic.restol=0.0001
+md=setflowequation(md,'SSA','all')
+md.stressbalance.isnewton=1
+md.stressbalance.restol=0.0001
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -22,7 +22,7 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test429.m
===================================================================
--- /issm/trunk/test/NightlyRun/test429.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test429.m	(revision 16137)
@@ -3,18 +3,18 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,5,1.);
-md=setflowequation(md,'pattyn','all');
-md.diagnostic.isnewton=1;
-md.diagnostic.restol=0.0001;
+md=setflowequation(md,'HO','all');
+md.stressbalance.isnewton=1;
+md.stressbalance.restol=0.0001;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
+field_tolerances={2e-06,1e-06,1e-06,1e-06,1e-06};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test429.py
===================================================================
--- /issm/trunk/test/NightlyRun/test429.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test429.py	(revision 16137)
@@ -13,18 +13,18 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(5,1.)
-md=setflowequation(md,'pattyn','all')
-md.diagnostic.isnewton=1
-md.diagnostic.restol=0.0001
+md=setflowequation(md,'HO','all')
+md.stressbalance.isnewton=1
+md.stressbalance.restol=0.0001
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09]
+field_tolerances=[2e-06,2e-06,1e-06,2e-06,1e-06]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: sm/trunk/test/NightlyRun/test430.m
===================================================================
--- /issm/trunk/test/NightlyRun/test430.m	(revision 16136)
+++ 	(revision )
@@ -1,20 +1,0 @@
-md=triangle(model(),'../Exp/Square.exp',180000.);
-md=setmask(md,'../Exp/SquareShelf.exp','');
-md=parameterize(md,'../Par/SquareSheetShelf.par');
-md=extrude(md,3,1.);
-md=setflowequation(md,'stokes','all');
-md.diagnostic.isnewton=1;
-md.diagnostic.restol=0.0001;
-md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
-
-%Fields and tolerances to track changes
-field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
-field_tolerances={1e-07,1e-07,1e-06,1e-07,1e-07};
-field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
-	};
Index: sm/trunk/test/NightlyRun/test430.py
===================================================================
--- /issm/trunk/test/NightlyRun/test430.py	(revision 16136)
+++ 	(revision )
@@ -1,30 +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/Square.exp',180000.)
-md=setmask(md,'../Exp/SquareShelf.exp','')
-md=parameterize(md,'../Par/SquareSheetShelf.py')
-md.extrude(3,1.)
-md=setflowequation(md,'stokes','all')
-md.diagnostic.isnewton=1
-md.diagnostic.restol=0.0001
-md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
-
-#Fields and tolerances to track changes
-field_names     =['Vx','Vy','Vz','Vel','Pressure']
-field_tolerances=[1e-07,1e-07,1e-06,1e-07,1e-07]
-field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
-	]
Index: /issm/trunk/test/NightlyRun/test431.m
===================================================================
--- /issm/trunk/test/NightlyRun/test431.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test431.m	(revision 16137)
@@ -3,9 +3,10 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_step=0.;
 md.thermal.isenthalpy=1;
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
+md.initialization.watercolumn=zeros(md.mesh.numberofvertices,1);
 md=solve(md,SteadystateSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test431.py
===================================================================
--- /issm/trunk/test/NightlyRun/test431.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test431.py	(revision 16137)
@@ -13,9 +13,10 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(3,2.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_step=0.
 md.thermal.isenthalpy=1
 md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
 md=solve(md,SteadystateSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test432.m
===================================================================
--- /issm/trunk/test/NightlyRun/test432.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test432.m	(revision 16137)
@@ -3,14 +3,15 @@
 md=parameterize(md,'../Par/SquareSheetShelf.par');
 md=extrude(md,3,2.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_step=0.;
 md.thermal.isenthalpy=1;
 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','Water fraction','Enthalpy'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-13,1e-10,1e-10,1e-10};
+field_tolerances={2e-09,1e-09,1e-09,1e-09,1e-13,1e-10,1e-10,1e-10};
 field_values={...
 	(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test432.py
===================================================================
--- /issm/trunk/test/NightlyRun/test432.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test432.py	(revision 16137)
@@ -13,9 +13,10 @@
 md=parameterize(md,'../Par/SquareSheetShelf.py')
 md.extrude(3,2.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_step=0.
 md.thermal.isenthalpy=1
 md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.watercolumn=numpy.zeros((md.mesh.numberofvertices,1))
 md=solve(md,SteadystateSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test433.m
===================================================================
--- /issm/trunk/test/NightlyRun/test433.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test433.m	(revision 16137)
@@ -15,11 +15,11 @@
 md=setmask(md,flags,''); 
 md=parameterize(md,'../Par/RoundSheetShelf.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md=extrude(md,3,1);
 md.cluster=generic('name',oshostname(),'np',3);
 
 md.transient.isthermal=0;
-md.transient.isprognostic=0;
-md.transient.isdiagnostic=0;
+md.transient.ismasstransport=0;
+md.transient.isstressbalance=0;
 md.transient.isgroundingline=1;
 
@@ -27,16 +27,20 @@
 md.groundingline.migration='AgressiveMigration';
 md=solve(md,TransientSolutionEnum());
-element_on_iceshelf_agressive=(md.results.TransientSolution.MaskElementonfloatingice);
+element_on_iceshelf_agressive=(md.results.TransientSolution.MaskGroundediceLevelset);
 
 md.groundingline.migration='SoftMigration';
 md=solve(md,TransientSolutionEnum());
-element_on_iceshelf_soft=(md.results.TransientSolution.MaskElementonfloatingice);
+element_on_iceshelf_soft=(md.results.TransientSolution.MaskGroundediceLevelset);
 
 md.groundingline.migration='SubelementMigration';
 md=solve(md,TransientSolutionEnum());
-element_on_iceshelf_subelement=(md.results.TransientSolution.GLlevelset);
+element_on_iceshelf_subelement=(md.results.TransientSolution.MaskGroundediceLevelset);
+
+md.groundingline.migration='SubelementMigration2';
+md=solve(md,TransientSolutionEnum());
+element_on_iceshelf_subelement2=(md.results.TransientSolution.MaskGroundediceLevelset);
 
 %Fields and tolerances to track changes
-field_names     ={'ElementOnIceShelfAgressive','ElementOnIceShelfSoft','ElementOnIceShelfSubelement'};
-field_tolerances={1e-13,1e-13,1e-13};
-field_values={element_on_iceshelf_agressive,element_on_iceshelf_soft,element_on_iceshelf_subelement};
+field_names     ={'ElementOnIceShelfAgressive','ElementOnIceShelfSoft','ElementOnIceShelfSubelement','ElementOnIceShelfSubelement'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
+field_values={element_on_iceshelf_agressive,element_on_iceshelf_soft,element_on_iceshelf_subelement,element_on_iceshelf_subelement2};
Index: /issm/trunk/test/NightlyRun/test433.py
===================================================================
--- /issm/trunk/test/NightlyRun/test433.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test433.py	(revision 16137)
@@ -26,11 +26,11 @@
 md=setmask(md,flags,'') 
 md=parameterize(md,'../Par/RoundSheetShelf.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.extrude(3,1.)
 md.cluster=generic('name',oshostname(),'np',3)
 
 md.transient.isthermal=False
-md.transient.isprognostic=False
-md.transient.isdiagnostic=False
+md.transient.ismasstransport=False
+md.transient.isstressbalance=False
 md.transient.isgroundingline=True
 
@@ -38,13 +38,13 @@
 md.groundingline.migration='AgressiveMigration'
 md=solve(md,TransientSolutionEnum())
-element_on_iceshelf_agressive=md.results.TransientSolution[0].MaskElementonfloatingice
+element_on_iceshelf_agressive=md.results.TransientSolution[0].MaskGroundediceLevelset
 
 md.groundingline.migration='SoftMigration'
 md=solve(md,TransientSolutionEnum())
-element_on_iceshelf_soft=md.results.TransientSolution[0].MaskElementonfloatingice
+element_on_iceshelf_soft=md.results.TransientSolution[0].MaskGroundediceLevelset
 
 md.groundingline.migration='SubelementMigration'
 md=solve(md,TransientSolutionEnum())
-element_on_iceshelf_subelement=md.results.TransientSolution[0].GLlevelset
+element_on_iceshelf_subelement=md.results.TransientSolution[0].MaskGroundediceLevelset
 
 #Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test434.m
===================================================================
--- /issm/trunk/test/NightlyRun/test434.m	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test434.m	(revision 16137)
@@ -0,0 +1,18 @@
+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,'L1L2','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,StressbalanceSolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'Vx','Vy','Vz','Vel','Pressure'};
+field_tolerances={1e-06,1e-06,2e-07,1e-06,1e-07};
+field_values={...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
Index: /issm/trunk/test/NightlyRun/test434.py
===================================================================
--- /issm/trunk/test/NightlyRun/test434.py	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test434.py	(revision 16137)
@@ -0,0 +1,28 @@
+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/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(4,1.)
+md=setflowequation(md,'L1L2','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,StressbalanceSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-06,1e-06,1e-06,1e-06,1e-07]
+field_values=[\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
+	]
Index: /issm/trunk/test/NightlyRun/test450.m
===================================================================
--- /issm/trunk/test/NightlyRun/test450.m	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test450.m	(revision 16137)
@@ -0,0 +1,21 @@
+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.cluster=generic('name',oshostname(),'np',3);
+
+field_names={};
+field_tolerances={};
+field_values={};
+for i={'P1bubble','P1bubblecondensed','P2'}
+	md.flowequation.fe_SSA=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{:},1e-12,1e-13,1e-13,1e-13};
+	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/test450.py
===================================================================
--- /issm/trunk/test/NightlyRun/test450.py	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test450.py	(revision 16137)
@@ -0,0 +1,30 @@
+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/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+field_names=[]
+field_tolerances=[]
+field_values=[]
+for i in ['P1bubble','P1bubblecondensed','P2']:
+	md.flowequation.fe_SSA=i
+	md=solve(md,StressbalanceSolutionEnum())
+	field_names     =field_names+['Vx'+i,'Vy'+i,'Vel'+i,'Pressure'+i]
+	field_tolerances=field_tolerances+[1e-12,1e-13,1e-13,1e-13]
+	field_values=field_values+[\
+		md.results.StressbalanceSolution.Vx,\
+		md.results.StressbalanceSolution.Vy,\
+		md.results.StressbalanceSolution.Vel,\
+		md.results.StressbalanceSolution.Pressure,\
+		]
Index: /issm/trunk/test/NightlyRun/test455.m
===================================================================
--- /issm/trunk/test/NightlyRun/test455.m	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test455.m	(revision 16137)
@@ -0,0 +1,23 @@
+md=triangle(model(),'../Exp/Square.exp',180000.);
+md=setmask(md,'../Exp/SquareShelf.exp','');
+md=parameterize(md,'../Par/SquareSheetShelf.par');
+md=extrude(md,5,1.);
+md=setflowequation(md,'HO','all');
+md.cluster=generic('name',oshostname(),'np',3);
+
+field_names={};
+field_tolerances={};
+field_values={};
+for i={'P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2'}
+	md.flowequation.fe_HO=i{1};
+	md=solve(md,StressbalanceSolutionEnum());
+	field_names     ={field_names{:},['Vx' i{1}],['Vy' i{1}],['Vz' i{1}],['Vel' i{1}],['Pressure' i{1}]};
+	field_tolerances={field_tolerances{:},1e-08,1e-08,1e-08,1e-08,1e-13};
+	field_values={field_values{:},...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
+	};
+end
Index: /issm/trunk/test/NightlyRun/test455.py
===================================================================
--- /issm/trunk/test/NightlyRun/test455.py	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test455.py	(revision 16137)
@@ -0,0 +1,32 @@
+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/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(5,1.)
+md=setflowequation(md,'HO','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+field_names=[]
+field_tolerances=[]
+field_values=[]
+for i in ['P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2']:
+	md.flowequation.fe_HO=i
+	md=solve(md,StressbalanceSolutionEnum())
+	field_names     =field_names+['Vx'+i,'Vy'+i,'Vz'+i,'Vel'+i,'Pressure'+i]
+	field_tolerances=field_tolerances+[1e-08,1e-08,1e-08,1e-08,1e-13]
+	field_values=field_values+[\
+			md.results.StressbalanceSolution.Vx,\
+			md.results.StressbalanceSolution.Vy,\
+			md.results.StressbalanceSolution.Vz,\
+			md.results.StressbalanceSolution.Vel,\
+			md.results.StressbalanceSolution.Pressure,\
+			]
Index: /issm/trunk/test/NightlyRun/test501.m
===================================================================
--- /issm/trunk/test/NightlyRun/test501.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test501.m	(revision 16137)
@@ -2,7 +2,7 @@
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -10,7 +10,7 @@
 field_tolerances={1e-13,1e-13,1e-13,1e-13};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test501.py
===================================================================
--- /issm/trunk/test/NightlyRun/test501.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test501.py	(revision 16137)
@@ -11,7 +11,7 @@
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
 md=parameterize(md,'../Par/Pig.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 # Fields and tolerances to track changes
@@ -19,7 +19,7 @@
 field_tolerances=[1e-13,1e-13,1e-13,1e-13]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test502.m
===================================================================
--- /issm/trunk/test/NightlyRun/test502.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test502.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,3,0.9);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test502.py
===================================================================
--- /issm/trunk/test/NightlyRun/test502.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test502.py	(revision 16137)
@@ -12,7 +12,7 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(3,0.9)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 # Fields and tolerances to track changes
@@ -20,8 +20,8 @@
 field_tolerances=[1e-08,1e-08,1e-08,1e-08,1e-08]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test503.m
===================================================================
--- /issm/trunk/test/NightlyRun/test503.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test503.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,3,0.9);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'FS','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,8 +11,8 @@
 field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09};
 field_values={...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy),...
-	(md.results.DiagnosticSolution.Vz),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy),...
+	(md.results.StressbalanceSolution.Vz),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Pressure),...
 	};
Index: /issm/trunk/test/NightlyRun/test503.py
===================================================================
--- /issm/trunk/test/NightlyRun/test503.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test503.py	(revision 16137)
@@ -12,7 +12,7 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(3,0.9)
-md=setflowequation(md,'stokes','all')
+md=setflowequation(md,'FS','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 # Fields and tolerances to track changes
@@ -20,8 +20,8 @@
 field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09]
 field_values=[\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
-	md.results.DiagnosticSolution.Vz,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Pressure,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
+	md.results.StressbalanceSolution.Vz,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Pressure,\
 	]
Index: /issm/trunk/test/NightlyRun/test504.m
===================================================================
--- /issm/trunk/test/NightlyRun/test504.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test504.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test504.py
===================================================================
--- /issm/trunk/test/NightlyRun/test504.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test504.py	(revision 16137)
@@ -11,5 +11,5 @@
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
 md=parameterize(md,'../Par/Pig.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test505.m
===================================================================
--- /issm/trunk/test/NightlyRun/test505.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test505.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
@@ -11,5 +11,5 @@
 				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
 field_tolerances={1e-12,1e-12,1e-10,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
-						1e-13,1e-12,1e-10,1e-12,1e-13,1e-11,1e-11,1e-12,1e-11,1e-8};
+						1e-13,1e-12,1e-10,1e-12,1e-13,1e-11,1e-11,2e-12,1e-11,1e-8};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test505.py
===================================================================
--- /issm/trunk/test/NightlyRun/test505.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test505.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
@@ -20,5 +20,5 @@
 				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2']
 field_tolerances=[1e-12,1e-12,1e-10,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13, \
-						1e-13,1e-12,1e-10,1e-12,1e-13,1e-11,1e-11,1e-12,1e-11,1e-8]
+						1e-13,1e-12,1e-10,1e-12,1e-13,1e-11,1e-11,2e-12,1e-11,1e-8]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test506.m
===================================================================
--- /issm/trunk/test/NightlyRun/test506.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test506.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,2,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
@@ -10,6 +10,6 @@
 field_names     ={'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', ...
 				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2'};
-field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,1e-12,1e-11,1e-12,1e-12,...
-						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,1e-08};
+field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,2e-12,1e-11,1e-12,1e-09,...
+						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,2e-08};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test506.py
===================================================================
--- /issm/trunk/test/NightlyRun/test506.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test506.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(2,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
@@ -19,6 +19,6 @@
 field_names     =['Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
 				      'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2']
-field_tolerances=[1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,1e-12,1e-11,1e-12,1e-12,\
-						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,1e-08]
+field_tolerances=[1e-10,1e-10,1e-10,1e-10,1e-12,1e-11,2e-12,1e-11,1e-12,1e-09,\
+						1e-11,1e-11,1e-09,1e-11,1e-11,1e-10,1e-11,1e-10,1e-11,2e-08]
 field_values=[\
 	md.results.TransientSolution[0].Vx,\
Index: /issm/trunk/test/NightlyRun/test507.m
===================================================================
--- /issm/trunk/test/NightlyRun/test507.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test507.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,2,1.);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'FS','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test507.py
===================================================================
--- /issm/trunk/test/NightlyRun/test507.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test507.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(2,1.)
-md=setflowequation(md,'stokes','all')
+md=setflowequation(md,'FS','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,TransientSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test508.m
===================================================================
--- /issm/trunk/test/NightlyRun/test508.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test508.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,4,1.1);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_step=0.;
@@ -10,5 +10,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-08};
+field_tolerances={7.85e-09,8.15e-09,1.5e-08,8.5e-09,1e-09,1e-09,1e-07};
 field_values={...
 	(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test508.py
===================================================================
--- /issm/trunk/test/NightlyRun/test508.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test508.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(4,1.1)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_step=0.
@@ -19,5 +19,5 @@
 # Fields and tolerances to track changes
 field_names     =['Vx','Vy','Vz','Vel','Pressure','Temperature','BasalforcingsMeltingRate']
-field_tolerances=[1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-08]
+field_tolerances=[7.85e-09,8.15e-09,1.5e-08,8.5e-09,1e-09,1e-09,1e-07]
 field_values=[\
 	md.results.SteadystateSolution.Vx,\
Index: /issm/trunk/test/NightlyRun/test509.m
===================================================================
--- /issm/trunk/test/NightlyRun/test509.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test509.m	(revision 16137)
@@ -3,7 +3,8 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_step=0.;
+md.thermal.penalty_threshold=7;
 md=solve(md,SteadystateSolutionEnum());
 
Index: /issm/trunk/test/NightlyRun/test509.py
===================================================================
--- /issm/trunk/test/NightlyRun/test509.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test509.py	(revision 16137)
@@ -12,7 +12,8 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_step=0.
+md.thermal.penalty_threshold=7
 md=solve(md,SteadystateSolutionEnum())
 
Index: /issm/trunk/test/NightlyRun/test510.m
===================================================================
--- /issm/trunk/test/NightlyRun/test510.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test510.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,2,1.);
-md=setflowequation(md,'stokes','all');
+md=setflowequation(md,'FS','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_step=0.;
Index: /issm/trunk/test/NightlyRun/test510.py
===================================================================
--- /issm/trunk/test/NightlyRun/test510.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test510.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(2,1.)
-md=setflowequation(md,'stokes','all')
+md=setflowequation(md,'FS','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md.timestepping.time_step=0.
Index: /issm/trunk/test/NightlyRun/test511.m
===================================================================
--- /issm/trunk/test/NightlyRun/test511.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test511.m	(revision 16137)
@@ -1,3 +1,3 @@
-md=triangle(model(),'../Exp/Pig.exp',10000.);
+md=triangle(model(),'../Exp/Pig.exp',11000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
@@ -7,6 +7,6 @@
 md.geometry.surface=md.geometry.bed+md.geometry.thickness;
 md=extrude(md,3,1.);
-md=setflowequation(md,'stokes','all');
-md=extract(md,md.mask.elementonfloatingice);
+md=setflowequation(md,'FS','all');
+md=extract(md,md.mask.groundedice_levelset<0.);
 
 %control parameters
@@ -24,5 +24,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -30,10 +30,10 @@
 field_tolerances={1e-11,1e-12,1e-12,1e-09,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	(md.results.DiagnosticSolution.J),...
-	(md.results.DiagnosticSolution.MaterialsRheologyB),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
+	(md.results.StressbalanceSolution.Gradient1),...
+	(md.results.StressbalanceSolution.J),...
+	(md.results.StressbalanceSolution.MaterialsRheologyB),...
+	(md.results.StressbalanceSolution.Pressure),...
+	(md.results.StressbalanceSolution.Vel),...
+	(md.results.StressbalanceSolution.Vx),...
+	(md.results.StressbalanceSolution.Vy)
 };
Index: /issm/trunk/test/NightlyRun/test511.py
===================================================================
--- /issm/trunk/test/NightlyRun/test511.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test511.py	(revision 16137)
@@ -9,5 +9,5 @@
 from MatlabFuncs import *
 
-md=triangle(model(),'../Exp/Pig.exp',10000.)
+md=triangle(model(),'../Exp/Pig.exp',11000.)
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
 md=parameterize(md,'../Par/Pig.py')
@@ -17,6 +17,6 @@
 md.geometry.surface=md.geometry.bed+md.geometry.thickness
 md.extrude(3,1.)
-md=setflowequation(md,'stokes','all')
-md=md.extract(md.mask.elementonfloatingice)
+md=setflowequation(md,'FS','all')
+md=md.extract(md.mask.groundedice_levelset<0.)
 
 #control parameters
@@ -35,5 +35,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -41,10 +41,10 @@
 field_tolerances=[1e-11,1e-12,1e-12,1e-09,1e-12,1e-12,1e-12,1e-12,1e-12,1e-12]
 field_values=[\
-	md.results.DiagnosticSolution.Gradient1,\
-	md.results.DiagnosticSolution.J,\
-	md.results.DiagnosticSolution.MaterialsRheologyB,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy,\
+	md.results.StressbalanceSolution.Gradient1,\
+	md.results.StressbalanceSolution.J,\
+	md.results.StressbalanceSolution.MaterialsRheologyB,\
+	md.results.StressbalanceSolution.Pressure,\
+	md.results.StressbalanceSolution.Vel,\
+	md.results.StressbalanceSolution.Vx,\
+	md.results.StressbalanceSolution.Vy,\
 ]
Index: /issm/trunk/test/NightlyRun/test512.m
===================================================================
--- /issm/trunk/test/NightlyRun/test512.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test512.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 
 %control parameters
@@ -19,5 +19,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum());
+md=solve(md,StressbalanceSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -25,10 +25,10 @@
 field_tolerances={1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11};
 field_values={...
-	(md.results.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
-	(md.results.DiagnosticSolution.FrictionCoefficient),...
-	(md.results.DiagnosticSolution.Pressure),...
-	(md.results.DiagnosticSolution.Vel),...
-	(md.results.DiagnosticSolution.Vx),...
-	(md.results.DiagnosticSolution.Vy)
+	(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/test512.py
===================================================================
--- /issm/trunk/test/NightlyRun/test512.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test512.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 
 # control parameters
@@ -31,5 +31,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,DiagnosticSolutionEnum())
+md=solve(md,StressbalanceSolutionEnum())
 
 # Fields and tolerances to track changes
@@ -37,10 +37,10 @@
 field_tolerances=[1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11,1e-11]
 field_values=[\
-	md.results.DiagnosticSolution.Gradient1,\
-	md.results.DiagnosticSolution.J,\
-	md.results.DiagnosticSolution.FrictionCoefficient,\
-	md.results.DiagnosticSolution.Pressure,\
-	md.results.DiagnosticSolution.Vel,\
-	md.results.DiagnosticSolution.Vx,\
-	md.results.DiagnosticSolution.Vy
+	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/test513.m
===================================================================
--- /issm/trunk/test/NightlyRun/test513.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test513.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 
 %control parameters
@@ -25,5 +25,5 @@
 %Fields and tolerances to track changes
 field_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-10,1e-10,1e-10,1e-10,1e-6,1e-6,1e-6,1e-6,1e-6,1e-06};
+field_tolerances={2e-10,2e-10,1e-10,1e-10,1e-6,1e-6,1e-6,1e-6,1e-6,1e-06};
 field_values={...
 	(md.results.SteadystateSolution.Gradient1),...
Index: /issm/trunk/test/NightlyRun/test513.py
===================================================================
--- /issm/trunk/test/NightlyRun/test513.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test513.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 
 # control parameters
@@ -36,5 +36,5 @@
 # Fields and tolerances to track changes
 field_names     =['Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsMeltingRate']
-field_tolerances=[1e-10,1e-10,1e-10,1e-10,1e-6,1e-6,1e-6,1e-6,1e-6,1e-06]
+field_tolerances=[2e-10,2e-10,1e-10,1e-10,1e-6,1e-6,1e-6,1e-6,1e-6,1e-06]
 field_values=[\
 	md.results.SteadystateSolution.Gradient1,\
Index: /issm/trunk/test/NightlyRun/test514.m
===================================================================
--- /issm/trunk/test/NightlyRun/test514.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test514.m	(revision 16137)
@@ -44,13 +44,5 @@
 
 %Fields and tolerances to track changes
-field_names     ={'x1y1x2y2x3y3x4y4x5y5x6y6'  'x7y7' };
-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};
-field_values={...
-	x1, y1,...
-	y2, y2,...
-	y3, y3,...
-	y4, y4,...
-	y5, y5,...
-	y6, y6,...
-	y7, y7,...
-	};
+field_names      = {'x1' ,'y1' ,'x2' ,'y2' ,'x3' ,'y3' ,'x4' ,'y4' ,'x5' ,'y5' ,'x6' ,'y6' ,'x7' ,'y7' };
+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};
+field_values     = { x1  ,y1   ,y2   ,y2   ,y3   ,y3   ,y4   ,y4   ,y5   ,y5   ,y6   ,y6   ,y7   ,y7   };
Index: /issm/trunk/test/NightlyRun/test515.m
===================================================================
--- /issm/trunk/test/NightlyRun/test515.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test515.m	(revision 16137)
@@ -3,9 +3,9 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.thermal.stabilization=2;
 md.cluster=generic('name',oshostname(),'np',3);
-md.transient.isdiagnostic=0;
-md.transient.isprognostic=0;
+md.transient.isstressbalance=0;
+md.transient.ismasstransport=0;
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
Index: /issm/trunk/test/NightlyRun/test515.py
===================================================================
--- /issm/trunk/test/NightlyRun/test515.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test515.py	(revision 16137)
@@ -12,9 +12,9 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.thermal.stabilization=2
 md.cluster=generic('name',oshostname(),'np',3)
-md.transient.isdiagnostic=False
-md.transient.isprognostic=False
+md.transient.isstressbalance=False
+md.transient.ismasstransport=False
 md.transient.isthermal=True
 md.transient.isgroundingline=False
Index: /issm/trunk/test/NightlyRun/test516.m
===================================================================
--- /issm/trunk/test/NightlyRun/test516.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test516.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/Pig.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.thermal.stabilization=2;
 md.cluster=generic('name',oshostname(),'np',3);
Index: /issm/trunk/test/NightlyRun/test516.py
===================================================================
--- /issm/trunk/test/NightlyRun/test516.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test516.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/Pig.py')
 md.extrude(3,1.)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.thermal.stabilization=2
 md.cluster=generic('name',oshostname(),'np',3)
Index: /issm/trunk/test/NightlyRun/test530.m
===================================================================
--- /issm/trunk/test/NightlyRun/test530.m	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test530.m	(revision 16137)
@@ -0,0 +1,15 @@
+md=triangle(model(),'../Exp/Pig.exp',20000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancevelocitySolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeX','Vel'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.BalancevelocitySolution.SurfaceSlopeX),...
+	(md.results.BalancevelocitySolution.SurfaceSlopeY),...
+	(md.results.BalancevelocitySolution.Vel),...
+	};
Index: /issm/trunk/test/NightlyRun/test530.py
===================================================================
--- /issm/trunk/test/NightlyRun/test530.py	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test530.py	(revision 16137)
@@ -0,0 +1,24 @@
+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/Pig.exp',20000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BalancevelocitySolutionEnum())
+
+# Fields and tolerances to track changes
+field_names     =['SurfaceSlopeX','SurfaceSlopeY','Vel']
+field_tolerances=[1e-13,1e-13,1e-13]
+field_values=[\
+		md.results.BalancevelocitySolution.SurfaceSlopeX,\
+		md.results.BalancevelocitySolution.SurfaceSlopeY,\
+		md.results.BalancevelocitySolution.Vel,\
+		]
Index: /issm/trunk/test/NightlyRun/test531.m
===================================================================
--- /issm/trunk/test/NightlyRun/test531.m	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test531.m	(revision 16137)
@@ -0,0 +1,17 @@
+md=triangle(model(),'../Exp/Pig.exp',20000.);
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
+md=parameterize(md,'../Par/Pig.par');
+md.initialization.vx(:)=0;
+md.initialization.vy(:)=0;
+md=setflowequation(md,'SSA','all');
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,BalancevelocitySolutionEnum());
+
+%Fields and tolerances to track changes
+field_names     ={'SurfaceSlopeX','SurfaceSlopeX','Vel'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={...
+	(md.results.BalancevelocitySolution.SurfaceSlopeX),...
+	(md.results.BalancevelocitySolution.SurfaceSlopeY),...
+	(md.results.BalancevelocitySolution.Vel),...
+	};
Index: /issm/trunk/test/NightlyRun/test531.py
===================================================================
--- /issm/trunk/test/NightlyRun/test531.py	(revision 16137)
+++ /issm/trunk/test/NightlyRun/test531.py	(revision 16137)
@@ -0,0 +1,26 @@
+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/Pig.exp',20000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.initialization.vx[:]=0.
+md.initialization.vy[:]=0.
+md=setflowequation(md,'SSA','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BalancevelocitySolutionEnum())
+
+# Fields and tolerances to track changes
+field_names     =['SurfaceSlopeX','SurfaceSlopeY','Vel']
+field_tolerances=[1e-13,1e-13,1e-13]
+field_values=[\
+		md.results.BalancevelocitySolution.SurfaceSlopeX,\
+		md.results.BalancevelocitySolution.SurfaceSlopeY,\
+		md.results.BalancevelocitySolution.Vel,\
+		]
Index: /issm/trunk/test/NightlyRun/test601.m
===================================================================
--- /issm/trunk/test/NightlyRun/test601.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test601.m	(revision 16137)
@@ -2,7 +2,7 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -10,4 +10,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test601.py
===================================================================
--- /issm/trunk/test/NightlyRun/test601.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test601.py	(revision 16137)
@@ -11,7 +11,7 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','')
 md=parameterize(md,'../Par/79North.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -19,4 +19,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test602.m
===================================================================
--- /issm/trunk/test/NightlyRun/test602.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test602.m	(revision 16137)
@@ -3,9 +3,9 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
-md.prognostic.stabilization=3;
-md.prognostic.spcthickness=md.geometry.thickness;
+md=setflowequation(md,'SSA','all');
+md.masstransport.stabilization=3;
+md.masstransport.spcthickness=md.geometry.thickness;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -13,4 +13,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test602.py
===================================================================
--- /issm/trunk/test/NightlyRun/test602.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test602.py	(revision 16137)
@@ -14,9 +14,9 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','')
 md=parameterize(md,'../Par/79North.py')
-md=setflowequation(md,'macayeal','all')
-md.prognostic.stabilization=3
-md.prognostic.spcthickness=md.geometry.thickness
+md=setflowequation(md,'SSA','all')
+md.masstransport.stabilization=3
+md.masstransport.spcthickness=md.geometry.thickness
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -24,4 +24,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test603.m
===================================================================
--- /issm/trunk/test/NightlyRun/test603.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test603.m	(revision 16137)
@@ -3,7 +3,7 @@
 md=parameterize(md,'../Par/79North.par');
 md=extrude(md,6,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum());
+md=solve(md,MasstransportSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -11,4 +11,4 @@
 field_tolerances={1e-13};
 field_values={...
-	(md.results.PrognosticSolution.Thickness),...
+	(md.results.MasstransportSolution.Thickness),...
 	};
Index: /issm/trunk/test/NightlyRun/test603.py
===================================================================
--- /issm/trunk/test/NightlyRun/test603.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test603.py	(revision 16137)
@@ -13,7 +13,7 @@
 md=parameterize(md,'../Par/79North.py')
 md.extrude(6,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
-md=solve(md,PrognosticSolutionEnum())
+md=solve(md,MasstransportSolutionEnum())
 
 #Fields and tolerances to track changes
@@ -21,4 +21,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results.PrognosticSolution.Thickness,\
+	md.results.MasstransportSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test604.m
===================================================================
--- /issm/trunk/test/NightlyRun/test604.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test604.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,SurfaceSlopeSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test604.py
===================================================================
--- /issm/trunk/test/NightlyRun/test604.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test604.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','')
 md=parameterize(md,'../Par/79North.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,SurfaceSlopeSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test605.m
===================================================================
--- /issm/trunk/test/NightlyRun/test605.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test605.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/79North.par');
 md=extrude(md,5,1.5);
-md=setflowequation(md,'pattyn','all');
+md=setflowequation(md,'HO','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,SurfaceSlopeSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test605.py
===================================================================
--- /issm/trunk/test/NightlyRun/test605.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test605.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/79North.py')
 md.extrude(5,1.5)
-md=setflowequation(md,'pattyn','all')
+md=setflowequation(md,'HO','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,SurfaceSlopeSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test606.m
===================================================================
--- /issm/trunk/test/NightlyRun/test606.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test606.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,BedSlopeSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test606.py
===================================================================
--- /issm/trunk/test/NightlyRun/test606.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test606.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','')
 md=parameterize(md,'../Par/79North.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,BedSlopeSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test607.m
===================================================================
--- /issm/trunk/test/NightlyRun/test607.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test607.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/79North.par');
 md=extrude(md,2,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,BedSlopeSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test607.py
===================================================================
--- /issm/trunk/test/NightlyRun/test607.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test607.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/79North.py')
 md.extrude(2,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,BedSlopeSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test608.m
===================================================================
--- /issm/trunk/test/NightlyRun/test608.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test608.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,BalancethicknessSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test608.py
===================================================================
--- /issm/trunk/test/NightlyRun/test608.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test608.py	(revision 16137)
@@ -12,5 +12,5 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','')
 md=parameterize(md,'../Par/79North.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,BalancethicknessSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test609.m
===================================================================
--- /issm/trunk/test/NightlyRun/test609.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test609.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.balancethickness.stabilization=3;
 md.cluster=generic('name',oshostname(),'np',3);
Index: /issm/trunk/test/NightlyRun/test609.py
===================================================================
--- /issm/trunk/test/NightlyRun/test609.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test609.py	(revision 16137)
@@ -14,5 +14,5 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','')
 md=parameterize(md,'../Par/79North.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.balancethickness.stabilization=3
 md.cluster=generic('name',oshostname(),'np',3)
Index: /issm/trunk/test/NightlyRun/test610.m
===================================================================
--- /issm/trunk/test/NightlyRun/test610.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test610.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=parameterize(md,'../Par/79North.par');
 md=extrude(md,3,1.);
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',3);
 md=solve(md,BalancethicknessSolutionEnum());
Index: /issm/trunk/test/NightlyRun/test610.py
===================================================================
--- /issm/trunk/test/NightlyRun/test610.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test610.py	(revision 16137)
@@ -13,5 +13,5 @@
 md=parameterize(md,'../Par/79North.py')
 md.extrude(3,1.)
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,BalancethicknessSolutionEnum())
Index: /issm/trunk/test/NightlyRun/test611.m
===================================================================
--- /issm/trunk/test/NightlyRun/test611.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test611.m	(revision 16137)
@@ -2,9 +2,9 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 
 %control parameters
 md.inversion.nsteps=2;
-md.prognostic.stabilization=1;
+md.masstransport.stabilization=1;
 md.inversion.iscontrol=1;
 md.inversion.control_parameters={'BalancethicknessThickeningRate'};
Index: /issm/trunk/test/NightlyRun/test611.py
===================================================================
--- /issm/trunk/test/NightlyRun/test611.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test611.py	(revision 16137)
@@ -12,9 +12,9 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','')
 md=parameterize(md,'../Par/79North.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 
 #control parameters
 md.inversion.nsteps=2
-md.prognostic.stabilization=1
+md.masstransport.stabilization=1
 md.inversion.iscontrol=1
 md.inversion.control_parameters=['BalancethicknessThickeningRate']
Index: /issm/trunk/test/NightlyRun/test612.m
===================================================================
--- /issm/trunk/test/NightlyRun/test612.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test612.m	(revision 16137)
@@ -3,5 +3,5 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 
 %control parameters
Index: /issm/trunk/test/NightlyRun/test612.py
===================================================================
--- /issm/trunk/test/NightlyRun/test612.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test612.py	(revision 16137)
@@ -14,5 +14,5 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','')
 md=parameterize(md,'../Par/79North.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 
 #control parameters
Index: /issm/trunk/test/NightlyRun/test613.m
===================================================================
--- /issm/trunk/test/NightlyRun/test613.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test613.m	(revision 16137)
@@ -3,8 +3,8 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 
 %Ice sheet only
-md=extract(md,md.mask.elementongroundedice);
+md=extract(md,md.mask.groundedice_levelset>0.);
 pos=find(md.mesh.vertexonboundary);
 md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
Index: /issm/trunk/test/NightlyRun/test613.py
===================================================================
--- /issm/trunk/test/NightlyRun/test613.py	(revision 16136)
+++ /issm/trunk/test/NightlyRun/test613.py	(revision 16137)
@@ -15,8 +15,8 @@
 md=setmask(md,'../Exp/79NorthShelf.exp','')
 md=parameterize(md,'../Par/79North.py')
-md=setflowequation(md,'macayeal','all')
+md=setflowequation(md,'SSA','all')
 
 #Ice sheet only
-md=md.extract(md.mask.elementongroundedice)
+md=md.extract(md.mask.groundedice_levelset>0.)
 pos=numpy.nonzero(md.mesh.vertexonboundary)
 md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
Index: /issm/trunk/test/NightlyRun/tmp332.m
===================================================================
--- /issm/trunk/test/NightlyRun/tmp332.m	(revision 16136)
+++ /issm/trunk/test/NightlyRun/tmp332.m	(revision 16137)
@@ -2,5 +2,5 @@
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=setflowequation(md,'macayeal','all');
+md=setflowequation(md,'SSA','all');
 md.cluster=generic('name',oshostname(),'np',2);
 md.hydrology=(hydrologydc);
Index: /issm/trunk/test/Par/79North.par
===================================================================
--- /issm/trunk/test/Par/79North.par	(revision 16136)
+++ /issm/trunk/test/Par/79North.par	(revision 16137)
@@ -22,19 +22,17 @@
 
 %Friction
-pos=find(md.mask.elementonfloatingice);
 md.friction.coefficient=50.*ones(md.mesh.numberofvertices,1);
-md.friction.coefficient(md.mesh.elements(pos,:))=0.;
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
 
 %Ice shelf melting and surface mass balance 
-pos=find(md.mask.elementonfloatingice);
 md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate(md.mesh.elements(pos,:))=10;
+md.basalforcings.melting_rate(find(md.mask.groundedice_levelset<0.))=0.;
 md.surfaceforcings.mass_balance=15.*ones(md.mesh.numberofvertices,1);
 
 %Numerical parameters
-md.diagnostic.viscosity_overshoot=0.3;
-md.prognostic.stabilization=1;
+md.stressbalance.viscosity_overshoot=0.3;
+md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
 md.verbose=verbose(0);
@@ -42,8 +40,8 @@
 md.timestepping.time_step=1.;
 md.timestepping.final_time=3.;
-md.diagnostic.restol=0.05;
-md.diagnostic.reltol=0.005;
+md.stressbalance.restol=0.05;
+md.stressbalance.reltol=0.005;
 md.steadystate.reltol=0.005;
-md.diagnostic.abstol=NaN;
+md.stressbalance.abstol=NaN;
 
 %Boundary conditions:
@@ -51,5 +49,5 @@
 pos=find(md.mesh.vertexonboundary);
 md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
-md.prognostic.spcthickness(pos)=md.geometry.thickness(pos);
+md.masstransport.spcthickness(pos)=md.geometry.thickness(pos);
 
 %Change name so that no test have the same name
Index: /issm/trunk/test/Par/79North.py
===================================================================
--- /issm/trunk/test/Par/79North.py	(revision 16136)
+++ /issm/trunk/test/Par/79North.py	(revision 16137)
@@ -34,19 +34,17 @@
 
 #Friction
-pos=numpy.nonzero(md.mask.elementonfloatingice)
 md.friction.coefficient=50.*ones((md.mesh.numberofvertices,1))
-md.friction.coefficient[md.mesh.elements[pos].astype(int)-1]=0.
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=ones((md.mesh.numberofelements,1))
 md.friction.q=ones((md.mesh.numberofelements,1))
 
 #Ice shelf melting and surface mass balance 
-pos=numpy.nonzero(md.mask.elementonfloatingice)
 md.basalforcings.melting_rate=zeros((md.mesh.numberofvertices,1))
-md.basalforcings.melting_rate[md.mesh.elements[pos].astype(int)-1]=10.
+md.basalforcings.melting_rate[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.surfaceforcings.mass_balance=15*numpy.ones((md.mesh.numberofvertices,1))
 
 #Numerical parameters
-md.diagnostic.viscosity_overshoot=0.3
-md.prognostic.stabilization=1
+md.stressbalance.viscosity_overshoot=0.3
+md.masstransport.stabilization=1
 md.thermal.stabilization=1
 md.verbose=verbose(0)
@@ -54,8 +52,8 @@
 md.timestepping.time_step=1.
 md.timestepping.final_time=3.
-md.diagnostic.restol=0.05
-md.diagnostic.reltol=0.005
+md.stressbalance.restol=0.05
+md.stressbalance.reltol=0.005
 md.steadystate.reltol=0.005
-md.diagnostic.abstol=float('NaN')
+md.stressbalance.abstol=float('NaN')
 
 #Boundary conditions:
@@ -63,5 +61,5 @@
 pos=numpy.nonzero(md.mesh.vertexonboundary)
 md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
-md.prognostic.spcthickness[pos]=md.geometry.thickness[pos]
+md.masstransport.spcthickness[pos]=md.geometry.thickness[pos]
 
 #Change name so that no test have the same name
Index: /issm/trunk/test/Par/GiaBenchmarksAB.par
===================================================================
--- /issm/trunk/test/Par/GiaBenchmarksAB.par	(revision 16136)
+++ /issm/trunk/test/Par/GiaBenchmarksAB.par	(revision 16137)
@@ -45,20 +45,19 @@
 
 %Friction
-pos=find(md.mask.elementonfloatingice);
 md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
-md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
 
 %Numerical parameters
-md.diagnostic.viscosity_overshoot=0.0;
-md.prognostic.stabilization=1.;
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1.;
 md.thermal.stabilization=1.;
 md.verbose=verbose(0);
 md.settings.waitonlock=30;
-md.diagnostic.restol=0.05;
+md.stressbalance.restol=0.05;
 md.steadystate.reltol=0.05;
-md.diagnostic.reltol=0.05;
-md.diagnostic.abstol=NaN;
+md.stressbalance.reltol=0.05;
+md.stressbalance.abstol=NaN;
 md.timestepping.time_step=1.;
 md.timestepping.final_time=3.;
Index: /issm/trunk/test/Par/GiaBenchmarksCD.par
===================================================================
--- /issm/trunk/test/Par/GiaBenchmarksCD.par	(revision 16136)
+++ /issm/trunk/test/Par/GiaBenchmarksCD.par	(revision 16137)
@@ -44,20 +44,19 @@
 
 %Friction
-pos=find(md.mask.elementonfloatingice);
 md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
-md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
 
 %Numerical parameters
-md.diagnostic.viscosity_overshoot=0.0;
-md.prognostic.stabilization=1.;
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1.;
 md.thermal.stabilization=1.;
 md.verbose=verbose(0);
 md.settings.waitonlock=30;
-md.diagnostic.restol=0.05;
+md.stressbalance.restol=0.05;
 md.steadystate.reltol=0.05;
-md.diagnostic.reltol=0.05;
-md.diagnostic.abstol=NaN;
+md.stressbalance.reltol=0.05;
+md.stressbalance.abstol=NaN;
 md.timestepping.time_step=1.;
 md.timestepping.final_time=3.;
Index: /issm/trunk/test/Par/ISMIPA.par
===================================================================
--- /issm/trunk/test/Par/ISMIPA.par	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPA.par	(revision 16137)
@@ -7,8 +7,6 @@
 
 disp('      creating drag');
-md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1); %q=1.
-%Take care of iceshelves: no basal drag
-pos=find(md.mask.elementonfloatingice);
-md.friction.coefficient(md.mesh.elements(pos,:))=0.;
+md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
@@ -18,5 +16,5 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
-disp('      boundary conditions for diagnostic model');
+disp('      boundary conditions for stressbalance model');
 %Create node on boundary first (because we cannot use mesh)
 md=SetIceSheetBC(md);
Index: /issm/trunk/test/Par/ISMIPA.py
===================================================================
--- /issm/trunk/test/Par/ISMIPA.py	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPA.py	(revision 16137)
@@ -10,8 +10,6 @@
 
 print "      creating drag"
-md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))    #q=1.
-#Take care of iceshelves: no basal drag
-pos=numpy.nonzero(md.mask.elementonfloatingice)[0]
-md.friction.coefficient[md.mesh.elements[pos,:]-1]=0.
+md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=numpy.ones((md.mesh.numberofelements,1))
 md.friction.q=numpy.ones((md.mesh.numberofelements,1))
@@ -21,5 +19,5 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
-print "      boundary conditions for diagnostic model"
+print "      boundary conditions for stressbalance model"
 #Create node on boundary first (because we cannot use mesh)
 md=SetIceSheetBC(md)
Index: /issm/trunk/test/Par/ISMIPB.par
===================================================================
--- /issm/trunk/test/Par/ISMIPB.par	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPB.par	(revision 16137)
@@ -7,8 +7,6 @@
 
 disp('      creating drag');
-md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1); %q=1.
-%Take care of iceshelves: no basal drag
-pos=find(md.mask.elementonfloatingice);
-md.friction.coefficient(md.mesh.elements(pos,:))=0.;
+md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
@@ -18,5 +16,5 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
-disp('      boundary conditions for diagnostic model');
+disp('      boundary conditions for stressbalance model');
 %Create node on boundary first (because we cannot use mesh)
 md=SetIceSheetBC(md);
Index: /issm/trunk/test/Par/ISMIPB.py
===================================================================
--- /issm/trunk/test/Par/ISMIPB.py	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPB.py	(revision 16137)
@@ -10,8 +10,6 @@
 
 print "      creating drag"
-md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))    #q=1.
-#Take care of iceshelves: no basal drag
-pos=numpy.nonzero(md.mask.elementonfloatingice)[0]
-md.friction.coefficient[md.mesh.elements[pos,:]-1]=0.
+md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=numpy.ones((md.mesh.numberofelements,1))
 md.friction.q=numpy.ones((md.mesh.numberofelements,1))
@@ -21,5 +19,5 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
-print "      boundary conditions for diagnostic model"
+print "      boundary conditions for stressbalance model"
 #Create node on boundary first (because we cannot use mesh)
 md=SetIceSheetBC(md)
Index: /issm/trunk/test/Par/ISMIPC.par
===================================================================
--- /issm/trunk/test/Par/ISMIPC.par	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPC.par	(revision 16137)
@@ -9,7 +9,5 @@
 %md.friction.coefficient=sqrt(md.constants.yts.*(1000.+1000.*sin(md.mesh.x*2.*pi/max(md.mesh.x/2.)).*sin(md.mesh.y*2.*pi/max(md.mesh.x/2.)))./(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed)));
 md.friction.coefficient=sqrt(md.constants.yts.*(1000.+1000.*sin(md.mesh.x*2.*pi/max(md.mesh.x)).*sin(md.mesh.y*2.*pi/max(md.mesh.x))));
-%Take care of iceshelves: no basal drag
-pos=find(md.mask.elementonfloatingice);
-md.friction.coefficient(md.mesh.elements(pos,:))=0.;
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=zeros(md.mesh.numberofelements,1);
@@ -19,5 +17,5 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
-disp('      boundary conditions for diagnostic model:');
+disp('      boundary conditions for stressbalance model:');
 %Create node on boundary first (because we can not use mesh)
 md=SetIceSheetBC(md);
Index: /issm/trunk/test/Par/ISMIPC.py
===================================================================
--- /issm/trunk/test/Par/ISMIPC.py	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPC.py	(revision 16137)
@@ -12,7 +12,5 @@
 #md.friction.coefficient=sqrt(md.constants.yts.*(1000.+1000.*sin(md.mesh.x*2.*pi/max(md.mesh.x/2.)).*sin(md.mesh.y*2.*pi/max(md.mesh.x/2.)))./(md.constants.g*(md.materials.rho_ice*md.geometry.thickness+md.materials.rho_water*md.geometry.bed)));
 md.friction.coefficient=numpy.sqrt(md.constants.yts*(1000.+1000.*numpy.sin(md.mesh.x.reshape(-1,1)*2.*numpy.pi/numpy.max(md.mesh.x))*numpy.sin(md.mesh.y.reshape(-1,1)*2.*numpy.pi/numpy.max(md.mesh.x))))
-#Take care of iceshelves: no basal drag
-pos=numpy.nonzero(md.mask.elementonfloatingice)[0]
-md.friction.coefficient[md.mesh.elements[pos,:]-1]=0.
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=numpy.ones((md.mesh.numberofelements,1))
 md.friction.q=numpy.zeros((md.mesh.numberofelements,1))
@@ -22,5 +20,5 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
-print "      boundary conditions for diagnostic model:"
+print "      boundary conditions for stressbalance model:"
 #Create node on boundary first (because we can not use mesh)
 md=SetIceSheetBC(md)
Index: /issm/trunk/test/Par/ISMIPD.par
===================================================================
--- /issm/trunk/test/Par/ISMIPD.par	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPD.par	(revision 16137)
@@ -8,7 +8,5 @@
 disp('      creating drag');
 md.friction.coefficient=sqrt(md.constants.yts.*(1000.+1000.*sin(md.mesh.x*2.*pi/max(md.mesh.x))));
-%Take care of iceshelves: no basal drag
-pos=find(md.mask.elementonfloatingice);
-md.friction.coefficient(md.mesh.elements(pos,:))=0.;
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=zeros(md.mesh.numberofelements,1);
@@ -18,5 +16,5 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
-disp('      boundary conditions for diagnostic model:');
+disp('      boundary conditions for stressbalance model:');
 %Create node on boundary first (because we can not use mesh)
 md=SetIceSheetBC(md);
Index: /issm/trunk/test/Par/ISMIPD.py
===================================================================
--- /issm/trunk/test/Par/ISMIPD.py	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPD.py	(revision 16137)
@@ -11,7 +11,5 @@
 print "      creating drag"
 md.friction.coefficient=numpy.sqrt(md.constants.yts*(1000.+1000.*numpy.sin(md.mesh.x.reshape(-1,1)*2.*numpy.pi/numpy.max(md.mesh.x))))
-#Take care of iceshelves: no basal drag
-pos=numpy.nonzero(md.mask.elementonfloatingice)[0]
-md.friction.coefficient[md.mesh.elements[pos,:]-1]=0.
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=numpy.ones((md.mesh.numberofelements,1))
 md.friction.q=numpy.zeros((md.mesh.numberofelements,1))
@@ -21,5 +19,5 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
-print "      boundary conditions for diagnostic model:"
+print "      boundary conditions for stressbalance model:"
 #Create node on boundary first (because we can not use mesh)
 md=SetIceSheetBC(md)
Index: /issm/trunk/test/Par/ISMIPE.par
===================================================================
--- /issm/trunk/test/Par/ISMIPE.par	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPE.par	(revision 16137)
@@ -26,5 +26,5 @@
 md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
-disp('      boundary conditions for diagnostic model:');
+disp('      boundary conditions for stressbalance model:');
 %Create node on boundary first (because we can not use mesh)
 md=SetIceSheetBC(md);
Index: /issm/trunk/test/Par/ISMIPE.py
===================================================================
--- /issm/trunk/test/Par/ISMIPE.py	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPE.py	(revision 16137)
@@ -31,5 +31,5 @@
 md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
 
-print "      boundary conditions for diagnostic model:"
+print "      boundary conditions for stressbalance model:"
 #Create node on boundary first (because we can not use mesh)
 md=SetIceSheetBC(md)
Index: /issm/trunk/test/Par/ISMIPF.par
===================================================================
--- /issm/trunk/test/Par/ISMIPF.par	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPF.par	(revision 16137)
@@ -18,8 +18,8 @@
 md.materials.rheology_law='None';
 
-disp('      boundary conditions for diagnostic model');
+disp('      boundary conditions for stressbalance model');
 %Create node on boundary first (because we cannot use mesh)
 md=SetIceSheetBC(md);
-md.diagnostic.spcvx=100.*ones(md.mesh.numberofvertices,1);
+md.stressbalance.spcvx=100.*ones(md.mesh.numberofvertices,1);
 md.initialization.vx=zeros(md.mesh.numberofvertices,1);
 md.initialization.vy=zeros(md.mesh.numberofvertices,1);
@@ -31,6 +31,6 @@
 md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 md.balancethickness.spcthickness(pos)=md.geometry.thickness(pos);
-md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
-md.prognostic.spcthickness(pos)=md.geometry.thickness(pos);
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.masstransport.spcthickness(pos)=md.geometry.thickness(pos);
 md.thermal.spctemperature=255.*ones(md.mesh.numberofvertices,1);
 md.basalforcings.geothermalflux=0.4*ones(md.mesh.numberofvertices,1);
@@ -42,5 +42,5 @@
 md.timestepping.time_step=1.;
 md.timestepping.final_time=10.;
-md.prognostic.stabilization=1;
+md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
 md.thermal.penalty_threshold=10^5;
Index: /issm/trunk/test/Par/ISMIPF.py
===================================================================
--- /issm/trunk/test/Par/ISMIPF.py	(revision 16136)
+++ /issm/trunk/test/Par/ISMIPF.py	(revision 16137)
@@ -21,8 +21,8 @@
 md.materials.rheology_law='None'
 
-print "      boundary conditions for diagnostic model"
+print "      boundary conditions for stressbalance model"
 #Create node on boundary first (because we cannot use mesh)
 md=SetIceSheetBC(md)
-md.diagnostic.spcvx=100.*numpy.ones((md.mesh.numberofvertices,1))
+md.stressbalance.spcvx=100.*numpy.ones((md.mesh.numberofvertices,1))
 md.initialization.vx=numpy.zeros((md.mesh.numberofvertices,1))
 md.initialization.vy=numpy.zeros((md.mesh.numberofvertices,1))
@@ -34,6 +34,6 @@
 md.balancethickness.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
 md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
-md.prognostic.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-md.prognostic.spcthickness[pos]=md.geometry.thickness[pos]
+md.masstransport.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+md.masstransport.spcthickness[pos]=md.geometry.thickness[pos]
 md.thermal.spctemperature=255.*numpy.ones((md.mesh.numberofvertices,1))
 md.basalforcings.geothermalflux=0.4*numpy.ones((md.mesh.numberofvertices,1))
@@ -45,5 +45,5 @@
 md.timestepping.time_step=1.
 md.timestepping.final_time=10.
-md.prognostic.stabilization=1
+md.masstransport.stabilization=1
 md.thermal.stabilization=1
 md.thermal.penalty_threshold=10**5
Index: /issm/trunk/test/Par/Pig.par
===================================================================
--- /issm/trunk/test/Par/Pig.par	(revision 16136)
+++ /issm/trunk/test/Par/Pig.par	(revision 16137)
@@ -27,21 +27,20 @@
 
 %Friction
-pos=find(md.mask.elementonfloatingice);
 md.friction.coefficient=50*ones(md.mesh.numberofvertices,1);
-md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
 
 %Numerical parameters
-md.diagnostic.viscosity_overshoot=0.3;
-md.prognostic.stabilization=1;
+md.stressbalance.viscosity_overshoot=0.3;
+md.masstransport.stabilization=1;
 md.verbose=verbose(0);
 md.settings.waitonlock=30;
 md.timestepping.time_step=1;
 md.timestepping.final_time=2;
-md.diagnostic.restol=0.05;
-md.diagnostic.reltol=1;
+md.stressbalance.restol=0.05;
+md.stressbalance.reltol=1;
 md.steadystate.reltol=1;
-md.diagnostic.abstol=NaN;
+md.stressbalance.abstol=NaN;
 
 %Boundary conditions:
Index: /issm/trunk/test/Par/Pig.py
===================================================================
--- /issm/trunk/test/Par/Pig.py	(revision 16136)
+++ /issm/trunk/test/Par/Pig.py	(revision 16137)
@@ -38,21 +38,20 @@
 
 #Friction
-pos=numpy.nonzero(md.mask.elementonfloatingice)
 md.friction.coefficient=50.*ones((md.mesh.numberofvertices,1))
-md.friction.coefficient[md.mesh.elements[pos].astype(int)-1]=0.
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=ones((md.mesh.numberofelements,1))
 md.friction.q=ones((md.mesh.numberofelements,1))
 
 #Numerical parameters
-md.diagnostic.viscosity_overshoot=0.3
-md.prognostic.stabilization=1.
+md.stressbalance.viscosity_overshoot=0.3
+md.masstransport.stabilization=1.
 md.verbose=verbose(0)
 md.settings.waitonlock=30
 md.timestepping.time_step=1.
 md.timestepping.final_time=2.
-md.diagnostic.restol=0.05
-md.diagnostic.reltol=1.
+md.stressbalance.restol=0.05
+md.stressbalance.reltol=1.
 md.steadystate.reltol=1.
-md.diagnostic.abstol=float('nan')
+md.stressbalance.abstol=float('nan')
 
 #Boundary conditions:
Index: /issm/trunk/test/Par/RoundSheetEISMINT.par
===================================================================
--- /issm/trunk/test/Par/RoundSheetEISMINT.par	(revision 16136)
+++ /issm/trunk/test/Par/RoundSheetEISMINT.par	(revision 16137)
@@ -6,5 +6,5 @@
 
 disp('      creating drag');
-md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1); %q=1. no drag is specified in the analytical solution
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
@@ -38,5 +38,5 @@
 
 %Deal with boundary conditions:
-disp('      boundary conditions for diagnostic model:');
+disp('      boundary conditions for stressbalance model:');
 md=SetMarineIceSheetBC(md,'../Exp/RoundFrontEISMINT.exp');
 
@@ -45,7 +45,7 @@
 md.mesh.x(pos)=0.; md.mesh.y(pos)=0.; %the closest node to the center is changed to be exactly at the center
 
-md.diagnostic.spcvx(pos)=0.;
-md.diagnostic.spcvy(pos)=0.;
-md.diagnostic.spcvz(pos)=0.;
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
 
 %parallel options
Index: /issm/trunk/test/Par/RoundSheetEISMINT.py
===================================================================
--- /issm/trunk/test/Par/RoundSheetEISMINT.py	(revision 16136)
+++ /issm/trunk/test/Par/RoundSheetEISMINT.py	(revision 16137)
@@ -9,5 +9,5 @@
 
 print "      creating drag"
-md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))    #q=1. no drag is specified in the analytical solution
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1)) 
 md.friction.p=numpy.ones((md.mesh.numberofelements,1))
 md.friction.q=numpy.ones((md.mesh.numberofelements,1))
@@ -41,5 +41,5 @@
 
 #Deal with boundary conditions:
-print "      boundary conditions for diagnostic model:"
+print "      boundary conditions for stressbalance model:"
 md=SetMarineIceSheetBC(md,'../Exp/RoundFrontEISMINT.exp')
 
@@ -49,7 +49,7 @@
 md.mesh.y[pos]=0.    #the closest node to the center is changed to be exactly at the center
 
-md.diagnostic.spcvx[pos]=0.
-md.diagnostic.spcvy[pos]=0.
-md.diagnostic.spcvz[pos]=0.
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
 
 #parallel options
Index: /issm/trunk/test/Par/RoundSheetShelf.par
===================================================================
--- /issm/trunk/test/Par/RoundSheetShelf.par	(revision 16136)
+++ /issm/trunk/test/Par/RoundSheetShelf.par	(revision 16137)
@@ -13,5 +13,5 @@
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
 
-pos=find(md.mask.vertexongroundedice);
+pos=find(md.mask.groundedice_levelset>0.);
 md.geometry.bed(pos)=md.geometry.bed(pos)-300.*(radius(pos)-(rad-shelfextent))/(rad-shelfextent);
 md.geometry.surface=md.geometry.bed+md.geometry.thickness;
@@ -64,24 +64,30 @@
 md.surfaceforcings.mass_balance=-10.*ones(md.mesh.numberofvertices,1);
 md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
-pos=find(md.mask.vertexonfloatingice);md.basalforcings.melting_rate(pos)=10.;
+pos=find(md.mask.groundedice_levelset>0.);md.basalforcings.melting_rate(pos)=10.;
 md.basalforcings.geothermalflux=ones(md.mesh.numberofvertices,1);
 
 %Friction
-pos=find(md.mask.elementonfloatingice);
+radius=1.e6;
+shelfextent=2.e5;
 md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
-md.friction.coefficient(md.mesh.elements(pos,:))=0;
+xelem=md.mesh.x(md.mesh.elements)*[1;1;1]/3.;
+yelem=md.mesh.y(md.mesh.elements)*[1;1;1]/3.;
+rad=sqrt(xelem.^2+yelem.^2);
+flags=zeros(md.mesh.numberofelements,1);
+pos=find(rad>=(radius-shelfextent));
+md.friction.coefficient(md.mesh.elements(pos,:))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
 
 %Numerical parameters
-md.diagnostic.viscosity_overshoot=0.0;
-md.prognostic.stabilization=1;
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
 md.verbose=verbose(0);
 md.settings.waitonlock=30;
-md.diagnostic.restol=0.05;
-md.diagnostic.reltol=0.05;
+md.stressbalance.restol=0.05;
+md.stressbalance.reltol=0.05;
 md.steadystate.reltol=0.05;
-md.diagnostic.abstol=NaN;
+md.stressbalance.abstol=NaN;
 md.timestepping.time_step=5.;
 md.timestepping.final_time=5.;
@@ -90,22 +96,20 @@
 md.groundingline.migration='AgressiveMigration';
 md.geometry.bathymetry=md.geometry.bed;
-pos=find(md.mask.vertexonfloatingice); md.geometry.bathymetry(pos)=md.geometry.bed(pos)-900.;
+pos=find(md.mask.groundedice_levelset<0.); md.geometry.bathymetry(pos)=md.geometry.bed(pos)-900.;
 
 %Deal with boundary conditions:
-md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+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);
 
 pos=find(md.mesh.x==0 & md.mesh.y==0);
-md.diagnostic.spcvx(pos)=0;
-md.diagnostic.spcvy(pos)=0;
+md.stressbalance.spcvx(pos)=0;
+md.stressbalance.spcvy(pos)=0;
 
-pressureload=md.mesh.segments;
-pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end)) + 0*md.mask.elementongroundedice(pressureload(:,end))];
-md.diagnostic.icefront=pressureload;
+md.mask.ice_levelset(find(md.mesh.vertexonboundary))=0;
 md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
-md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
-md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
-md.diagnostic.loadingforce=0*ones(md.mesh.numberofvertices,3);
+md.masstransport.spcthickness=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.thermal.spctemperature=737.*ones(md.mesh.numberofvertices,1);
 
Index: /issm/trunk/test/Par/RoundSheetShelf.py
===================================================================
--- /issm/trunk/test/Par/RoundSheetShelf.py	(revision 16136)
+++ /issm/trunk/test/Par/RoundSheetShelf.py	(revision 16137)
@@ -20,5 +20,5 @@
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
 
-pos=numpy.nonzero(md.mask.vertexongroundedice)
+pos=numpy.nonzero(md.mask.groundedice_levelset>0.)[0]
 md.geometry.bed[pos]=md.geometry.bed[pos]-300.*(radius[pos]-(rad-shelfextent))/(rad-shelfextent)
 md.geometry.surface=md.geometry.bed+md.geometry.thickness
@@ -71,25 +71,31 @@
 md.surfaceforcings.mass_balance=-10.*numpy.ones((md.mesh.numberofvertices,1))
 md.basalforcings.melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
-pos=numpy.nonzero(md.mask.vertexonfloatingice)
+pos=numpy.nonzero(md.mask.groundedice_levelset>0.)[0]
 md.basalforcings.melting_rate[pos]=10.
 md.basalforcings.geothermalflux=numpy.ones((md.mesh.numberofvertices,1))
 
 #Friction
-pos=numpy.nonzero(md.mask.elementonfloatingice)
+radius=1.e6
+shelfextent=2.e5
 md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
-md.friction.coefficient[md.mesh.elements[pos,:].astype(int)-1]=0
+xelem=numpy.mean(md.mesh.x[md.mesh.elements.astype(int)-1],axis=1)
+yelem=numpy.mean(md.mesh.y[md.mesh.elements.astype(int)-1],axis=1)
+rad=numpy.sqrt(xelem**2+yelem**2)
+flags=numpy.zeros(md.mesh.numberofelements)
+pos=numpy.nonzero(rad>=(radius-shelfextent))
+md.friction.coefficient[md.mesh.elements[pos,:]-1]=0.
 md.friction.p=numpy.ones((md.mesh.numberofelements,1))
 md.friction.q=numpy.ones((md.mesh.numberofelements,1))
 
 #Numerical parameters
-md.diagnostic.viscosity_overshoot=0.0
-md.prognostic.stabilization=1
+md.stressbalance.viscosity_overshoot=0.0
+md.masstransport.stabilization=1
 md.thermal.stabilization=1
 md.verbose=verbose(0)
 md.settings.waitonlock=30
-md.diagnostic.restol=0.05
-md.diagnostic.reltol=0.05
+md.stressbalance.restol=0.05
+md.stressbalance.reltol=0.05
 md.steadystate.reltol=0.05
-md.diagnostic.abstol=float('nan')
+md.stressbalance.abstol=float('nan')
 md.timestepping.time_step=5.
 md.timestepping.final_time=5.
@@ -98,23 +104,22 @@
 md.groundingline.migration='AgressiveMigration'
 md.geometry.bathymetry=copy.deepcopy(md.geometry.bed)
-pos=numpy.nonzero(md.mask.vertexonfloatingice)
+pos=numpy.nonzero(md.mask.groundedice_levelset<0.)[0]
 md.geometry.bathymetry[pos]=md.geometry.bed[pos]-900.
 
 #Deal with boundary conditions:
-md.diagnostic.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-md.diagnostic.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-md.diagnostic.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.stressbalance.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.stressbalance.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.stressbalance.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 
 pos=numpy.nonzero(numpy.logical_and(md.mesh.x==0,md.mesh.y==0))
-md.diagnostic.spcvx[pos]=0
-md.diagnostic.spcvy[pos]=0
+md.stressbalance.spcvx[pos]=0
+md.stressbalance.spcvy[pos]=0
 
-pressureload=copy.deepcopy(md.mesh.segments)
-pressureload=numpy.hstack((pressureload,(1*md.mask.elementonfloatingice[pressureload[:,-1].astype(int)-1] + 0*md.mask.elementongroundedice[pressureload[:,-1].astype(int)-1]).reshape(-1,1)))
-md.diagnostic.icefront=pressureload
+pos=numpy.nonzero(md.mesh.vertexonboundary)
+md.mask.ice_levelset[pos]=0
 md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-md.prognostic.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
-md.diagnostic.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
-md.diagnostic.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
+md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
+md.stressbalance.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
 md.thermal.spctemperature=737.*numpy.ones((md.mesh.numberofvertices,1))
 
Index: /issm/trunk/test/Par/RoundSheetStaticEISMINT.par
===================================================================
--- /issm/trunk/test/Par/RoundSheetStaticEISMINT.par	(revision 16136)
+++ /issm/trunk/test/Par/RoundSheetStaticEISMINT.par	(revision 16137)
@@ -10,8 +10,6 @@
 
 disp('      creating drag');
-md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1); %q=1. no drag is specified in the analytical solution
-%Take care of iceshelves: no basal drag
-pos=find(md.mask.elementonfloatingice);
-md.friction.coefficient(md.mesh.elements(pos,:))=0.;
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
@@ -44,5 +42,5 @@
 
 %Deal with boundary conditions:
-disp('      boundary conditions for diagnostic model:');
+disp('      boundary conditions for stressbalance model:');
 md=SetMarineIceSheetBC(md,'../Exp/RoundFrontEISMINT.exp');
 
@@ -51,5 +49,5 @@
 md.mesh.x(pos)=0.; md.mesh.y(pos)=0.; %the closest node to the center is changed to be exactly at the center
 
-md.diagnostic.spcvx(pos)=0.;
-md.diagnostic.spcvy(pos)=0.;
-md.diagnostic.spcvz(pos)=0.;
+md.stressbalance.spcvx(pos)=0.;
+md.stressbalance.spcvy(pos)=0.;
+md.stressbalance.spcvz(pos)=0.;
Index: /issm/trunk/test/Par/RoundSheetStaticEISMINT.py
===================================================================
--- /issm/trunk/test/Par/RoundSheetStaticEISMINT.py	(revision 16136)
+++ /issm/trunk/test/Par/RoundSheetStaticEISMINT.py	(revision 16137)
@@ -13,8 +13,6 @@
 
 print "      creating drag"
-md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))    #q=1. no drag is specified in the analytical solution
-#Take care of iceshelves: no basal drag
-pos=numpy.nonzero(md.mask.elementonfloatingice)[0]
-md.friction.coefficient[md.mesh.elements[pos,:]-1]=0.
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=numpy.ones((md.mesh.numberofelements,1))
 md.friction.q=numpy.ones((md.mesh.numberofelements,1))
@@ -47,5 +45,5 @@
 
 #Deal with boundary conditions:
-print "      boundary conditions for diagnostic model:"
+print "      boundary conditions for stressbalance model:"
 md=SetMarineIceSheetBC(md,'../Exp/RoundFrontEISMINT.exp')
 
@@ -55,5 +53,5 @@
 md.mesh.y[pos]=0.    #the closest node to the center is changed to be exactly at the center
 
-md.diagnostic.spcvx[pos]=0.
-md.diagnostic.spcvy[pos]=0.
-md.diagnostic.spcvz[pos]=0.
+md.stressbalance.spcvx[pos]=0.
+md.stressbalance.spcvy[pos]=0.
+md.stressbalance.spcvz[pos]=0.
Index: /issm/trunk/test/Par/SquareEISMINT.par
===================================================================
--- /issm/trunk/test/Par/SquareEISMINT.par	(revision 16136)
+++ /issm/trunk/test/Par/SquareEISMINT.par	(revision 16137)
@@ -9,8 +9,6 @@
 
 disp('      creating drag');
-md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1); %q=1.
-%Take care of iceshelves: no basal drag
-pos=find(md.mask.elementonfloatingice);
-md.friction.coefficient(md.mesh.elements(pos,:))=0.;
+md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
@@ -39,7 +37,7 @@
 md.balancethickness.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 md.balancethickness.spcthickness(pos)=500.;
-md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
-md.prognostic.spcthickness(pos)=500.;
-md.prognostic.stabilization=0; %Better result with no artificial diffusivity
+md.masstransport.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
+md.masstransport.spcthickness(pos)=500.;
+md.masstransport.stabilization=0; %Better result with no artificial diffusivity
 md.thermal.stabilization=0;
 md.timestepping.final_time=500.;
Index: /issm/trunk/test/Par/SquareEISMINT.py
===================================================================
--- /issm/trunk/test/Par/SquareEISMINT.py	(revision 16136)
+++ /issm/trunk/test/Par/SquareEISMINT.py	(revision 16137)
@@ -12,8 +12,6 @@
 
 print "      creating drag"
-md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))    #q=1.
-#Take care of iceshelves: no basal drag
-pos=numpy.nonzero(md.mask.elementonfloatingice)[0]
-md.friction.coefficient[md.mesh.elements[pos,:]-1]=0.
+md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=numpy.ones((md.mesh.numberofelements,1))
 md.friction.q=numpy.ones((md.mesh.numberofelements,1))
@@ -42,7 +40,7 @@
 md.balancethickness.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
 md.balancethickness.spcthickness[pos]=500.
-md.prognostic.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
-md.prognostic.spcthickness[pos]=500.
-md.prognostic.stabilization=0    #Better result with no artificial diffusivity
+md.masstransport.spcthickness=float('NaN')*numpy.ones((md.mesh.numberofvertices,1))
+md.masstransport.spcthickness[pos]=500.
+md.masstransport.stabilization=0    #Better result with no artificial diffusivity
 md.thermal.stabilization=0
 md.timestepping.final_time=500.
Index: /issm/trunk/test/Par/SquareSheetConstrained.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 16136)
+++ /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 16137)
@@ -6,6 +6,7 @@
 ymin=min(md.mesh.y);
 ymax=max(md.mesh.y);
-
-md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness+20.;
 md.geometry.surface=md.geometry.bed+md.geometry.thickness;
@@ -30,20 +31,19 @@
 
 %Friction
-pos=find(md.mask.elementonfloatingice);
 md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
-md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
 
 %Numerical parameters
-md.diagnostic.viscosity_overshoot=0.0;
-md.prognostic.stabilization=1.;
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1.;
 md.thermal.stabilization=1.;
 md.verbose=verbose(0);
 md.settings.waitonlock=30;
-md.diagnostic.restol=0.05;
+md.stressbalance.restol=0.05;
 md.steadystate.reltol=0.05;
-md.diagnostic.reltol=0.05;
-md.diagnostic.abstol=NaN;
+md.stressbalance.reltol=0.05;
+md.stressbalance.abstol=NaN;
 md.timestepping.time_step=1.;
 md.timestepping.final_time=3.;
Index: /issm/trunk/test/Par/SquareSheetConstrained.py
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 16136)
+++ /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 16137)
@@ -15,6 +15,7 @@
 ymin=numpy.min(md.mesh.y)
 ymax=numpy.max(md.mesh.y)
-
-md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)
+xmin=min(md.mesh.x)
+xmax=max(md.mesh.x)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x.reshape(-1,1)-xmin)/(xmax-xmin)
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness+20.
 md.geometry.surface=md.geometry.bed+md.geometry.thickness
@@ -40,20 +41,19 @@
 
 #Friction
-pos=numpy.nonzero(md.mask.elementonfloatingice)
 md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
-md.friction.coefficient[md.mesh.elements[pos,:].astype(int)-1]=0.
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=numpy.ones((md.mesh.numberofelements,1))
 md.friction.q=numpy.ones((md.mesh.numberofelements,1))
 
 #Numerical parameters
-md.diagnostic.viscosity_overshoot=0.0
-md.prognostic.stabilization=1.
+md.stressbalance.viscosity_overshoot=0.0
+md.masstransport.stabilization=1.
 md.thermal.stabilization=1.
 md.verbose=verbose(0)
 md.settings.waitonlock=30
-md.diagnostic.restol=0.05
+md.stressbalance.restol=0.05
 md.steadystate.reltol=0.05
-md.diagnostic.reltol=0.05
-md.diagnostic.abstol=float('NaN')
+md.stressbalance.reltol=0.05
+md.stressbalance.abstol=float('NaN')
 md.timestepping.time_step=1.
 md.timestepping.final_time=3.
Index: /issm/trunk/test/Par/SquareSheetShelf.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetShelf.par	(revision 16136)
+++ /issm/trunk/test/Par/SquareSheetShelf.par	(revision 16137)
@@ -6,5 +6,7 @@
 ymin=min(md.mesh.y);
 ymax=max(md.mesh.y);
-md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
 bed_sheet=-md.materials.rho_ice/md.materials.rho_water*(hmax+(hmin-hmax)*(ymax/2-ymin)/(ymax-ymin));
@@ -35,20 +37,19 @@
 
 %Friction
-pos=find(md.mask.elementonfloatingice);
 md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
-md.friction.coefficient(md.mesh.elements(pos,:))=0.;
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
 
 %Numerical parameters
-md.diagnostic.viscosity_overshoot=0.0;
-md.prognostic.stabilization=1;
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
 md.verbose=verbose(0);
 md.settings.waitonlock=30;
-md.diagnostic.restol=0.05;
+md.stressbalance.restol=0.05;
 md.steadystate.reltol=0.05;
-md.diagnostic.reltol=0.05;
-md.diagnostic.abstol=NaN;
+md.stressbalance.reltol=0.05;
+md.stressbalance.abstol=NaN;
 md.timestepping.time_step=1.;
 md.timestepping.final_time=3.;
Index: /issm/trunk/test/Par/SquareSheetShelf.py
===================================================================
--- /issm/trunk/test/Par/SquareSheetShelf.py	(revision 16136)
+++ /issm/trunk/test/Par/SquareSheetShelf.py	(revision 16137)
@@ -15,5 +15,7 @@
 ymin=min(md.mesh.y)
 ymax=max(md.mesh.y)
-md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)
+xmin=min(md.mesh.x)
+xmax=max(md.mesh.x)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x.reshape(-1,1)-xmin)/(xmax-xmin)
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
 bed_sheet=-md.materials.rho_ice/md.materials.rho_water*(hmax+(hmin-hmax)*(ymax/2-ymin)/(ymax-ymin))
@@ -46,20 +48,19 @@
 
 #Friction
-pos=numpy.nonzero(md.mask.elementonfloatingice)
 md.friction.coefficient=20.*ones((md.mesh.numberofvertices,1))
-md.friction.coefficient[md.mesh.elements[pos].astype(int)-1]=0.
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=ones((md.mesh.numberofelements,1))
 md.friction.q=ones((md.mesh.numberofelements,1))
 
 #Numerical parameters
-md.diagnostic.viscosity_overshoot=0.0
-md.prognostic.stabilization=1
+md.stressbalance.viscosity_overshoot=0.0
+md.masstransport.stabilization=1
 md.thermal.stabilization=1
 md.verbose=verbose(0)
 md.settings.waitonlock=30
-md.diagnostic.restol=0.05
+md.stressbalance.restol=0.05
 md.steadystate.reltol=0.05
-md.diagnostic.reltol=0.05
-md.diagnostic.abstol=float('NaN')
+md.stressbalance.reltol=0.05
+md.stressbalance.abstol=float('NaN')
 md.timestepping.time_step=1.
 md.timestepping.final_time=3.
Index: /issm/trunk/test/Par/SquareShelf.par
===================================================================
--- /issm/trunk/test/Par/SquareShelf.par	(revision 16136)
+++ /issm/trunk/test/Par/SquareShelf.par	(revision 16137)
@@ -6,5 +6,7 @@
 ymin=min(md.mesh.y);
 ymax=max(md.mesh.y);
-md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
 md.geometry.surface=md.geometry.bed+md.geometry.thickness;
@@ -28,20 +30,19 @@
 
 %Friction
-pos=find(md.mask.elementonfloatingice);
 md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
-md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
 
 %Numerical parameters
-md.diagnostic.viscosity_overshoot=0.3;
-md.prognostic.stabilization=1;
+md.stressbalance.viscosity_overshoot=0.3;
+md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
 md.settings.waitonlock=30;
 md.verbose=verbose(0);
-md.diagnostic.restol=0.10;
+md.stressbalance.restol=0.10;
 md.steadystate.reltol=0.02;
-md.diagnostic.reltol=0.02;
-md.diagnostic.abstol=NaN;
+md.stressbalance.reltol=0.02;
+md.stressbalance.abstol=NaN;
 md.timestepping.time_step=1;
 md.timestepping.final_time=3;
Index: /issm/trunk/test/Par/SquareShelf.py
===================================================================
--- /issm/trunk/test/Par/SquareShelf.py	(revision 16136)
+++ /issm/trunk/test/Par/SquareShelf.py	(revision 16137)
@@ -14,6 +14,7 @@
 ymin=min(md.mesh.y)
 ymax=max(md.mesh.y)
-
-md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)
+xmin=min(md.mesh.x)
+xmax=max(md.mesh.x)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x.reshape(-1,1)-xmin)/(xmax-xmin)
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
 md.geometry.surface=md.geometry.bed+md.geometry.thickness
@@ -59,20 +60,19 @@
 
 #Friction
-pos=nonzero(md.mask.elementonfloatingice)
 md.friction.coefficient = 20.*ones((md.mesh.numberofvertices,1))
-md.friction.coefficient[md.mesh.elements[pos,:].astype(int)-1] = 0.
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p = ones((md.mesh.numberofelements,1))
 md.friction.q = ones((md.mesh.numberofelements,1))
 
 #Numerical parameters
-md.diagnostic.viscosity_overshoot = 0.3
-md.prognostic.stabilization = 1.
+md.stressbalance.viscosity_overshoot = 0.3
+md.masstransport.stabilization = 1.
 md.thermal.stabilization = 1.
 md.settings.waitonlock = 30
 md.verbose=verbose()
-md.diagnostic.restol = 0.10
+md.stressbalance.restol = 0.10
 md.steadystate.reltol = 0.02
-md.diagnostic.reltol = 0.02
-md.diagnostic.abstol = nan
+md.stressbalance.reltol = 0.02
+md.stressbalance.abstol = nan
 md.timestepping.time_step = 1.
 md.timestepping.final_time = 3.
Index: /issm/trunk/test/Par/SquareShelf2.par
===================================================================
--- /issm/trunk/test/Par/SquareShelf2.par	(revision 16137)
+++ /issm/trunk/test/Par/SquareShelf2.par	(revision 16137)
@@ -0,0 +1,55 @@
+%Start defining model parameters here
+
+%Geometry
+hmin=300;
+hmax=1000;
+ymin=min(md.mesh.y);
+ymax=max(md.mesh.y);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+
+%Initial velocity and pressure
+x     = transpose(ncread('../Data/SquareShelf.nc','x'));
+y     = transpose(ncread('../Data/SquareShelf.nc','y'));
+vx    = transpose(ncread('../Data/SquareShelf.nc','vx'));
+vy    = transpose(ncread('../Data/SquareShelf.nc','vy'));
+index = transpose(ncread('../Data/SquareShelf.nc','index'));
+md.initialization.vx=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y);
+md.initialization.vy=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y);
+clear vx vy x y index;
+md.initialization.vz=zeros(md.mesh.numberofvertices,1);
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1);
+
+%Materials
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+md.materials.rheology_B=paterson(md.initialization.temperature);
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+
+%Friction
+md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
+md.friction.p=ones(md.mesh.numberofelements,1);
+md.friction.q=ones(md.mesh.numberofelements,1);
+
+%Numerical parameters
+md.stressbalance.viscosity_overshoot=0.3;
+md.masstransport.stabilization=1;
+md.thermal.stabilization=1;
+md.settings.waitonlock=30;
+md.verbose=verbose(0);
+md.stressbalance.restol=0.10;
+md.steadystate.reltol=0.02;
+md.stressbalance.reltol=0.02;
+md.stressbalance.abstol=NaN;
+md.timestepping.time_step=1;
+md.timestepping.final_time=3;
+
+%Boundary conditions:
+md=SetIceShelfBC(md,'../Exp/SquareFront2.exp');
+
+%Change name so that no test have the same name
+A=dbstack;
+if (length(A)>2), md.miscellaneous.name=A(3).file(1:end-2); end
Index: /issm/trunk/test/Par/SquareShelf2.py
===================================================================
--- /issm/trunk/test/Par/SquareShelf2.py	(revision 16137)
+++ /issm/trunk/test/Par/SquareShelf2.py	(revision 16137)
@@ -0,0 +1,86 @@
+import os.path
+import inspect
+import netCDF4
+from numpy import *
+from verbose import *
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import *
+from SetIceShelfBC import *
+
+#Start defining model parameters here
+#Geometry
+hmin=300.
+hmax=1000.
+ymin=min(md.mesh.y)
+ymax=max(md.mesh.y)
+xmin=min(md.mesh.x)
+xmax=max(md.mesh.x)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x.reshape(-1,1)-xmin)/(xmax-xmin)
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+
+#Initial velocity and pressure
+iVelF = netCDF4.Dataset('../Data/SquareShelf.nc','r')
+
+x=reshape(iVelF.variables['x'][:],(-1))
+y=reshape(iVelF.variables['y'][:],(-1))
+vx=iVelF.variables['vx'][:]
+vy=iVelF.variables['vy'][:]
+index=iVelF.variables['index'][:].astype(int)
+
+#dbg - begin
+# #print 'vars in SquareShelf.nc:'
+# #for v in iVelF.variables:
+# #	print v
+#dbg - end 
+
+iVelF.close()
+
+[md.initialization.vx]=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)
+[md.initialization.vy]=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)
+md.initialization.vz=zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=zeros((md.mesh.numberofvertices,1))
+
+#dbg - begin
+#print '...vx:'
+#print md.initialization.vx
+#print '...vy:'
+#print md.initialization.vy
+##print '...vz:'
+##print md.initialization.vz
+##print '...pressure:'
+##print md.initialization.pressure
+#dbg - end 
+
+
+#Materials
+md.initialization.temperature = (273.-20.)*ones((md.mesh.numberofvertices,1))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3.*ones((md.mesh.numberofelements,1))
+
+#Friction
+md.friction.coefficient = 20.*ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
+md.friction.p = ones((md.mesh.numberofelements,1))
+md.friction.q = ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.stressbalance.viscosity_overshoot = 0.3
+md.masstransport.stabilization = 1.
+md.thermal.stabilization = 1.
+md.settings.waitonlock = 30
+md.verbose=verbose()
+md.stressbalance.restol = 0.10
+md.steadystate.reltol = 0.02
+md.stressbalance.reltol = 0.02
+md.stressbalance.abstol = nan
+md.timestepping.time_step = 1.
+md.timestepping.final_time = 3.
+
+#Boundary conditions:
+# #md=SetIceShelfBC(md)
+md=SetIceShelfBC(md,'../Exp/SquareFront2.exp')
+
+#Change name so that no test have the same name
+if len(inspect.stack()) > 2:
+	md.miscellaneous.name=os.path.basename(inspect.stack()[2][1]).split('.')[0]
Index: /issm/trunk/test/Par/SquareShelfConstrained.par
===================================================================
--- /issm/trunk/test/Par/SquareShelfConstrained.par	(revision 16136)
+++ /issm/trunk/test/Par/SquareShelfConstrained.par	(revision 16137)
@@ -6,5 +6,7 @@
 ymin=min(md.mesh.y);
 ymax=max(md.mesh.y);
-md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin);
+xmin=min(md.mesh.x);
+xmax=max(md.mesh.x);
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x-xmin)/(xmax-xmin);
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
 md.geometry.surface=md.geometry.bed+md.geometry.thickness;
@@ -32,20 +34,19 @@
 
 %Friction
-pos=find(md.mask.elementonfloatingice);
 md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
-md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
 
 %Numerical parameters
-md.diagnostic.viscosity_overshoot=0.0;
-md.prognostic.stabilization=1;
+md.stressbalance.viscosity_overshoot=0.0;
+md.masstransport.stabilization=1;
 md.thermal.stabilization=1;
 md.verbose=verbose(0);
 md.settings.waitonlock=30;
-md.diagnostic.restol=0.05;
-md.diagnostic.reltol=0.05;
+md.stressbalance.restol=0.05;
+md.stressbalance.reltol=0.05;
 md.steadystate.reltol=0.05;
-md.diagnostic.abstol=NaN;
+md.stressbalance.abstol=NaN;
 md.timestepping.time_step=1;
 md.timestepping.final_time=3;
Index: /issm/trunk/test/Par/SquareShelfConstrained.py
===================================================================
--- /issm/trunk/test/Par/SquareShelfConstrained.py	(revision 16136)
+++ /issm/trunk/test/Par/SquareShelfConstrained.py	(revision 16137)
@@ -14,6 +14,7 @@
 ymin=numpy.min(md.mesh.y)
 ymax=numpy.max(md.mesh.y)
-
-md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)
+xmin=min(md.mesh.x)
+xmax=max(md.mesh.x)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)+0.1*(hmin-hmax)*(md.mesh.x.reshape(-1,1)-xmin)/(xmax-xmin)
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
 md.geometry.surface=md.geometry.bed+md.geometry.thickness
@@ -44,20 +45,19 @@
 
 #Friction
-pos=numpy.nonzero(md.mask.elementonfloatingice)
 md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
-md.friction.coefficient[md.mesh.elements[pos,:].astype(int)-1]=0.
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=numpy.ones((md.mesh.numberofelements,1))
 md.friction.q=numpy.ones((md.mesh.numberofelements,1))
 
 #Numerical parameters
-md.diagnostic.viscosity_overshoot=0.0
-md.prognostic.stabilization=1.
+md.stressbalance.viscosity_overshoot=0.0
+md.masstransport.stabilization=1.
 md.thermal.stabilization=1.
 md.verbose = verbose(0)
 md.settings.waitonlock=30
-md.diagnostic.restol=0.05
-md.diagnostic.reltol=0.05
+md.stressbalance.restol=0.05
+md.stressbalance.reltol=0.05
 md.steadystate.reltol=0.05
-md.diagnostic.abstol=float('nan')
+md.stressbalance.abstol=float('nan')
 md.timestepping.time_step=1.
 md.timestepping.final_time=3.
Index: /issm/trunk/test/Par/SquareThermal.par
===================================================================
--- /issm/trunk/test/Par/SquareThermal.par	(revision 16136)
+++ /issm/trunk/test/Par/SquareThermal.par	(revision 16137)
@@ -15,8 +15,6 @@
 
 disp('      creating drag');
-md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1); %q=1.
-%Take care of iceshelves: no basal drag
-pos=find(md.mask.elementonfloatingice);
-md.friction.coefficient(md.mesh.elements(pos,:))=0.;
+md.friction.coefficient=200.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(find(md.mask.groundedice_levelset<0.))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
@@ -35,5 +33,5 @@
 %Deal with boundary conditions:
 
-disp('      boundary conditions for diagnostic model');
+disp('      boundary conditions for stressbalance model');
 md=SetMarineIceSheetBC(md,'../Exp/SquareFront.exp');
 
@@ -41,3 +39,3 @@
 md.thermal.spctemperature(:)=md.initialization.temperature;
 md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1); 
-pos=find(md.mask.elementongroundedice);md.basalforcings.geothermalflux(md.mesh.elements(pos,:))=1.*10^-3; %1 mW/m^2
+md.basalforcings.geothermalflux(find(md.mask.groundedice_levelset>0.)=1.*10^-3; %1 mW/m^2
Index: /issm/trunk/test/Par/SquareThermal.py
===================================================================
--- /issm/trunk/test/Par/SquareThermal.py	(revision 16136)
+++ /issm/trunk/test/Par/SquareThermal.py	(revision 16137)
@@ -19,8 +19,6 @@
 
 print "      creating drag"
-md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))    #q=1.
-#Take care of iceshelves: no basal drag
-pos=numpy.nonzero(md.mask.elementonfloatingice)[0]
-md.friction.coefficient[md.mesh.elements[pos,:]-1]=0.
+md.friction.coefficient=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[numpy.nonzero(md.mask.groundedice_levelset<0.)[0]]=0.
 md.friction.p=numpy.ones((md.mesh.numberofelements,1))
 md.friction.q=numpy.ones((md.mesh.numberofelements,1))
@@ -39,5 +37,5 @@
 #Deal with boundary conditions:
 
-print "      boundary conditions for diagnostic model"
+print "      boundary conditions for stressbalance model"
 md=SetMarineIceSheetBC(md,'../Exp/SquareFront.exp')
 
@@ -45,4 +43,3 @@
 md.thermal.spctemperature[:]=md.initialization.temperature
 md.basalforcings.geothermalflux=numpy.zeros((md.mesh.numberofvertices,1)) 
-pos=numpy.nonzero(md.mask.elementongroundedice)[0]
-md.basalforcings.geothermalflux[md.mesh.elements[pos,:]-1]=1.*10**-3    #1 mW/m^2
+md.basalforcings.geothermalflux[numpy.nonzero(md.mask.groundedice_levelset>0.)[0]]=1.*10**-3    #1 mW/m^2
